S1-B D2.2: B 层搬运 template(模板域,P1 等价零改动;audit_mode 文案校准留 D2 收口统一处理)
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
// Package template Day 41(阶段 4):短信模板服务——CRUD+状态机(待审/通过/拒绝)+占位符解析。
|
||||
// 模板仅「通过」态可被发送引用;内容编辑后自动回到待审(合规重新过审)。
|
||||
package template
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
errs "go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/repository/mysql"
|
||||
"go-sms/internal/util"
|
||||
)
|
||||
|
||||
// 模板状态机。
|
||||
const (
|
||||
StatusPending int8 = 0 // 待审(新建/编辑后)
|
||||
StatusPassed int8 = 1 // 审核通过(可引用)
|
||||
StatusRefused int8 = -1 // 审核拒绝
|
||||
)
|
||||
|
||||
// MaxVars 模板变量上限(与账号级频控等配置解耦,平台级约束)。
|
||||
const MaxVars = 10
|
||||
|
||||
// Service 模板服务。
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
dao *mysql.BaseDAO[*entity.TemplateSMS]
|
||||
}
|
||||
|
||||
// NewService 构造。
|
||||
func NewService(db *gorm.DB) *Service {
|
||||
return &Service{db: db, dao: mysql.NewBaseDAO[*entity.TemplateSMS](db)}
|
||||
}
|
||||
|
||||
// CreateReq 新建请求。
|
||||
type CreateReq struct {
|
||||
AccountID int64 `json:"account_id"`
|
||||
Name string `json:"name"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Update 校验+落库;Variables 自动提取存储;新建即待审。
|
||||
func (s *Service) Create(ctx context.Context, req *CreateReq) (*entity.TemplateSMS, error) {
|
||||
if req.AccountID <= 0 || req.Name == "" {
|
||||
return nil, errs.InvalidParam.WithMsg("account_id/name 必填")
|
||||
}
|
||||
if err := validateContent(req.Content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := &entity.TemplateSMS{
|
||||
AccountID: req.AccountID, Name: req.Name, Content: req.Content,
|
||||
Variables: joinVars(req.Content), ExactMatch: 1, Status: StatusPending,
|
||||
}
|
||||
if err := s.dao.Create(ctx, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Update 编辑内容/名称(白名单);内容变更即回待审并清空过审时间。
|
||||
func (s *Service) Update(ctx context.Context, id int64, fields map[string]any) error {
|
||||
t, err := s.dao.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return errs.NotFound.WithMsg("模板不存在")
|
||||
}
|
||||
allowed := map[string]bool{"name": true, "content": true}
|
||||
ups := map[string]any{}
|
||||
for k, v := range fields {
|
||||
if allowed[k] {
|
||||
ups[k] = v
|
||||
}
|
||||
}
|
||||
if len(ups) == 0 {
|
||||
return errs.InvalidParam.WithMsg("无可更新字段")
|
||||
}
|
||||
if content, ok := ups["content"].(string); ok {
|
||||
if err := validateContent(content); err != nil {
|
||||
return err
|
||||
}
|
||||
ups["variables"] = joinVars(content)
|
||||
ups["status"] = StatusPending // 内容变更回待审
|
||||
ups["audit_at"] = nil
|
||||
}
|
||||
return s.db.WithContext(ctx).Model(&entity.TemplateSMS{}).Where("id = ?", t.ID).Updates(ups).Error
|
||||
}
|
||||
|
||||
// Review 审核(仅 待审→通过/拒绝;通过/拒绝 可复审改判)。
|
||||
func (s *Service) Review(ctx context.Context, id int64, pass bool, reason string) error {
|
||||
t, err := s.dao.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return errs.NotFound.WithMsg("模板不存在")
|
||||
}
|
||||
next := StatusRefused
|
||||
if pass {
|
||||
next = StatusPassed
|
||||
}
|
||||
ups := map[string]any{"status": next, "audit_at": time.Now()}
|
||||
if reason != "" {
|
||||
ups["reason"] = reason
|
||||
}
|
||||
return s.db.WithContext(ctx).Model(&entity.TemplateSMS{}).Where("id = ?", t.ID).Updates(ups).Error
|
||||
}
|
||||
|
||||
// BatchReview Day 44(D20):批量审核——事务内逐条原子翻转(UPDATE ... WHERE status=0,
|
||||
// 与消息审核 Day43 同规则;已审条目跳过不报错),返回成功数。
|
||||
func (s *Service) BatchReview(ctx context.Context, ids []int64, pass bool, reason string) (int, error) {
|
||||
if len(ids) == 0 {
|
||||
return 0, errs.InvalidParam.WithMsg("ids 为空")
|
||||
}
|
||||
if len(ids) > 100 {
|
||||
return 0, errs.InvalidParam.WithMsg("单批最多 100 条")
|
||||
}
|
||||
next := StatusRefused
|
||||
if pass {
|
||||
next = StatusPassed
|
||||
}
|
||||
ok := 0
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, id := range ids {
|
||||
ups := map[string]any{"status": next, "audit_at": time.Now()}
|
||||
if reason != "" {
|
||||
ups["reason"] = reason
|
||||
}
|
||||
res := tx.Model(&entity.TemplateSMS{}).
|
||||
Where("id = ? AND status = ?", id, StatusPending).
|
||||
Updates(ups)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
ok += int(res.RowsAffected)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, errs.DBError.WithMsg("批量审核失败: " + err.Error())
|
||||
}
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
// Query 列表过滤(account_id/status/name)。
|
||||
type Query struct {
|
||||
Page, PageSize int
|
||||
AccountID int64
|
||||
Status *int8 // nil 不过滤(状态域含 -1 拒绝,故用指针消零值歧义)
|
||||
Name string
|
||||
}
|
||||
|
||||
// List 分页(id 倒序)。
|
||||
func (s *Service) List(ctx context.Context, q *Query) ([]entity.TemplateSMS, int64, error) {
|
||||
if q.Page <= 0 {
|
||||
q.Page = 1
|
||||
}
|
||||
if q.PageSize <= 0 || q.PageSize > 100 {
|
||||
q.PageSize = 20
|
||||
}
|
||||
tx := s.db.WithContext(ctx).Model(&entity.TemplateSMS{})
|
||||
if q.AccountID > 0 {
|
||||
tx = tx.Where("account_id = ?", q.AccountID)
|
||||
}
|
||||
if q.Status != nil { // 指针语义:nil 不过滤(状态域含 -1 拒绝,零值歧义已消)
|
||||
tx = tx.Where("status = ?", *q.Status)
|
||||
}
|
||||
if q.Name != "" {
|
||||
tx = tx.Where("name LIKE ?", "%"+q.Name+"%")
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var out []entity.TemplateSMS
|
||||
if err := tx.Order("id DESC").Offset((q.Page - 1) * q.PageSize).Limit(q.PageSize).Find(&out).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return out, total, nil
|
||||
}
|
||||
|
||||
// GetByID 详情。
|
||||
func (s *Service) GetByID(ctx context.Context, id int64) (*entity.TemplateSMS, error) {
|
||||
t, err := s.dao.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, errs.NotFound.WithMsg("模板不存在")
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Delete 删除(仅 待审/拒绝 可删;通过态先拒审或强制下线)。
|
||||
func (s *Service) Delete(ctx context.Context, id int64) error {
|
||||
t, err := s.dao.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return errs.NotFound.WithMsg("模板不存在")
|
||||
}
|
||||
if t.Status == StatusPassed {
|
||||
return errs.InvalidParam.WithMsg("模板审核通过中,须先拒审再删除")
|
||||
}
|
||||
return s.dao.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// Render 占位符解析:vars 缺模板任一变量 → InvalidParam(拒绝路径);
|
||||
// 多余变量忽略(调用方上下文携带公共变量属正常)。
|
||||
func (s *Service) Render(t *entity.TemplateSMS, vars map[string]string) (string, error) {
|
||||
for _, name := range util.ExtractVariables(t.Content) {
|
||||
if _, ok := vars[name]; !ok {
|
||||
return "", errs.InvalidParam.WithMsg(fmt.Sprintf("缺少模板变量 {%s}", name))
|
||||
}
|
||||
}
|
||||
out := t.Content
|
||||
for k, v := range vars {
|
||||
out = strings.ReplaceAll(out, "{"+k+"}", v)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// validateContent 内容校验:非空/长度≤500/变量格式与个数。
|
||||
func validateContent(content string) error {
|
||||
if content == "" {
|
||||
return errs.InvalidParam.WithMsg("模板内容必填")
|
||||
}
|
||||
if n := len([]rune(content)); n > 500 {
|
||||
return errs.InvalidParam.WithMsg(fmt.Sprintf("内容 %d 字超上限 500", n))
|
||||
}
|
||||
if err := util.ValidateVariables(content, MaxVars); err != nil {
|
||||
return errs.InvalidParam.WithMsg(err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// joinVars 变量提取为逗号分隔存储字段。
|
||||
func joinVars(content string) string {
|
||||
return strings.Join(util.ExtractVariables(content), ",")
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// service_test.go Day 41:模板 CRUD+状态机+占位符解析。
|
||||
package template
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
)
|
||||
|
||||
func newTplSvc(t *testing.T) *Service {
|
||||
t.Helper()
|
||||
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.TemplateSMS{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return NewService(db)
|
||||
}
|
||||
|
||||
// TestBatchReview Day 44(D20):批量审核——待审全翻/已审跳过/幂等重放。
|
||||
func TestBatchReview(t *testing.T) {
|
||||
s := newTplSvc(t)
|
||||
ctx := context.Background()
|
||||
var ids []int64
|
||||
for i := 0; i < 3; i++ {
|
||||
tpl, err := s.Create(ctx, &CreateReq{AccountID: 1, Name: "b" + string(rune('a'+i)), Content: "【店】您好{name}"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids = append(ids, tpl.ID)
|
||||
}
|
||||
// 批量通过:3 条全翻
|
||||
ok, err := s.BatchReview(ctx, ids, true, "")
|
||||
if err != nil || ok != 3 {
|
||||
t.Fatalf("批量通过: ok=%d err=%v", ok, err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
got, _ := s.GetByID(ctx, id)
|
||||
if got.Status != StatusPassed {
|
||||
t.Fatalf("模板 %d 应已过审: %d", id, got.Status)
|
||||
}
|
||||
}
|
||||
// 重放(已审跳过):ok=0 不报错
|
||||
ok, err = s.BatchReview(ctx, ids, true, "")
|
||||
if err != nil || ok != 0 {
|
||||
t.Fatalf("重放应 0 成功: ok=%d err=%v", ok, err)
|
||||
}
|
||||
// 批量拒绝带原因
|
||||
t4, _ := s.Create(ctx, &CreateReq{AccountID: 1, Name: "b4", Content: "【店】拒绝样例"})
|
||||
if ok, err = s.BatchReview(ctx, []int64{t4.ID}, false, "含敏感词"); err != nil || ok != 1 {
|
||||
t.Fatalf("批量拒绝: ok=%d err=%v", ok, err)
|
||||
}
|
||||
got, _ := s.GetByID(ctx, t4.ID)
|
||||
if got.Status != StatusRefused || got.Reason != "含敏感词" {
|
||||
t.Fatalf("拒绝态/原因: %+v", got)
|
||||
}
|
||||
// 空数组/超 100
|
||||
if _, err = s.BatchReview(ctx, nil, true, ""); err == nil {
|
||||
t.Fatal("空 ids 应拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func stPtr(v int8) *int8 { return &v }
|
||||
|
||||
|
||||
// TestTemplateLifecycle 验收:状态机合法迁移——新建待审→过审可引用→编辑回待审→拒审可删。
|
||||
func TestTemplateLifecycle(t *testing.T) {
|
||||
s := newTplSvc(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 变量超限拒绝(11 个)
|
||||
tooMany := "a{v1}{v2}{v3}{v4}{v5}{v6}{v7}{v8}{v9}{v10}{v11}"
|
||||
if _, err := s.Create(ctx, &CreateReq{AccountID: 1, Name: "x", Content: tooMany}); err == nil {
|
||||
t.Fatal("11 变量应拒绝")
|
||||
}
|
||||
// 非法变量名({1a} 不匹配 [A-Za-z][A-Za-z0-9_]*)不计数,合法创建
|
||||
tpl, err := s.Create(ctx, &CreateReq{AccountID: 1, Name: "验证码", Content: "您的验证码{code},5分钟内有效"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tpl.Status != StatusPending || tpl.Variables != "code" {
|
||||
t.Fatalf("新建应待审且变量提取: %+v", tpl)
|
||||
}
|
||||
// 过审
|
||||
if err := s.Review(ctx, tpl.ID, true, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.GetByID(ctx, tpl.ID)
|
||||
if got.Status != StatusPassed || got.AuditAt == nil {
|
||||
t.Fatal("过审失败")
|
||||
}
|
||||
// 通过态不可删
|
||||
if err := s.Delete(ctx, tpl.ID); err == nil {
|
||||
t.Fatal("通过态删除应拒绝")
|
||||
}
|
||||
// 编辑内容 → 回待审
|
||||
if err := s.Update(ctx, tpl.ID, map[string]any{"content": "新验证码{code}{ttl}"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = s.GetByID(ctx, tpl.ID)
|
||||
if got.Status != StatusPending || got.Variables != "code,ttl" || got.AuditAt != nil {
|
||||
t.Fatalf("编辑应回待审并重提变量: %+v", got)
|
||||
}
|
||||
// 拒审(带理由) → 可删
|
||||
if err := s.Review(ctx, tpl.ID, false, "内容不合规"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Delete(ctx, tpl.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 状态过滤:nil 全量 / 0 待审 / -1 拒绝
|
||||
s.Create(ctx, &CreateReq{AccountID: 1, Name: "a", Content: "aa"})
|
||||
if _, total, _ := s.List(ctx, &Query{Status: stPtr(StatusRefused)}); total != 0 {
|
||||
t.Fatal("拒绝态应为 0(已删)")
|
||||
}
|
||||
if _, total, _ := s.List(ctx, &Query{Status: nil}); total != 1 {
|
||||
t.Fatalf("全量应 1,得 %d", total)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRender 验收:占位符替换+缺参拒绝+多余忽略。
|
||||
func TestRender(t *testing.T) {
|
||||
s := newTplSvc(t)
|
||||
tpl, err := s.Create(context.Background(), &CreateReq{AccountID: 1, Name: "n", Content: "你好{name},订单{order}已发货"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := s.Render(tpl, map[string]string{"name": "张三", "order": "A1", "extra": "x"})
|
||||
if err != nil || out != "你好张三,订单A1已发货" {
|
||||
t.Fatalf("渲染错: %q err=%v", out, err)
|
||||
}
|
||||
if _, err := s.Render(tpl, map[string]string{"name": "张三"}); err == nil {
|
||||
t.Fatal("缺 order 应拒绝")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user