236 lines
6.9 KiB
Go
236 lines
6.9 KiB
Go
// 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), ",")
|
|
}
|