S1-B D2.4: B 层搬运 account(开户/充值/切挂/代理树,P1 等价零改动;82.8% 覆盖;audit_mode=2 文案校准点待收口)

This commit is contained in:
2026-11-13 16:34:23 +08:00
parent f4723d4b16
commit 838937ddbb
14 changed files with 2858 additions and 0 deletions
+338
View File
@@ -0,0 +1,338 @@
package account
import (
"context"
crand "crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// ---- Day 23:IP 白名单 / 审核模式 / 业务开关 ----
// SetProtocol 更新账号接入协议(Day 30/A-2.1:HTTP/CMPP/SMPP/Web 四类账号)。
func (s *Service) SetProtocol(ctx context.Context, accountID int64, business, protocol string) error {
valid := map[string]bool{"http": true, "cmpp": true, "smpp": true, "web": true}
if !valid[protocol] {
return errs.InvalidParam.WithMsg("协议仅支持 http/cmpp/smpp/web")
}
res := s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
Where("account_id = ? AND business = ?", accountID, business).
Update("protocol", protocol)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg("账号或业务线不存在(须先开户)")
}
return nil
}
// GetIPBindings 获取账号的 IP 白名单(JSON 数组,存于 account_user.ip_bind)。
func (s *Service) GetIPBindings(ctx context.Context, accountID int64) ([]string, error) {
u, err := s.dao.GetByID(ctx, accountID)
if err != nil {
return nil, errs.NotFound.WithMsg("账号不存在")
}
return parseIPList(u.IPBind), nil
}
// SetIPBindings 设置 IP 白名单(存储为 JSON 数组;空列表=不限制)。
func (s *Service) SetIPBindings(ctx context.Context, accountID int64, ips []string) error {
for _, ip := range ips {
if !isValidIP(ip) {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法 IP 地址: %q", ip))
}
}
jsonStr := ""
if len(ips) > 0 {
b, _ := json.Marshal(ips)
jsonStr = string(b)
}
return s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
Where("id = ?", accountID).Update("ip_bind", jsonStr).Error
}
// CheckIPAllowed 校验请求 IP 是否在白名单内(空白名单=允许所有)。
func (s *Service) CheckIPAllowed(ctx context.Context, accountID int64, clientIP string) (bool, error) {
u, err := s.dao.GetByID(ctx, accountID)
if err != nil {
return true, nil // 账号不存在则不限制(由 JWT 层拦截)
}
return IPAllowed(u.IPBind, clientIP), nil
}
// IPAllowed 判定 clientIP 是否命中 ip_bind JSON 白名单(Day 46 导出供外部 API 验签复用;
// 空白名单=允许所有;支持精确 IP 与 a.b.c.* 前缀通配)。
func IPAllowed(ipBindJSON, clientIP string) bool {
ips := parseIPList(ipBindJSON)
if len(ips) == 0 {
return true
}
for _, allowed := range ips {
if ipMatch(allowed, clientIP) {
return true
}
}
return false
}
// ---- 审核模式 ----
// SetAuditMode 设置审核模式(0免审/1手动/2自动拒绝)。
func (s *Service) SetAuditMode(ctx context.Context, accountID int64, business string, mode int) error {
if mode < 0 || mode > 2 {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法审核模式 %d(0免审/1手动/2自动拒绝)", mode))
}
result := s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
Where("account_id = ? AND business = ?", accountID, business).
Update("audit_mode", mode)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return errs.NotFound.WithMsg("账号业务配置不存在")
}
return nil
}
// ---- 业务开关(按位操作) ----
// EnableBusiness 开通业务线(在 account_config 中添加行)。
func (s *Service) EnableBusiness(ctx context.Context, accountID int64, business string) error {
if !isBusinessCode(business) {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法业务线 %q", business))
}
// 检查是否已开通
var n int64
s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
Where("account_id = ? AND business = ?", accountID, business).Count(&n)
if n > 0 {
return errs.InvalidParam.WithMsg("该业务线已开通")
}
return s.config.DB().WithContext(ctx).Create(&entity.AccountConfig{
AccountID: accountID, Business: business, Protocol: "http", AuditMode: 0, FailRefund: 1,
}).Error
}
// DisableBusiness 关闭业务线(删除 account_config 行)。
func (s *Service) DisableBusiness(ctx context.Context, accountID int64, business string) error {
result := s.config.DB().WithContext(ctx).Unscoped().
Where("account_id = ? AND business = ?", accountID, business).
Delete(&entity.AccountConfig{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return errs.NotFound.WithMsg("该业务线未开通")
}
return nil
}
// GetBusinessStatus 获取账号全部业务线开通状态。
func (s *Service) GetBusinessStatus(ctx context.Context, accountID int64) (map[string]bool, error) {
var cfgs []entity.AccountConfig
if err := s.config.DB().WithContext(ctx).Where("account_id = ?", accountID).Find(&cfgs).Error; err != nil {
return nil, err
}
status := map[string]bool{}
for _, code := range businessCode {
status[code] = false
}
for _, c := range cfgs {
status[c.Business] = true
}
return status, nil
}
// ---- 内部工具 ----
func parseIPList(jsonStr string) []string {
if jsonStr == "" {
return nil
}
var ips []string
_ = json.Unmarshal([]byte(jsonStr), &ips)
return ips
}
func isValidIP(ip string) bool {
// 简单校验:IPv4 或 CIDR
if strings.Contains(ip, "/") {
parts := strings.SplitN(ip, "/", 2)
return isValidIPv4(parts[0])
}
return isValidIPv4(ip)
}
func isValidIPv4(ip string) bool {
parts := strings.Split(ip, ".")
if len(parts) != 4 {
return false
}
for _, p := range parts {
if p == "" || len(p) > 3 {
return false
}
n := 0
for _, c := range p {
if c < '0' || c > '9' {
return false
}
n = n*10 + int(c-'0')
}
if n > 255 {
return false
}
}
return true
}
// ipMatch 支持 CIDR 前缀匹配(如 192.168.1.0/24)。
func ipMatch(rule, ip string) bool {
if !strings.Contains(rule, "/") {
return rule == ip
}
// 简化 CIDR:前缀匹配
parts := strings.SplitN(rule, "/", 2)
prefix := strings.TrimSuffix(parts[0], "0") // 移除末尾 0(如 192.168.1.0 → 192.168.1.)
return strings.HasPrefix(ip, prefix) || strings.HasPrefix(ip, strings.TrimSuffix(parts[0], "0"))
}
func isBusinessCode(code string) bool {
for _, c := range businessCode {
if c == code {
return true
}
}
return false
}
// ---- Day 46:外部 HTTP API 配置(回调绑定/限速/扩展码/接口密钥) ----
// ApiConfigReq 外部 API 配置更新请求(零值字段不覆盖;ResetSecret 重发密钥)。
type ApiConfigReq struct {
ReportURL string `json:"report_url"` // 状态回执推送地址(http/https)
UplinkURL string `json:"uplink_url"` // 上行消息推送地址
SpeedLimit int `json:"speed_limit"` // 接口提交限速(条/秒;0=不修改)
ExtCode string `json:"ext_code"` // 通道扩展码默认值(≤32)
ResetSecret bool `json:"reset_secret"` // true=重新生成接口密钥
// Day 62→改版:自定义密码(6~64 字符;非空时优先于 ResetSecret 的随机生成)。
// 口径「库值即密码」:平台零转换原样入库,客户 CMPP/SMPP/HTTP 均直接填该值;
// CMPP Authenticator=MD5(密码+spid+ts) 由客户程序自行拼接,平台同式比对。
CustomSecret string `json:"custom_secret"`
// Day 62:CMPP 账号级接入配额(0=不修改;-1=恢复系统默认即置 0;正数=设置)。
CmppMaxConns int `json:"cmpp_max_conns"` // 每账号最大连接数(1~1024)
CmppSpeed int `json:"cmpp_speed"` // 单链提交限速 条/s(1~100000)
}
// ApiConfigResult 配置更新结果(密码原样入库与回显,口径「库值即密码」)。
type ApiConfigResult struct {
Secret string `json:"secret"` // 新密码原文(未重发时为空;CMPP/SMPP/HTTP 客户端均填它)
CmppPassword string `json:"cmpp_password"` // Day 62:CMPP 密码=库值原文(与 Secret 同值,便于前端分区展示)
}
// SetApiConfig 更新账号外部 API 配置(Day 46;短信业务线 account_config)。
// 密码口径「库值即密码」(Day62 改版):custom(6~64)/随机 32hex 均原样入库,平台零转换;
// HTTP 验签 expect=MD5(userName+timestamp+MD5(库值)),客户 password 即填库值。
func (s *Service) SetApiConfig(ctx context.Context, accountID int64, req *ApiConfigReq) (*ApiConfigResult, error) {
if req.SpeedLimit < 0 || req.SpeedLimit > 100000 {
return nil, errs.InvalidParam.WithMsg("speed_limit 须在 0~100000 条/秒")
}
for _, u := range []string{req.ReportURL, req.UplinkURL} {
if u != "" && !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
return nil, errs.InvalidParam.WithMsg("回调地址须以 http:// 或 https:// 开头: " + u)
}
if len(u) > 255 {
return nil, errs.InvalidParam.WithMsg("回调地址超 255 字符")
}
}
if len(req.ExtCode) > 32 {
return nil, errs.InvalidParam.WithMsg("ext_code 超 32 字符")
}
// Day 62:CMPP 账号级配额校验(0=不修改;-1=恢复系统默认;正数=设置)。
for _, v := range []struct {
name string
val int
max int
}{{"cmpp_max_conns", req.CmppMaxConns, 1024}, {"cmpp_speed", req.CmppSpeed, 100000}} {
if (v.val < -1) || (v.val > 0 && v.val > v.max) {
return nil, errs.InvalidParam.WithMsg(
v.name + " 须为 -1(恢复默认)/0(不修改)/1~" + strconv.Itoa(v.max))
}
}
// Day 62:自定义密码长度校验(≥6;协议拼接由客户自行处理,平台不转换)。
if req.CustomSecret != "" && (len(req.CustomSecret) < 6 || len(req.CustomSecret) > 64) {
return nil, errs.InvalidParam.WithMsg("custom_secret 须为 6~64 字符")
}
updates := map[string]interface{}{}
if req.ReportURL != "" {
updates["report_url"] = req.ReportURL
}
if req.UplinkURL != "" {
updates["uplink_url"] = req.UplinkURL
}
if req.SpeedLimit > 0 {
updates["speed_limit"] = req.SpeedLimit
}
if req.ExtCode != "" {
updates["ext_code"] = req.ExtCode
}
// Day 62:CMPP 配额(-1=恢复系统默认即置 0;正数=设置;0=不修改)。
if req.CmppMaxConns == -1 || req.CmppMaxConns > 0 {
v := 0
if req.CmppMaxConns > 0 {
v = req.CmppMaxConns
}
updates["cmpp_max_conns"] = v
}
if req.CmppSpeed == -1 || req.CmppSpeed > 0 {
v := 0
if req.CmppSpeed > 0 {
v = req.CmppSpeed
}
updates["cmpp_speed"] = v
}
out := &ApiConfigResult{}
// Day 62「库值即密码」:自定义优先于随机重发;原样入库(零转换),
// CMPP(拼接 Authenticator)/SMPP(明文比对)/HTTP(填库值原文)均直接使用该值。
plain := ""
if req.CustomSecret != "" {
plain = req.CustomSecret
} else if req.ResetSecret {
plain = GenApiSecret()
}
if plain != "" {
updates["api_secret"] = plain
out.Secret = plain
out.CmppPassword = plain
}
if len(updates) == 0 {
return out, nil
}
res := s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
Where("account_id = ? AND business = ?", accountID, "sms").Updates(updates)
if res.Error != nil {
return nil, res.Error
}
if res.RowsAffected == 0 {
return nil, errs.NotFound.WithMsg("账号短信业务配置不存在(须先开户)")
}
return out, nil
}
// GenApiSecret 生成 32hex 随机密钥(crypto/rand)。
func GenApiSecret() string {
b := make([]byte, 16)
if _, err := crand.Read(b); err != nil {
// rand 失败极端场景:时间戳兜底(仍有随机前缀碰撞窗口,可忽略)
return fmt.Sprintf("%x", time.Now().UnixNano())
}
return hex.EncodeToString(b)
}
@@ -0,0 +1,237 @@
package account
import (
"context"
"testing"
"go-sms/internal/model/entity"
)
// newCfgTestService 独立内存库 + 种子账号。
func newCfgTestService(t *testing.T) *Service {
t.Helper()
db := newTestDB(t)
s := NewService(db, BcryptMinCost)
ctx := context.Background()
u, err := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "cfg-user", Password: "secret66", Role: "customer",
Business: BusinessSMS | BusinessVideo, // sms + video
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = u })
return s
}
func cfgSeedID(t *testing.T, s *Service) int64 {
t.Helper()
u, err := s.dao.GetByUsername(context.Background(), "cfg-user")
if err != nil {
t.Fatal(err)
}
return u.ID
}
// ---- IP 白名单 ----
func TestIPBindings_SetGetClear(t *testing.T) {
s := newCfgTestService(t)
ctx := context.Background()
id := cfgSeedID(t, s)
// 初始为空(不限制)
ips, _ := s.GetIPBindings(ctx, id)
if len(ips) != 0 {
t.Fatalf("initial ips = %v", ips)
}
// 设置
if err := s.SetIPBindings(ctx, id, []string{"192.168.1.100", "10.0.0.0/24"}); err != nil {
t.Fatal(err)
}
ips, _ = s.GetIPBindings(ctx, id)
if len(ips) != 2 || ips[0] != "192.168.1.100" {
t.Fatalf("ips = %v", ips)
}
// 清空
if err := s.SetIPBindings(ctx, id, nil); err != nil {
t.Fatal(err)
}
ips, _ = s.GetIPBindings(ctx, id)
if len(ips) != 0 {
t.Fatalf("after clear ips = %v", ips)
}
}
func TestIPBindings_InvalidIP(t *testing.T) {
s := newCfgTestService(t)
ctx := context.Background()
id := cfgSeedID(t, s)
for _, bad := range []string{"abc", "1.2.3", "999.1.1.1", ""} {
if err := s.SetIPBindings(ctx, id, []string{bad}); err == nil {
t.Errorf("invalid IP %q should fail", bad)
}
}
}
func TestIPBindings_CheckAllowed(t *testing.T) {
s := newCfgTestService(t)
ctx := context.Background()
id := cfgSeedID(t, s)
// 空白名单:全放行
ok, _ := s.CheckIPAllowed(ctx, id, "1.2.3.4")
if !ok {
t.Fatal("empty whitelist should allow all")
}
// 设置白名单
if err := s.SetIPBindings(ctx, id, []string{"192.168.1.100", "10.0.0.0/24"}); err != nil {
t.Fatal(err)
}
// 精确匹配
ok, _ = s.CheckIPAllowed(ctx, id, "192.168.1.100")
if !ok {
t.Error("exact match should allow")
}
// 前缀匹配
ok, _ = s.CheckIPAllowed(ctx, id, "10.0.0.55")
if !ok {
t.Error("prefix match should allow")
}
// 不在白名单
ok, _ = s.CheckIPAllowed(ctx, id, "172.16.0.1")
if ok {
t.Error("non-whitelisted IP should deny")
}
}
// ---- 审核模式 ----
func TestAuditMode_Set(t *testing.T) {
s := newCfgTestService(t)
ctx := context.Background()
id := cfgSeedID(t, s)
for _, mode := range []int{0, 1, 2} {
if err := s.SetAuditMode(ctx, id, "sms", mode); err != nil {
t.Errorf("SetAuditMode(%d) failed: %v", mode, err)
}
}
// 验证 DB
var cfg entity.AccountConfig
s.config.DB().Where("account_id = ? AND business = ?", id, "sms").First(&cfg)
if cfg.AuditMode != 2 {
t.Errorf("audit_mode = %d, want 2", cfg.AuditMode)
}
// 非法值
if err := s.SetAuditMode(ctx, id, "sms", 3); err == nil {
t.Error("mode 3 should fail")
}
// 不存在的业务
if err := s.SetAuditMode(ctx, id, "nonexist", 1); err == nil {
t.Error("nonexist business should fail")
}
}
// ---- 业务开关 ----
// Day62「库值即密码」:自定义密码原样入库(零转换),6~64 校验。
func TestSetApiConfig_CustomSecretPlain(t *testing.T) {
s := newCfgTestService(t)
ctx := context.Background()
id := cfgSeedID(t, s)
// 6 位(新下限)原样入库。
res, err := s.SetApiConfig(ctx, id, &ApiConfigReq{CustomSecret: "abc123"})
if err != nil {
t.Fatalf("6-char custom_secret failed: %v", err)
}
if res.Secret != "abc123" || res.CmppPassword != "abc123" {
t.Fatalf("res = %v, want secret=cmpp_password=abc123", res)
}
var cfg entity.AccountConfig
s.config.DB().Where("account_id = ? AND business = ?", id, "sms").First(&cfg)
if cfg.ApiSecret != "abc123" {
t.Fatalf("api_secret = %q, want 原样 abc123(平台零转换)", cfg.ApiSecret)
}
// 5 位拒绝(旧 8 位下限废弃)。
if _, err := s.SetApiConfig(ctx, id, &ApiConfigReq{CustomSecret: "abc12"}); err == nil {
t.Fatal("5-char custom_secret should fail")
}
// 65 位拒绝。
if _, err := s.SetApiConfig(ctx, id, &ApiConfigReq{CustomSecret: string(make([]byte, 65))}); err == nil {
t.Fatal("65-char custom_secret should fail")
}
// 随机重置同样原样入库(32hex 即库值,客户直接填它)。
res2, err := s.SetApiConfig(ctx, id, &ApiConfigReq{ResetSecret: true})
if err != nil {
t.Fatal(err)
}
s.config.DB().Where("account_id = ? AND business = ?", id, "sms").First(&cfg)
if cfg.ApiSecret != res2.Secret || len(cfg.ApiSecret) != 32 {
t.Fatalf("reset: api_secret=%q secret=%q, want 一致且 32hex", cfg.ApiSecret, res2.Secret)
}
}
func TestBusinessToggle(t *testing.T) {
s := newCfgTestService(t)
ctx := context.Background()
id := cfgSeedID(t, s)
// 初始:sms=true, video=true, intl=false
status, _ := s.GetBusinessStatus(ctx, id)
if !status["sms"] || !status["video"] || status["intl"] {
t.Fatalf("initial status = %v", status)
}
// 关闭 video
if err := s.DisableBusiness(ctx, id, "video"); err != nil {
t.Fatal(err)
}
status, _ = s.GetBusinessStatus(ctx, id)
if status["video"] {
t.Error("video should be disabled")
}
// 再关闭(已关)
if err := s.DisableBusiness(ctx, id, "video"); err == nil {
t.Error("disable twice should fail")
}
// 重新开通
if err := s.EnableBusiness(ctx, id, "video"); err != nil {
t.Fatal(err)
}
status, _ = s.GetBusinessStatus(ctx, id)
if !status["video"] {
t.Error("video should be re-enabled")
}
// 再开通(已开)
if err := s.EnableBusiness(ctx, id, "video"); err == nil {
t.Error("enable twice should fail")
}
// 开通新业务
if err := s.EnableBusiness(ctx, id, "intl"); err != nil {
t.Fatal(err)
}
status, _ = s.GetBusinessStatus(ctx, id)
if !status["intl"] {
t.Error("intl should be enabled")
}
// 非法业务线
if err := s.EnableBusiness(ctx, id, "hacker"); err == nil {
t.Error("invalid business code should fail")
}
}
+162
View File
@@ -0,0 +1,162 @@
// hierarchy.go Day 28:上级切换——物化路径(/1/5/9/)防环 + 子孙级联重写。
//
// 不变量:任一账号 path = parent.path + id + "/";root 为 "/<id>/"。
// 防环:newParent 不能是自身或自身后代(以 newParent.path 含 "/<id>/" 判定,等价判定祖先链)。
package account
import (
"context"
"fmt"
"strings"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// ensurePath 补写账号物化路径(开户后调用;幂等)。
func (s *Service) ensurePath(ctx context.Context, u *entity.AccountUser) error {
if u.Path != "" {
return nil
}
p := fmt.Sprintf("/%d/", u.ID)
if u.ParentID > 0 {
var parent entity.AccountUser
if err := s.config.DB().WithContext(ctx).Select("id, path").
Where("id = ?", u.ParentID).Take(&parent).Error; err == nil && parent.Path != "" {
p = parent.Path + fmt.Sprintf("%d/", u.ID)
}
}
u.Path = p
return s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
Where("id = ?", u.ID).Update("path", p).Error
}
// ChangeParent 切换上级(事务):防环校验 → 更新 parent_id/path → 子孙 path 前缀级联重写。
func (s *Service) ChangeParent(ctx context.Context, id, newParentID int64) error {
if newParentID <= 0 {
return errs.InvalidParam.WithMsg("新上级 ID 非法")
}
if id == newParentID {
return errs.InvalidParam.WithMsg("不能将账号切换为自己的上级")
}
var self, parent entity.AccountUser
if err := s.config.DB().WithContext(ctx).Where("id = ?", id).Take(&self).Error; err != nil {
return errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
if err := s.config.DB().WithContext(ctx).Where("id = ?", newParentID).Take(&parent).Error; err != nil {
return errs.NotFound.WithMsg(fmt.Sprintf("新上级 %d 不存在", newParentID))
}
// 路径兜底(存量数据无 path 时现算:沿 parent_id 上溯)
if err := s.rebuildPathIfNeeded(ctx, &self); err != nil {
return err
}
if err := s.rebuildPathIfNeeded(ctx, &parent); err != nil {
return err
}
// 防环:新上级的祖先链(其 path)包含当前账号 → 成环
if strings.Contains(parent.Path, fmt.Sprintf("/%d/", id)) {
return errs.InvalidParam.WithMsg(
fmt.Sprintf("非法切换:账号 %d 是新上级 %d 的上级/后代,将形成环", id, newParentID))
}
oldPrefix := self.Path
newPrefix := parent.Path + fmt.Sprintf("%d/", id)
return s.config.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Model(&entity.AccountUser{}).Where("id = ?", id).Updates(map[string]any{
"parent_id": newParentID, "path": newPrefix,
}).Error; err != nil {
return err
}
// 子孙级联:前缀整体替换(逐行重写,兼容 MySQL/SQLite —— 不用 SQL 字符串拼接)
var subs []entity.AccountUser
if err := tx.Where("path LIKE ?", oldPrefix+"%").Find(&subs).Error; err != nil {
return err
}
for i := range subs {
if subs[i].ID == id {
continue // 自身已更新
}
np := newPrefix + subs[i].Path[len(oldPrefix):]
if err := tx.Model(&entity.AccountUser{}).Where("id = ?", subs[i].ID).
Update("path", np).Error; err != nil {
return err
}
}
return nil
})
}
// rebuildPathIfNeeded 存量账号无 path 时沿 parent_id 上溯补算,并递归修复其子树
// (否则子孙空 path 无法被前缀 LIKE 命中,级联与后代查询都会漏)。
func (s *Service) rebuildPathIfNeeded(ctx context.Context, u *entity.AccountUser) error {
if u.Path != "" {
return nil
}
// 上溯(最多 32 层防脏数据环)
chain := []int64{u.ID}
cur := u.ParentID
for i := 0; i < 32 && cur > 0; i++ {
var p entity.AccountUser
if err := s.config.DB().WithContext(ctx).Select("id, parent_id").
Where("id = ?", cur).Take(&p).Error; err != nil {
break
}
chain = append([]int64{cur}, chain...)
cur = p.ParentID
}
var b strings.Builder
b.WriteByte('/')
for _, id := range chain {
fmt.Fprintf(&b, "%d/", id)
}
u.Path = b.String()
if err := s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
Where("id = ?", u.ID).Update("path", u.Path).Error; err != nil {
return err
}
return s.rebuildChildren(ctx, u.ID, u.Path)
}
// rebuildChildren 递归补算直接子节点中 path 为空者(存量数据整树修复)。
func (s *Service) rebuildChildren(ctx context.Context, parentID int64, parentPath string) error {
var kids []entity.AccountUser
if err := s.config.DB().WithContext(ctx).
Where("parent_id = ? AND (path IS NULL OR path = '')", parentID).
Find(&kids).Error; err != nil {
return err
}
for i := range kids {
p := fmt.Sprintf("%s%d/", parentPath, kids[i].ID)
if err := s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
Where("id = ?", kids[i].ID).Update("path", p).Error; err != nil {
return err
}
if err := s.rebuildChildren(ctx, kids[i].ID, p); err != nil {
return err
}
}
return nil
}
// Descendants 直系及间接后代(path 前缀匹配,排除自身)。
func (s *Service) Descendants(ctx context.Context, id int64) ([]entity.AccountUser, error) {
var self entity.AccountUser
if err := s.config.DB().WithContext(ctx).Where("id = ?", id).Take(&self).Error; err != nil {
return nil, errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
if err := s.rebuildPathIfNeeded(ctx, &self); err != nil {
return nil, err
}
var out []entity.AccountUser
err := s.config.DB().WithContext(ctx).
Where("path LIKE ?", self.Path+"%").Order("path").Find(&out).Error
// 排除自身
for i := range out {
if out[i].ID == id {
out = append(out[:i], out[i+1:]...)
break
}
}
return out, err
}
+140
View File
@@ -0,0 +1,140 @@
// profile.go Day 28:标星 / 服务团队 / 实名认证(存储+审核状态机)。
package account
import (
"context"
"fmt"
"strings"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// 实名审核状态。
const (
RealnamePending int8 = 0 // 待审核(含未提交资料)
RealnameApproved int8 = 1 // 已通过
RealnameRejected int8 = 2 // 已驳回(可重新提交)
)
// SetStar 标星/取消(列表置顶由 ListAccounts 排序保证)。
func (s *Service) SetStar(ctx context.Context, id int64, starred bool) error {
v := 0
if starred {
v = 1
}
res := s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
Where("id = ?", id).Update("is_starred", v)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
return nil
}
// SetSvcTeam 绑定/变更服务团队(空串清除)。
func (s *Service) SetSvcTeam(ctx context.Context, id int64, team string) error {
team = strings.TrimSpace(team)
if len(team) > 64 {
return errs.InvalidParam.WithMsg("服务团队名过长(≤64)")
}
res := s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
Where("id = ?", id).Update("svc_team", team)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
return nil
}
// RealnameSubmit 提交实名资料(本人或 admin 代提交):状态置 0 待审核。
// 状态机:任意状态可提交,但已通过(1)再提交 → 400(实名信息不可变更,需线下申诉)。
func (s *Service) RealnameSubmit(ctx context.Context, id int64, realName, idCard string) error {
realName, idCard = strings.TrimSpace(realName), strings.TrimSpace(idCard)
if realName == "" || len(idCard) < 15 {
return errs.InvalidParam.WithMsg("实名信息不完整(姓名必填,证件号 ≥15 位)")
}
if len([]rune(realName)) > 64 || len(idCard) > 32 {
return errs.InvalidParam.WithMsg("姓名/证件号超长")
}
var u entity.AccountUser
if err := s.config.DB().WithContext(ctx).Select("id, realname_status").
Where("id = ?", id).Take(&u).Error; err != nil {
return errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
if u.RealnameStatus == RealnameApproved {
return errs.InvalidParam.WithMsg("实名已通过,不可重复提交")
}
return s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).Where("id = ?", id).
Updates(map[string]any{
"real_name": realName, "real_id_card": idCard, "realname_status": RealnamePending,
}).Error
}
// RealnameReview 审核流转(仅待审核状态可审):approve=true → 1 通过;false → 2 驳回(带原因)。
// 状态机:0 → 1|2;非 0 状态审核 → 400(已终态/未提交资料)。
func (s *Service) RealnameReview(ctx context.Context, id int64, approve bool, reason string) error {
var u entity.AccountUser
if err := s.config.DB().WithContext(ctx).Select("id, real_name, real_id_card, realname_status").
Where("id = ?", id).Take(&u).Error; err != nil {
return errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
if u.RealnameStatus != RealnamePending || u.RealIDCard == "" {
return errs.InvalidParam.WithMsg(
fmt.Sprintf("账号 %d 当前实名状态 %d 非待审核(或未提交资料),不可审核", id, u.RealnameStatus))
}
target := RealnameApproved
if !approve {
target = RealnameRejected
}
return s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).Where("id = ?", id).
Updates(map[string]any{
"realname_status": target,
"remark": reviewRemark(approve, reason),
}).Error
}
// reviewRemark 审核备注留痕。
func reviewRemark(approve bool, reason string) string {
if approve {
return "实名审核通过"
}
if reason == "" {
return "实名审核驳回"
}
return "实名审核驳回: " + reason
}
// MaskIDCard 证件号脱敏(保留前 4 后 4;不足 10 位全掩码)。
func MaskIDCard(card string) string {
if len(card) < 10 {
return strings.Repeat("*", len(card))
}
return card[:4] + strings.Repeat("*", len(card)-8) + card[len(card)-4:]
}
// RealnameInfo 实名信息视图(脱敏)。
type RealnameInfo struct {
RealName string `json:"real_name"`
IDCard string `json:"id_card"` // 脱敏后
Status int8 `json:"status"`
}
// GetRealname 查询实名信息(证件号脱敏;未提交时 IDCard 为空)。
func (s *Service) GetRealname(ctx context.Context, id int64) (*RealnameInfo, error) {
var u entity.AccountUser
if err := s.config.DB().WithContext(ctx).
Select("id, real_name, real_id_card, realname_status").
Where("id = ?", id).Take(&u).Error; err != nil {
return nil, errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", id))
}
card := ""
if u.RealIDCard != "" {
card = MaskIDCard(u.RealIDCard)
}
return &RealnameInfo{RealName: u.RealName, IDCard: card, Status: u.RealnameStatus}, nil
}
+209
View File
@@ -0,0 +1,209 @@
// recharge.go Day 26:充值(单笔/CSV 批量)+ 余额查询。
//
// 语义:充值仅允许正数金额(负数调整属于后续"人工调整"能力,避免充值通道被滥用);
// 单笔与流水同事务落库,balance_after 取自事务内回读,保证与 account_user.balance 一致;
// 批量充值逐行独立事务——单行失败(账号不存在/金额非法)不影响其余行,结果按数据行号定位。
package account
import (
"bytes"
"context"
"encoding/csv"
"errors"
"fmt"
"io"
"strconv"
"strings"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
"go-sms/internal/repository/mysql"
)
// 充值约束(单位:条/分,与 account_user.balance 一致)。
const (
// MaxRechargeAmount 单笔上限 1 亿(防溢出与误操作)。
MaxRechargeAmount int64 = 10_000_000_000
// MaxBatchRechargeLines CSV 批量单次行数上限。
MaxBatchRechargeLines = 1000
// BalanceLogRecent 余额查询默认携带近期流水条数。
BalanceLogRecent = 20
)
// RechargeRequest 单笔充值请求(POST /accounts/:id/recharge)。
type RechargeRequest struct {
AccountID int64
Amount int64 // 必须 >0
Operator string // 操作人(登录账号)
Remark string
}
// Recharge 单笔充值:事务(余额原子自增 → 回读 → 写流水);返回流水记录(含新余额)。
func (s *Service) Recharge(ctx context.Context, req *RechargeRequest) (*entity.AccountBalanceLog, error) {
if req.AccountID <= 0 {
return nil, errs.InvalidParam.WithMsg("账号 ID 非法")
}
if req.Amount <= 0 || req.Amount > MaxRechargeAmount {
return nil, errs.InvalidParam.WithMsg(
fmt.Sprintf("充值金额 %d 非法(须为 1~%d 的正整数)", req.Amount, MaxRechargeAmount))
}
var out entity.AccountBalanceLog
err := s.config.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 原子自增(数据库层保证并发安全,不做读-改-写)
res := tx.Model(&entity.AccountUser{}).Where("id = ?", req.AccountID).
Update("balance", gorm.Expr("balance + ?", req.Amount))
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", req.AccountID))
}
// 同事务回读新余额,写流水(balance_after 与余额严格一致)
var bal int64
if err := tx.Model(&entity.AccountUser{}).Where("id = ?", req.AccountID).
Pluck("balance", &bal).Error; err != nil {
return err
}
out = entity.AccountBalanceLog{
AccountID: req.AccountID, BizType: "recharge",
Amount: req.Amount, BalanceAfter: bal,
Operator: req.Operator, Remark: req.Remark,
}
return tx.Create(&out).Error
})
if err != nil {
return nil, err
}
return &out, nil
}
// BatchRowResult CSV 批量单行结果(行号按数据行计,表头不计)。
type BatchRowResult struct {
Line int `json:"line"`
Username string `json:"username"`
OK bool `json:"ok"`
Balance int64 `json:"balance,omitempty"`
Err string `json:"err,omitempty"`
}
// BatchRechargeResult CSV 批量充值汇总。
type BatchRechargeResult struct {
Total int `json:"total"`
Success int `json:"success"`
Failed int `json:"failed"`
Rows []BatchRowResult `json:"rows"`
}
// RechargeBatch CSV 批量充值:格式 username,amount[,remark];
// 自动跳过 UTF-8 BOM 与表头行(首字段 username);行级失败仅记录,不中断其余行。
func (s *Service) RechargeBatch(ctx context.Context, data []byte, operator string) (*BatchRechargeResult, error) {
rows, err := parseRechargeCSV(data)
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, errs.InvalidParam.WithMsg("CSV 无有效数据行")
}
if len(rows) > MaxBatchRechargeLines {
return nil, errs.InvalidParam.WithMsg(
fmt.Sprintf("批量充值最多 %d 行,当前 %d 行", MaxBatchRechargeLines, len(rows)))
}
res := &BatchRechargeResult{Total: len(rows), Rows: make([]BatchRowResult, 0, len(rows))}
for i, r := range rows {
out := BatchRowResult{Line: i + 1, Username: r.username}
u, err := s.dao.GetByUsername(ctx, r.username)
if err != nil {
out.Err = fmt.Sprintf("用户名 %s 不存在", r.username)
res.Failed++
res.Rows = append(res.Rows, out)
continue
}
if log, err := s.Recharge(ctx, &RechargeRequest{
AccountID: u.ID, Amount: r.amount, Operator: operator, Remark: r.remark,
}); err != nil {
out.Err = errText(err)
res.Failed++
} else {
out.OK, out.Balance = true, log.BalanceAfter
res.Success++
}
res.Rows = append(res.Rows, out)
}
return res, nil
}
// csvRow 解析后的充值行。
type csvRow struct {
username string
amount int64
remark string
}
// parseRechargeCSV 解析并预校验(用户名存在性/金额在行级 Recharge 中复核)。
func parseRechargeCSV(data []byte) ([]csvRow, error) {
data = bytes.TrimPrefix(data, []byte("\ufeff"))
r := csv.NewReader(bytes.NewReader(data))
r.TrimLeadingSpace = true
var out []csvRow
first := true
for {
rec, err := r.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, errs.InvalidParam.WithMsg("CSV 解析失败: " + err.Error())
}
if len(rec) == 0 || strings.TrimSpace(rec[0]) == "" {
continue // 空行
}
// 表头:首行首字段 username(不区分大小写)则跳过
if first && strings.EqualFold(strings.TrimSpace(rec[0]), "username") {
first = false
continue
}
first = false
if len(rec) < 2 {
return nil, errs.InvalidParam.WithMsg(
fmt.Sprintf("CSV 第 %d 行字段不足(须为 username,amount[,remark])", len(out)+1))
}
name := strings.TrimSpace(rec[0])
amount, err := strconv.ParseInt(strings.TrimSpace(rec[1]), 10, 64)
if err != nil {
return nil, errs.InvalidParam.WithMsg(
fmt.Sprintf("CSV 第 %d 行金额 %q 不是整数", len(out)+1, rec[1]))
}
row := csvRow{username: name, amount: amount}
if len(rec) >= 3 {
row.remark = strings.TrimSpace(rec[2])
}
out = append(out, row)
}
return out, nil
}
// GetBalance 余额查询:账号余额/授信 + 近期流水(倒序)。
func (s *Service) GetBalance(ctx context.Context, id int64) (*entity.AccountUser, []entity.AccountBalanceLog, error) {
u, err := s.dao.GetByID(ctx, id)
if err != nil {
return nil, nil, err
}
var logs []entity.AccountBalanceLog
err = s.config.DB().WithContext(ctx).Where("account_id = ?", id).
Order("id DESC").Limit(BalanceLogRecent).Find(&logs).Error
return u, logs, err
}
// errText 业务错误取消息,未知错误统一文案(批量结果行内展示)。
func errText(err error) string {
var biz *errs.Error
if errors.As(err, &biz) {
return biz.Msg
}
if errors.Is(err, mysql.ErrNotFound) {
return "账号不存在"
}
return "系统错误"
}
+328
View File
@@ -0,0 +1,328 @@
// Package account 账号领域服务(Day 21):开户(业务位掩码展开为多业务配置)、
// bcrypt 口令哈希;Day 22-29 将扩展 CRUD/认证/权限/充值/审计。
package account
import (
"context"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"go-sms/internal/model/entity"
"go-sms/internal/pkg/casbin"
errs "go-sms/internal/pkg/errors"
"go-sms/internal/repository/mysql"
)
// 业务线位掩码(需求:一条开通命令可同时开国内/国际/视频/空号/CSP 等业务)。
const (
BusinessSMS int = 1 << iota // 1 国内短信
BusinessIntl // 2 国际短信
BusinessVideo // 4 视频短信
BusinessCSP // 8 CSP 5G 消息
BusinessNullFilter // 16 空号过滤
BusinessShortLink // 32 短链
BusinessAll = BusinessSMS | BusinessIntl | BusinessVideo | BusinessCSP | BusinessNullFilter | BusinessShortLink
)
// businessCode 掩码位 → account_config.business 取值。
var businessCode = map[int]string{
BusinessSMS: "sms",
BusinessIntl: "intl",
BusinessVideo: "video",
BusinessCSP: "csp",
BusinessNullFilter: "nullfilter",
BusinessShortLink: "shortlink",
}
// BcryptMinCost 测试注入用最小 cost(加速单测;生产用 DefaultCost)。
const BcryptMinCost = bcrypt.MinCost
// 支持的内置角色。
var validRoles = map[string]bool{"admin": true, "ops": true, "service": true, "group": true, "customer": true}
// CreateAccountRequest 开户请求(POST /api/v1/accounts)。
type CreateAccountRequest struct {
Username string `json:"username" binding:"required,min=3,max=64"`
Password string `json:"password" binding:"required,min=6,max=64"`
RealName string `json:"real_name"`
Role string `json:"role" binding:"required"`
ParentID int64 `json:"parent_id"`
Business int `json:"business" binding:"required"` // 位掩码,至少一条业务线
CreditBalance int64 `json:"credit_balance"`
SvcTeam string `json:"svc_team"`
Remark string `json:"remark"`
}
// Service 账号服务。
type Service struct {
dao *mysql.AccountDAO
config *mysql.BaseDAO[*entity.AccountConfig]
cost int // bcrypt cost(测试注入 MinCost)
rbac *casbin.Enforcer // Casbin 引擎(Day 25 策略同步;nil 时跳过同步)
}
// NewService 构造;cost<=0 使用 bcrypt.DefaultCost。
func NewService(db *gorm.DB, cost int) *Service {
if cost <= 0 {
cost = bcrypt.DefaultCost
}
return &Service{
dao: mysql.NewAccountDAO(db),
config: mysql.NewBaseDAO[*entity.AccountConfig](db),
cost: cost,
}
}
// WithEnforcer 注入 Casbin 引擎(Day 25:开户/改角色自动同步 casbin_rule;
// 链式调用;未注入时策略同步静默跳过,账号功能不受影响)。
func (s *Service) WithEnforcer(e *casbin.Enforcer) *Service {
s.rbac = e
return s
}
// CreateAccount 开户:校验 → bcrypt → 账号 + 掩码展开的业务配置行 + 授信流水(单事务)。
// 返回创建后的账号(含 ID)。
func (s *Service) CreateAccount(ctx context.Context, req *CreateAccountRequest) (*entity.AccountUser, error) {
req.Username = strings.TrimSpace(req.Username)
if err := s.validate(req); err != nil {
return nil, err
}
if _, err := s.dao.GetByUsername(ctx, req.Username); err == nil {
return nil, errs.InvalidParam.WithMsg(fmt.Sprintf("用户名 %s 已存在", req.Username))
} else if !errors.Is(err, mysql.ErrNotFound) {
return nil, err
}
// Day 61:软删僵尸行仍占物理唯一键 uk_username(删号重建场景),预检查须含软删行,
// 否则插入撞 1062 被包装成 500 通用错误,前端只见"其他错误"无从排查。
var tombstone int64
if err := s.dao.DB().WithContext(ctx).Unscoped().Model(&entity.AccountUser{}).
Where("username = ?", req.Username).Count(&tombstone).Error; err == nil && tombstone > 0 {
return nil, errs.InvalidParam.WithMsg(fmt.Sprintf("用户名 %s 已存在(含已删除账号,请更换用户名)", req.Username))
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), s.cost)
if err != nil {
return nil, fmt.Errorf("account: 口令哈希失败: %w", err)
}
u := &entity.AccountUser{
Username: req.Username, PasswordHash: string(hash), RealName: req.RealName,
Role: req.Role, ParentID: req.ParentID, Status: 1,
CreditBalance: req.CreditBalance, SvcTeam: req.SvcTeam, Remark: req.Remark,
}
configs := s.expandBusiness(req)
if err := s.dao.CreateWithTx(ctx, u, configs); err != nil {
return nil, fmt.Errorf("account: 开户事务失败: %w", err)
}
// Day 28:物化路径初始化(/parent.../id/)
if err := s.ensurePath(ctx, u); err != nil {
return nil, fmt.Errorf("account: 路径初始化失败: %w", err)
}
// Day 25:开户自动同步 Casbin 角色绑定(BindRole 写 casbin_rule)
s.syncRole(u.ID, req.Role)
return u, nil
}
// syncRole 角色绑定同步(enforcer 未注入/失败不影响账号主流程,记错误由调用方测试覆盖)。
func (s *Service) syncRole(accountID int64, role string) {
if s.rbac == nil {
return
}
_, _ = s.rbac.BindRole(accountID, role)
}
// validate 请求校验(角色/协议/业务掩码)。
func (s *Service) validate(req *CreateAccountRequest) error {
if !validRoles[req.Role] {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法角色 %q(可选 admin/ops/service/group/customer)", req.Role))
}
if req.Business <= 0 || req.Business&^BusinessAll != 0 {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法业务掩码 %d(有效位:%d)", req.Business, BusinessAll))
}
return nil
}
// expandBusiness 将业务位掩码展开为逐业务配置行(默认审核模式免审;协议经配置接口 Day 23 细化)。
func (s *Service) expandBusiness(req *CreateAccountRequest) []*entity.AccountConfig {
var out []*entity.AccountConfig
for bit, code := range businessCode {
if req.Business&bit == 0 {
continue
}
out = append(out, &entity.AccountConfig{
Business: code, Protocol: "http", AuditMode: 0, FailRefund: 1,
})
}
return out
}
// VerifyPassword 口令校验(登录/测试)。
func VerifyPassword(hash, plain string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
}
// ---- Day 22:CRUD 全量 ----
// ListQuery 列表过滤(Day 22:username/protocol/status + 分页;Day 28:OnlyStarred)。
type ListQuery struct {
Page, PageSize int
Username string
Protocol string // 经 account_configs 存在性联查
Status int // -1 表示不过滤
OnlyStarred bool // Day 28:仅看标星
}
// ListAccounts 分页列表。
func (s *Service) ListAccounts(ctx context.Context, q *ListQuery) ([]entity.AccountUser, int64, error) {
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
tx := s.dao.DB().WithContext(ctx).Model(&entity.AccountUser{})
if q.Username != "" {
tx = tx.Where("username LIKE ?", "%"+q.Username+"%")
}
if q.Status >= 0 {
tx = tx.Where("status = ?", q.Status)
}
if q.OnlyStarred {
tx = tx.Where("is_starred = 1")
}
if q.Protocol != "" {
tx = tx.Where("id IN (SELECT account_id FROM account_config WHERE protocol = ?)", q.Protocol)
}
var total int64
if err := tx.Count(&total).Error; err != nil {
return nil, 0, err
}
var users []entity.AccountUser
// Day 28:标星置顶,其余按 id 倒序
if err := tx.Order("is_starred DESC").Order("id DESC").
Offset((q.Page - 1) * q.PageSize).Limit(q.PageSize).Find(&users).Error; err != nil {
return nil, 0, err
}
return users, total, nil
}
// GetAccount 详情(账号 + 业务配置)。
func (s *Service) GetAccount(ctx context.Context, id int64) (*entity.AccountUser, []entity.AccountConfig, error) {
u, err := s.dao.GetByID(ctx, id)
if err != nil {
return nil, nil, err
}
var cfgs []entity.AccountConfig
err = s.config.DB().WithContext(ctx).Where("account_id = ?", id).Find(&cfgs).Error
return u, cfgs, err
}
// UpdateAccountFields 白名单部分更新(联系人/角色/上级/服务团队/备注)。
// 角色变更时自动重绑 Casbin(Day 25)。
func (s *Service) UpdateAccountFields(ctx context.Context, id int64, fields map[string]any) error {
allowed := map[string]bool{"real_name": true, "role": true, "parent_id": true, "svc_team": true, "remark": true}
for k := range fields {
if !allowed[k] {
return errs.InvalidParam.WithMsg(fmt.Sprintf("不允许更新字段 %q", k))
}
}
newRole := ""
if v, ok := fields["role"]; ok {
role, _ := v.(string)
if !validRoles[role] {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法角色 %q", v))
}
newRole = role
}
if err := s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).Where("id = ?", id).Updates(fields).Error; err != nil {
return err
}
// Day 25:角色变更 → 先解绑全部旧角色再绑定新角色(casbin_rule 同步)
if newRole != "" && s.rbac != nil {
_, _ = s.rbac.UnbindAllRoles(id)
_, _ = s.rbac.BindRole(id, newRole)
}
return nil
}
// SetStatus 启用/禁用(禁用即刻生效:Token 校验经 CheckEnabled 拦截)。
func (s *Service) SetStatus(ctx context.Context, id int64, status int) error {
if status != 0 && status != 1 {
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法状态 %d(0/1)", status))
}
return s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).Where("id = ?", id).
Update("status", status).Error
}
// CheckEnabled 账号是否启用(Token 校验回调;不存在/禁用均视为失效)。
func (s *Service) CheckEnabled(ctx context.Context, id int64) (bool, error) {
u, err := s.dao.GetByID(ctx, id)
if err != nil {
return false, nil // 已删除:令牌失效
}
return u.Status == 1, nil
}
// DeleteAccount 删除守卫(Day 22 验收):存在发送明细(活跃/近期)→ 业务错误;
// 沉默账号软删。60 天全量窗口依赖阶段 5 历史库,当前以 5 天热表近似。
// Day 25:删除后同步解绑 Casbin 全部角色。
func (s *Service) DeleteAccount(ctx context.Context, id int64) error {
if _, err := s.dao.GetByID(ctx, id); err != nil {
return err
}
var n int64
s.config.DB().WithContext(ctx).Model(&entity.MessageDetail{}).Where("account_id = ?", id).Count(&n)
if n > 0 {
return errs.SendLimited.WithMsg(fmt.Sprintf("账号近 5 天存在 %d 条发送记录,不可删除(沉默或 60 天未发送可删)", n))
}
if err := s.dao.Delete(ctx, id); err != nil {
return err
}
if s.rbac != nil {
_, _ = s.rbac.UnbindAllRoles(id)
}
return nil
}
// ---- Day 25:二级权限标记(recharge/proxy_send/export/send)----
// GrantSecondary 授予账户二级权限(写 casbin_rule p 规则,sub=accountID)。
// perm 合法性由调用方(handler)校验;引擎未注入返回业务错误。
func (s *Service) GrantSecondary(ctx context.Context, id int64, perm string) error {
if s.rbac == nil {
return errs.InternalError.WithMsg("权限引擎未初始化,无法授予二级权限")
}
if _, err := s.dao.GetByID(ctx, id); err != nil {
return err
}
if _, err := s.rbac.GrantPermission(id, "account", perm); err != nil {
return fmt.Errorf("account: 授予二级权限失败: %w", err)
}
return nil
}
// RevokeSecondary 撤销账户二级权限。
func (s *Service) RevokeSecondary(ctx context.Context, id int64, perm string) error {
if s.rbac == nil {
return errs.InternalError.WithMsg("权限引擎未初始化,无法撤销二级权限")
}
if _, err := s.dao.GetByID(ctx, id); err != nil {
return err
}
if _, err := s.rbac.RevokePermission(id, "account", perm); err != nil {
return fmt.Errorf("account: 撤销二级权限失败: %w", err)
}
return nil
}
// ListSecondary 账户全部二级权限(account:perm 列表)。
func (s *Service) ListSecondary(ctx context.Context, id int64) []string {
if s.rbac == nil {
return nil
}
return s.rbac.PermissionsFor(id)
}
@@ -0,0 +1,144 @@
package account
import (
"context"
"testing"
"gorm.io/gorm"
"go-sms/internal/model/entity"
)
// seedAccounts 预置多样账号(供列表过滤/删除守卫用)。
func seedAccounts(t *testing.T, db *gorm.DB) {
t.Helper()
rows := []entity.AccountUser{
{Username: "alice", PasswordHash: "x", Role: "customer", Status: 1},
{Username: "bob-ops", PasswordHash: "x", Role: "ops", Status: 1},
{Username: "carol", PasswordHash: "x", Role: "customer", Status: 1},
}
for i := range rows {
if err := db.Create(&rows[i]).Error; err != nil {
t.Fatal(err)
}
}
// bob 置为禁用(Status 零值有 gorm default:1,经显式 Update 写 0)
db.Model(&entity.AccountUser{}).Where("username = ?", "bob-ops").Update("status", 0)
// carol 配置 cmpp(协议过滤);carol 有发送明细(删除守卫)
db.Create(&entity.AccountConfig{AccountID: rows[2].ID, Business: "sms", Protocol: "cmpp"})
db.Create(&entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: 7301}, AccountID: rows[2].ID, Mobile: "13800138000"})
}
// TestListAccounts_Filters 列表过滤与分页(Day 22)。
func TestListAccounts_Filters(t *testing.T) {
db := newTestDB(t)
seedAccounts(t, db)
s := NewService(db, BcryptMinCost)
ctx := context.Background()
// 全量
users, total, err := s.ListAccounts(ctx, &ListQuery{Status: -1})
if err != nil || total != 3 || len(users) != 3 {
t.Fatalf("全量 = (%d,%d,%v)", len(users), total, err)
}
// username 模糊
_, total, _ = s.ListAccounts(ctx, &ListQuery{Username: "bob", Status: -1})
if total != 1 {
t.Errorf("username 过滤 total=%d, 期望 1", total)
}
// status
_, total, _ = s.ListAccounts(ctx, &ListQuery{Status: 1})
if total != 2 {
t.Errorf("status=1 total=%d, 期望 2", total)
}
// protocol(联查 config:仅 carol 为 cmpp)
users, total, _ = s.ListAccounts(ctx, &ListQuery{Protocol: "cmpp", Status: -1})
if total != 1 || users[0].Username != "carol" {
t.Errorf("protocol 过滤 = (%v,%d)", users, total)
}
// 分页
users, _, _ = s.ListAccounts(ctx, &ListQuery{Page: 2, PageSize: 2, Status: -1})
if len(users) != 1 {
t.Errorf("分页第2页 = %d 条, 期望 1", len(users))
}
}
// TestUpdateAndStatus 更新白名单与状态切换(含禁用后 CheckEnabled=false)。
func TestUpdateAndStatus(t *testing.T) {
db := newTestDB(t)
seedAccounts(t, db)
s := NewService(db, BcryptMinCost)
ctx := context.Background()
var alice entity.AccountUser
db.Where("username = ?", "alice").First(&alice)
if err := s.UpdateAccountFields(ctx, alice.ID, map[string]any{"real_name": "爱丽丝", "svc_team": "A组"}); err != nil {
t.Fatal(err)
}
if err := s.UpdateAccountFields(ctx, alice.ID, map[string]any{"balance": 999}); err == nil {
t.Error("非白名单字段应拒绝")
}
if err := s.UpdateAccountFields(ctx, alice.ID, map[string]any{"role": "hacker"}); err == nil {
t.Error("非法角色应拒绝")
}
enabled, _ := s.CheckEnabled(ctx, alice.ID)
if !enabled {
t.Fatal("初始应启用")
}
if err := s.SetStatus(ctx, alice.ID, 0); err != nil {
t.Fatal(err)
}
if enabled, _ = s.CheckEnabled(ctx, alice.ID); enabled {
t.Fatal("禁用后 CheckEnabled 应为 false(Token 即失效)")
}
if err := s.SetStatus(ctx, alice.ID, 2); err == nil {
t.Error("非法状态应拒绝")
}
}
// TestDeleteAccount_Guard 删除守卫:活跃拒绝、沉默可删(软删)。
func TestDeleteAccount_Guard(t *testing.T) {
db := newTestDB(t)
seedAccounts(t, db)
s := NewService(db, BcryptMinCost)
ctx := context.Background()
var carol, bob, alice entity.AccountUser
db.Where("username = ?", "carol").First(&carol)
db.Where("username = ?", "bob-ops").First(&bob)
db.Where("username = ?", "alice").First(&alice)
// carol 有发送明细 → 业务错误
if err := s.DeleteAccount(ctx, carol.ID); err == nil {
t.Fatal("活跃账号应拒绝删除")
}
// bob 禁用但无明细 → 可删;alice 启用无明细 → 可删
if err := s.DeleteAccount(ctx, bob.ID); err != nil {
t.Fatalf("沉默账号应可删: %v", err)
}
if err := s.DeleteAccount(ctx, alice.ID); err != nil {
t.Fatalf("沉默账号应可删: %v", err)
}
var n int64
db.Model(&entity.AccountUser{}).Where("username IN ?", []string{"alice"}).Count(&n)
if n != 0 {
t.Error("软删后应不可见")
}
}
// TestGetAccountWithConfigs 详情含业务配置。
func TestGetAccountWithConfigs(t *testing.T) {
db := newTestDB(t)
seedAccounts(t, db)
s := NewService(db, BcryptMinCost)
var carol entity.AccountUser
db.Where("username = ?", "carol").First(&carol)
u, cfgs, err := s.GetAccount(context.Background(), carol.ID)
if err != nil || u.Username != "carol" || len(cfgs) != 1 || cfgs[0].Protocol != "cmpp" {
t.Fatalf("详情 = (%v,%v,%v)", u, cfgs, err)
}
}
@@ -0,0 +1,138 @@
// service_day25_test.go Day 25:Casbin 策略同步(开户绑定/改角重绑/删除解绑)+ 二级权限。
package account
import (
"context"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
"go-sms/internal/pkg/casbin"
errs "go-sms/internal/pkg/errors"
)
// newSvcWithRBAC 内存库 + enforcer(含基础角色策略)+ 注入 service。
func newSvcWithRBAC(t *testing.T) (*Service, *casbin.Enforcer) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.MessageDetail{}); err != nil {
t.Fatal(err)
}
e, err := casbin.New(db)
if err != nil {
t.Fatal(err)
}
for _, p := range [][]string{
{"admin", "*", "*"},
{"ops", "account", "write"},
{"customer", "message", "write"},
} {
if _, err := e.AddPolicy(p[0], p[1], p[2]); err != nil {
t.Fatal(err)
}
}
return NewService(db, BcryptMinCost).WithEnforcer(e), e
}
// TestCreateAccount_BindsRole 验收:开户自动写入 casbin_rule(BindRole)。
func TestCreateAccount_BindsRole(t *testing.T) {
s, e := newSvcWithRBAC(t)
ctx := context.Background()
u, err := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d25-cust", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err != nil {
t.Fatal(err)
}
if ok, _ := e.Check(u.ID, "message", "write"); !ok {
t.Fatal("开户后应自动绑定 customer 角色(message:write 放行)")
}
if ok, _ := e.Check(u.ID, "account", "export"); ok {
t.Fatal("customer 不应有 account:export")
}
}
// TestUpdateRole_Rebind 角色变更 → 旧绑定解绑、新角色即时生效。
func TestUpdateRole_Rebind(t *testing.T) {
s, e := newSvcWithRBAC(t)
ctx := context.Background()
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d25-rebind", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err := s.UpdateAccountFields(ctx, u.ID, map[string]any{"role": "ops"}); err != nil {
t.Fatal(err)
}
if ok, _ := e.Check(u.ID, "account", "write"); !ok {
t.Fatal("改为 ops 后应有 account:write")
}
if ok, _ := e.Check(u.ID, "message", "write"); ok {
t.Fatal("旧 customer 绑定应已解绑(message:write 拒绝)")
}
}
// TestDeleteAccount_Unbinds 删除账号 → Casbin 角色同步解绑。
func TestDeleteAccount_Unbinds(t *testing.T) {
s, e := newSvcWithRBAC(t)
ctx := context.Background()
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d25-del", Password: "secret66", Role: "ops", Business: BusinessSMS,
})
if ok, _ := e.Check(u.ID, "account", "write"); !ok {
t.Fatal("前置:ops 已绑定")
}
if err := s.DeleteAccount(ctx, u.ID); err != nil {
t.Fatal(err)
}
if ok, _ := e.Check(u.ID, "account", "write"); ok {
t.Fatal("删除后角色绑定应解绑")
}
}
// TestSecondaryPermissions 二级权限授予/撤销/列表;未注入引擎返回业务错误。
func TestSecondaryPermissions(t *testing.T) {
s, e := newSvcWithRBAC(t)
ctx := context.Background()
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d25-perm", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err := s.GrantSecondary(ctx, u.ID, "export"); err != nil {
t.Fatal(err)
}
if perms := s.ListSecondary(ctx, u.ID); len(perms) != 1 || perms[0] != "account:export" {
t.Fatalf("二级权限列表 = %v, 期望 [account:export]", perms)
}
if ok, _ := e.Check(u.ID, "account", "export"); !ok {
t.Fatal("授予 export 后应放行")
}
if err := s.RevokeSecondary(ctx, u.ID, "export"); err != nil {
t.Fatal(err)
}
if ok, _ := e.Check(u.ID, "account", "export"); ok {
t.Fatal("撤销 export 后应拒绝")
}
if perms := s.ListSecondary(ctx, u.ID); len(perms) != 0 {
t.Fatalf("撤销后列表 = %v, 期望空", perms)
}
// 引擎未注入:授权业务错误;开户/改角不受影响(nil 安全)
s2 := newTestService(t)
if err := s2.GrantSecondary(ctx, 1, "export"); err == nil {
t.Fatal("未注入引擎应返回错误")
} else if bizErr, ok := err.(*errs.Error); !ok || bizErr.Code != errs.InternalError.Code {
t.Fatalf("期望 ISC:500 业务错误,实际 %v", err)
}
if _, err := s2.CreateAccount(ctx, &CreateAccountRequest{
Username: "d25-norbac", Password: "secret66", Role: "customer", Business: BusinessSMS,
}); err != nil {
t.Fatalf("未注入引擎开户应正常: %v", err)
}
}
@@ -0,0 +1,222 @@
// service_day26_test.go Day 26:充值(单笔/批量)+ 余额查询。
// 验收锚点:充值即余额+流水一致(事务);批量行级报错定位。
package account
import (
"context"
"strings"
"sync"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// newSvc26 内存库(含余额流水表)。
func newSvc26(t *testing.T) *Service {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:d26?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.MessageDetail{}, &entity.AccountBalanceLog{}); err != nil {
t.Fatal(err)
}
return NewService(db, BcryptMinCost)
}
// mustCreate26 开户并断言成功。
func mustCreate26(t *testing.T, s *Service, username string) *entity.AccountUser {
t.Helper()
u, err := s.CreateAccount(context.Background(), &CreateAccountRequest{
Username: username, Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err != nil {
t.Fatal(err)
}
return u
}
// TestRecharge_BalanceAndLogConsistent 验收:充值后余额累加正确、流水 balance_after 一致。
func TestRecharge_BalanceAndLogConsistent(t *testing.T) {
s := newSvc26(t)
ctx := context.Background()
u := mustCreate26(t, s, "d26-cust")
l1, err := s.Recharge(ctx, &RechargeRequest{AccountID: u.ID, Amount: 1000, Operator: "admin"})
if err != nil {
t.Fatal(err)
}
if l1.BalanceAfter != 1000 {
t.Fatalf("首次充值后 balance_after = %d, 期望 1000", l1.BalanceAfter)
}
l2, err := s.Recharge(ctx, &RechargeRequest{AccountID: u.ID, Amount: 500, Operator: "admin", Remark: "二次"})
if err != nil {
t.Fatal(err)
}
if l2.BalanceAfter != 1500 {
t.Fatalf("二次充值后 balance_after = %d, 期望 1500", l2.BalanceAfter)
}
fresh, logs, err := s.GetBalance(ctx, u.ID)
if err != nil {
t.Fatal(err)
}
if fresh.Balance != 1500 {
t.Fatalf("DB 余额 = %d, 期望 1500", fresh.Balance)
}
if len(logs) != 2 || logs[0].Amount != 500 || logs[0].BalanceAfter != 1500 {
t.Fatalf("流水异常: %+v", logs)
}
if logs[0].BizType != "recharge" || logs[0].Operator != "admin" {
t.Fatalf("流水字段异常: %+v", logs[0])
}
}
// TestRecharge_InvalidAmountAndAccount 非法金额/账号 → 业务错误。
func TestRecharge_InvalidAmountAndAccount(t *testing.T) {
s := newSvc26(t)
ctx := context.Background()
u := mustCreate26(t, s, "d26-inv")
for _, amount := range []int64{0, -100, MaxRechargeAmount + 1} {
if _, err := s.Recharge(ctx, &RechargeRequest{AccountID: u.ID, Amount: amount}); err == nil {
t.Fatalf("金额 %d 应被拒绝", amount)
} else if bizErr, ok := err.(*errs.Error); !ok || bizErr.Code != errs.InvalidParam.Code {
t.Fatalf("金额 %d 应 ISC:400, 实际 %v", amount, err)
}
}
if _, err := s.Recharge(ctx, &RechargeRequest{AccountID: 99999, Amount: 100}); err == nil {
t.Fatal("不存在账号应报错")
} else if bizErr, ok := err.(*errs.Error); !ok || bizErr.Code != errs.NotFound.Code {
t.Fatalf("不存在账号应 ISC:404, 实际 %v", err)
}
}
// TestRecharge_ConcurrentAtomic 并发充值原子性:10 协程 × 100 = 1000,无丢失更新。
// (cache=shared + 单连接串行化,验证 UPDATE 原子自增语义)
func TestRecharge_ConcurrentAtomic(t *testing.T) {
s := newSvc26(t)
ctx := context.Background()
u := mustCreate26(t, s, "d26-conc")
if sqlDB, err := s.config.DB().DB(); err == nil {
sqlDB.SetMaxOpenConns(1)
}
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = s.Recharge(ctx, &RechargeRequest{AccountID: u.ID, Amount: 100, Operator: "admin"})
}()
}
wg.Wait()
fresh, logs, err := s.GetBalance(ctx, u.ID)
if err != nil {
t.Fatal(err)
}
if fresh.Balance != 1000 {
t.Fatalf("并发充值后余额 = %d, 期望 1000(原子性被破坏)", fresh.Balance)
}
if len(logs) != 10 {
t.Fatalf("流水条数 = %d, 期望 10", len(logs))
}
}
// TestRechargeBatch_RowLevelErrors 验收:CSV 批量行级报错定位;单行失败不影响其余行。
func TestRechargeBatch_RowLevelErrors(t *testing.T) {
s := newSvc26(t)
ctx := context.Background()
good := mustCreate26(t, s, "d26-good")
mustCreate26(t, s, "d26-zero")
csvData := "\ufeffusername,amount,remark\n" +
"d26-good,300,首批\n" +
"nobody,100,不存在\n" +
"d26-zero,-5,负数\n" +
"d26-good,200,二批\n"
res, err := s.RechargeBatch(ctx, []byte(csvData), "admin")
if err != nil {
t.Fatal(err)
}
if res.Total != 4 || res.Success != 2 || res.Failed != 2 {
t.Fatalf("total/success/failed = %d/%d/%d, 期望 4/2/2", res.Total, res.Success, res.Failed)
}
if res.Rows[1].Line != 2 || res.Rows[1].OK || !strings.Contains(res.Rows[1].Err, "不存在") {
t.Fatalf("第 2 行结果异常: %+v", res.Rows[1])
}
if res.Rows[2].Line != 3 || res.Rows[2].OK || !strings.Contains(res.Rows[2].Err, "非法") {
t.Fatalf("第 3 行结果异常: %+v", res.Rows[2])
}
fresh, _, err := s.GetBalance(ctx, good.ID)
if err != nil {
t.Fatal(err)
}
if fresh.Balance != 500 {
t.Fatalf("批量充值后余额 = %d, 期望 500", fresh.Balance)
}
}
// TestRechargeBatch_Bounds 空数据/超行数/坏格式 → ISC:400。
func TestRechargeBatch_Bounds(t *testing.T) {
s := newSvc26(t)
ctx := context.Background()
if _, err := s.RechargeBatch(ctx, []byte("username,amount\n"), "admin"); err == nil {
t.Fatal("无数据行应 400")
}
if _, err := s.RechargeBatch(ctx, []byte("a,1\nbad\n"), "admin"); err == nil {
t.Fatal("字段不足应 400")
}
var big strings.Builder
big.WriteString("username,amount\n")
for i := 0; i <= MaxBatchRechargeLines; i++ {
big.WriteString("u" + itoa(i) + ",1\n")
}
if _, err := s.RechargeBatch(ctx, []byte(big.String()), "admin"); err == nil {
t.Fatal("超 1000 行应 400")
} else if bizErr, ok := err.(*errs.Error); !ok || bizErr.Code != errs.InvalidParam.Code {
t.Fatalf("超行数应 ISC:400, 实际 %v", err)
}
}
// itoa 测试小工具。
func itoa(i int) string {
if i == 0 {
return "0"
}
var b []byte
for i > 0 {
b = append([]byte{byte('0' + i%10)}, b...)
i /= 10
}
return string(b)
}
// TestGetBalance_LogsDesc 余额查询:流水倒序 + 上限。
func TestGetBalance_LogsDesc(t *testing.T) {
s := newSvc26(t)
ctx := context.Background()
u := mustCreate26(t, s, "d26-query")
for i := 1; i <= BalanceLogRecent+3; i++ {
if _, err := s.Recharge(ctx, &RechargeRequest{AccountID: u.ID, Amount: 10, Remark: "r" + itoa(i)}); err != nil {
t.Fatal(err)
}
}
fresh, logs, err := s.GetBalance(ctx, u.ID)
if err != nil {
t.Fatal(err)
}
if fresh.Balance != int64(10*(BalanceLogRecent+3)) {
t.Fatalf("余额 = %d", fresh.Balance)
}
if len(logs) != BalanceLogRecent {
t.Fatalf("流水条数 = %d, 期望 %d(上限)", len(logs), BalanceLogRecent)
}
if logs[0].Remark != "r"+itoa(BalanceLogRecent+3) {
t.Fatalf("流水应倒序, 首条 = %s", logs[0].Remark)
}
}
@@ -0,0 +1,268 @@
// service_day27_test.go Day 27:余额预警——阈值触发/冷却去重/可用额度/停用跳过/配置 upsert。
package account
import (
"context"
"strings"
"sync"
"testing"
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
"go-sms/internal/pkg/notify"
)
// fakeNotifier 计数型假通知器(可注入失败)。
type fakeNotifier struct {
mu sync.Mutex
calls int
titles []string
err error
}
func (f *fakeNotifier) Send(_ context.Context, title, _ string) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.err != nil {
return f.err
}
f.calls++
f.titles = append(f.titles, title)
return nil
}
func (f *fakeNotifier) count() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls
}
// newWarn27 内存库(单连接独享,完全隔离)+ 假通知器注入。
func newWarn27(t *testing.T) (*WarningService, *fakeNotifier) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if sqlDB, err := db.DB(); err == nil { // 单连接:避免 :memory: 多连接各自建库
sqlDB.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.MessageDetail{},
&entity.AccountBalanceLog{}, &entity.SystemAlertRule{}); err != nil {
t.Fatal(err)
}
fn := &fakeNotifier{}
return NewWarningService(db, func(string, string) notify.Notifier { return fn }), fn
}
// newTestServiceFromDB27 复用 WarningService 同一 db 构造账号服务(开户辅助)。
func newTestServiceFromDB27(t *testing.T, w *WarningService) *Service {
t.Helper()
return NewService(w.db, BcryptMinCost)
}
// TestWarning_TriggerAndNotify 验收:余额低于阈值 → 1 轮扫描内收到告警。
func TestWarning_TriggerAndNotify(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, err := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-cust", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err != nil {
t.Fatal(err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{
Threshold: 200, NotifyType: "wechat", NotifyTo: "http://hook/x",
}); err != nil {
t.Fatal(err)
}
res, err := w.ScanOnce(ctx)
if err != nil {
t.Fatal(err)
}
if res.Rules != 1 || res.Triggered != 1 || fn.count() != 1 {
t.Fatalf("rules/triggered/notified = %d/%d/%d, 期望 1/1/1", res.Rules, res.Triggered, fn.count())
}
}
// TestWarning_CooldownDedup 验收:同账号冷却期内不重复通知;冷却过后恢复。
func TestWarning_CooldownDedup(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-cool", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 100, CooldownMin: 30}); err != nil {
t.Fatal(err)
}
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
for i := 0; i < 3; i++ { // 冷却期内再扫 3 轮:不再通知
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
}
if fn.count() != 1 {
t.Fatalf("冷却期内通知次数 = %d, 期望 1", fn.count())
}
// 回拨 LastAlertAt 超过冷却 → 恢复通知
past := time.Now().Add(-time.Hour)
if err := w.db.WithContext(ctx).Model(&entity.SystemAlertRule{}).
Where("target_id = ?", u.ID).Update("last_alert_at", past).Error; err != nil {
t.Fatal(err)
}
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
if fn.count() != 2 {
t.Fatalf("冷却过后应再次通知, 次数 = %d", fn.count())
}
}
// TestWarning_NotifyFailRetry 通知失败不写 LastAlertAt → 下轮重试成功。
func TestWarning_NotifyFailRetry(t *testing.T) {
w, fn := newWarn27(t)
fn.err = context.Canceled // 先制造失败
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-retry", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 100, CooldownMin: 30})
if res, _ := w.ScanOnce(ctx); res.Triggered != 0 {
t.Fatal("失败轮不应计入 triggered")
}
rule, _ := w.GetWarningConfig(ctx, u.ID)
if rule.LastAlertAt != nil {
t.Fatal("通知失败不应写 LastAlertAt")
}
fn.err = nil // 恢复
if res, _ := w.ScanOnce(ctx); res.Triggered != 1 {
t.Fatal("下轮应重试成功")
}
}
// TestWarning_CreditCounts 可用额度=余额+授信:透支额度充足不告警。
func TestWarning_CreditCounts(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-credit", Password: "secret66", Role: "customer", Business: BusinessSMS,
CreditBalance: 5000,
})
// 余额 0 + 授信 5000,阈值 2000 → 可用 5000 ≥ 2000 不触发
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 2000})
if res, _ := w.ScanOnce(ctx); res.Triggered != 0 || fn.count() != 0 {
t.Fatal("授信额度充足不应告警")
}
// 阈值 8000 > 5000 → 触发(配置变更重置冷却)
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 8000})
if res, _ := w.ScanOnce(ctx); res.Triggered != 1 {
t.Fatal("可用额度低于阈值应告警")
}
}
// TestWarning_SkipDisabled 规则停用/账号禁用均跳过。
func TestWarning_SkipDisabled(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u1, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-off-rule", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
u2, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-off-acct", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
_ = w.SetWarningConfig(ctx, u1.ID, &WarningConfig{Threshold: 100})
_ = w.SetWarningConfig(ctx, u2.ID, &WarningConfig{Threshold: 100})
if err := w.DisableWarningConfig(ctx, u1.ID); err != nil {
t.Fatal(err)
}
if err := s.SetStatus(ctx, u2.ID, 0); err != nil { // 账号禁用
t.Fatal(err)
}
if res, _ := w.ScanOnce(ctx); res.Triggered != 0 {
t.Fatal("规则停用/账号禁用均不应触发")
}
if fn.count() != 0 {
t.Fatal("不应发出任何通知")
}
}
// TestWarningConfig_Validation 参数校验与 upsert。
func TestWarningConfig_Validation(t *testing.T) {
w, _ := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-cfg", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 0}); err == nil {
t.Fatal("阈值 0 应 400")
} else if b, ok := err.(*errs.Error); !ok || b.Code != errs.InvalidParam.Code {
t.Fatalf("应 ISC:400: %v", err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 10, NotifyType: "sms"}); err == nil {
t.Fatal("sms 渠道应 400")
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 10, CooldownMin: 2000}); err == nil {
t.Fatal("冷却超 1440 应 400")
}
// upsert:两次设置仅一条规则且参数更新
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 10, CooldownMin: 5}); err != nil {
t.Fatal(err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 20, CooldownMin: 10}); err != nil {
t.Fatal(err)
}
rule, err := w.GetWarningConfig(ctx, u.ID)
if err != nil || rule == nil {
t.Fatalf("规则应存在: %v", err)
}
if rule.Threshold != 20 || rule.CooldownMin != 10 {
t.Fatalf("upsert 参数未更新: %+v", rule)
}
var n int64
w.db.WithContext(ctx).Model(&entity.SystemAlertRule{}).Where("target_id = ?", u.ID).Count(&n)
if n != 1 {
t.Fatalf("规则条数 = %d, 期望 1", n)
}
if err := w.SetWarningConfig(ctx, 99999, &WarningConfig{Threshold: 10}); err == nil {
t.Fatal("不存在账号应报错")
}
if r, _ := w.GetWarningConfig(ctx, 88888); r != nil {
t.Fatal("未配置应返回 nil")
}
}
// TestWarning_ContentContainsContext 告警标题完整(信息可辨识)。
func TestWarning_ContentContainsContext(t *testing.T) {
w, fn := newWarn27(t)
ctx := context.Background()
s := newTestServiceFromDB27(t, w)
u, _ := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d27-ctx", Password: "secret66", Role: "customer", Business: BusinessSMS,
CreditBalance: 77,
})
_ = w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 500})
if _, err := w.ScanOnce(ctx); err != nil {
t.Fatal(err)
}
fn.mu.Lock()
defer fn.mu.Unlock()
if fn.calls != 1 {
t.Fatal("应通知一次")
}
if !strings.Contains(fn.titles[0], "余额预警") {
t.Fatalf("标题异常: %q", fn.titles[0])
}
}
@@ -0,0 +1,242 @@
// service_day28_test.go Day 28:上级切换(级联路径+防环)/标星置顶/服务团队/实名状态机。
package account
import (
"context"
"fmt"
"testing"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// newSvc28 内存库(单连接隔离)。
func newSvc28(t *testing.T) *Service {
t.Helper()
s := newTestService(t)
if sqlDB, err := s.config.DB().DB(); err == nil {
sqlDB.SetMaxOpenConns(1)
}
return s
}
// create28 开户(parent 可为 0)并断言 path 已初始化。
func create28(t *testing.T, s *Service, username string, parent int64) *entity.AccountUser {
t.Helper()
u, err := s.CreateAccount(context.Background(), &CreateAccountRequest{
Username: username, Password: "secret66", Role: "customer", Business: BusinessSMS,
ParentID: parent,
})
if err != nil {
t.Fatal(err)
}
if u.Path == "" || u.Path[len(u.Path)-1] != '/' {
t.Fatalf("%s path 未初始化: %q", username, u.Path)
}
return u
}
// pathOf 读库中当前 path。
func pathOf(t *testing.T, s *Service, id int64) string {
t.Helper()
var u entity.AccountUser
if err := s.config.DB().Select("id, path").Where("id = ?", id).Take(&u).Error; err != nil {
t.Fatal(err)
}
return u.Path
}
// TestChangeParent_PathCascade 验收:切换后自身与子孙路径级联重写,旁支不变。
func TestChangeParent_PathCascade(t *testing.T) {
s := newSvc28(t)
ctx := context.Background()
root := create28(t, s, "d28-root", 0) // /root/
a := create28(t, s, "d28-a", root.ID) // /root/a/
b := create28(t, s, "d28-b", a.ID) // /root/a/b/
c := create28(t, s, "d28-c", b.ID) // /root/a/b/c/
other := create28(t, s, "d28-o", root.ID) // /root/o/
// B 切换挂到 root 下:/root/b/c/,A 不受影响
if err := s.ChangeParent(ctx, b.ID, root.ID); err != nil {
t.Fatal(err)
}
if got := pathOf(t, s, b.ID); got != root.Path+fmt.Sprintf("%d/", b.ID) {
t.Fatalf("B path = %q, 期望 %q", got, root.Path+fmt.Sprintf("%d/", b.ID))
}
if got := pathOf(t, s, c.ID); got != root.Path+fmt.Sprintf("%d/%d/", b.ID, c.ID) {
t.Fatalf("子孙 C 未级联: %q", got)
}
if got := pathOf(t, s, a.ID); got != root.Path+fmt.Sprintf("%d/", a.ID) {
t.Fatalf("旁支 A 不应变: %q", got)
}
if got := pathOf(t, s, other.ID); got != root.Path+fmt.Sprintf("%d/", other.ID) {
t.Fatalf("旁支 O 不应变: %q", got)
}
var b2 entity.AccountUser
s.config.DB().Select("id, parent_id").Where("id = ?", b.ID).Take(&b2)
if b2.ParentID != root.ID {
t.Fatalf("parent_id = %d, 期望 %d", b2.ParentID, root.ID)
}
desc, err := s.Descendants(ctx, root.ID)
if err != nil {
t.Fatal(err)
}
if len(desc) != 4 { // a, b, c, other
t.Fatalf("root 后代 = %d, 期望 4", len(desc))
}
}
// TestChangeParent_PreventCycle 验收:切给自己/切给自己后代/不存在 → 拒绝且路径不变。
func TestChangeParent_PreventCycle(t *testing.T) {
s := newSvc28(t)
ctx := context.Background()
root := create28(t, s, "d28-r2", 0)
a := create28(t, s, "d28-a2", root.ID)
b := create28(t, s, "d28-b2", a.ID)
before := pathOf(t, s, a.ID)
if err := s.ChangeParent(ctx, a.ID, a.ID); err == nil {
t.Fatal("切给自己应拒绝")
}
if err := s.ChangeParent(ctx, a.ID, b.ID); err == nil {
t.Fatal("切给自己的后代应拒绝(防环)")
} else if bizErr, ok := err.(*errs.Error); !ok || bizErr.Code != errs.InvalidParam.Code {
t.Fatalf("防环应 ISC:400, 实际 %v", err)
}
if err := s.ChangeParent(ctx, a.ID, 99999); err == nil {
t.Fatal("新上级不存在应 404")
}
if got := pathOf(t, s, a.ID); got != before {
t.Fatalf("失败切换不应改动路径: %q -> %q", before, got)
}
}
// TestStar_PinnedTop 验收:标星账号在列表置顶;OnlyStarred 过滤。
func TestStar_PinnedTop(t *testing.T) {
s := newSvc28(t)
ctx := context.Background()
u1 := create28(t, s, "d28-s1", 0)
u2 := create28(t, s, "d28-s2", 0)
u3 := create28(t, s, "d28-s3", 0)
if err := s.SetStar(ctx, u1.ID, true); err != nil { // 最早创建但标星
t.Fatal(err)
}
users, _, err := s.ListAccounts(ctx, &ListQuery{Page: 1, PageSize: 10, Status: -1})
if err != nil {
t.Fatal(err)
}
if users[0].ID != u1.ID || users[0].IsStarred != 1 {
t.Fatalf("标星应置顶, 首行 id=%d starred=%d", users[0].ID, users[0].IsStarred)
}
if users[1].ID != u3.ID { // 其余按 id 倒序
t.Fatalf("次行应 id 倒序, got %d", users[1].ID)
}
only, total, _ := s.ListAccounts(ctx, &ListQuery{Page: 1, PageSize: 10, Status: -1, OnlyStarred: true})
if total != 1 || only[0].ID != u1.ID {
t.Fatalf("OnlyStarred 过滤异常: total=%d", total)
}
if err := s.SetStar(ctx, u1.ID, false); err != nil {
t.Fatal(err)
}
users, _, _ = s.ListAccounts(ctx, &ListQuery{Page: 1, PageSize: 10, Status: -1})
if users[0].ID == u1.ID {
t.Fatal("取消标星后不应置顶")
}
if err := s.SetStar(ctx, 99999, true); err == nil {
t.Fatal("不存在账号应 404")
}
_ = u2
}
// TestSvcTeam_Bind 绑定/变更/清除 + 长度校验。
func TestSvcTeam_Bind(t *testing.T) {
s := newSvc28(t)
ctx := context.Background()
u := create28(t, s, "d28-team", 0)
if err := s.SetSvcTeam(ctx, u.ID, "华南一组"); err != nil {
t.Fatal(err)
}
fresh, _, err := s.GetAccount(ctx, u.ID)
if err != nil {
t.Fatal(err)
}
if fresh.SvcTeam != "华南一组" {
t.Fatalf("svc_team = %q", fresh.SvcTeam)
}
if err := s.SetSvcTeam(ctx, u.ID, " "); err != nil { // 清除
t.Fatal(err)
}
if fresh, _, _ = s.GetAccount(ctx, u.ID); fresh.SvcTeam != "" {
t.Fatalf("清除失败: %q", fresh.SvcTeam)
}
if err := s.SetSvcTeam(ctx, u.ID, string(make([]byte, 65))); err == nil {
t.Fatal("超长应 400")
}
if err := s.SetSvcTeam(ctx, 99999, "x"); err == nil {
t.Fatal("不存在账号应 404")
}
}
// TestRealname_StateMachine 验收:审核流转状态机合法(提交→通过终态;驳回→可重提)。
func TestRealname_StateMachine(t *testing.T) {
s := newSvc28(t)
ctx := context.Background()
u := create28(t, s, "d28-real", 0)
if err := s.RealnameReview(ctx, u.ID, true, ""); err == nil { // 未提交直接审核
t.Fatal("未提交资料不可审核")
}
if err := s.RealnameSubmit(ctx, u.ID, "张三", "123"); err == nil {
t.Fatal("证件号过短应 400")
}
if err := s.RealnameSubmit(ctx, u.ID, "张三", "350203199001011234"); err != nil {
t.Fatal(err)
}
info, _ := s.GetRealname(ctx, u.ID)
if info.Status != RealnamePending || info.IDCard != MaskIDCard("350203199001011234") {
t.Fatalf("提交后状态/脱敏异常: %+v", info)
}
if err := s.RealnameReview(ctx, u.ID, false, "证件照片模糊"); err != nil {
t.Fatal(err)
}
if info, _ = s.GetRealname(ctx, u.ID); info.Status != RealnameRejected {
t.Fatalf("驳回后状态 = %d", info.Status)
}
if err := s.RealnameSubmit(ctx, u.ID, "张三", "350203199001011235"); err != nil {
t.Fatal(err)
}
if err := s.RealnameReview(ctx, u.ID, true, ""); err != nil {
t.Fatal(err)
}
if info, _ = s.GetRealname(ctx, u.ID); info.Status != RealnameApproved {
t.Fatalf("通过后状态 = %d", info.Status)
}
if err := s.RealnameSubmit(ctx, u.ID, "张三", "350203199001011236"); err == nil {
t.Fatal("已通过不可重复提交")
}
if err := s.RealnameReview(ctx, u.ID, true, ""); err == nil {
t.Fatal("终态不可再审核")
}
if err := s.RealnameSubmit(ctx, 99999, "李四", "350203199001011237"); err == nil {
t.Fatal("不存在账号应 404")
}
fresh, _, _ := s.GetAccount(ctx, u.ID)
if fresh.Remark != "实名审核通过" {
t.Fatalf("审核备注 = %q", fresh.Remark)
}
}
// TestMaskIDCard 脱敏边界。
func TestMaskIDCard(t *testing.T) {
if MaskIDCard("1234567890") != "1234**7890" {
t.Fatalf("10 位脱敏 = %q", MaskIDCard("1234567890"))
}
if MaskIDCard("123") != "***" {
t.Fatalf("短串应全掩码: %q", MaskIDCard("123"))
}
if MaskIDCard("350203199001011234") != "3502**********1234" {
t.Fatalf("18 位脱敏 = %q", MaskIDCard("350203199001011234"))
}
}
@@ -0,0 +1,133 @@
// service_day29_test.go Day 29:覆盖率补齐——存量路径重建/nil 引擎降级/默认构造分支。
package account
import (
"context"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
)
// TestRebuildPathLegacy 存量数据(无 path)切换上级/查后代时沿 parent_id 上溯补算。
func TestRebuildPathLegacy(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if sqlDB, e := db.DB(); e == nil {
sqlDB.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.MessageDetail{}); err != nil {
t.Fatal(err)
}
// 手工造三代存量账号(无 path,模拟 Day 28 之前的数据)
root := entity.AccountUser{Username: "leg-root", Role: "customer", Status: 1}
mid := entity.AccountUser{Username: "leg-mid", Role: "customer", Status: 1, ParentID: 0}
leaf := entity.AccountUser{Username: "leg-leaf", Role: "customer", Status: 1}
if err := db.Create(&root).Error; err != nil {
t.Fatal(err)
}
mid.ParentID = root.ID
if err := db.Create(&mid).Error; err != nil {
t.Fatal(err)
}
leaf.ParentID = mid.ID
if err := db.Create(&leaf).Error; err != nil {
t.Fatal(err)
}
s := NewService(db, BcryptMinCost)
ctx := context.Background()
// Descendants 触发 rebuild(root)
desc, err := s.Descendants(ctx, root.ID)
if err != nil {
t.Fatal(err)
}
if len(desc) != 2 || desc[0].ID != mid.ID || desc[1].ID != leaf.ID {
t.Fatalf("存量后代 = %+v", desc)
}
// ChangeParent 触发 rebuild(leaf 挂到 root)且防环仍生效
if err := s.ChangeParent(ctx, leaf.ID, root.ID); err != nil {
t.Fatal(err)
}
var rootFresh, got entity.AccountUser
db.Select("id,path").Where("id = ?", root.ID).Take(&rootFresh)
db.Select("id,path,parent_id").Where("id = ?", leaf.ID).Take(&got)
if want := rootFresh.Path + itoa(int(leaf.ID)) + "/"; got.Path != want {
t.Fatalf("leaf path = %q, 期望 %q", got.Path, want)
}
// mid 挂到 leaf 下:合法(root→leaf→mid),path 级联正确
if err := s.ChangeParent(ctx, mid.ID, leaf.ID); err != nil {
t.Fatalf("重挂后 mid→leaf 应合法: %v", err)
}
var midFresh entity.AccountUser
db.Select("id,path").Where("id = ?", mid.ID).Take(&midFresh)
if want := got.Path + itoa(int(mid.ID)) + "/"; midFresh.Path != want {
t.Fatalf("mid path = %q, 期望 %q", midFresh.Path, want)
}
// root 挂到 mid 下:mid 在 root 子树内 → 成环拒绝
if err := s.ChangeParent(ctx, root.ID, mid.ID); err == nil {
t.Fatal("root 挂到自身后代应成环拒绝")
}
}
// TestSecondaryNilRBACBranch 未注入引擎:Revoke/List 二级权限降级路径。
func TestSecondaryNilRBACBranch(t *testing.T) {
s := newTestService(t)
ctx := context.Background()
if err := s.RevokeSecondary(ctx, 1, PermX("export")); err == nil {
t.Fatal("nil 引擎 Revoke 应报错")
}
if got := s.ListSecondary(ctx, 1); got != nil {
t.Fatalf("nil 引擎 List 应为 nil, got %v", got)
}
}
// PermX 测试辅助(将字符串原样返回;避免引入 middleware 包)。
func PermX(s string) string { return s }
// TestNewServiceDefaultCost cost<=0 → bcrypt.DefaultCost(开户可用)。
func TestNewServiceDefaultCost(t *testing.T) {
s := NewService(newTestDB(t), 0)
if _, err := s.CreateAccount(context.Background(), &CreateAccountRequest{
Username: "d29-cost", Password: "secret66", Role: "customer", Business: BusinessSMS,
}); err != nil {
t.Fatalf("默认 cost 开户失败: %v", err)
}
}
// TestNewWarningServiceDefaultNotifier 工厂为 nil → 默认 Webhook(空 URL 发送失败,
// 不写 LastAlertAt,下轮可重试)。
func TestNewWarningServiceDefaultNotifier(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if sqlDB, e := db.DB(); e == nil {
sqlDB.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{},
&entity.MessageDetail{}, &entity.AccountBalanceLog{}, &entity.SystemAlertRule{}); err != nil {
t.Fatal(err)
}
w := NewWarningService(db, nil) // 默认工厂
s := NewService(db, BcryptMinCost)
ctx := context.Background()
u, err := s.CreateAccount(ctx, &CreateAccountRequest{
Username: "d29-warn", Password: "secret66", Role: "customer", Business: BusinessSMS,
})
if err != nil {
t.Fatal(err)
}
if err := w.SetWarningConfig(ctx, u.ID, &WarningConfig{Threshold: 100}); err != nil {
t.Fatal(err)
}
// NotifyTo 为空 → 默认 Webhook 发送失败 → triggered=0(不 panic、不写 LastAlertAt)
res, err := w.ScanOnce(ctx)
if err != nil || res.Triggered != 0 {
t.Fatalf("空地址通知应失败不崩溃: res=%+v err=%v", res, err)
}
}
+136
View File
@@ -0,0 +1,136 @@
package account
import (
"context"
"errors"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// newTestDB 内存库 + 账号相关表。
func newTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}, &entity.MessageDetail{}); err != nil {
t.Fatal(err)
}
return db
}
func newTestService(t *testing.T) *Service {
return NewService(newTestDB(t), BcryptMinCost)
}
func baseReq() *CreateAccountRequest {
return &CreateAccountRequest{
Username: "day21-cust", Password: "secret66", RealName: "zhang",
Role: "customer", Business: BusinessSMS, CreditBalance: 1000,
}
}
// TestCreateAccount_OK 验收:开户成功,DB 记录正确 + 密码 bcrypt。
func TestCreateAccount_OK(t *testing.T) {
s := newTestService(t)
ctx := context.Background()
u, err := s.CreateAccount(ctx, baseReq())
if err != nil {
t.Fatal(err)
}
if u.ID == 0 || u.Status != 1 {
t.Fatalf("account abnormal: %+v", u)
}
if u.PasswordHash == "secret66" || !VerifyPassword(u.PasswordHash, "secret66") {
t.Fatalf("password not bcrypt: %q", u.PasswordHash)
}
if VerifyPassword(u.PasswordHash, "wrong") {
t.Fatal("wrong password should fail")
}
var cfgCount, logCount int64
s.dao.DB().Model(&entity.AccountConfig{}).Where("account_id = ?", u.ID).Count(&cfgCount)
if cfgCount != 1 {
t.Errorf("config rows = %d, want 1", cfgCount)
}
s.dao.DB().Model(&entity.AccountBalanceLog{}).Where("account_id = ?", u.ID).Count(&logCount)
if logCount != 1 {
t.Errorf("credit log = %d, want 1", logCount)
}
}
// TestCreateAccount_BusinessMask 多业务位掩码展开。
func TestCreateAccount_BusinessMask(t *testing.T) {
s := newTestService(t)
req := baseReq()
req.Username = "multi-biz"
req.Business = BusinessSMS | BusinessVideo | BusinessNullFilter
u, err := s.CreateAccount(context.Background(), req)
if err != nil {
t.Fatal(err)
}
var cfgs []entity.AccountConfig
s.dao.DB().Where("account_id = ?", u.ID).Find(&cfgs)
if len(cfgs) != 3 {
t.Fatalf("config rows = %d, want 3", len(cfgs))
}
got := map[string]bool{}
for _, c := range cfgs {
got[c.Business] = true
}
for _, want := range []string{"sms", "video", "nullfilter"} {
if !got[want] {
t.Errorf("missing business %s", want)
}
}
}
// TestCreateAccount_DuplicateUsername 用户名唯一。
func TestCreateAccount_DuplicateUsername(t *testing.T) {
s := newTestService(t)
ctx := context.Background()
if _, err := s.CreateAccount(ctx, baseReq()); err != nil {
t.Fatal(err)
}
_, err := s.CreateAccount(ctx, baseReq())
if err == nil {
t.Fatal("duplicate should fail")
}
var biz *errs.Error
if !errors.As(err, &biz) || biz.Code != errs.InvalidParam.Code {
t.Fatalf("want ISC:400, got %v", err)
}
}
// TestCreateAccount_InvalidRoleOrBusiness 非法角色/掩码。
func TestCreateAccount_InvalidRoleOrBusiness(t *testing.T) {
s := newTestService(t)
ctx := context.Background()
req := baseReq()
req.Username = "badrole"
req.Role = "hacker"
if _, err := s.CreateAccount(ctx, req); err == nil {
t.Error("invalid role should fail")
}
req = baseReq()
req.Username = "nobiz"
req.Business = 0
if _, err := s.CreateAccount(ctx, req); err == nil {
t.Error("empty business should fail")
}
req = baseReq()
req.Username = "outbiz"
req.Business = BusinessAll << 1
if _, err := s.CreateAccount(ctx, req); err == nil {
t.Error("out-of-range business should fail")
}
}
+161
View File
@@ -0,0 +1,161 @@
// warning.go Day 27:余额预警——配置(阈值/通知方式/接收人)+ 周期扫描 + 冷却去重。
//
// 规则落 system_alert_rule(TargetType=account, Metric=balance, Op=lt);
// 可用额度 = balance + credit_balance(授信支持透支,预警按总额度计);
// 冷却:LastAlertAt + CooldownMin 未到不再通知;通知失败不写 LastAlertAt(下轮重试)。
package account
import (
"context"
"fmt"
"time"
"gorm.io/gorm"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
"go-sms/internal/pkg/notify"
"go-sms/internal/repository/mysql"
)
// 支持的通知渠道(群机器人 webhook)。
var validNotifyTypes = map[string]bool{"wechat": true, "dingtalk": true}
// 冷却范围(分钟)。
const (
CooldownMinDefault = 30
CooldownMax = 1440 // 24h
)
// WarningService 余额预警服务。
type WarningService struct {
db *gorm.DB
dao *mysql.AccountDAO
newNotifier func(notifyType, url string) notify.Notifier
}
// NewWarningService 构造;newNotifier 注入通知器工厂(测试可换假实现)。
func NewWarningService(db *gorm.DB, newNotifier func(notifyType, url string) notify.Notifier) *WarningService {
if newNotifier == nil {
newNotifier = func(t, u string) notify.Notifier { return notify.NewWebhook(t, u) }
}
return &WarningService{db: db, dao: mysql.NewAccountDAO(db), newNotifier: newNotifier}
}
// WarningConfig 预警配置(用户级:阈值/冷却/通知方式/接收 webhook 地址)。
type WarningConfig struct {
Threshold float64 `json:"threshold"`
CooldownMin int `json:"cooldown_min"`
NotifyType string `json:"notify_type"`
NotifyTo string `json:"notify_to"`
}
// SetWarningConfig upsert 账号余额预警规则(每账号一条)。
func (w *WarningService) SetWarningConfig(ctx context.Context, accountID int64, cfg *WarningConfig) error {
if _, err := w.dao.GetByID(ctx, accountID); err != nil {
return err
}
if cfg.Threshold <= 0 {
return errs.InvalidParam.WithMsg("预警阈值必须为正数")
}
if cfg.NotifyType == "" {
cfg.NotifyType = "wechat"
}
if !validNotifyTypes[cfg.NotifyType] {
return errs.InvalidParam.WithMsg("通知方式仅支持 wechat/dingtalk")
}
if cfg.CooldownMin <= 0 {
cfg.CooldownMin = CooldownMinDefault
}
if cfg.CooldownMin > CooldownMax {
return errs.InvalidParam.WithMsg(fmt.Sprintf("冷却分钟最大 %d", CooldownMax))
}
var rule entity.SystemAlertRule
err := w.db.WithContext(ctx).Where(
"target_type = ? AND target_id = ? AND metric = ?", "account", accountID, "balance",
).Take(&rule).Error
if err == gorm.ErrRecordNotFound {
rule = entity.SystemAlertRule{
TargetType: "account", TargetID: accountID, Metric: "balance", Op: "lt",
Threshold: cfg.Threshold, NotifyType: cfg.NotifyType, NotifyTo: cfg.NotifyTo,
CooldownMin: cfg.CooldownMin, Status: 1,
}
return w.db.WithContext(ctx).Create(&rule).Error
}
if err != nil {
return err
}
// 已有规则:更新参数并重置冷却(配置变更立即生效)
return w.db.WithContext(ctx).Model(&rule).Updates(map[string]any{
"threshold": cfg.Threshold, "notify_type": cfg.NotifyType, "notify_to": cfg.NotifyTo,
"cooldown_min": cfg.CooldownMin, "status": 1, "last_alert_at": nil,
}).Error
}
// GetWarningConfig 查询配置(未配置返回 nil)。
func (w *WarningService) GetWarningConfig(ctx context.Context, accountID int64) (*entity.SystemAlertRule, error) {
var rule entity.SystemAlertRule
err := w.db.WithContext(ctx).Where(
"target_type = ? AND target_id = ? AND metric = ?", "account", accountID, "balance",
).Take(&rule).Error
if err == gorm.ErrRecordNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
return &rule, nil
}
// DisableWarningConfig 停用预警(Status=0,保留参数便于恢复)。
func (w *WarningService) DisableWarningConfig(ctx context.Context, accountID int64) error {
return w.db.WithContext(ctx).Model(&entity.SystemAlertRule{}).Where(
"target_type = ? AND target_id = ? AND metric = ?", "account", accountID, "balance",
).Update("status", 0).Error
}
// ScanResult 单轮扫描结果。
type ScanResult struct {
Rules int // 扫描的启用规则数
Triggered int // 触发并成功通知数
}
// ScanOnce 单轮扫描:可用额度低于阈值 → 通知(冷却去重);返回触发数。
// 供 cron 周期调用与测试直接调用(1 分钟窗口由调度器保证)。
func (w *WarningService) ScanOnce(ctx context.Context) (ScanResult, error) {
var rules []entity.SystemAlertRule
if err := w.db.WithContext(ctx).Where(
"status = 1 AND target_type = ? AND metric = ?", "account", "balance",
).Find(&rules).Error; err != nil {
return ScanResult{}, err
}
res := ScanResult{Rules: len(rules)}
now := time.Now()
for i := range rules {
rule := &rules[i]
var acct entity.AccountUser
// 账号禁用/已删(软删过滤)→ 跳过
if err := w.db.WithContext(ctx).Where("id = ? AND status = 1", rule.TargetID).Take(&acct).Error; err != nil {
continue
}
avail := float64(acct.Balance + acct.CreditBalance)
if !(avail < rule.Threshold) { // Op 固定 lt
continue
}
// 冷却期内不重复通知
if rule.LastAlertAt != nil && now.Sub(*rule.LastAlertAt) < time.Duration(rule.CooldownMin)*time.Minute {
continue
}
n := w.newNotifier(rule.NotifyType, rule.NotifyTo)
title := "【go-sms 余额预警】"
content := fmt.Sprintf("账号 %s(id=%d)可用额度 %d 低于阈值 %.0f(余额 %d + 授信 %d),请及时充值。",
acct.Username, acct.ID, int64(avail), rule.Threshold, acct.Balance, acct.CreditBalance)
if err := n.Send(ctx, title, content); err != nil {
// 通知失败不写 LastAlertAt,下轮重试;继续处理其余规则
continue
}
res.Triggered++
_ = w.db.WithContext(ctx).Model(rule).Update("last_alert_at", now).Error
}
return res, nil
}