S2-D1 结算域表设计评审+迁移 v20+契约草案: 六项裁决定稿(docs/review/s2-settle-table-review.md)——R1 出账时刻计价(用户拍板:明细 Fee 保持片数/send 域零改动,金额=Σ日成功条数×生效单价,时间线+阶梯 D4 price.go 单点推导)/R2 消耗事实源统一 billing_consume_log+stats_channel_daily,stats_user_daily 废弃/R3 充值双通道(即时+BillingOrder 审核)/R4 rebate_rate 单级返点历史不重算/R5 settle_ladder 阶梯表/R6 条/元口径单点换算;v20_settle_domain(billing_consume_log +unknown_count/updated_at,account_user +rebate_rate,DROP stats_user_daily,settle_ladder 建表,casbin 补 ops settle:write/customer settle:read;显式 ALTER+HasColumn 守卫/空库 HasTable 守卫三路径收敛,零新增索引复用 v16);实体同步 All() 39 个;openapi v1.3.0 +20 结算端点(js-yaml 84 paths 过);迁移测试末七窗口 v14..v20 两遍幂等+五项 v20 断言;门禁全绿:vet 0/-race 38 包零 FAIL/lint 0/集成 AutoMigrate 39 表+Casbin PASS;dev 库实跑 v19→v20+information_schema 五项核验过;验收单 s2-d1.md+CHANGELOG+memory-bank 回填

This commit is contained in:
2026-11-14 09:56:54 +08:00
parent 24f7b3dd02
commit 5159e3c634
12 changed files with 481 additions and 46 deletions
+1
View File
@@ -18,6 +18,7 @@ type AccountUser struct {
IPBind string `gorm:"size:256" json:"ip_bind"`
Balance int64 `json:"balance"`
CreditBalance int64 `json:"credit_balance"`
RebateRate float64 `gorm:"type:decimal(5,4);default:0" json:"rebate_rate"` // v20:代理返点率(小数,0.1200=12%;0=无返点;上级对直线下级结算额的分成)
SvcTeam string `gorm:"size:64" json:"svc_team"`
ExpiredAt *time.Time `json:"expired_at"`
LastLoginAt *time.Time `json:"last_login_at"`
+2 -2
View File
@@ -46,8 +46,8 @@ func All() []any {
// 计费与结算(5)
&BillingOrder{}, &BillingConsumeLog{}, &SettleCustomer{}, &SettleUpstream{},
&SettleRecord{},
// 统计与运维(8)
&StatsUserDaily{}, &StatsChannelDaily{}, &SystemConfig{}, &SystemAlertRule{},
// 统计与运维(7)
&StatsChannelDaily{}, &SystemConfig{}, &SystemAlertRule{},
&SystemLoginLog{}, &SystemOperateLog{}, &SystemErrorCode{}, &FeErrorLog{},
}
}
+24 -5
View File
@@ -19,7 +19,9 @@ type BillingOrder struct {
func (BillingOrder) TableName() string { return "billing_order" }
// BillingConsumeLog 消耗日志(按账号/业务/天)。
// BillingConsumeLog 消耗日志(按账号/业务/天)——S2 起为结算域消耗事实源
// (R2 裁决:stats_user_daily 同粒度双空壳废弃,单一事实源归本表);
// 日汇总 job T+1 凌晨幂等 UPSERT(明细热窗仅 5 天,月结必须走本表)。
type BillingConsumeLog struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
AccountID int64 `gorm:"uniqueIndex:uk_account_date,priority:1" json:"account_id"`
@@ -28,21 +30,24 @@ type BillingConsumeLog struct {
SubmitCount int `json:"submit_count"`
SuccessCount int `json:"success_count"`
FailCount int `json:"fail_count"`
FeeTotal float64 `gorm:"type:decimal(12,4)" json:"fee_total"`
UnknownCount int `json:"unknown_count"` // v20:未知(72h 窗后仍 UNKNOWN)——上家 success_unknown 口径依赖
FeeTotal float64 `gorm:"type:decimal(12,4)" json:"fee_total"` // 单位=条(=Σ明细 fee,片数口径 Day70)
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` // v20:UPSERT 重跑痕迹
}
func (BillingConsumeLog) TableName() string { return "billing_consume_log" }
// SettleCustomer 下家(客户)月度结算单。
// SettleCustomer 下家(客户)月度结算单——金额=Σ(日成功条数×生效单价),
// 出账时刻按价格时间线推导(R1 裁决:明细 Fee 保持片数,不在受理侧金额化)。
type SettleCustomer struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
SettleNo string `gorm:"size:32" json:"settle_no"`
AccountID int64 `gorm:"uniqueIndex:uk_account_period,priority:1" json:"account_id"`
Period string `gorm:"size:7;uniqueIndex:uk_account_period,priority:2;index:idx_period" json:"period"`
SuccessCount int64 `json:"success_count"`
Amount float64 `gorm:"type:decimal(12,2)" json:"amount"`
Status int8 `gorm:"default:0" json:"status"`
Amount float64 `gorm:"type:decimal(12,2)" json:"amount"` // 应收(元)
Status int8 `gorm:"default:0" json:"status"` // 0草稿 1已确认 2已结账(已结拒重算)
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}
@@ -76,3 +81,17 @@ type SettleRecord struct {
}
func (SettleRecord) TableName() string { return "settle_record" }
// SettleLadder 阶梯价档位(S2·R5:出账时按月成功总量落档,档内单价覆写
// 时间线价;tier_from=档位下限(含),0=首档,上一档与下一档的 from 界定区间;
// owner_type=account(下家应收)/upstream(上家成本)两类锚点各自配档)。
type SettleLadder struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
OwnerType string `gorm:"size:8;uniqueIndex:uk_owner_tier,priority:1" json:"owner_type"` // account/upstream
OwnerID int64 `gorm:"uniqueIndex:uk_owner_tier,priority:2" json:"owner_id"`
TierFrom int64 `gorm:"uniqueIndex:uk_owner_tier,priority:3" json:"tier_from"` // 档位下限(含,条)
Price float64 `gorm:"type:decimal(10,4)" json:"price"` // 该档单价(元/条)
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}
func (SettleLadder) TableName() string { return "settle_ladder" }
+3 -14
View File
@@ -2,20 +2,9 @@ package entity
import "time"
// StatsUserDaily 用户日统计(偶数整点刷新)。
type StatsUserDaily struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
AccountID int64 `gorm:"uniqueIndex:uk_account_date,priority:1" json:"account_id"`
StatDate time.Time `gorm:"type:date;uniqueIndex:uk_account_date,priority:2;index:idx_date" json:"stat_date"`
SubmitCount int `json:"submit_count"`
SuccessCount int `json:"success_count"`
FailCount int `json:"fail_count"`
UnknownCount int `json:"unknown_count"`
FeeTotal float64 `gorm:"type:decimal(12,4)" json:"fee_total"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}
func (StatsUserDaily) TableName() string { return "stats_user_daily" }
// (S2·R2 裁决)StatsUserDaily 用户日统计已废弃:与 billing_consume_log
// 同粒度双空壳,消耗事实源统一归 billing_consume_log(账号×业务×天),
// 表由迁移 v20 DROP;用户侧统计查询走 billing_consume_log API。
// StatsChannelDaily 通道日统计(含估算余额)。
type StatsChannelDaily struct {
+28 -16
View File
@@ -29,8 +29,8 @@ func TestMigrations_IdempotentAndVersioned(t *testing.T) {
seen[mig.ID] = true
last = mig
}
if last == nil || last.ID != "v19_longsms_pending" {
t.Fatalf("终版迁移应为 v19_longsms_pending,实际 %v", last)
if last == nil || last.ID != "v20_settle_domain" {
t.Fatalf("终版迁移应为 v20_settle_domain,实际 %v", last)
}
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
@@ -42,31 +42,28 @@ func TestMigrations_IdempotentAndVersioned(t *testing.T) {
}
opts := gormigrate.DefaultOptions
opts.TableName = "schema_migrations"
// 注册末七迁移(现 v13..v19;历史 v10/V11 含 MessageTask AutoMigrate,gleberez
// sqlite 索引不查重,双块连跑撞 idx_account_time——同 v1+v6 已知方言缺口;v13/v14
// 各建各表、v15 AutoMigrate 加列、v16/v17 空库守卫补建 detail 后加查询索引、
// v18/v19 新表 AutoMigrate,单块两遍覆盖幂等)。
// 注册末七迁移(现 v14..v20;历史 v10/V11 含 MessageTask AutoMigrate,gleberez
// sqlite 索引不查重,双块连跑撞 idx_account_time——同 v1+v6 已知方言缺口;
// v14 各建各表、v15 AutoMigrate 加列、v16/v17/v20 空库守卫补建表后加列/索引、
// v18/v19 新表 AutoMigrate,v20 另含 DROP IF EXISTS 与 casbin HasTable 守卫,
// 单块两遍覆盖幂等)。
migs := Migrations()
gm := gormigrate.New(db.Session(&gorm.Session{Logger: logger.Discard}), opts, migs[len(migs)-7:])
if err := gm.Migrate(); err != nil {
t.Fatalf("v13..v19 首遍失败: %v", err)
t.Fatalf("v14..v20 首遍失败: %v", err)
}
if err := gm.Migrate(); err != nil {
t.Fatalf("v13..v19 二遍不幂等: %v", err)
t.Fatalf("v14..v20 二遍不幂等: %v", err)
}
v, err := CurrentMigrationVersion(db)
if err != nil {
t.Fatalf("查版本失败: %v", err)
}
if v == nil || *v != "v19_longsms_pending" {
t.Fatalf("版本应为 v19_longsms_pending,实际 %v", v)
}
if !db.Migrator().HasTable(&entity.MessageReportSeg{}) {
t.Fatal("v13 后应存在 message_report_seg 表")
}
if !db.Migrator().HasColumn(&entity.MessageReportSeg{}, "PkTotal") {
t.Fatal("v13 后应存在 pk_total 列(段级配对键)")
if v == nil || *v != "v20_settle_domain" {
t.Fatalf("版本应为 v20_settle_domain,实际 %v", v)
}
// (v13 断言随窗口右移移除:message_report_seg/pk_total 由 v13 建,
// 现窗口 v14..v20 不含 v13;全量链路覆盖仍由 dev MySQL 实库验证。)
// Day 62:v15 后 account_config 应有账号级 CMPP 配额两列。
if !db.Migrator().HasColumn(&entity.AccountConfig{}, "CmppMaxConns") ||
!db.Migrator().HasColumn(&entity.AccountConfig{}, "CmppSpeed") {
@@ -85,6 +82,21 @@ func TestMigrations_IdempotentAndVersioned(t *testing.T) {
if !db.Migrator().HasIndex(&entity.MessageDetail{}, "idx_business_created") {
t.Fatal("v17 后应存在 idx_business_created 索引")
}
// S2:v20 后 billing_consume_log 应有 unknown_count/updated_at 列,
// account_user 应有 rebate_rate 列,settle_ladder 建表且 stats_user_daily 废弃。
if !db.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UnknownCount") ||
!db.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UpdatedAt") {
t.Fatal("v20 后 billing_consume_log 应有 unknown_count/updated_at 列")
}
if !db.Migrator().HasColumn(&entity.AccountUser{}, "RebateRate") {
t.Fatal("v20 后 account_user 应有 rebate_rate 列")
}
if !db.Migrator().HasTable(&entity.SettleLadder{}) {
t.Fatal("v20 后应存在 settle_ladder 表")
}
if db.Migrator().HasTable("stats_user_daily") {
t.Fatal("v20 后 stats_user_daily 应已 DROP(R2 单一事实源裁决)")
}
}
// newTestDB 内存 SQLite + 自动建表。
+74
View File
@@ -393,6 +393,80 @@ func Migrations() []*gormigrate.Migration {
return nil // 表可手工 DROP,回滚为空操作
},
},
{
// S2(结算域 D 层)表基线,详见 docs/review/s2-settle-table-review.md:
// ①billing_consume_log 补 unknown_count/updated_at——消耗事实源
// (R2:stats_user_daily 废弃),幂等 UPSERT 重跑需更新痕迹;
// ②account_user 补 rebate_rate——代理返点率(R4,小数表示);
// ③DROP stats_user_daily——同粒度双空壳,单一事实源归 billing_
// consume_log;空库路径 v0 已不再建它,DROP IF EXISTS 双方言幂等;
// ④新表 settle_ladder——阶梯价档位(R5,出账时按月成功总量落档);
// ⑤casbin 补结算域策略(ops settle:write / customer settle:read,
// 逐条 NOT EXISTS 守卫;末段迁移单块重放路径无 casbin_rule 表,
// HasTable 守卫跳过,全量链路种入)。
// 加列走显式 SQL 不走 AutoMigrate——glebarez SQLite 下 entity 加
// 字段触发表 diff 重建会抹既有索引(v16/v17 教训);空库守卫分支
// AutoMigrate 整表无此风险(表本不存在)。
ID: "v20_settle_domain",
Migrate: func(tx *gorm.DB) error {
if !tx.Migrator().HasTable(&entity.BillingConsumeLog{}) { // 空库守卫(同 v16/v17)
if err := tx.AutoMigrate(&entity.BillingConsumeLog{}); err != nil {
return err
}
}
if !tx.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UnknownCount") {
if err := tx.Exec("ALTER TABLE billing_consume_log ADD COLUMN unknown_count INT NOT NULL DEFAULT 0").Error; err != nil {
return err
}
}
if !tx.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UpdatedAt") {
if err := tx.Exec("ALTER TABLE billing_consume_log ADD COLUMN updated_at DATETIME NULL DEFAULT NULL").Error; err != nil {
return err
}
}
if !tx.Migrator().HasTable(&entity.AccountUser{}) { // 空库守卫
if err := tx.AutoMigrate(&entity.AccountUser{}); err != nil {
return err
}
}
if !tx.Migrator().HasColumn(&entity.AccountUser{}, "RebateRate") {
if err := tx.Exec("ALTER TABLE account_user ADD COLUMN rebate_rate DECIMAL(5,4) NOT NULL DEFAULT 0").Error; err != nil {
return err
}
}
if err := tx.Exec("DROP TABLE IF EXISTS stats_user_daily").Error; err != nil {
return err
}
if !tx.Migrator().HasTable(&entity.SettleLadder{}) { // 新表,AutoMigrate 安全(同 v18/v19)
if err := tx.AutoMigrate(&entity.SettleLadder{}); err != nil {
return err
}
}
if tx.Migrator().HasTable(&casbinRule{}) { // v5 才建 casbin_rule
policies := []casbinRule{
{Ptype: "p", V0: "ops", V1: "settle", V2: "write"},
{Ptype: "p", V0: "customer", V1: "settle", V2: "read"}, // 客户查自己账单,scope 在 handler 侧过滤
}
for _, p := range policies {
var n int64
if err := tx.Model(&casbinRule{}).
Where("ptype = ? AND v0 = ? AND v1 = ? AND v2 = ?", p.Ptype, p.V0, p.V1, p.V2).
Count(&n).Error; err != nil {
return err
}
if n == 0 {
if err := tx.Create(&p).Error; err != nil {
return err
}
}
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil // 列/表/策略可手工重建或清除,回滚为空操作(v16~v19 惯例)
},
},
}
}