494 lines
19 KiB
Go
494 lines
19 KiB
Go
package send
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
"time"
|
|
|
|
"go-sms/internal/model/entity"
|
|
"go-sms/internal/pkg/errors"
|
|
"go-sms/internal/service/balance"
|
|
"go-sms/internal/service/interceptor"
|
|
"go-sms/internal/util"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// TaskRouter 审核分流接口(audit.ReviewService 实现;依赖倒置避免 send→audit 包依赖)。
|
|
// nil 时不分流,任务停留待审(由 48h 超时扫描兜底)。
|
|
type TaskRouter interface {
|
|
Route(ctx context.Context, taskID int64) (*entity.MessageTask, *entity.AuditRecord, error)
|
|
}
|
|
|
|
// SubmitService 发送提交服务(Day 43 修复循环起步,Day 48 升级全流程状态机)。
|
|
// 链路:校验→预扣→落库→拦截(退费)→审核分流(拒绝退费)→Kafka 事件;
|
|
// 路由与下发移交 submit 消费者(同步链路 MySQL 禁令,技术方案 10.4.3)。
|
|
type SubmitService struct {
|
|
db *gorm.DB
|
|
sf *util.Snowflake
|
|
rt TaskRouter
|
|
chain *interceptor.Chain // Day 48:受理期拦截(nil=跳过,兼容测试)
|
|
sink EventSink // Day 48:sms-submit 统一出口(nil=不投)
|
|
bal balance.Store // Day 54 R1:资金预扣/退款(mysql 行锁|redis Lua)
|
|
}
|
|
|
|
// NewSubmitService 构造(rt 可 nil:single-test/未装配审核时分流跳过;
|
|
// opts 按 Day48 链路注入拦截链/事件出口,Day54 R1 注入资金 Store)。
|
|
func NewSubmitService(db *gorm.DB, sf *util.Snowflake, rt TaskRouter, opts ...SubmitOption) *SubmitService {
|
|
s := &SubmitService{db: db, sf: sf, rt: rt}
|
|
for _, opt := range opts {
|
|
opt(s)
|
|
}
|
|
if s.bal == nil { // 未注入退化为 MySQL 原路径(既有测试/降级装配零破坏)
|
|
s.bal = balance.NewMySQLStore(db)
|
|
}
|
|
return s
|
|
}
|
|
|
|
// SubmitResult 提交结果(任务+分流后审核态+预估)。
|
|
type SubmitResult struct {
|
|
Task *entity.MessageTask
|
|
Record *entity.AuditRecord // 自动档留痕(其余 nil)
|
|
Estimate *Estimate
|
|
}
|
|
|
|
// Submit 受理发送任务(Day 48 全流程状态机):
|
|
// ①Validate ②余额快检 ③holdFee 原子预扣(不足→ISC:007;扣后失败环节全对冲)
|
|
// ④事务{task+明细(拦截号直接终态 5)}(失败→Refund 全额)
|
|
// ⑤拦截费即时退(RefundTask blockedFee) ⑥Route 审核(拒绝→退剩余)
|
|
// ⑦EmitSubmit(有存活号才投;0 号存活=全拦终态)。
|
|
// taskNo 幂等:请求带则用(uk 冲突→ISC:400),缺省生成 T+时间戳+随机。
|
|
func (s *SubmitService) Submit(ctx context.Context, req *SubmitReq, tpl *entity.TemplateSMS,
|
|
content string, clientIP string) (*SubmitResult, error) {
|
|
est, err := req.Validate(tpl)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 定时时刻(Validate 已保证 type3 非空;格式与 reschedule 同口径)。
|
|
var scheduleAt *time.Time
|
|
if req.SendType == SendTypeTimer {
|
|
at, perr := time.ParseInLocation("2006-01-02 15:04", req.SendAt, time.Local)
|
|
if perr != nil {
|
|
return nil, errors.InvalidParam.WithMsg("send_at 格式须为 YYYY-MM-DD HH:mm")
|
|
}
|
|
if !at.After(time.Now()) {
|
|
return nil, errors.InvalidParam.WithMsg("定时时刻须在未来")
|
|
}
|
|
scheduleAt = &at
|
|
}
|
|
// ②余额只读快检(快速失败体验;并发竞态由 ③原子预扣兜底精确拒绝)。
|
|
var acct entity.AccountUser
|
|
if err := s.db.WithContext(ctx).Select("id", "balance").
|
|
First(&acct, req.AccountID).Error; err != nil {
|
|
return nil, errors.NotFound.WithMsg("账号不存在")
|
|
}
|
|
if acct.Balance < int64(est.TotalFee) {
|
|
return nil, errors.Arrears.WithMsg(
|
|
fmt.Sprintf("余额不足:当前 %d 条,本次需 %d 条", acct.Balance, est.TotalFee))
|
|
}
|
|
// Day 49:video 须账号已开通(AccountConfig 业务行,openapi 鉴权同口径);
|
|
// 未开通拒绝发生在预扣前,无需退款对冲。
|
|
if req.Business == BusinessVideo {
|
|
var n int64
|
|
if err := s.db.WithContext(ctx).Model(&entity.AccountConfig{}).
|
|
Where("account_id = ? AND business = ?", req.AccountID, BusinessVideo).
|
|
Count(&n).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
if n == 0 {
|
|
return nil, errors.Forbidden.WithMsg("账号未开通视频短信业务")
|
|
}
|
|
}
|
|
// 幂等任务号。
|
|
taskNo := strings.TrimSpace(req.TaskNo)
|
|
if taskNo == "" {
|
|
taskNo = genTaskNo()
|
|
}
|
|
// ③原子预扣(WHERE balance>=fee;Day48 状态机起点——此后失败环节必有退款)。
|
|
if err := s.holdFee(ctx, req.AccountID, int64(est.TotalFee), taskNo); err != nil {
|
|
return nil, err
|
|
}
|
|
task := entity.MessageTask{
|
|
TaskNo: taskNo, AccountID: req.AccountID,
|
|
SendType: req.SendType, Content: content, Sign: req.Sign,
|
|
MobileCount: est.ValidCount, FeeTotal: float64(est.TotalFee),
|
|
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt, SubmitIP: clientIP,
|
|
CallData: util.Truncate(req.CallData, 64), // Day 46:回执回传数据(截断防溢出)
|
|
Business: req.Business, // Day 49:sms/video(Validate 已规范化)
|
|
Source: NormalizeTaskSource(req.Source), // Day 60:受理来源(WEB=4/CMPP=2/SMPP=3/API=1)
|
|
}
|
|
// ⑤拦截预判定(内存;落库时拦截号直接终态 5,存活号才进下发域)。
|
|
mobiles := validMobiles(req)
|
|
blocks := make([]*interceptor.Block, len(mobiles))
|
|
blockedFee, passCount := 0, 0
|
|
// Day51 R3:请求级快照——白名单/黑名单批量 IN+策略/签名跨号复用(100 号 400 查→≤3 查)。
|
|
sc := s.chain.NewScope(ctx, req.AccountID, mobiles)
|
|
for i, m := range mobiles {
|
|
if b := s.intercept(ctx, taskNo, req.AccountID, req.SendType, m, content, sc); b != nil {
|
|
blocks[i] = b
|
|
blockedFee += est.Segments
|
|
continue
|
|
}
|
|
passCount++
|
|
}
|
|
details := make([]entity.MessageDetail, 0, est.ValidCount)
|
|
for i, m := range mobiles {
|
|
d := entity.MessageDetail{
|
|
TaskID: 0, AccountID: req.AccountID,
|
|
Mobile: m, Content: content, Status: 0, Fee: float64(est.Segments),
|
|
ExtCode: util.Truncate(req.Extend, 32), // Day 46:扩展码透传
|
|
CallData: util.Truncate(req.CallData, 64),
|
|
Business: req.Business, Source: NormalizeTaskSource(req.Source), // Day66:明细单表化冗余
|
|
}
|
|
if blocks[i] != nil { // 拦截号:受理期即终态(ISC 码 16 字符截断)
|
|
d.Status = 5
|
|
d.ErrorCode = util.Truncate(blocks[i].Code, 16)
|
|
}
|
|
d.ID = s.sf.NextID() // 雪花主键(嵌入结构体,赋值式填入)
|
|
details = append(details, d)
|
|
}
|
|
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Create(&task).Error; err != nil {
|
|
msg := strings.ToUpper(err.Error())
|
|
if strings.Contains(msg, "DUPLICATE") || strings.Contains(msg, "1062") || // MySQL
|
|
strings.Contains(msg, "UNIQUE CONSTRAINT") { // SQLite
|
|
return errors.InvalidParam.WithMsg("任务号已存在: " + taskNo)
|
|
}
|
|
return err
|
|
}
|
|
return nil // Day52 R2:入口事务仅落 task(同步链路零明细写,方案 10.4.3)
|
|
})
|
|
if err != nil {
|
|
// ④落库失败:预扣全额对冲(状态机不变量——受理失败余额零损)。
|
|
_ = s.refund(ctx, req.AccountID, int64(est.TotalFee), taskNo, "落库失败退回")
|
|
return nil, err
|
|
}
|
|
for i := range details { // 事件/降级路径共用:TaskID 事务后回填(消费侧落库亦用)
|
|
details[i].TaskID = task.ID
|
|
}
|
|
// ⑤拦截号费用即时退(预扣按全额,被拦号未消费;RefundTask 幂等由一次性调用保证)。
|
|
if blockedFee > 0 {
|
|
_ = s.refund(ctx, req.AccountID, int64(blockedFee), taskNo, "拦截号码退费")
|
|
}
|
|
// Day52 R2:明细随 sms-submit 投递(全拦/定时亦投——拦截记录与定时明细同为对账事实源;
|
|
// 消费侧 claim 不认领全拦终态 2/待审 audit=0/定时域 send_type=3,仅落明细即返回)。
|
|
s.emitOrFallback(ctx, &task, details)
|
|
// 全拦:任务直接终态(事件已投,拦截明细由消费侧落库;计数=fail)。
|
|
if passCount == 0 {
|
|
_ = s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
|
Where("id = ? AND status = ?", task.ID, 0).
|
|
Updates(map[string]any{
|
|
"status": taskStDone, "fail_count": len(mobiles), "finished_at": time.Now(),
|
|
}).Error
|
|
task.Status = taskStDone
|
|
task.FailCount = len(mobiles)
|
|
return &SubmitResult{Task: &task, Estimate: est}, nil
|
|
}
|
|
// 审核分流(事务外;三模式落定。失败不回滚受理——任务停留待审,48h Scanner 兜底)。
|
|
var rec *entity.AuditRecord
|
|
if s.rt != nil {
|
|
t2, r2, rerr := s.rt.Route(ctx, task.ID)
|
|
if rerr != nil {
|
|
return nil, fmt.Errorf("任务已受理(任务号 %s)但审核分流失败: %w", taskNo, rerr)
|
|
}
|
|
task, rec = *t2, r2
|
|
// ⑥审核拒绝:存活号费用全退(拦截费 ⑤ 已退;幂等由 Route 原子翻转保证只进一次)。
|
|
if task.AuditStatus == 2 {
|
|
_ = s.refund(ctx, req.AccountID,
|
|
int64(est.TotalFee)-int64(blockedFee), taskNo, "审核拒绝退费")
|
|
}
|
|
}
|
|
return &SubmitResult{Task: &task, Record: rec, Estimate: est}, nil
|
|
}
|
|
|
|
// NextMsgID 预生成雪花 MsgID(入向长短信聚合组ID;与 DetailID 同源空间,
|
|
// 供接入层首片分配、N 片 Resp 复用、合并受理时注入为首条 DetailID)。
|
|
func (s *SubmitService) NextMsgID() int64 { return s.sf.NextID() }
|
|
|
|
// FastResult 快路径受理结果(P0-1)。
|
|
type FastResult struct {
|
|
MsgID int64 // =首条 DetailID 雪花(CMPP Submit_Resp 与 Deliver msg_id 同口径)
|
|
TaskNo string // 幂等任务号(对账/退费键)
|
|
}
|
|
|
|
// SubmitFast P0-1(Day 63)接入快路径:CMPP 高并发压测 80 并发封顶 ~45/s
|
|
// (fsync 调优后),根因=同步链 5-8 次 DB 往返。快路径只做四件事:
|
|
// ①Validate(内存) ②holdFee 原子预扣(Redis Lua ~1ms;欠费快速失败+防透支)
|
|
// ③DetailID 雪花预生成 ④EmitSubmit(Deferred 事件,task.ID=0);
|
|
// 拦截判定/任务落库/退费/审核分流全部移消费侧 handleDeferred 补全——
|
|
// 平台=中间削峰缓存,受理速率与下发速率解耦(上下游流速不对齐是常态)。
|
|
// 零 DB 读写;sink 未装配或投递失败→全额退费+返回错误(客户端重试,不丢)。
|
|
func (s *SubmitService) SubmitFast(ctx context.Context, req *SubmitReq,
|
|
content string, clientIP string) (*FastResult, error) {
|
|
est, err := req.Validate(nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 定时校验(与 Submit 同口径;CMPP 无定时,HTTP 走老路径,防御性保留)。
|
|
var scheduleAt *time.Time
|
|
if req.SendType == SendTypeTimer {
|
|
at, perr := time.ParseInLocation("2006-01-02 15:04", req.SendAt, time.Local)
|
|
if perr != nil {
|
|
return nil, errors.InvalidParam.WithMsg("send_at 格式须为 YYYY-MM-DD HH:mm")
|
|
}
|
|
if !at.After(time.Now()) {
|
|
return nil, errors.InvalidParam.WithMsg("定时时刻须在未来")
|
|
}
|
|
scheduleAt = &at
|
|
}
|
|
taskNo := strings.TrimSpace(req.TaskNo)
|
|
if taskNo == "" {
|
|
taskNo = genTaskNo()
|
|
}
|
|
// 原子预扣(Redis 优先;不足→ISC:007 同步拒绝——欠费是受理侧唯一同步拒绝语义)。
|
|
tHold := time.Now()
|
|
holdErr := s.holdFee(ctx, req.AccountID, int64(est.TotalFee), taskNo)
|
|
holdCost := time.Since(tHold)
|
|
if holdErr != nil {
|
|
return nil, holdErr
|
|
}
|
|
task := entity.MessageTask{ // ID=0:自增主键由消费侧 handleDeferred 生成。
|
|
TaskNo: taskNo, AccountID: req.AccountID,
|
|
SendType: req.SendType, Content: content, Sign: req.Sign,
|
|
MobileCount: est.ValidCount, FeeTotal: float64(est.TotalFee),
|
|
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt, SubmitIP: clientIP,
|
|
CallData: util.Truncate(req.CallData, 64),
|
|
Business: req.Business, Source: NormalizeTaskSource(req.Source),
|
|
}
|
|
mobiles := validMobiles(req)
|
|
details := make([]entity.MessageDetail, 0, len(mobiles))
|
|
for i, m := range mobiles {
|
|
d := entity.MessageDetail{
|
|
AccountID: req.AccountID, Mobile: m, Content: content,
|
|
Status: 0, Fee: float64(est.Segments), // 未拦截判定:消费侧 Check 后终态化
|
|
ExtCode: util.Truncate(req.Extend, 32), CallData: util.Truncate(req.CallData, 64),
|
|
Business: req.Business, Source: NormalizeTaskSource(req.Source), // Day66:明细单表化冗余
|
|
}
|
|
d.ID = s.sf.NextID()
|
|
if i == 0 && req.PresetMsgID != 0 { // 长短信聚合组ID 注入:Resp/Deliver/明细三口径同 ID
|
|
d.ID = req.PresetMsgID
|
|
}
|
|
details = append(details, d)
|
|
}
|
|
if len(details) == 0 { // 合格号为 0:预扣按 0 条(Validate 已拒空号列表,防御)。
|
|
return &FastResult{MsgID: 0, TaskNo: taskNo}, nil
|
|
}
|
|
// 投递(Deferred 事件);快路径无 DB 降级路径——失败退全款+拒绝(客户端重试)。
|
|
tEmit := time.Now()
|
|
var emitErr error
|
|
if s.sink == nil {
|
|
emitErr = errors.InternalError.WithMsg("事件出口未装配")
|
|
} else {
|
|
emitErr = s.sink.EmitSubmit(ctx, &task, details)
|
|
}
|
|
if emitCost := time.Since(tEmit); emitCost > 80*time.Millisecond {
|
|
WarnSubmitFastSlow(emitCost, holdCost) // P0-1 诊断(临时)
|
|
}
|
|
if emitErr != nil {
|
|
_ = s.refund(ctx, req.AccountID, int64(est.TotalFee), taskNo, "快路径投递失败退回")
|
|
return nil, emitErr
|
|
}
|
|
return &FastResult{MsgID: details[0].ID, TaskNo: taskNo}, nil
|
|
}
|
|
|
|
// emitOrFallback 投递明细事件(Day52 R2);sink 未装配或投递失败降级同步落明细
|
|
// (明细=对账事实源,零丢失红线;任务下发由 ReclaimScanner/Timer 扫描兜底认领)。
|
|
func (s *SubmitService) emitOrFallback(ctx context.Context, task *entity.MessageTask,
|
|
details []entity.MessageDetail) {
|
|
if len(details) == 0 {
|
|
return
|
|
}
|
|
if s.sink != nil {
|
|
if err := s.sink.EmitSubmit(ctx, task, details); err == nil {
|
|
return
|
|
}
|
|
// Kafka 故障窗口:降级回同步落库旧路径(性能让位于正确性)。
|
|
}
|
|
_ = s.db.WithContext(ctx).CreateInBatches(details, 500).Error
|
|
}
|
|
|
|
// validMobiles 归一去重后的合格号码(与 Validate 同规则,供明细落库)。
|
|
func validMobiles(r *SubmitReq) []string {
|
|
seen := make(map[string]struct{}, len(r.Mobiles))
|
|
out := make([]string, 0, len(r.Mobiles))
|
|
for _, m := range r.Mobiles {
|
|
n := util.NormalizeMobile(m)
|
|
if !util.IsValidMainlandMobile(n) {
|
|
continue
|
|
}
|
|
if _, dup := seen[n]; !dup {
|
|
seen[n] = struct{}{}
|
|
out = append(out, n)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// genTaskNo 生成任务号 T+yyyyMMddHHmmss+6 位随机(≤32 字符)。
|
|
// Day50 压测修复:4 位随机在 ~17 req/s 下 5min 即碰撞 3 次(实测);
|
|
// 50 req/s(5000TPS 批量)时扩至 6 位,碰撞由任务号唯一索引+code:5 幂等兜底。
|
|
func genTaskNo() string {
|
|
n, _ := rand.Int(rand.Reader, big.NewInt(1000000))
|
|
return fmt.Sprintf("T%s%06d", time.Now().Format("20060102150405"), n.Int64())
|
|
}
|
|
|
|
// PersonalItem 个性短信条目(逐号独立内容;Day 46 sendMessageOne)。
|
|
type PersonalItem struct {
|
|
Mobile string
|
|
Content string
|
|
}
|
|
|
|
// MaxPersonalItems 单次个性短信条目上限(协议文档 sendMessageOne 上限 1000)。
|
|
const MaxPersonalItems = 1000
|
|
|
|
// SubmitPersonal 个性短信受理(Day 46 外部 API sendMessageOne):
|
|
// 单 task(SendType=2)+逐 detail 独立内容;费用=逐条 segments 累计;
|
|
// 余额校验/事务落库/审核分流与 Submit 同口径。号码去重取首条内容。
|
|
// source Day 60:受理来源打标(0→API 归一)。
|
|
func (s *SubmitService) SubmitPersonal(ctx context.Context, accountID int64,
|
|
items []PersonalItem, scheduleAt *time.Time, extend, callData, clientIP string,
|
|
source int8) (*SubmitResult, error) {
|
|
if len(items) == 0 {
|
|
return nil, errors.InvalidParam.WithMsg("个性短信条目为空")
|
|
}
|
|
if len(items) > MaxPersonalItems {
|
|
return nil, errors.InvalidParam.WithMsg(fmt.Sprintf("条目 %d 超单次上限 %d", len(items), MaxPersonalItems))
|
|
}
|
|
seen := make(map[string]struct{}, len(items))
|
|
merged := make([]PersonalItem, 0, len(items))
|
|
totalFee := 0
|
|
for _, it := range items {
|
|
n := util.NormalizeMobile(it.Mobile)
|
|
if !util.IsValidMainlandMobile(n) {
|
|
return nil, errors.InvalidParam.WithMsg("非法手机号: " + it.Mobile)
|
|
}
|
|
if it.Content == "" {
|
|
return nil, errors.InvalidParam.WithMsg("内容为空: " + n)
|
|
}
|
|
if rc := len([]rune(it.Content)); rc > MaxTextLen {
|
|
return nil, errors.InvalidParam.WithMsg(fmt.Sprintf("内容 %d 字超上限 %d: %s", rc, MaxTextLen, n))
|
|
}
|
|
if _, dup := seen[n]; dup {
|
|
continue
|
|
}
|
|
seen[n] = struct{}{}
|
|
_, seg := util.SmsLength(it.Content)
|
|
if seg == 0 {
|
|
seg = 1
|
|
}
|
|
totalFee += seg
|
|
merged = append(merged, PersonalItem{Mobile: n, Content: it.Content})
|
|
}
|
|
if len(merged) == 0 {
|
|
return nil, errors.InvalidParam.WithMsg("无有效条目")
|
|
}
|
|
// 余额只读快检 + 原子预扣(Day48 与 Submit 同口径)。
|
|
var acct entity.AccountUser
|
|
if err := s.db.WithContext(ctx).Select("id", "balance").
|
|
First(&acct, accountID).Error; err != nil {
|
|
return nil, errors.NotFound.WithMsg("账号不存在")
|
|
}
|
|
if acct.Balance < int64(totalFee) {
|
|
return nil, errors.Arrears.WithMsg(
|
|
fmt.Sprintf("余额不足:当前 %d 条,本次需 %d 条", acct.Balance, totalFee))
|
|
}
|
|
taskNo := genTaskNo()
|
|
if err := s.holdFee(ctx, accountID, int64(totalFee), taskNo); err != nil {
|
|
return nil, err
|
|
}
|
|
task := entity.MessageTask{
|
|
TaskNo: taskNo, AccountID: accountID,
|
|
SendType: SendTypePersonal, Content: merged[0].Content,
|
|
MobileCount: len(merged), FeeTotal: float64(totalFee),
|
|
AuditStatus: 0, Status: 0, ScheduleAt: scheduleAt, SubmitIP: clientIP,
|
|
CallData: util.Truncate(callData, 64),
|
|
Source: NormalizeTaskSource(source), // Day 60:受理来源
|
|
}
|
|
// 逐号拦截(独立内容;命中号受理期终态 5+计费退)。
|
|
// Day51 R3:请求级快照同 Submit(个性批量同受益)。
|
|
blocks := make([]*interceptor.Block, len(merged))
|
|
blockedFee, passCount := 0, 0
|
|
pm := make([]string, len(merged))
|
|
for i, it := range merged {
|
|
pm[i] = it.Mobile
|
|
}
|
|
sc := s.chain.NewScope(ctx, accountID, pm)
|
|
for i, it := range merged {
|
|
if b := s.intercept(ctx, taskNo, accountID, SendTypePersonal, it.Mobile, it.Content, sc); b != nil {
|
|
blocks[i] = b
|
|
if _, seg := util.SmsLength(it.Content); seg > 0 {
|
|
blockedFee += seg
|
|
} else {
|
|
blockedFee++
|
|
}
|
|
continue
|
|
}
|
|
passCount++
|
|
}
|
|
details := make([]entity.MessageDetail, 0, len(merged))
|
|
for i, it := range merged {
|
|
_, seg := util.SmsLength(it.Content)
|
|
if seg == 0 {
|
|
seg = 1
|
|
}
|
|
d := entity.MessageDetail{
|
|
AccountID: accountID, Mobile: it.Mobile, Content: it.Content,
|
|
Status: 0, Fee: float64(seg),
|
|
ExtCode: util.Truncate(extend, 32),
|
|
CallData: util.Truncate(callData, 64),
|
|
Business: task.Business, Source: task.Source, // Day66:明细单表化冗余(个性发 task 已 Normalize)
|
|
}
|
|
if blocks[i] != nil {
|
|
d.Status = 5
|
|
d.ErrorCode = util.Truncate(blocks[i].Code, 16)
|
|
}
|
|
d.ID = s.sf.NextID()
|
|
details = append(details, d)
|
|
}
|
|
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Create(&task).Error; err != nil {
|
|
return err
|
|
}
|
|
return nil // Day52 R2:入口事务仅落 task(明细移消费侧批量落库)
|
|
})
|
|
if err != nil {
|
|
_ = s.refund(ctx, accountID, int64(totalFee), taskNo, "落库失败退回")
|
|
return nil, err
|
|
}
|
|
for i := range details { // Day52 R2:事件/降级路径共用 TaskID 回填
|
|
details[i].TaskID = task.ID
|
|
}
|
|
if blockedFee > 0 {
|
|
_ = s.refund(ctx, accountID, int64(blockedFee), taskNo, "拦截号码退费")
|
|
}
|
|
// Day52 R2:明细随事件投递(全拦/定时亦投;消费侧 claim 域外仅落明细)。
|
|
s.emitOrFallback(ctx, &task, details)
|
|
if passCount == 0 {
|
|
_ = s.db.WithContext(ctx).Model(&entity.MessageTask{}).
|
|
Where("id = ? AND status = ?", task.ID, 0).
|
|
Updates(map[string]any{
|
|
"status": taskStDone, "fail_count": len(merged), "finished_at": time.Now(),
|
|
}).Error
|
|
task.Status = taskStDone
|
|
task.FailCount = len(merged)
|
|
return &SubmitResult{Task: &task}, nil
|
|
}
|
|
var rec *entity.AuditRecord
|
|
if s.rt != nil {
|
|
t2, r2, rerr := s.rt.Route(ctx, task.ID)
|
|
if rerr != nil {
|
|
return nil, fmt.Errorf("任务已受理(任务号 %s)但审核分流失败: %w", taskNo, rerr)
|
|
}
|
|
task, rec = *t2, r2
|
|
if task.AuditStatus == 2 { // 审核拒绝:存活号费用退(拦截费已退)
|
|
_ = s.refund(ctx, accountID,
|
|
int64(totalFee)-int64(blockedFee), taskNo, "审核拒绝退费")
|
|
}
|
|
}
|
|
est := &Estimate{ValidCount: len(merged), TotalFee: totalFee}
|
|
return &SubmitResult{Task: &task, Record: rec, Estimate: est}, nil
|
|
}
|