S2-D5 利润/返点/三方对账——S2 泳道收官: profit.go(UserProfit 时间线价收入+成本占比分摊+直线下级返点 R4 历史不重算=不落档现算+parent_id 子树 Path 过滤+平台净利双口径;ChannelProfit 同分母分摊 Σ守恒;阶梯不进分析=与账单金额差为口径差异)+reconcile.go(三方对账:账号=明细直查↔billing_consume_log↔settle_customer 条数/通道两方/上家=当前归并口径重推↔快照;金额不比=快照语义防调价噪音;bill_missing 不判失败;AllZero=出口判据)+cmd/reconcile/settle-check(-period/-json,exit 0=all_zero)+handler /stats/profit/users·channels 双端点(平台角色门,缺省窗本月至今)+openapi 描述对齐;测试 5 件(利润树/返点/分摊/子树/守恒+对账全零+篡改逐项暴露+missing 语义+handler 数值/403/坏日期);真机全链:2026-10 空月种链→汇总 1/1→下家 0.2→阶梯覆写 0.1→结账 SettleRecord→上家 2/0.1→利润双端点(rev0.2 时间线 vs 账单 0.1 口径差异实证)→settle-check all_zero=true EXIT=0(S2 出口判据)→清理 11 项零残留;走查脚本扩 D4/D5 全域 AI 预走查 27 PASS/0 FAIL+修复两存量 bug(明细 ID 9302 段超 int64 拒收→7302 段/清理段 $ON $B0 单引号不展开致 SQL 语法错→printf|mysql_pipe);门禁 vet/-race 39 包/lint 0;收官判定 s2-closeout.md(出口两项全过+六项裁决 R1~R6 全闭环)+验收单 s2-d5.md+CHANGELOG+memory-bank 回填

This commit is contained in:
2026-11-14 23:06:12 +08:00
parent 59483ed15f
commit c9cd6e51a5
14 changed files with 1506 additions and 28 deletions
+89
View File
@@ -65,6 +65,10 @@ func registerSettleRoutes(protected *gin.RouterGroup, deps Deps) {
middleware.RequirePermission(deps.Perm, "settle", "write"), h.ladderUpdate)
protected.DELETE("/settle/ladder/:id",
middleware.RequirePermission(deps.Perm, "settle", "write"), h.ladderDelete)
// S2-D5:利润分析双端点(平台角色门——利润含全平台资金信息,group/customer
// 403,与充值订单列表同口径;查询类不挂 settle:write)。
protected.GET("/stats/profit/users", h.profitUsers)
protected.GET("/stats/profit/channels", h.profitChannels)
}
// StartSettleAggregateJob v1 层装配入口(照 StartStatsRefresher 模式,仅
@@ -517,3 +521,88 @@ func (h *settleHandler) ladderDelete(c *gin.Context) {
}
response.Success(c, nil)
}
// ---- S2-D5:利润分析 ----
// parseProfitDates date_from/date_to 解析(YYYY-MM-DD;零值兜底=本月 1 号~今天,
// 月度利润视角)。返回 ok=false 时已写响应。
func parseProfitDates(c *gin.Context) (from, to time.Time, ok bool) {
now := time.Now()
from = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
to = now
if s := c.Query("date_from"); s != "" {
d, err := time.ParseInLocation("2006-01-02", s, time.Local)
if err != nil {
response.Error(c, errs.InvalidParam.WithMsg("date_from 须为 YYYY-MM-DD"))
return time.Time{}, time.Time{}, false
}
from = d
}
if s := c.Query("date_to"); s != "" {
d, err := time.ParseInLocation("2006-01-02", s, time.Local)
if err != nil {
response.Error(c, errs.InvalidParam.WithMsg("date_to 须为 YYYY-MM-DD"))
return time.Time{}, time.Time{}, false
}
to = d
}
return from, to, true
}
// profitUsers GET /stats/profit/users:用户利润(时间线价收入/成本分摊/直线下级
// 返点 R4/子树过滤;平台角色)。口径详见 settle/profit.go 头注。
func (h *settleHandler) profitUsers(c *gin.Context) {
if !statsIsPlatform(c) {
response.Error(c, errs.Forbidden.WithMsg("仅平台角色可查看利润分析"))
return
}
from, to, ok := parseProfitDates(c)
if !ok {
return
}
q := settle.UserProfitQuery{From: from, To: to, Page: 1, PageSize: 20}
if v, err := strconv.ParseInt(c.Query("parent_id"), 10, 64); err == nil && v > 0 {
q.ParentID = v
}
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
}
res, err := h.svc.UserProfit(c.Request.Context(), q)
if err != nil {
bizResp(c, err)
return
}
response.Success(c, res)
}
// profitChannels GET /stats/profit/channels:通道利润(通道价成本直算/收入占比
// 分摊;平台角色)。
func (h *settleHandler) profitChannels(c *gin.Context) {
if !statsIsPlatform(c) {
response.Error(c, errs.Forbidden.WithMsg("仅平台角色可查看利润分析"))
return
}
from, to, ok := parseProfitDates(c)
if !ok {
return
}
q := settle.ChannelProfitQuery{From: from, To: to, Page: 1, PageSize: 20}
if v, err := strconv.ParseInt(c.Query("channel_id"), 10, 64); err == nil && v > 0 {
q.ChannelID = v
}
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
}
res, err := h.svc.ChannelProfit(c.Request.Context(), q)
if err != nil {
bizResp(c, err)
return
}
response.Success(c, res)
}
+103 -1
View File
@@ -39,7 +39,8 @@ func newSettleRouterWithPerm(t *testing.T, perm middleware.PermissionChecker) (*
s.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.MessageDetail{}, &entity.BillingConsumeLog{},
&entity.StatsChannelDaily{}, &entity.AccountUser{}, &entity.BillingOrder{}); err != nil {
&entity.StatsChannelDaily{}, &entity.AccountUser{}, &entity.BillingOrder{},
&entity.AccountPrice{}, &entity.ChannelPrice{}, &entity.ChannelChannel{}); err != nil {
t.Fatal(err)
}
// 流水表手动建:idx_account_time 与 BillingOrder 同名,glebarez 索引名
@@ -368,3 +369,104 @@ func TestSettleBill_FullFlow(t *testing.T) {
t.Fatalf("无 settle:write 应 403: %d %s", w.Code, w.Body.String())
}
}
// TestSettleProfit_Endpoints S2-D5:利润双端点——平台角色可查(数值口径),
// customer 403;坏日期 400。种子=helper 明细(账号1/100 今日各 1 成功,通道1)
// + 价(账号1=1.0,通道1=0.5):acc1 rev1.0/cost0.5(分摊 1.0×1/2)/profit0.5;
// ch1 succ2/cost1.0/rev1.0/profit0(账号100 无账号行,消耗行不入结果)。
func TestSettleProfit_Endpoints(t *testing.T) {
rg, db, setClaims := newSettleRouter(t)
today := time.Now().Format("2006-01-02")
yday := time.Now().AddDate(0, 0, -1)
if err := db.Create(&[]entity.AccountPrice{
{AccountID: 1, Business: "sms", Price: 1.0, EffectiveAt: yday},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.ChannelPrice{
{ChannelID: 1, Price: 0.5, EffectiveAt: yday},
}).Error; err != nil {
t.Fatal(err)
}
if _, _, err := settle.NewService(db).AggregateDay(t.Context(), time.Now()); err != nil {
t.Fatal(err)
}
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
w := httptest.NewRecorder()
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/api/v1/stats/profit/users?date_from="+today+"&date_to="+today, nil))
if w.Code != 200 {
t.Fatalf("users status=%d body=%s", w.Code, w.Body.String())
}
var users struct {
Data struct {
Total int64 `json:"total"`
List []struct {
AccountID int64 `json:"account_id"`
Revenue float64 `json:"revenue"`
Cost float64 `json:"cost"`
Profit float64 `json:"profit"`
} `json:"list"`
Summary struct {
TotalRevenue float64 `json:"total_revenue"`
} `json:"summary"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &users); err != nil {
t.Fatal(err)
}
if users.Data.Total != 1 || len(users.Data.List) != 1 {
t.Fatalf("users 应 1 行(账号100 无账号实体): %+v", users.Data)
}
r := users.Data.List[0]
if r.AccountID != 1 || r.Revenue != 1.0 || r.Cost != 0.5 || r.Profit != 0.5 {
t.Fatalf("acc1 利润行错: %+v", r)
}
w = httptest.NewRecorder()
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/api/v1/stats/profit/channels?date_from="+today+"&date_to="+today, nil))
if w.Code != 200 {
t.Fatalf("channels status=%d body=%s", w.Code, w.Body.String())
}
var channels struct {
Data struct {
Total int64 `json:"total"`
List []struct {
ChannelID int64 `json:"channel_id"`
SuccessCount int64 `json:"success_count"`
Revenue float64 `json:"revenue"`
Cost float64 `json:"cost"`
Profit float64 `json:"profit"`
} `json:"list"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &channels); err != nil {
t.Fatal(err)
}
if channels.Data.Total != 1 || len(channels.Data.List) != 1 {
t.Fatalf("channels 应 1 行: %+v", channels.Data)
}
c := channels.Data.List[0]
if c.ChannelID != 1 || c.SuccessCount != 2 || c.Revenue != 1.0 || c.Cost != 1.0 || c.Profit != 0 {
t.Fatalf("ch1 利润行错: %+v", c)
}
// customer → 403;坏日期 → 400。
setClaims(&middleware.Claims{AccountID: 100, Username: "cust", Roles: []string{"customer"}})
for _, path := range []string{"/stats/profit/users", "/stats/profit/channels"} {
w = httptest.NewRecorder()
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1"+path, nil))
if w.Code != http.StatusForbidden {
t.Fatalf("customer %s 应 403: %d %s", path, w.Code, w.Body.String())
}
}
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
w = httptest.NewRecorder()
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/api/v1/stats/profit/users?date_from=2026/11/14", nil))
if w.Code == 200 {
t.Fatalf("坏日期应 4xx: %d %s", w.Code, w.Body.String())
}
}
+342
View File
@@ -0,0 +1,342 @@
// profit.go S2-D5:利润分析引擎——用户(含下级树/返点)与通道双视角。
//
// 口径(与 D4 出账同源、分析性差异如实声明):
// - revenue(用户)=Σ(日成功条数×PriceAtAccount 时间线价)——与 GenerateCustomerBills
// 同口径;**阶梯不进分析**(阶梯是月结出账的整月覆写项,分析用时间线价,
// 启用阶梯的账号利润行与账单金额可能不同,属口径差异非数据错误);
// - cost(用户)=全平台通道成本×该账号成功条数/全平台通道成功条数——**占比分摊**
// (billing_consume_log 与 stats_channel_daily 无账号×通道交叉粒度,精确归因
// 需新增事实粒度,留 S3+;分摊在总量守恒下误差可控);
// - rebate(R4)=Σ 直线下级窗口结算额×下级 rebate_rate——该账号(作为上级)的
// 返点收入,等价于平台让利支出;**历史不重算**:返点不落档,每次查询按当前
// 树(直线下级)+当前 rate×窗口推导,不存在回溯修正动作(换上级只影响未来
// 窗口的归属);
// - profit(用户)=revenue-cost+rebate;平台净利(summary)=Σrevenue-Σcost-Σrebate
// (返点从平台口径流出、计入上级账号口径);
// - 通道侧:cost=Σ(日成功×PriceAtChannel);revenue=全平台用户收入×通道成功占比
// (同分摊口径,与用户侧共用同一分母,Σ通道revenue=Σ用户revenue 恒成立)。
// 单位:金额均=元(R6;条→元换算仍只在 price.go)。
package settle
import (
"context"
"sort"
"strconv"
"strings"
"time"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// dayWindow 分析窗口归一:零值兜底(From=本月 1 号/To=今天),闭区间转 [lo,hi) 半开。
func dayWindow(from, to time.Time) (time.Time, time.Time) {
now := time.Now()
if to.IsZero() {
to = now
}
hi := time.Date(to.Year(), to.Month(), to.Day(), 0, 0, 0, 0, to.Location()).
AddDate(0, 0, 1) // 含当日
if from.IsZero() {
from = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
}
lo := time.Date(from.Year(), from.Month(), from.Day(), 0, 0, 0, 0, from.Location())
return lo, hi
}
// UserProfitQuery 用户利润查询条件。
type UserProfitQuery struct {
From time.Time // 闭区间起(零值=本月 1 号)
To time.Time // 闭区间止(零值=今天)
ParentID int64 // >0:仅该账号为根的子树(Path 前缀)
Page int
PageSize int
}
// UserProfitRow 单账号利润行。
type UserProfitRow struct {
AccountID int64 `json:"account_id"`
Username string `json:"username"`
Role string `json:"role"`
SuccessCount int64 `json:"success_count"`
Revenue float64 `json:"revenue"` // 应收(元,时间线价)
Cost float64 `json:"cost"` // 通道成本分摊(元)
Rebate float64 `json:"rebate"` // 直线下级返点(R4)
Profit float64 `json:"profit"` // revenue-cost+rebate
}
// UserProfitSummary 汇总(与列表同 scope:parent_id 过滤后)。
type UserProfitSummary struct {
Count int `json:"count"`
TotalRevenue float64 `json:"total_revenue"`
TotalCost float64 `json:"total_cost"`
TotalRebate float64 `json:"total_rebate"`
PlatformProfit float64 `json:"platform_profit"` // Σrevenue-Σcost-Σrebate
}
// UserProfitResult 用户利润结果集。
type UserProfitResult struct {
List []UserProfitRow `json:"list"`
Total int64 `json:"total"`
Summary UserProfitSummary `json:"summary"`
}
// UserProfit 用户利润分析。行集=窗口内有消耗的账号 ∪ 收到返点的上级
// (无自身流量但下级活跃的代理也有行);按 revenue 降序分页(内存排序,
// 账号量级=运营开户数,非明细量级)。
func (s *Service) UserProfit(ctx context.Context, q UserProfitQuery) (*UserProfitResult, error) {
lo, hi := dayWindow(q.From, q.To)
// ① 消耗事实源(账号×业务×天)→ 逐行业务线时间线计价。
var consumes []entity.BillingConsumeLog
if err := s.db.WithContext(ctx).
Where("stat_date >= ? AND stat_date < ?", lo, hi).
Order("stat_date").Find(&consumes).Error; err != nil {
return nil, err
}
var accounts []entity.AccountUser
if err := s.db.WithContext(ctx).Find(&accounts).Error; err != nil {
return nil, err
}
accByID := make(map[int64]*entity.AccountUser, len(accounts))
for i := range accounts {
accByID[accounts[i].ID] = &accounts[i]
}
byID := make(map[int64]*UserProfitRow)
order := make([]int64, 0)
get := func(id int64) *UserProfitRow {
if r, ok := byID[id]; ok {
return r
}
acc := accByID[id]
if acc == nil { // 软删/孤儿消耗行:不入行集(分摊分母走通道侧)
return nil
}
r := &UserProfitRow{AccountID: id, Username: acc.Username, Role: acc.Role}
byID[id] = r
order = append(order, id)
return r
}
for _, c := range consumes {
r := get(c.AccountID)
if r == nil {
continue
}
r.SuccessCount += int64(c.SuccessCount)
price, _ := s.PriceAtAccount(ctx, c.AccountID, c.Business, c.StatDate)
r.Revenue += float64(c.SuccessCount) * price
}
// ② 通道成本总额 + 通道侧成功总数(分摊分母,与通道利润同源)。
channelCost, channelSuccess, err := s.channelCostTotal(ctx, lo, hi)
if err != nil {
return nil, err
}
for _, id := range order {
r := byID[id]
if channelSuccess > 0 {
r.Cost = channelCost * float64(r.SuccessCount) / float64(channelSuccess)
}
}
// ③ 返点(R4):直线下级窗口结算额×下级 rebate_rate → 计入上级行。
for _, id := range order {
child := byID[id]
if child.Revenue <= 0 {
continue
}
acc := accByID[id]
if acc == nil || acc.RebateRate <= 0 || acc.ParentID <= 0 {
continue
}
if parent := get(acc.ParentID); parent != nil {
parent.Rebate += child.Revenue * acc.RebateRate
}
}
// ④ 子树过滤(Path 物化路径前缀;path 空兜底 "/<id>/")。
if q.ParentID > 0 {
var root entity.AccountUser
if err := s.db.WithContext(ctx).First(&root, q.ParentID).Error; err != nil {
return nil, errs.NotFound.WithMsg("parent_id 账号不存在")
}
prefix := root.Path
if prefix == "" {
prefix = "/" + strconv.FormatInt(root.ID, 10) + "/"
}
filtered := make([]int64, 0, len(order))
for _, id := range order {
if id == root.ID || strings.HasPrefix(accByID[id].Path, prefix) {
filtered = append(filtered, id)
}
}
order = filtered
}
rows := make([]UserProfitRow, 0, len(order))
sum := UserProfitSummary{}
for _, id := range order {
r := byID[id]
r.Profit = r.Revenue - r.Cost + r.Rebate
sum.Count++
sum.TotalRevenue += r.Revenue
sum.TotalCost += r.Cost
sum.TotalRebate += r.Rebate
rows = append(rows, *r)
}
sum.PlatformProfit = sum.TotalRevenue - sum.TotalCost - sum.TotalRebate
sort.Slice(rows, func(i, j int) bool {
if rows[i].Revenue != rows[j].Revenue {
return rows[i].Revenue > rows[j].Revenue
}
return rows[i].AccountID < rows[j].AccountID
})
total := int64(len(rows))
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
start := (q.Page - 1) * q.PageSize
if start >= len(rows) {
rows = []UserProfitRow{}
} else if start+q.PageSize < len(rows) {
rows = rows[start : start+q.PageSize]
} else {
rows = rows[start:]
}
return &UserProfitResult{List: rows, Total: total, Summary: sum}, nil
}
// channelCostTotal 窗口内全平台通道成本(Σ日成功×PriceAtChannel)与通道侧
// 成功总条数(分摊分母)。
func (s *Service) channelCostTotal(ctx context.Context, lo, hi time.Time) (cost float64, success int64, err error) {
var rows []entity.StatsChannelDaily
if err = s.db.WithContext(ctx).
Where("stat_date >= ? AND stat_date < ?", lo, hi).
Order("stat_date").Find(&rows).Error; err != nil {
return 0, 0, err
}
for _, r := range rows {
success += int64(r.SuccessCount)
price, _ := s.PriceAtChannel(ctx, r.ChannelID, r.StatDate)
cost += float64(r.SuccessCount) * price
}
return cost, success, nil
}
// ChannelProfitQuery 通道利润查询条件。
type ChannelProfitQuery struct {
From time.Time
To time.Time
ChannelID int64 // 0=全部
Page int
PageSize int
}
// ChannelProfitRow 单通道利润行。
type ChannelProfitRow struct {
ChannelID int64 `json:"channel_id"`
Name string `json:"name"`
UpstreamID int64 `json:"upstream_id"`
SuccessCount int64 `json:"success_count"`
Revenue float64 `json:"revenue"` // 全平台用户收入×成功占比(分摊)
Cost float64 `json:"cost"` // Σ日成功×通道时间线价
Profit float64 `json:"profit"`
}
// ChannelProfitResult 通道利润结果集。
type ChannelProfitResult struct {
List []ChannelProfitRow `json:"list"`
Total int64 `json:"total"`
}
// ChannelProfit 通道利润分析:成本=通道价直算;收入=占比分摊(无账号×通道
// 交叉粒度事实源,见文件头注);Σ通道 revenue=Σ用户 revenue 恒成立。
func (s *Service) ChannelProfit(ctx context.Context, q ChannelProfitQuery) (*ChannelProfitResult, error) {
lo, hi := dayWindow(q.From, q.To)
var stats []entity.StatsChannelDaily
db := s.db.WithContext(ctx).
Where("stat_date >= ? AND stat_date < ?", lo, hi).
Order("stat_date")
if q.ChannelID > 0 {
db = db.Where("channel_id = ?", q.ChannelID)
}
if err := db.Find(&stats).Error; err != nil {
return nil, err
}
var channels []entity.ChannelChannel
if err := s.db.WithContext(ctx).Find(&channels).Error; err != nil {
return nil, err
}
chByID := make(map[int64]*entity.ChannelChannel, len(channels))
for i := range channels {
chByID[channels[i].ID] = &channels[i]
}
// 全平台用户收入与通道侧成功总数(收入分摊分母;不随 channel_id 过滤,保证守恒)。
var totalRevenue float64
var consumes []entity.BillingConsumeLog
if err := s.db.WithContext(ctx).
Where("stat_date >= ? AND stat_date < ?", lo, hi).Find(&consumes).Error; err != nil {
return nil, err
}
for _, c := range consumes {
price, _ := s.PriceAtAccount(ctx, c.AccountID, c.Business, c.StatDate)
totalRevenue += float64(c.SuccessCount) * price
}
_, channelSuccess, err := s.channelCostTotal(ctx, lo, hi)
if err != nil {
return nil, err
}
byID := map[int64]*ChannelProfitRow{}
order := make([]int64, 0)
for _, r := range stats {
row := byID[r.ChannelID]
if row == nil {
row = &ChannelProfitRow{ChannelID: r.ChannelID}
if ch := chByID[r.ChannelID]; ch != nil {
row.Name, row.UpstreamID = ch.Name, ch.UpstreamID
}
byID[r.ChannelID] = row
order = append(order, r.ChannelID)
}
row.SuccessCount += int64(r.SuccessCount)
price, _ := s.PriceAtChannel(ctx, r.ChannelID, r.StatDate)
row.Cost += float64(r.SuccessCount) * price
}
rows := make([]ChannelProfitRow, 0, len(order))
for _, id := range order {
r := byID[id]
if channelSuccess > 0 {
r.Revenue = totalRevenue * float64(r.SuccessCount) / float64(channelSuccess)
}
r.Profit = r.Revenue - r.Cost
rows = append(rows, *r)
}
sort.Slice(rows, func(i, j int) bool {
if rows[i].SuccessCount != rows[j].SuccessCount {
return rows[i].SuccessCount > rows[j].SuccessCount
}
return rows[i].ChannelID < rows[j].ChannelID
})
total := int64(len(rows))
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
start := (q.Page - 1) * q.PageSize
if start >= len(rows) {
rows = []ChannelProfitRow{}
} else if start+q.PageSize < len(rows) {
rows = rows[start : start+q.PageSize]
} else {
rows = rows[start:]
}
return &ChannelProfitResult{List: rows, Total: total}, nil
}
+241
View File
@@ -0,0 +1,241 @@
package settle
// profit_test.go S2-D5:利润分析单测——时间线价收入/成本占比分摊/直线下级
// 返点(R4,单级)/子树过滤(Path 前缀)/汇总守恒;通道侧成本直算+收入分摊。
// 口径差异声明:阶梯不进分析(与账单金额的差=口径差异,见 profit.go 头注)。
import (
"context"
"testing"
"time"
"gorm.io/gorm"
"go-sms/internal/model/entity"
)
// newProfitDB 出账全家桶 + 账号树。
func newProfitDB(t *testing.T) *gorm.DB {
t.Helper()
db := newBillDB(t)
if err := db.AutoMigrate(&entity.AccountUser{}); err != nil {
t.Fatal(err)
}
return db
}
// seedProfitTree 树:1(root)→{10(rate .10),12(rate 0)};10→11(rate .20)。
// 价:acc1=0.10 / acc10=0.20 / acc11=0.30 / acc12 无价(Q1:0 元入账)。
func seedProfitTree(t *testing.T, db *gorm.DB) {
t.Helper()
d := func(s string) time.Time {
v, _ := time.ParseInLocation("2006-01-02", s, time.Local)
return v
}
if err := db.Create(&[]entity.AccountUser{
{Model: entity.Model{ID: 1}, Username: "root", Role: "group", Path: "/1/"},
{Model: entity.Model{ID: 10}, Username: "a10", Role: "customer", ParentID: 1, Path: "/1/10/", RebateRate: 0.10},
{Model: entity.Model{ID: 11}, Username: "a11", Role: "customer", ParentID: 10, Path: "/1/10/11/", RebateRate: 0.20},
{Model: entity.Model{ID: 12}, Username: "a12", Role: "customer", ParentID: 1, Path: "/1/12/"},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.AccountPrice{
{AccountID: 1, Business: "sms", Price: 0.10, EffectiveAt: d("2026-11-01")},
{AccountID: 10, Business: "sms", Price: 0.20, EffectiveAt: d("2026-11-01")},
{AccountID: 11, Business: "sms", Price: 0.30, EffectiveAt: d("2026-11-01")},
}).Error; err != nil {
t.Fatal(err)
}
}
// seedProfitFlow 消耗(acc1:100/acc10:50/acc11:40/acc12:10 无价)+ 通道侧
// (ch1:150 + ch2:50=200,成本价均 0.04 → 总成本 8)。账号/通道成功总数一致=200。
func seedProfitFlow(t *testing.T, db *gorm.DB) {
t.Helper()
d := func(s string) time.Time {
v, _ := time.ParseInLocation("2006-01-02", s, time.Local)
return v
}
if err := db.Create(&[]entity.BillingConsumeLog{
{AccountID: 1, Business: "sms", StatDate: d("2026-11-10"), SuccessCount: 100},
{AccountID: 10, Business: "sms", StatDate: d("2026-11-10"), SuccessCount: 50},
{AccountID: 11, Business: "sms", StatDate: d("2026-11-20"), SuccessCount: 40},
{AccountID: 12, Business: "sms", StatDate: d("2026-11-10"), SuccessCount: 10},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.ChannelChannel{
{Model: entity.Model{ID: 1}, Name: "c1", Code: "pfc1", UpstreamID: 7},
{Model: entity.Model{ID: 2}, Name: "c2", Code: "pfc2"},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.ChannelPrice{
{ChannelID: 1, Price: 0.04, EffectiveAt: d("2026-11-01")},
{ChannelID: 2, Price: 0.04, EffectiveAt: d("2026-11-01")},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.StatsChannelDaily{
{ChannelID: 1, StatDate: d("2026-11-10"), SuccessCount: 150},
{ChannelID: 2, StatDate: d("2026-11-20"), SuccessCount: 50},
}).Error; err != nil {
t.Fatal(err)
}
}
// findRow 按账号取行。
func findRow(t *testing.T, res *UserProfitResult, id int64) UserProfitRow {
t.Helper()
for _, r := range res.List {
if r.AccountID == id {
return r
}
}
t.Fatalf("账号 %d 不在结果中: %+v", id, res.List)
return UserProfitRow{}
}
// TestProfit_Users 时间线价收入+占比分摊成本+单级返点+子树过滤+平台净利守恒。
//
// 期望:acc1 rev10/cost4/rebate1.0(=子10 rev10×0.10)/profit7;
// acc10 rev10/cost2/rebate2.4(=子11 rev12×0.20)/profit10.4;
// acc11 rev12/cost1.6/profit10.4;acc12 无价 rev0/cost0.4/profit-0.4;
// 汇总 rev32/cost8/rebate3.4/平台净利 32-8-3.4=20.6。
func TestProfit_Users(t *testing.T) {
db := newProfitDB(t)
seedProfitTree(t, db)
seedProfitFlow(t, db)
svc := NewService(db)
ctx := context.Background()
from, _ := time.ParseInLocation("2006-01-02", "2026-11-01", time.Local)
to, _ := time.ParseInLocation("2006-01-02", "2026-11-30", time.Local)
res, err := svc.UserProfit(ctx, UserProfitQuery{From: from, To: to})
if err != nil {
t.Fatal(err)
}
if res.Total != 4 || res.Summary.Count != 4 {
t.Fatalf("行数=%d/%d 期望 4", res.Total, res.Summary.Count)
}
r1 := findRow(t, res, 1)
if r1.SuccessCount != 100 || !feq(r1.Revenue, 10) || !feq(r1.Cost, 4) ||
!feq(r1.Rebate, 1.0) || !feq(r1.Profit, 7) {
t.Fatalf("acc1 错: %+v", r1)
}
r10 := findRow(t, res, 10)
if !feq(r10.Revenue, 10) || !feq(r10.Cost, 2) || !feq(r10.Rebate, 2.4) || !feq(r10.Profit, 10.4) {
t.Fatalf("acc10 错: %+v", r10)
}
r11 := findRow(t, res, 11)
if !feq(r11.Revenue, 12) || !feq(r11.Cost, 1.6) || r11.Rebate != 0 || !feq(r11.Profit, 10.4) {
t.Fatalf("acc11 错: %+v", r11)
}
r12 := findRow(t, res, 12)
if r12.Revenue != 0 || !feq(r12.Cost, 0.4) || !feq(r12.Profit, -0.4) {
t.Fatalf("acc12 错(无价 0 元入账): %+v", r12)
}
s := res.Summary
if !feq(s.TotalRevenue, 32) || !feq(s.TotalCost, 8) || !feq(s.TotalRebate, 3.4) ||
!feq(s.PlatformProfit, 20.6) {
t.Fatalf("汇总错: %+v", s)
}
// 子树过滤 parent_id=10:仅 10/11 两行,汇总随 scope 收窄。
res, err = svc.UserProfit(ctx, UserProfitQuery{From: from, To: to, ParentID: 10})
if err != nil {
t.Fatal(err)
}
if res.Total != 2 || res.Summary.Count != 2 {
t.Fatalf("子树行数=%d 期望 2", res.Total)
}
findRow(t, res, 10)
findRow(t, res, 11)
if !feq(res.Summary.TotalRevenue, 22) || !feq(res.Summary.TotalCost, 3.6) ||
!feq(res.Summary.TotalRebate, 2.4) {
t.Fatalf("子树汇总错: %+v", res.Summary)
}
// parent 不存在 → 404 业务错误。
if _, err := svc.UserProfit(ctx, UserProfitQuery{From: from, To: to, ParentID: 999}); err == nil {
t.Fatal("parent_id=999 应报错")
}
}
// TestProfit_Users_ParentWithoutTraffic 无自身流量的上级也有行(代理纯返点场景)。
func TestProfit_Users_ParentWithoutTraffic(t *testing.T) {
db := newProfitDB(t)
d := func(s string) time.Time {
v, _ := time.ParseInLocation("2006-01-02", s, time.Local)
return v
}
if err := db.Create(&[]entity.AccountUser{
{Model: entity.Model{ID: 20}, Username: "agent", Role: "group", Path: "/20/"},
{Model: entity.Model{ID: 21}, Username: "c21", Role: "customer", ParentID: 20, Path: "/20/21/", RebateRate: 0.5},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.AccountPrice{
{AccountID: 21, Business: "sms", Price: 0.10, EffectiveAt: d("2026-11-01")},
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.BillingConsumeLog{
{AccountID: 21, Business: "sms", StatDate: d("2026-11-10"), SuccessCount: 100},
}).Error; err != nil {
t.Fatal(err)
}
res, err := NewService(db).UserProfit(context.Background(), UserProfitQuery{
From: d("2026-11-01"), To: d("2026-11-30"),
})
if err != nil {
t.Fatal(err)
}
if res.Total != 2 {
t.Fatalf("行数=%d 期望 2(agent+c21)", res.Total)
}
agent := findRow(t, res, 20)
if agent.SuccessCount != 0 || agent.Revenue != 0 || !feq(agent.Rebate, 5.0) || !feq(agent.Profit, 5.0) {
t.Fatalf("agent 行错(纯返点): %+v", agent)
}
}
// TestProfit_Channels 通道成本直算+收入占比分摊+channel_id 过滤。
// ch1: succ150 cost6(150×0.04) rev24(32×150/200) profit18;
// ch2: succ50 cost2 rev8 profit6。
func TestProfit_Channels(t *testing.T) {
db := newProfitDB(t)
seedProfitTree(t, db)
seedProfitFlow(t, db)
svc := NewService(db)
ctx := context.Background()
from, _ := time.ParseInLocation("2006-01-02", "2026-11-01", time.Local)
to, _ := time.ParseInLocation("2006-01-02", "2026-11-30", time.Local)
res, err := svc.ChannelProfit(ctx, ChannelProfitQuery{From: from, To: to})
if err != nil {
t.Fatal(err)
}
if res.Total != 2 {
t.Fatalf("通道行数=%d 期望 2", res.Total)
}
if res.List[0].ChannelID != 1 { // succ 降序
t.Fatalf("排序错: %+v", res.List)
}
c1 := res.List[0]
if c1.Name != "c1" || c1.UpstreamID != 7 || c1.SuccessCount != 150 ||
!feq(c1.Cost, 6) || !feq(c1.Revenue, 24) || !feq(c1.Profit, 18) {
t.Fatalf("ch1 错: %+v", c1)
}
c2 := res.List[1]
if !feq(c2.Cost, 2) || !feq(c2.Revenue, 8) || !feq(c2.Profit, 6) {
t.Fatalf("ch2 错: %+v", c2)
}
// channel_id 过滤。
res, err = svc.ChannelProfit(ctx, ChannelProfitQuery{From: from, To: to, ChannelID: 2})
if err != nil || res.Total != 1 || res.List[0].ChannelID != 2 {
t.Fatalf("过滤错: %+v err=%v", res, err)
}
}
+235
View File
@@ -0,0 +1,235 @@
// reconcile.go S2-D5:三方对账——明细直查 vs 日汇总(R2 事实源)vs 结算单,
// diff=0 为 S2 泳道出口判据(《重建计划》S2 行)。
//
// 比对口径(全部为**条数**,status=2 成功侧):
// - 账号三方:message_detail 直查聚合 ↔ billing_consume_log 月和 ↔
// settle_customer.success_count(有单才比;未生成=流程状态,BillMissing
// 单列不判失败);
// - 通道两方:message_detail 直查聚合 ↔ stats_channel_daily 月和;
// - 上家:settle_upstream 快照 ↔ 日汇总×**当前**通道归并/billing_mode 重推
// (Q4/Q6 快照语义:生成后换绑/改模式/重刷会如实暴露差异——这正是对账目的);
// - 金额不比:结算单金额是出账时点价/阶梯快照(Q6),事后调价重算必生噪音;
// 金额核对走账单导出 XLSX 人工比对(D4 已验)。
// 注意:明细热窗仅 5 天(S4 分区规划)——历史月的"明细直查"侧在数据清退后
// 不再完整,届时对账基线=日汇总 vs 结算单两方;当前 dev 明细全量在库。
package settle
import (
"context"
"time"
"go-sms/internal/model/entity"
)
// ReconcileSummary 对账汇总计数。
type ReconcileSummary struct {
AccountsChecked int `json:"accounts_checked"` // 账号并集(明细∪汇总∪账单)
AccountDiffs int `json:"account_diffs"` // 账号侧差异行数
BillMissing int `json:"bill_missing"` // 有消耗无账单(流程状态,不判失败)
ChannelsChecked int `json:"channels_checked"` // 通道并集(明细∪汇总)
ChannelDiffs int `json:"channel_diffs"` // 通道侧差异行数
UpstreamsChecked int `json:"upstreams_checked"` // 上家并集(重推∪账单)
UpstreamDiffs int `json:"upstream_diffs"` // 上家侧差异行数(缺账单不计入)
AllZero bool `json:"all_zero"` // 三方差异全零(S2 出口判据)
}
// AccountDiffRow 账号对账行(仅差异/缺单账号入列)。
type AccountDiffRow struct {
AccountID int64 `json:"account_id"`
DetailSuccess int64 `json:"detail_success"` // 明细直查
ConsumeSuccess int64 `json:"consume_success"` // 日汇总
BillSuccess *int64 `json:"bill_success"` // 结算单(nil=未生成)
}
// ChannelDiffRow 通道对账行(仅差异通道入列)。
type ChannelDiffRow struct {
ChannelID int64 `json:"channel_id"`
DetailSuccess int64 `json:"detail_success"`
DailySuccess int64 `json:"daily_success"`
}
// UpstreamDiffRow 上家对账行(差异/缺单入列;重推=当前归并×当前口径)。
type UpstreamDiffRow struct {
UpstreamID int64 `json:"upstream_id"`
DailyCount int64 `json:"daily_count"` // 日汇总重推
BillSuccess *int64 `json:"bill_success"` // 账单快照(nil=未生成)
}
// ReconcileReport 对账报告(AsOf 时点;rows 仅异常行,全对=空)。
type ReconcileReport struct {
Period string `json:"period"`
AsOf time.Time `json:"as_of"`
Accounts []AccountDiffRow `json:"accounts"`
Channels []ChannelDiffRow `json:"channels"`
Upstreams []UpstreamDiffRow `json:"upstreams"`
Summary ReconcileSummary `json:"summary"`
}
// successAgg 明细直查聚合 DTO。
type successAgg struct {
ID int64
N int64
}
// detailSuccessBy 明细直查:窗口内按 key 维度聚合成功条数(ground truth)。
func (s *Service) detailSuccessBy(ctx context.Context, lo, hi time.Time, key string) (map[int64]int64, error) {
var rows []successAgg
if err := s.db.WithContext(ctx).Table("message_detail").
Select(key+" AS id, COALESCE(SUM(status = 2), 0) AS n").
Where("created_at >= ? AND created_at < ?", lo, hi).
Group(key).Scan(&rows).Error; err != nil {
return nil, err
}
out := make(map[int64]int64, len(rows))
for _, r := range rows {
out[r.ID] = r.N
}
return out, nil
}
// ReconcilePeriod 三方对账(period=YYYY-MM)。
func (s *Service) ReconcilePeriod(ctx context.Context, period string) (*ReconcileReport, error) {
lo, hi, err := PeriodBounds(period)
if err != nil {
return nil, err
}
rep := &ReconcileReport{Period: period, AsOf: time.Now(),
Accounts: []AccountDiffRow{}, Channels: []ChannelDiffRow{}, Upstreams: []UpstreamDiffRow{}}
// ① 账号三方:明细直查 ↔ 消耗日汇总 ↔ 下家结算单。
detailAcc, err := s.detailSuccessBy(ctx, lo, hi, "account_id")
if err != nil {
return nil, err
}
consumeAcc := map[int64]int64{}
var consumeRows []entity.BillingConsumeLog
if err := s.db.WithContext(ctx).
Where("stat_date >= ? AND stat_date < ?", lo, hi).Find(&consumeRows).Error; err != nil {
return nil, err
}
for _, r := range consumeRows {
consumeAcc[r.AccountID] += int64(r.SuccessCount)
}
var bills []entity.SettleCustomer
if err := s.db.WithContext(ctx).
Where("period = ?", period).Find(&bills).Error; err != nil {
return nil, err
}
billAcc := map[int64]entity.SettleCustomer{}
for _, b := range bills {
billAcc[b.AccountID] = b
}
accUnion := map[int64]struct{}{}
for id := range detailAcc {
accUnion[id] = struct{}{}
}
for id := range consumeAcc {
accUnion[id] = struct{}{}
}
for id := range billAcc {
accUnion[id] = struct{}{}
}
rep.Summary.AccountsChecked = len(accUnion)
for id := range accUnion {
d, c := detailAcc[id], consumeAcc[id]
bill, hasBill := billAcc[id]
billMismatch := hasBill && int64(bill.SuccessCount) != c
if d != c || billMismatch {
row := AccountDiffRow{AccountID: id, DetailSuccess: d, ConsumeSuccess: c}
if hasBill {
bs := int64(bill.SuccessCount)
row.BillSuccess = &bs
}
rep.Accounts = append(rep.Accounts, row)
rep.Summary.AccountDiffs++
} else if !hasBill {
rep.Accounts = append(rep.Accounts,
AccountDiffRow{AccountID: id, DetailSuccess: d, ConsumeSuccess: c})
rep.Summary.BillMissing++
}
}
// ② 通道两方:明细直查 ↔ 通道日汇总。
detailCh, err := s.detailSuccessBy(ctx, lo, hi, "channel_id")
if err != nil {
return nil, err
}
dailyCh := map[int64]int64{}
var statRows []entity.StatsChannelDaily
if err := s.db.WithContext(ctx).
Where("stat_date >= ? AND stat_date < ?", lo, hi).Find(&statRows).Error; err != nil {
return nil, err
}
for _, r := range statRows {
dailyCh[r.ChannelID] += int64(r.SuccessCount)
}
chUnion := map[int64]struct{}{}
for id := range detailCh {
chUnion[id] = struct{}{}
}
for id := range dailyCh {
chUnion[id] = struct{}{}
}
rep.Summary.ChannelsChecked = len(chUnion)
for id := range chUnion {
if detailCh[id] != dailyCh[id] {
rep.Channels = append(rep.Channels,
ChannelDiffRow{ChannelID: id, DetailSuccess: detailCh[id], DailySuccess: dailyCh[id]})
rep.Summary.ChannelDiffs++
}
}
// ③ 上家:日汇总×当前归并/口径重推 ↔ 账单快照。
dailyUp := map[int64]int64{}
var channels []entity.ChannelChannel
if err := s.db.WithContext(ctx).Find(&channels).Error; err != nil {
return nil, err
}
modeOf := map[int64]string{}
upstreamOf := map[int64]int64{}
for _, ch := range channels {
modeOf[ch.ID] = ch.BillingMode
upstreamOf[ch.ID] = ch.UpstreamID
}
for _, r := range statRows {
uid := upstreamOf[r.ChannelID]
if uid == 0 {
continue
}
dailyUp[uid] += int64(billableCount(modeOf[r.ChannelID], r))
}
var upBills []entity.SettleUpstream
if err := s.db.WithContext(ctx).
Where("period = ?", period).Find(&upBills).Error; err != nil {
return nil, err
}
billUp := map[int64]entity.SettleUpstream{}
for _, b := range upBills {
billUp[b.UpstreamID] = b
}
upUnion := map[int64]struct{}{}
for id := range dailyUp {
upUnion[id] = struct{}{}
}
for id := range billUp {
upUnion[id] = struct{}{}
}
rep.Summary.UpstreamsChecked = len(upUnion)
for id := range upUnion {
bill, hasBill := billUp[id]
if hasBill && int64(bill.SuccessCount) != dailyUp[id] {
bs := int64(bill.SuccessCount)
rep.Upstreams = append(rep.Upstreams,
UpstreamDiffRow{UpstreamID: id, DailyCount: dailyUp[id], BillSuccess: &bs})
rep.Summary.UpstreamDiffs++
} else if !hasBill {
// 有日汇总无账单:与账号侧 BillMissing 同语义,列行不计数。
rep.Upstreams = append(rep.Upstreams,
UpstreamDiffRow{UpstreamID: id, DailyCount: dailyUp[id]})
}
}
rep.Summary.AllZero = rep.Summary.AccountDiffs == 0 &&
rep.Summary.ChannelDiffs == 0 && rep.Summary.UpstreamDiffs == 0
return rep, nil
}
+174
View File
@@ -0,0 +1,174 @@
package settle
// reconcile_test.go S2-D5:三方对账单测——全链一致性(明细→日汇总→账单)
// diff=0;篡改各事实源逐项暴露差异;缺账单=流程状态不判失败。
import (
"context"
"testing"
"time"
"gorm.io/gorm"
"go-sms/internal/model/entity"
)
// seedReconcile 全链种子:明细(11-10:acc1 ch1 2成功+1未知;acc2 ch2 1成功)
// → AggregateDay → 双向出账。ch1 绑上家 7 且 success_unknown 口径,ch2 绑 7 默认 success。
func seedReconcile(t *testing.T, db *gorm.DB) {
t.Helper()
day, _ := time.ParseInLocation("2006-01-02 15:04", "2026-11-10 12:00", time.Local)
details := []entity.MessageDetail{
{SnowflakeModel: entity.SnowflakeModel{ID: 9200000001, CreatedAt: day},
TaskID: 900001, AccountID: 1, ChannelID: 1, Mobile: "13000000001",
Content: "t", Status: 2, Business: "sms", Fee: 1},
{SnowflakeModel: entity.SnowflakeModel{ID: 9200000002, CreatedAt: day},
TaskID: 900002, AccountID: 1, ChannelID: 1, Mobile: "13000000002",
Content: "t", Status: 2, Business: "sms", Fee: 1},
{SnowflakeModel: entity.SnowflakeModel{ID: 9200000003, CreatedAt: day},
TaskID: 900003, AccountID: 1, ChannelID: 1, Mobile: "13000000003",
Content: "t", Status: 4, Business: "sms", Fee: 1},
{SnowflakeModel: entity.SnowflakeModel{ID: 9200000004, CreatedAt: day},
TaskID: 900004, AccountID: 2, ChannelID: 2, Mobile: "13000000004",
Content: "t", Status: 2, Business: "sms", Fee: 1},
}
if err := db.Create(&details).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]entity.ChannelChannel{
{Model: entity.Model{ID: 1}, Name: "c1", Code: "rcc1", UpstreamID: 7, BillingMode: "success_unknown"},
{Model: entity.Model{ID: 2}, Name: "c2", Code: "rcc2", UpstreamID: 7},
}).Error; err != nil {
t.Fatal(err)
}
svc := NewService(db)
ctx := context.Background()
if _, _, err := svc.AggregateDay(ctx, day); err != nil {
t.Fatal(err)
}
if _, err := svc.GenerateCustomerBills(ctx, "2026-11"); err != nil {
t.Fatal(err)
}
if _, err := svc.GenerateUpstreamBills(ctx, "2026-11"); err != nil {
t.Fatal(err)
}
}
// TestReconcile_AllZero 全链一致:三方零差异(S2 出口判据)。
// 账号:acc1 明细2=汇总2=账单2;acc2 1=1=1。通道:ch1 2=2;ch2 1=1。
// 上家 7:重推(2+1未知)+(1)=4=账单 4。
func TestReconcile_AllZero(t *testing.T) {
db := newBillDB(t)
seedReconcile(t, db)
rep, err := NewService(db).ReconcilePeriod(context.Background(), "2026-11")
if err != nil {
t.Fatal(err)
}
s := rep.Summary
if !s.AllZero || s.AccountDiffs != 0 || s.ChannelDiffs != 0 || s.UpstreamDiffs != 0 {
t.Fatalf("应全零: %+v rows=%+v/%+v/%+v", s, rep.Accounts, rep.Channels, rep.Upstreams)
}
if s.AccountsChecked != 2 || s.BillMissing != 0 || s.ChannelsChecked != 2 || s.UpstreamsChecked != 1 {
t.Fatalf("checked 计数错: %+v", s)
}
var bill1, bill2 entity.SettleCustomer
var up7 entity.SettleUpstream
if err := db.Where("account_id = 1").First(&bill1).Error; err != nil {
t.Fatal(err)
}
if err := db.Where("account_id = 2").First(&bill2).Error; err != nil {
t.Fatal(err)
}
if err := db.Where("upstream_id = 7").First(&up7).Error; err != nil {
t.Fatal(err)
}
if bill1.SuccessCount != 2 || bill2.SuccessCount != 1 || up7.SuccessCount != 4 {
t.Fatalf("账单快照错: %+v/%+v/%+v", bill1, bill2, up7)
}
}
// TestReconcile_ExposesDiffs 篡改三处事实源逐项暴露:
// ①consume acc1 success 2→5 → AccountDiffs=1(明细2/汇总5/账单2 同行列出);
// ②stats ch1 success 2→9 → ChannelDiffs=1(明细2/日汇总9)+ 上家重推(9+1)+1=11
// vs 账单4 → UpstreamDiffs=1;③删 acc2 账单 → BillMissing=1 且 AllZero 仍真
// (在①②还原后单独验证:此处先验证 missing 计数,AllZero 断言只看 diffs)。
func TestReconcile_ExposesDiffs(t *testing.T) {
db := newBillDB(t)
seedReconcile(t, db)
svc := NewService(db)
ctx := context.Background()
// ① 篡改消耗日汇总。
if err := db.Model(&entity.BillingConsumeLog{}).
Where("account_id = 1").Update("success_count", 5).Error; err != nil {
t.Fatal(err)
}
// ② 篡改通道日汇总。
if err := db.Model(&entity.StatsChannelDaily{}).
Where("channel_id = 1").Update("success_count", 9).Error; err != nil {
t.Fatal(err)
}
rep, err := svc.ReconcilePeriod(ctx, "2026-11")
if err != nil {
t.Fatal(err)
}
if rep.Summary.AccountDiffs != 1 || len(rep.Accounts) != 1 {
t.Fatalf("账号差异应 1 行: %+v rows=%+v", rep.Summary, rep.Accounts)
}
a := rep.Accounts[0]
if a.AccountID != 1 || a.DetailSuccess != 2 || a.ConsumeSuccess != 5 ||
a.BillSuccess == nil || *a.BillSuccess != 2 {
t.Fatalf("账号差异行错: %+v", a)
}
if rep.Summary.ChannelDiffs != 1 || len(rep.Channels) != 1 ||
rep.Channels[0].ChannelID != 1 || rep.Channels[0].DetailSuccess != 2 || rep.Channels[0].DailySuccess != 9 {
t.Fatalf("通道差异行错: %+v", rep.Channels)
}
if rep.Summary.UpstreamDiffs != 1 || len(rep.Upstreams) != 1 {
t.Fatalf("上家差异应 1 行: %+v", rep.Upstreams)
}
u := rep.Upstreams[0]
if u.UpstreamID != 7 || u.DailyCount != 11 || u.BillSuccess == nil || *u.BillSuccess != 4 {
t.Fatalf("上家差异行错(重推 9+1未知+1=11 vs 账单 4): %+v", u)
}
if rep.Summary.AllZero {
t.Fatal("存在差异时 AllZero 应为 false")
}
// ③ 还原①②后删下家账单:BillMissing=1,但 diffs 全零 → AllZero 仍真。
if err := db.Model(&entity.BillingConsumeLog{}).
Where("account_id = 1").Update("success_count", 2).Error; err != nil {
t.Fatal(err)
}
if err := db.Model(&entity.StatsChannelDaily{}).
Where("channel_id = 1").Update("success_count", 2).Error; err != nil {
t.Fatal(err)
}
if err := db.Where("account_id = 2").Delete(&entity.SettleCustomer{}).Error; err != nil {
t.Fatal(err)
}
rep, err = svc.ReconcilePeriod(ctx, "2026-11")
if err != nil {
t.Fatal(err)
}
if rep.Summary.BillMissing != 1 || rep.Summary.AccountDiffs != 0 {
t.Fatalf("缺账单应 BillMissing=1 且 diffs=0: %+v", rep.Summary)
}
if !rep.Summary.AllZero {
t.Fatalf("缺账单=流程状态,不应判失败: %+v", rep.Summary)
}
var missing int
for _, r := range rep.Accounts {
if r.AccountID == 2 && r.BillSuccess == nil {
missing++
}
}
if missing != 1 {
t.Fatalf("acc2 应以 bill_success=nil 列出: %+v", rep.Accounts)
}
// ④ 非法 period → ISC:400。
if _, err := svc.ReconcilePeriod(ctx, "2026-1"); err == nil {
t.Fatal("非法 period 应报错")
}
}