S2-D3 充值审核流(R3 双通道落地): settle/recharge.go——CreateOrder(pay_status=0 不动余额;OrderNo=B+时间戳+4 随机 uk 重试)/ConfirmOrder 单事务四步(状态 CAS WHERE pay_status=0→ISC:039/余额原子自增 count/同事务回读/流水 ref_id=order_no=双通道区分锚点)/RejectOrder(0→2 不涉余额)/ListOrders;ISC:039 订单状态冲突三处同步(codes.go+registry+x-isc-dict+dict.ts 52 码,openapi_sync/codes_test 断言随更);四端点(列表平台角色门+创建/confirm/reject 挂 account:recharge 二级权限,审计自动留痕 module=billing);测试 7 件含并发 confirm 恰一成功(-race);真机全链冒烟(HS256 临时 token 非侵入):创建零动余额→confirm 余额+123→重复 409 ISC:039+流水 ref_id/审计留痕两设计实证+数据还原;门禁 vet/-race 39 包/lint 0;验收单 s2-d3.md+CHANGELOG+memory-bank 回填
This commit is contained in:
@@ -2,6 +2,14 @@
|
||||
|
||||
> 本仓 CHANGELOG 自重建起记(POC 明细见归档仓 /data/poc-archive/repos/go-sms.git 的 CHANGELOG.md,已冻结)。
|
||||
|
||||
## 2026-11-14(夜)· S2-D3 充值审核流(R3 双通道落地)
|
||||
|
||||
- **settle/recharge.go**:CreateOrder(pay_status=0 不动余额;OrderNo=B+时间戳+4 随机,uk 重试)/ConfirmOrder(**单事务=状态 CAS(WHERE pay_status=0→ISC:039)→余额原子自增 count→同事务回读→流水 ref_id=order_no**——双通道天然区分:即时充值流水 ref_id 空)/RejectOrder(0→2 不涉余额)/ListOrders。
|
||||
- **ISC:039 订单状态冲突(409)** 新增,三处同步(codes.go+registry+x-isc-dict+dict.ts 52 码;openapi_sync_test/codes_test 断言随更)。
|
||||
- **四端点**:列表(平台角色,group/customer 403)+创建/confirm/reject(account:recharge 二级权限同即时充值);审计自动留痕 module=billing。
|
||||
- **测试 7 件**:创建校验/confirm 事务语义/状态机(409 且余额二次不变)/**并发 confirm 恰一成功(-race)**/驳回/列表/handler 全流程+双 403。
|
||||
- **真机全链冒烟**(HS256 临时 token+dev secret 非侵入):创建零动余额→confirm 余额 0→123→重复 409 ISC:039;真库核验流水 ref_id 关联+审计留痕两设计实证;清理还原(审计行保留为证据)。门禁:vet/**-race 39 包**/lint 0。验收单 `docs/acceptance/s2-d3.md`。
|
||||
|
||||
## 2026-11-14(傍晚)· S2-D2 消耗日汇总引擎(settle 域首批业务代码)
|
||||
|
||||
- **settle/consume.go**:AggregateDay 账号×业务→billing_consume_log、通道→stats_channel_daily(GROUP BY+SUM(status=N)+[lo,hi) 半开窗双方言、OnConflict 复合 uk UPSERT、cost_total 不写守 R1)+ListConsume(时间窗按天归一修复:零点行不被带时刻参数误滤)。
|
||||
|
||||
+3
-2
@@ -787,13 +787,13 @@ paths:
|
||||
tags: [billing]
|
||||
summary: 付款审核确认(0→1;事务=状态 CAS+余额原子自增 count+流水 ref_id=order_no;并发/重复确认被 CAS 拒)
|
||||
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
|
||||
responses: {"200": {description: 新余额}, "409": {description: 状态非 0(已确认/已驳回)}}
|
||||
responses: {"200": {description: 新余额}, "409": {description: "状态非 0(ISC:039)"}}
|
||||
/billing/orders/{id}/reject:
|
||||
post:
|
||||
tags: [billing]
|
||||
summary: 驳回(0→2;不涉余额)
|
||||
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
|
||||
responses: {"200": {description: ok}, "409": {description: 状态非 0}}
|
||||
responses: {"200": {description: ok}, "409": {description: "状态非 0(ISC:039)"}}
|
||||
/billing/consume:
|
||||
get:
|
||||
tags: [billing]
|
||||
@@ -1044,6 +1044,7 @@ x-isc-dict:
|
||||
ISC:036: 地区屏蔽
|
||||
ISC:037: 审核状态冲突(非待审)
|
||||
ISC:038: 任务状态冲突(不可取消/改期)
|
||||
ISC:039: 订单状态冲突(非待确认)
|
||||
ISC:040: 夜间频控
|
||||
ISC:043: 5G消息拦截
|
||||
ISC:400: 参数错误
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# S2-D3 充值审核流 人工验收单(2026-11-14)
|
||||
|
||||
> 前置:s2-d2.md(消耗日汇总)。本单覆盖 D3:BillingOrder 订单审核族(R3 双通道裁决落地)。
|
||||
|
||||
## 一、交付物
|
||||
|
||||
| # | 任务 | 结果 | 证据 |
|
||||
|---|---|---|---|
|
||||
| 1 | **settle/recharge.go** | ✅ | CreateOrder(count 1~100 亿校验/账号存在性/pay_status=0 **不动余额**;OrderNo=B+时间戳+4 位随机,uk 冲突重试一次)/ConfirmOrder(**单事务四步**:状态 CAS(WHERE pay_status=0,RowsAffected=0→ISC:039)→余额原子自增 count→同事务回读→流水 ref_id=order_no)/RejectOrder(0→2 CAS 不涉余额,remark 留痕)/ListOrders(过滤分页 id 倒序) |
|
||||
| 2 | **错误码 ISC:039** | ✅ | 「订单状态冲突(非待确认)」HTTP 409;**三处同步**:codes.go+registry 手工清单+x-isc-dict+dict.ts 再生成(52 码);openapi_sync_test 双向锁绿 |
|
||||
| 3 | **四端点** | ✅ | GET /billing/orders(平台角色 admin/ops/service;group/customer 403)+POST /billing/orders、/:id/confirm、/:id/reject(挂 account:recharge 二级权限,与即时充值同门);审计自动留痕(module=billing action=orders:post/confirm:post) |
|
||||
| 4 | **测试 7 件** | ✅ | service:创建校验(0/负/超限/账号不存在/OrderNo 唯一批量 21 单)/confirm 事务语义(paid_at+operator+流水四字段+balance_after 一致)/状态机(重复 confirm 409 且余额二次不变;已确认 reject 409;不存在 404)/**并发 confirm 恰一成功**(-race)/驳回/列表;handler:全流程(创建→列表→confirm→409 ISC:039)/权限(恒拒 checker 403+customer 列表 403) |
|
||||
|
||||
## 二、门禁(七件套后端件)
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| go vet ./... | ✅ RC=0 |
|
||||
| go test -race ./...(全量) | ✅ **39 包 ok 零 FAIL** |
|
||||
| golangci-lint v2.1.6 | ✅ 0 issues |
|
||||
| openapi_sync_test + codes_test 数量断言 | ✅ 52 码同步(测试断言随更) |
|
||||
|
||||
## 三、真机验证(dev,2026-11-14 20:50)
|
||||
|
||||
1. **重驻**:gw-stop→gw-start,/health ok+md5 一致(6376ba52…);
|
||||
2. **JWT 临时签发**:HS256+dev secret(config loader 默认值,非侵入不触库),casbin g(1,admin) 通过 recharge 二级权限;
|
||||
3. **全链冒烟**:创建(count=123/amount=12.3,pay_status=0,OrderNo=B202611142050471417,**余额零动**)→confirm(**余额 0→123**+流水 id=1)→重复 confirm **HTTP 409+ISC:039**;
|
||||
4. **真库核验**:account_balance_log(biz_type=recharge/amount=123/balance_after=123/**ref_id=order_no**/operator=admin)+ system_operate_log 自动留痕(module=billing action=orders:post/confirm:post)——**双通道区分锚点(ref_id)与审计适配两项设计实证**;
|
||||
5. **清理还原**:余额归零/订单+流水删除(审计行保留=冒烟证据,日志性质 append-only);临时 token 清除。
|
||||
|
||||
## 四、口径留痕
|
||||
|
||||
- **双通道语义**(R3):即时充值=已线下确认快捷入账(流水 ref_id 空);订单流=付款审核确认(流水 ref_id=order_no)——D5 对账以 ref_id 有无区分两通道;
|
||||
- 并发安全:MySQL 行锁路径(与 account.Recharge 同代码形态,POC 期已真库验证)+ sqlite 单连接串行 CAS 语义等价(单测覆盖);
|
||||
- OrderNo 可读风格与 TaskNo(T 前缀)对齐,B 前缀=billing 域。
|
||||
|
||||
## 五、验收结论
|
||||
|
||||
**S2-D3 通过。** D4(出账引擎+阶梯)开工前置=本单归档+回填+提交。
|
||||
@@ -30,6 +30,16 @@ func registerSettleRoutes(protected *gin.RouterGroup, deps Deps) {
|
||||
// 手动触发回补(运维口径;settle:write)。
|
||||
protected.POST("/ops/settle/aggregate",
|
||||
middleware.RequirePermission(deps.Perm, "settle", "write"), h.aggregate)
|
||||
// S2-D3:充值订单审核族(R3 双通道——即时充值保留,订单流承载付款审核确认;
|
||||
// 创建/确认/驳回挂 account:recharge 二级权限与即时充值同门;列表=平台角色
|
||||
// admin/ops/service(group/customer 403——订单含全平台资金信息不放大)。
|
||||
protected.GET("/billing/orders", h.ordersList)
|
||||
protected.POST("/billing/orders",
|
||||
middleware.RequirePermission(deps.Perm, "account", middleware.PermRecharge), h.orderCreate)
|
||||
protected.POST("/billing/orders/:id/confirm",
|
||||
middleware.RequirePermission(deps.Perm, "account", middleware.PermRecharge), h.orderConfirm)
|
||||
protected.POST("/billing/orders/:id/reject",
|
||||
middleware.RequirePermission(deps.Perm, "account", middleware.PermRecharge), h.orderReject)
|
||||
}
|
||||
|
||||
// StartSettleAggregateJob v1 层装配入口(照 StartStatsRefresher 模式,仅
|
||||
@@ -112,3 +122,112 @@ func (h *settleHandler) aggregate(c *gin.Context) {
|
||||
"channel_rows": channelRows,
|
||||
})
|
||||
}
|
||||
|
||||
// ordersList GET /billing/orders:订单分页(account_id/pay_status 过滤;平台角色)。
|
||||
func (h *settleHandler) ordersList(c *gin.Context) {
|
||||
if !statsIsPlatform(c) {
|
||||
response.Error(c, errs.Forbidden.WithMsg("仅平台角色可查看充值订单"))
|
||||
return
|
||||
}
|
||||
q := settle.OrderQuery{Page: 1, PageSize: 20}
|
||||
if v, err := strconv.ParseInt(c.Query("account_id"), 10, 64); err == nil && v > 0 {
|
||||
q.AccountID = v
|
||||
}
|
||||
if s := c.Query("pay_status"); s != "" {
|
||||
v, err := strconv.Atoi(s)
|
||||
if err != nil || v < 0 || v > 2 {
|
||||
response.Error(c, errs.InvalidParam.WithMsg("pay_status 须为 0/1/2"))
|
||||
return
|
||||
}
|
||||
ps := int8(v)
|
||||
q.PayStatus = &ps
|
||||
}
|
||||
if v, err := strconv.Atoi(c.Query("page")); err == nil && v > 0 {
|
||||
q.Page = v
|
||||
}
|
||||
if v, err := strconv.Atoi(c.Query("page_size")); err == nil && v > 0 {
|
||||
q.PageSize = v
|
||||
}
|
||||
list, total, err := h.svc.ListOrders(c.Request.Context(), q)
|
||||
if err != nil {
|
||||
bizResp(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"total": total, "list": list})
|
||||
}
|
||||
|
||||
// orderCreate POST /billing/orders:创建待确认订单(不动余额;到账只发生在 confirm)。
|
||||
func (h *settleHandler) orderCreate(c *gin.Context) {
|
||||
var req struct {
|
||||
AccountID int64 `json:"account_id" binding:"required"`
|
||||
Count int64 `json:"count" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
PayType string `json:"pay_type"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, errs.InvalidParam.WithMsg("account_id/count 必填"))
|
||||
return
|
||||
}
|
||||
claims := statsClaims(c)
|
||||
operator := ""
|
||||
if claims != nil {
|
||||
operator = claims.Username
|
||||
}
|
||||
order, err := h.svc.CreateOrder(c.Request.Context(), &settle.CreateOrderRequest{
|
||||
AccountID: req.AccountID, Count: req.Count, Amount: req.Amount,
|
||||
PayType: req.PayType, Operator: operator, Remark: req.Remark,
|
||||
})
|
||||
if err != nil {
|
||||
bizResp(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, order)
|
||||
}
|
||||
|
||||
// orderConfirm POST /billing/orders/:id/confirm:付款审核确认(0→1,余额+count)。
|
||||
func (h *settleHandler) orderConfirm(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
response.Error(c, errs.InvalidParam.WithMsg("订单 ID 非法"))
|
||||
return
|
||||
}
|
||||
claims := statsClaims(c)
|
||||
operator := ""
|
||||
if claims != nil {
|
||||
operator = claims.Username
|
||||
}
|
||||
res, err := h.svc.ConfirmOrder(c.Request.Context(), id, operator)
|
||||
if err != nil {
|
||||
bizResp(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{
|
||||
"order_no": res.Order.OrderNo, "pay_status": res.Order.PayStatus,
|
||||
"count": res.Order.Count, "balance": res.Balance, "balance_log_id": res.BalanceLogID,
|
||||
})
|
||||
}
|
||||
|
||||
// orderReject POST /billing/orders/:id/reject:驳回(0→2,不涉余额)。
|
||||
func (h *settleHandler) orderReject(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
response.Error(c, errs.InvalidParam.WithMsg("订单 ID 非法"))
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
claims := statsClaims(c)
|
||||
operator := ""
|
||||
if claims != nil {
|
||||
operator = claims.Username
|
||||
}
|
||||
order, err := h.svc.RejectOrder(c.Request.Context(), id, operator, req.Remark)
|
||||
if err != nil {
|
||||
bizResp(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, order)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,11 @@ import (
|
||||
|
||||
// newSettleRouter 种子:账号 1/100 今日各 1 条成功明细(通道 1);返回注入器。
|
||||
func newSettleRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) {
|
||||
return newSettleRouterWithPerm(t, nil)
|
||||
}
|
||||
|
||||
// newSettleRouterWithPerm 可注入权限 checker(测试 403 路径);nil=仅要求已认证。
|
||||
func newSettleRouterWithPerm(t *testing.T, perm middleware.PermissionChecker) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
@@ -33,7 +38,16 @@ func newSettleRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Clai
|
||||
s.SetMaxOpenConns(1)
|
||||
}
|
||||
if err := db.AutoMigrate(&entity.MessageDetail{}, &entity.BillingConsumeLog{},
|
||||
&entity.StatsChannelDaily{}); err != nil {
|
||||
&entity.StatsChannelDaily{}, &entity.AccountUser{}, &entity.BillingOrder{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 流水表手动建:idx_account_time 与 BillingOrder 同名,glebarez 索引名
|
||||
// 全库唯一不查重(settle 包同款方言坑);无索引版本读写语义零影响。
|
||||
if err := db.Exec(`CREATE TABLE IF NOT EXISTS account_balance_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id INTEGER NOT NULL, biz_type TEXT, amount INTEGER,
|
||||
balance_after INTEGER, ref_id TEXT, operator TEXT, remark TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP)`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
@@ -48,6 +62,11 @@ func newSettleRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Clai
|
||||
if err := db.Create(&details).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&entity.AccountUser{
|
||||
Model: entity.Model{ID: 1}, Username: "admin", Role: "admin", Balance: 1000,
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rg := gin.New()
|
||||
api := rg.Group("/api/v1")
|
||||
var claims *middleware.Claims
|
||||
@@ -56,7 +75,7 @@ func newSettleRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Clai
|
||||
c.Set(middleware.ContextKeyClaims, claims)
|
||||
}
|
||||
})
|
||||
registerSettleRoutes(api, Deps{Settle: settle.NewService(db)})
|
||||
registerSettleRoutes(api, Deps{Settle: settle.NewService(db), Perm: perm})
|
||||
return rg, db, func(cl *middleware.Claims) { claims = cl }
|
||||
}
|
||||
|
||||
@@ -155,3 +174,99 @@ func TestSettleAggregate_Manual(t *testing.T) {
|
||||
t.Fatalf("坏日期应 4xx,got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSettleOrders_FullFlow 订单族全流程:创建(不动余额)→列表→confirm(余额+count)
|
||||
// →重复 confirm HTTP 409+ISC:039 →驳回路径;二级权限 403。
|
||||
func TestSettleOrders_FullFlow(t *testing.T) {
|
||||
rg, db, setClaims := newSettleRouter(t)
|
||||
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
|
||||
|
||||
// 创建(perm=nil:已认证即过,功能路径)。
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders",
|
||||
strings.NewReader(`{"account_id":1,"count":500,"amount":50.0,"pay_type":"bank"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rg.ServeHTTP(w, req)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("创建 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var created struct {
|
||||
Data entity.BillingOrder `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.Data.PayStatus != 0 || created.Data.ID == 0 {
|
||||
t.Fatalf("订单字段错: %+v", created.Data)
|
||||
}
|
||||
var bal int64
|
||||
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
||||
if bal != 1000 {
|
||||
t.Fatalf("创建不应动余额: %d", bal)
|
||||
}
|
||||
|
||||
// 列表(admin 平台角色)。
|
||||
w = httptest.NewRecorder()
|
||||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/billing/orders?pay_status=0", nil))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("列表 status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// confirm:余额+count。
|
||||
w = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders/1/confirm", nil)
|
||||
rg.ServeHTTP(w, req)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("confirm status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var res struct {
|
||||
Data struct {
|
||||
Balance int64 `json:"balance"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Data.Balance != 1500 {
|
||||
t.Fatalf("confirm 后余额=%d 期望 1500", res.Data.Balance)
|
||||
}
|
||||
|
||||
// 重复 confirm → HTTP 409 + ISC:039。
|
||||
w = httptest.NewRecorder()
|
||||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders/1/confirm", nil))
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("重复 confirm 应 409,got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "ISC:039") {
|
||||
t.Fatalf("409 响应应带 ISC:039: %s", w.Body.String())
|
||||
}
|
||||
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
||||
if bal != 1500 {
|
||||
t.Fatalf("重复 confirm 后余额=%d 应保持 1500", bal)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSettleOrders_PermissionAndScope 二级权限 403 与 customer 列表 403。
|
||||
func TestSettleOrders_PermissionAndScope(t *testing.T) {
|
||||
// 恒拒 checker:创建/confirm 应 403。
|
||||
denyAll := middleware.PermissionChecker(func(*middleware.Claims, string, string) bool { return false })
|
||||
rg, _, setClaims := newSettleRouterWithPerm(t, denyAll)
|
||||
setClaims(&middleware.Claims{AccountID: 1, Username: "ops", Roles: []string{"ops"}})
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders",
|
||||
strings.NewReader(`{"account_id":1,"count":100}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rg.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("无二级权限创建应 403,got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// customer 列表 → 403(perm 不参与,角色判定)。
|
||||
rg2, _, setClaims2 := newSettleRouter(t)
|
||||
setClaims2(&middleware.Claims{AccountID: 100, Username: "cust", Roles: []string{"customer"}})
|
||||
w = httptest.NewRecorder()
|
||||
rg2.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/billing/orders", nil))
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("customer 列表应 403,got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ var (
|
||||
BlockedRegion = &Error{"ISC:036", "地区屏蔽", "region blocked", http.StatusForbidden}
|
||||
AuditStatusConflict = &Error{"ISC:037", "审核状态冲突(非待审)", "audit status conflict", http.StatusConflict}
|
||||
TaskStatusConflict = &Error{"ISC:038", "任务状态冲突(不可取消/改期)", "task status conflict", http.StatusConflict}
|
||||
OrderStatusConflict = &Error{"ISC:039", "订单状态冲突(非待确认)", "order status conflict", http.StatusConflict}
|
||||
|
||||
// ---- 通用请求错误(400 段,段值与 HTTP 语义对齐)----
|
||||
InvalidParam = &Error{"ISC:400", "参数错误", "invalid parameter", http.StatusBadRequest}
|
||||
@@ -115,8 +116,8 @@ var registry = func() map[string]*Error {
|
||||
NoChannelRoute, ChannelRejected, ContentNonCompliant, SendLimited,
|
||||
TextTooLong, DailyLimitExceeded, CreditLimitExceeded, NightRateLimited, FiveGBlocked,
|
||||
BlockedRegion,
|
||||
// 审核与任务(Day 43)
|
||||
AuditStatusConflict, TaskStatusConflict,
|
||||
// 审核与任务(Day 43;S2 增订单冲突)
|
||||
AuditStatusConflict, TaskStatusConflict, OrderStatusConflict,
|
||||
// 通用
|
||||
InvalidParam, Unauthorized, TokenExpired, Forbidden, NotFound,
|
||||
MethodNotAllowed, RateLimited,
|
||||
|
||||
@@ -84,8 +84,8 @@ func TestAuthoritativeCatalog(t *testing.T) {
|
||||
t.Errorf("ByCode(%s) = {%s %s}, 期望 {%s %s}", code, got.Code, got.Msg, code, msg)
|
||||
}
|
||||
}
|
||||
// 全量 51 条 = 成功码 ISC:000 + 错误码 50 条(权威清单;Day42 +ISC:036;Day43 +037/038)。
|
||||
if n := len(All()); n != 51 {
|
||||
t.Errorf("预定义码数量 = %d, 期望 51(含成功码)", n)
|
||||
// 全量 52 条 = 成功码 ISC:000 + 错误码 51 条(权威清单;Day42 +ISC:036;Day43 +037/038;S2-D3 +039)。
|
||||
if n := len(All()); n != 52 {
|
||||
t.Errorf("预定义码数量 = %d, 期望 52(含成功码)", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
// 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 兼容,
|
||||
// 同 send/consume.isDupTaskNo 口径)。
|
||||
func isDuplicateKey(err error) bool {
|
||||
msg := 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
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package settle
|
||||
|
||||
// recharge_test.go S2-D3:充值订单审核流单测——创建校验/confirm 事务语义
|
||||
// (CAS+余额自增+流水 ref_id=order_no)/状态机冲突 ISC:039/**并发 confirm
|
||||
// 恰一成功**(-race 验收点)/驳回不涉余额/列表过滤。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
errs "go-sms/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// newRechargeDB 内存库 + 账号(Balance 1000)/订单/流水三表。
|
||||
// AccountBalanceLog 手动建表:其 idx_account_time 与 BillingOrder 同名,
|
||||
// glebarez SQLite 索引名全库唯一不查重(迁移测试已知方言缺口),无索引
|
||||
// 版本表对本测试读写语义零影响。
|
||||
func newRechargeDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := newConsumeDB(t) // 复用 sqlite 内存库骨架(单连接)
|
||||
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.BillingOrder{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`CREATE TABLE IF NOT EXISTS account_balance_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id INTEGER NOT NULL, biz_type TEXT, amount INTEGER,
|
||||
balance_after INTEGER, ref_id TEXT, operator TEXT, remark TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP)`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&entity.AccountUser{
|
||||
Model: entity.Model{ID: 1}, Username: "acct1", Role: "customer", Balance: 1000,
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func isErr(err error, want *errs.Error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
e, ok := err.(*errs.Error)
|
||||
return ok && e.Code == want.Code
|
||||
}
|
||||
|
||||
func TestOrder_Create(t *testing.T) {
|
||||
db := newRechargeDB(t)
|
||||
svc := NewService(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 正常创建:pay_status=0 且不动余额。
|
||||
o, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 500, Amount: 50.0, PayType: "bank"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o.PayStatus != 0 || o.Count != 500 || len(o.OrderNo) == 0 || o.OrderNo[0] != 'B' {
|
||||
t.Fatalf("订单字段错: %+v", o)
|
||||
}
|
||||
var bal int64
|
||||
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
||||
if bal != 1000 {
|
||||
t.Fatalf("创建不应动余额: %d", bal)
|
||||
}
|
||||
|
||||
// 边界:count 0/负/超上限/账号不存在。
|
||||
if _, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 0}); !isErr(err, errs.InvalidParam) {
|
||||
t.Fatalf("count=0 应 400: %v", err)
|
||||
}
|
||||
if _, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: -5}); !isErr(err, errs.InvalidParam) {
|
||||
t.Fatalf("count<0 应 400: %v", err)
|
||||
}
|
||||
if _, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: maxRechargeCount + 1}); !isErr(err, errs.InvalidParam) {
|
||||
t.Fatalf("count 超上限应 400: %v", err)
|
||||
}
|
||||
if _, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 999, Count: 10}); !isErr(err, errs.NotFound) {
|
||||
t.Fatalf("账号不存在应 404: %v", err)
|
||||
}
|
||||
|
||||
// OrderNo 唯一性:批量创建无 uk 冲突。
|
||||
for i := 0; i < 20; i++ {
|
||||
if _, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 1}); err != nil {
|
||||
t.Fatalf("第 %d 单创建失败: %v", i, err)
|
||||
}
|
||||
}
|
||||
var n int64
|
||||
db.Model(&entity.BillingOrder{}).Count(&n)
|
||||
if n != 21 {
|
||||
t.Fatalf("订单总数=%d 期望 21", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrder_ConfirmAndReject(t *testing.T) {
|
||||
db := newRechargeDB(t)
|
||||
svc := NewService(db)
|
||||
ctx := context.Background()
|
||||
|
||||
o, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 500})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// confirm 正常:0→1+余额+count+流水 ref_id=order_no+balance_after 一致。
|
||||
res, err := svc.ConfirmOrder(ctx, o.ID, "ops-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Order.PayStatus != 1 || res.Balance != 1500 || res.BalanceLogID == 0 {
|
||||
t.Fatalf("confirm 结果错: %+v", res)
|
||||
}
|
||||
if res.Order.PaidAt == nil || res.Order.Operator != "ops-a" {
|
||||
t.Fatalf("paid_at/operator 未落: %+v", res.Order)
|
||||
}
|
||||
var log entity.AccountBalanceLog
|
||||
if err := db.Where("ref_id = ?", o.OrderNo).First(&log).Error; err != nil {
|
||||
t.Fatalf("流水缺失: %v", err)
|
||||
}
|
||||
if log.BizType != "recharge" || log.Amount != 500 || log.BalanceAfter != 1500 {
|
||||
t.Fatalf("流水字段错: %+v", log)
|
||||
}
|
||||
|
||||
// 重复 confirm → ISC:039 且余额二次不变。
|
||||
if _, err := svc.ConfirmOrder(ctx, o.ID, "ops-b"); !isErr(err, errs.OrderStatusConflict) {
|
||||
t.Fatalf("重复 confirm 应 ISC:039: %v", err)
|
||||
}
|
||||
var bal int64
|
||||
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
||||
if bal != 1500 {
|
||||
t.Fatalf("重复 confirm 后余额=%d 应保持 1500", bal)
|
||||
}
|
||||
// 已确认后 reject → ISC:039。
|
||||
if _, err := svc.RejectOrder(ctx, o.ID, "ops-b", "x"); !isErr(err, errs.OrderStatusConflict) {
|
||||
t.Fatalf("已确认 reject 应 ISC:039: %v", err)
|
||||
}
|
||||
|
||||
// reject 正常:0→2 余额不变。
|
||||
o2, _ := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 300})
|
||||
ro, err := svc.RejectOrder(ctx, o2.ID, "ops-c", "付款凭证不符")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ro.PayStatus != 2 || ro.Remark != "付款凭证不符" {
|
||||
t.Fatalf("驳回结果错: %+v", ro)
|
||||
}
|
||||
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
||||
if bal != 1500 {
|
||||
t.Fatalf("驳回不应动余额: %d", bal)
|
||||
}
|
||||
|
||||
// 不存在订单 → 404。
|
||||
if _, err := svc.ConfirmOrder(ctx, 424242, "x"); !isErr(err, errs.NotFound) {
|
||||
t.Fatalf("不存在订单应 404: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrder_ConcurrentConfirm 并发 confirm:CAS 保证恰一成功(-race)。
|
||||
// sqlite 单连接下两事务串行,第二个 CAS 看到 pay_status=1 → ISC:039,
|
||||
// 余额只加一次——语义与 MySQL 行锁路径等价。
|
||||
func TestOrder_ConcurrentConfirm(t *testing.T) {
|
||||
db := newRechargeDB(t)
|
||||
svc := NewService(db)
|
||||
ctx := context.Background()
|
||||
o, err := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 777})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
okCount atomic.Int64
|
||||
conflict atomic.Int64
|
||||
)
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if _, err := svc.ConfirmOrder(ctx, o.ID, "ops-race"); err == nil {
|
||||
okCount.Add(1)
|
||||
} else if isErr(err, errs.OrderStatusConflict) {
|
||||
conflict.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if okCount.Load() != 1 || conflict.Load() != 1 {
|
||||
t.Fatalf("并发 confirm 应恰一成功一冲突: ok=%d conflict=%d", okCount.Load(), conflict.Load())
|
||||
}
|
||||
var bal int64
|
||||
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
||||
if bal != 1000+777 {
|
||||
t.Fatalf("余额=%d 应恰 +777", bal)
|
||||
}
|
||||
// 流水仅一条(ref_id=order_no)。
|
||||
var n int64
|
||||
db.Model(&entity.AccountBalanceLog{}).Where("ref_id = ?", o.OrderNo).Count(&n)
|
||||
if n != 1 {
|
||||
t.Fatalf("流水=%d 条应恰 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrder_List(t *testing.T) {
|
||||
db := newRechargeDB(t)
|
||||
svc := NewService(db)
|
||||
ctx := context.Background()
|
||||
o1, _ := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 10})
|
||||
o2, _ := svc.CreateOrder(ctx, &CreateOrderRequest{AccountID: 1, Count: 20})
|
||||
if _, err := svc.ConfirmOrder(ctx, o1.ID, "x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 全量(按 id 倒序:新单在前)。
|
||||
list, total, err := svc.ListOrders(ctx, OrderQuery{})
|
||||
if err != nil || total != 2 || len(list) != 2 || list[0].ID != o2.ID {
|
||||
t.Fatalf("列表错: total=%d len=%d err=%v", total, len(list), err)
|
||||
}
|
||||
// pay_status 过滤。
|
||||
confirmed := int8(1)
|
||||
_, total, err = svc.ListOrders(ctx, OrderQuery{PayStatus: &confirmed})
|
||||
if err != nil || total != 1 {
|
||||
t.Fatalf("状态过滤 total=%d err=%v", total, err)
|
||||
}
|
||||
// 账号过滤。
|
||||
_, total, err = svc.ListOrders(ctx, OrderQuery{AccountID: 999})
|
||||
if err != nil || total != 0 {
|
||||
t.Fatalf("账号过滤 total=%d err=%v", total, err)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
# 当前工作上下文(最近更新:2026-11-14)
|
||||
|
||||
## 当前状态快照(2026-11-14 傍晚,**S2-D2 收官**)
|
||||
## 当前状态快照(2026-11-14 夜,**S2-D3 收官,进度 3/5**)
|
||||
|
||||
- **仓库**:main 已推 Gitea(origin=192.168.5.27:24401/Tory/go-sms-V2);每日 bundle+push 双轨。
|
||||
- **S2 进度 2/5**:D1 ✅(表设计六裁决+v20+openapi v1.3.0)/ **D2 ✅(消耗日汇总引擎)**——settle/consume.go+job.go+两端点;**滚动重刷模型**(1h 重刷近 4 天,修正单日 T+1 的 72h UNKNOWN 迁移失真;月结建议 T+4 后生成);-race 39 包/lint 0/真 MySQL 端到端+收敛实证(success 1→2/unknown 1→0);gateway 已驻新二进制(md5 一致)。
|
||||
- **24h 稳定性门槛 ✅ 终判通过**(18:02 三项全绿;S1 完全闭环,S5 压测前置确认)。
|
||||
- **六项裁决速查**:R1 出账时刻计价(明细 Fee=片数不动,send 域零改动;金额=Σ日成功条数×生效单价,时间线+阶梯在 D4 settle/price.go 单点推导)/R2 消耗事实源=billing_consume_log(账号×业务×天)+stats_channel_daily(通道×天,已由 D2 job 落账)/R3 充值双通道/R4 rebate_rate 单级返点历史不重算/R5 settle_ladder(owner×tier_from)/R6 条/元换算只在出账引擎。
|
||||
- **下一步=S2-D3 充值审核流**:settle/recharge.go+`/billing/orders` 族四端点(创建 pay_status=0 不动余额/confirm=状态 CAS+余额自增 count+流水 ref_id=order_no 同事务/驳回/列表);R3 双通道语义(即时充值保留);并发 confirm -race 只入账一次为验收点。随后 D4 出账+阶梯(显式验收:阶梯结算单测)/D5 利润返点+三方对账(S2 出口 diff=0)。
|
||||
- **S2 进度 3/5**:D1 表设计+v20+契约 / D2 消耗日汇总(滚动重刷)/ **D3 ✅ 充值审核流**——recharge.go(创建 0 态不动余额/confirm 单事务 CAS+余额自增+流水 ref_id=order_no/驳回)+ISC:039(三处同步 52 码)+四端点(二级权限+平台角色门);测试 7 件含**并发 confirm 恰一成功(-race)**;**真机全链冒烟**(HS256 临时 token:创建→confirm 余额+123→重复 409;流水 ref_id+审计 module=billing 留痕两设计实证;数据已还原)。-race 39 包/lint 0。
|
||||
- **24h 稳定性门槛 ✅ 终判通过**(18:02;S1 完全闭环,S5 压测前置确认)。
|
||||
- **六项裁决速查**:R1 出账时刻计价(D4 price.go 单点推导)/R2 事实源=billing_consume_log+stats_channel_daily(D2 已落账)/R3 双通道(D3 已落地:即时充值流水 ref_id 空 vs 订单流=order_no,D5 对账区分锚点)/R4 rebate_rate/R5 settle_ladder/R6 条/元换算只在出账引擎。
|
||||
- **下一步=S2-D4 出账引擎+阶梯**(显式验收:阶梯结算单测):price.go(PriceAt 时间线回溯 EffectiveAt≤当日取最近+阶梯落档覆写)+bill.go(customer/upstream 生成-确认-结账-settle_record+XLSX 导出);幂等=uk(account|upstream,period)+status=2 拒重算;上家口径随通道 billing_mode(success/success_unknown/all);**月结建议 T+4 后生成**(滚动重刷 72h 收敛语义)。随后 D5 利润/返点/三方对账(S2 出口 diff=0)。
|
||||
- 归档仓(只读):/data/poc-archive/repos/go-sms.git(poc-final=5e09a4cc)。
|
||||
- **本会话运维教训**:①`pkill/pgrep -f` 自匹配(铁律:`[x]` 括号技巧);②大镜像单窗>体积÷带宽;③du 无 sudo 静默失败误诊;④sed 换行/sed 误伤方法名(重构期优先编辑器工具);⑤Go 工具忽略 `_` 前缀文件;⑥集成测试需 `sg docker` 包裹(docker 组未重登);⑦**Makefile recipe 的 `exit 0` 只退出当前行 shell 不终止目标**(幂等短路须 if/else 递归 `$(MAKE)` 子目标);⑧**管道 `| tail -N` 截首行误导诊断**(gw-start"玄学 NOMATCH"两轮误诊实为 THEN 分支已生效,排查须看全量输出)。
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
| S1-B 收尾项 | send P2 拆三子包(0550f2a,facade 门面)/dayNN 19 文件改名/storage 归一/文案校准/gofmt 清零 | ✅ 2026-11-13 夜(**S1 泳道收官**) |
|
||||
| S2-D1 表设计+v20+契约 | 六项裁决(R1 出账时刻计价/R2 事实源统一/R3 充值双通道/R4 返点/R5 阶梯表/R6 口径)+v20_settle_domain+openapi v1.3.0(+20 端点)+dev 库实跑 v20 | ✅ 2026-11-14(评审纪要 docs/review/s2-settle-table-review.md;验收单 s2-d1.md) |
|
||||
| S2-D2 消耗日汇总引擎 | settle/consume.go+job.go(**滚动重刷模型**:1h 重刷近 4 天,修正单日 T+1 的 72h 失真)+两端点+config/metrics/装配;sqlite 6 测试;真 MySQL 端到端+收敛实证 | ✅ 2026-11-14 傍晚(验收单 s2-d2.md) |
|
||||
| S2-D3~D5 | D3 充值审核流/D4 出账+阶梯(显式验收:阶梯结算单测)/D5 利润返点+三方对账(diff=0=S2 出口) | ⬜ 排期中 |
|
||||
| S2-D3 充值审核流 | recharge.go(创建/confirm 单事务 CAS+余额自增+流水 ref_id=order_no/驳回/列表)+ISC:039 三处同步+四端点(二级权限+平台角色门);测试 7 件含并发 confirm;真机全链冒烟+审计留痕实证 | ✅ 2026-11-14 夜(验收单 s2-d3.md) |
|
||||
| S2-D4~D5 | D4 出账+阶梯(显式验收:阶梯结算单测)/D5 利润返点+三方对账(diff=0=S2 出口) | ⬜ 排期中 |
|
||||
| 观察项 | 24h 稳定性门槛(11-13 17:55 起计;期内 21:33 宿主主动重启=已知事件不判失败)期满核验 11-14 17:55 | ✅ 2026-11-14 18:02 终判通过(dmesg 0/零重启/驻留+md5 一致;S5 压测前置确认,S1 完全闭环) |
|
||||
| S2~S5 | 结算域/前端收尾/C1C2+冷热/基线与灰度 | ⬜ 见《Go-sms-重建计划.md》 |
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ export const ISC_CN: Record<string, string> = {
|
||||
'ISC:036': '地区屏蔽',
|
||||
'ISC:037': '审核状态冲突(非待审)',
|
||||
'ISC:038': '任务状态冲突(不可取消/改期)',
|
||||
'ISC:039': '订单状态冲突(非待确认)',
|
||||
'ISC:040': '夜间频控',
|
||||
'ISC:043': '5G消息拦截',
|
||||
'ISC:400': '参数错误',
|
||||
|
||||
Reference in New Issue
Block a user