// recharge.go S2-D3:充值订单审核流(R3 双通道裁决——即时充值 /accounts/:id/recharge // 保留为"已线下确认的快捷入账",本文件承载需付款审核确认的订单流)。 // // 状态机:pay_status 0待确认 → 1已到账(confirm)/2失败(reject);confirm 单事务 // 四步=①状态 CAS(WHERE pay_status=0,RowsAffected=0 → ISC:039,并发/重复天然 // 只过一次)→②余额原子自增 count→③同事务回读→④流水(ref_id=order_no—— // 双通道天然区分:即时充值流水 ref_id 为空,D5 对账口径现成)。 // 单位口径(R6):Count=条(入账,与 balance 一致);Amount=元(记账展示,不参与余额)。 package settle import ( "context" "errors" "fmt" "math/rand" "strings" "time" "gorm.io/gorm" "go-sms/internal/model/entity" errs "go-sms/internal/pkg/errors" ) // orderNoRetry OrderNo uk 冲突重试次数(时间戳+4 位随机,碰撞概率极低)。 const orderNoRetry = 1 // maxRechargeCount 到账条数上限(与 account.MaxRechargeAmount 同值,不跨包依赖)。 const maxRechargeCount int64 = 10_000_000_000 // isDuplicateKey 唯一键冲突判定(MySQL 1062/DUPLICATE 与 SQLite 2067 // 兼容;统一大写,同 send/consume.isDupTaskNo 口径)。 func isDuplicateKey(err error) bool { msg := strings.ToUpper(err.Error()) return strings.Contains(msg, "DUPLICATE") || strings.Contains(msg, "1062") || strings.Contains(msg, "UNIQUE CONSTRAINT") } // wrapNotFound gorm record-not-found → 业务 404(其余原样透传)。 func wrapNotFound(err error, orderID int64) error { if errors.Is(err, gorm.ErrRecordNotFound) { return errs.NotFound.WithMsg(fmt.Sprintf("订单 %d 不存在", orderID)) } return err } // NewOrderNo 订单号:B+yyyyMMddHHmmss+4 位随机(照 TaskNo=T+时间戳 可读风格)。 func NewOrderNo() string { return fmt.Sprintf("B%s%04d", time.Now().Format("20060102150405"), rand.Intn(10000)) } // CreateOrderRequest 创建充值订单(POST /billing/orders;不动余额)。 type CreateOrderRequest struct { AccountID int64 Count int64 // 到账条数(必填>0,上限同即时充值) Amount float64 // 金额(元,可选,仅记账展示) PayType string Operator string Remark string } // CreateOrder 创建待确认订单(pay_status=0);余额零改动——到账只发生在 confirm。 func (s *Service) CreateOrder(ctx context.Context, req *CreateOrderRequest) (*entity.BillingOrder, error) { if req.AccountID <= 0 { return nil, errs.InvalidParam.WithMsg("账号 ID 非法") } if req.Count <= 0 || req.Count > maxRechargeCount { return nil, errs.InvalidParam.WithMsg( fmt.Sprintf("到账条数 %d 非法(须为 1~%d 的正整数)", req.Count, maxRechargeCount)) } var n int64 if err := s.db.WithContext(ctx).Model(&entity.AccountUser{}). Where("id = ?", req.AccountID).Count(&n).Error; err != nil { return nil, err } if n == 0 { return nil, errs.NotFound.WithMsg(fmt.Sprintf("账号 %d 不存在", req.AccountID)) } order := &entity.BillingOrder{ OrderNo: NewOrderNo(), AccountID: req.AccountID, Count: req.Count, Amount: req.Amount, PayType: req.PayType, PayStatus: 0, Operator: req.Operator, Remark: req.Remark, } // uk 冲突兜底重试一次(同秒同随机碰撞,概率趋零)。 if err := s.db.WithContext(ctx).Create(order).Error; err != nil { if !isDuplicateKey(err) || orderNoRetry == 0 { return nil, err } order.OrderNo = NewOrderNo() if err := s.db.WithContext(ctx).Create(order).Error; err != nil { return nil, err } } return order, nil } // ConfirmResult confirm 返回(新余额与流水号)。 type ConfirmResult struct { Order *entity.BillingOrder Balance int64 BalanceLogID int64 } // ConfirmOrder 付款审核确认(0→1):单事务=状态 CAS→余额自增 count→回读→流水。 func (s *Service) ConfirmOrder(ctx context.Context, orderID int64, operator string) (*ConfirmResult, error) { var ( order entity.BillingOrder balance int64 balanceLog entity.AccountBalanceLog ) err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { // ① 状态 CAS:非 0 即冲突(并发/重复/已驳回),余额零副作用。 res := tx.Model(&entity.BillingOrder{}). Where("id = ? AND pay_status = 0", orderID). Updates(map[string]any{ "pay_status": 1, "operator": operator, "paid_at": time.Now(), }) if res.Error != nil { return res.Error } if res.RowsAffected == 0 { if err := tx.First(&order, orderID).Error; err != nil { return wrapNotFound(err, orderID) } return errs.OrderStatusConflict.WithMsg( fmt.Sprintf("订单 %d 状态非待确认(当前 %d)", orderID, order.PayStatus)) } if err := tx.First(&order, orderID).Error; err != nil { return err } // ② 余额原子自增(数据库层并发安全)+ ③ 同事务回读。 if err := tx.Model(&entity.AccountUser{}).Where("id = ?", order.AccountID). Update("balance", gorm.Expr("balance + ?", order.Count)).Error; err != nil { return err } if err := tx.Model(&entity.AccountUser{}).Where("id = ?", order.AccountID). Pluck("balance", &balance).Error; err != nil { return err } // ④ 流水:ref_id=order_no(双通道区分锚点;biz_type 同 recharge)。 balanceLog = entity.AccountBalanceLog{ AccountID: order.AccountID, BizType: "recharge", Amount: order.Count, BalanceAfter: balance, RefID: order.OrderNo, Operator: operator, Remark: "充值订单确认 " + order.OrderNo, } return tx.Create(&balanceLog).Error }) if err != nil { return nil, err } return &ConfirmResult{Order: &order, Balance: balance, BalanceLogID: balanceLog.ID}, nil } // RejectOrder 驳回(0→2):状态 CAS,不涉余额;remark 可选留痕。 func (s *Service) RejectOrder(ctx context.Context, orderID int64, operator, remark string) (*entity.BillingOrder, error) { res := s.db.WithContext(ctx).Model(&entity.BillingOrder{}). Where("id = ? AND pay_status = 0", orderID). Updates(map[string]any{"pay_status": 2, "operator": operator}) if res.Error != nil { return nil, res.Error } if res.RowsAffected == 0 { var order entity.BillingOrder if err := s.db.WithContext(ctx).First(&order, orderID).Error; err != nil { return nil, wrapNotFound(err, orderID) } return nil, errs.OrderStatusConflict.WithMsg( fmt.Sprintf("订单 %d 状态非待确认(当前 %d)", orderID, order.PayStatus)) } if remark != "" { if err := s.db.WithContext(ctx).Model(&entity.BillingOrder{}). Where("id = ?", orderID).Update("remark", remark).Error; err != nil { return nil, err } } var order entity.BillingOrder if err := s.db.WithContext(ctx).First(&order, orderID).Error; err != nil { return nil, err } return &order, nil } // OrderQuery 订单列表查询条件。 type OrderQuery struct { AccountID int64 PayStatus *int8 // nil=全部 Page int PageSize int } // ListOrders 订单分页(id 倒序,新单在前)。 func (s *Service) ListOrders(ctx context.Context, q OrderQuery) ([]entity.BillingOrder, int64, error) { db := s.db.WithContext(ctx).Model(&entity.BillingOrder{}) if q.AccountID > 0 { db = db.Where("account_id = ?", q.AccountID) } if q.PayStatus != nil { db = db.Where("pay_status = ?", *q.PayStatus) } var total int64 if err := db.Count(&total).Error; err != nil { return nil, 0, err } if q.Page <= 0 { q.Page = 1 } if q.PageSize <= 0 || q.PageSize > 100 { q.PageSize = 20 } var list []entity.BillingOrder err := db.Order("id DESC"). Limit(q.PageSize).Offset((q.Page - 1) * q.PageSize). Find(&list).Error return list, total, err }