divide_service_test.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. // DivideService 单测(AC-09):100 节点随机树不变式 / BFS 上游入账 / 两级幂等 / 撤销两分支 /
  2. // 额度级联下降。
  3. //
  4. // 测试栈:glebarez/sqlite 文件库(真实事务)。每个用例独立 DB,避免树区间互相污染。
  5. package service
  6. import (
  7. "context"
  8. "errors"
  9. "fmt"
  10. "math/rand"
  11. "path/filepath"
  12. "strings"
  13. "testing"
  14. "time"
  15. gormsqlite "github.com/glebarez/sqlite"
  16. "gorm.io/gorm"
  17. "yuansiwei/unified-backend/internal/academic/apperr"
  18. "yuansiwei/unified-backend/internal/academic/model"
  19. "yuansiwei/unified-backend/internal/academic/money"
  20. "yuansiwei/unified-backend/internal/academic/repository"
  21. infraerrors "yuansiwei/unified-backend/internal/infra/errors"
  22. )
  23. // newDivideServiceDB 分账域真实库(2 表 AutoMigrate)。
  24. func newDivideServiceDB(t *testing.T) *gorm.DB {
  25. t.Helper()
  26. dsn := filepath.Join(t.TempDir(), "academic_divide_service_test.db")
  27. db, err := gorm.Open(gormsqlite.Open(dsn), &gorm.Config{})
  28. if err != nil {
  29. t.Fatalf("gorm.Open(分账服务文件库) 失败: %v", err)
  30. }
  31. t.Cleanup(func() {
  32. if sqlDB, e := db.DB(); e == nil {
  33. _ = sqlDB.Close()
  34. }
  35. })
  36. if err := db.AutoMigrate(&model.UserDivideInto{}, &model.UserDivideIntoLog{}); err != nil {
  37. t.Fatalf("AutoMigrate(分账 2 表) 失败: %v", err)
  38. }
  39. return db
  40. }
  41. // nodeID 生成 26 位类 ULID 的测试用户 ID(t_user_divide_into.user_id 为 VARCHAR(26))。
  42. func nodeID(i int) string { return fmt.Sprintf("01H%023d", i) }
  43. // seedRoot 直接落一棵树的根节点(dump 中根节点由后台/迁移建立,不在 4 个 SP 范围内)。
  44. func seedRoot(t *testing.T, db *gorm.DB, userID string, typ int8, quota string) {
  45. t.Helper()
  46. root := userID
  47. row := &model.UserDivideInto{
  48. UserID: userID,
  49. Type: typ,
  50. Quota: quota,
  51. TotalIncome: "0.00",
  52. TotalIncomePayed: "0.00",
  53. RootUserID: &root,
  54. LeftVal: 1,
  55. RightVal: 2,
  56. Layer: 1,
  57. }
  58. if err := db.Create(row).Error; err != nil {
  59. t.Fatalf("seed 根节点(%s) 失败: %v", userID, err)
  60. }
  61. }
  62. // loadDivideNode 读节点。
  63. func loadDivideNode(t *testing.T, db *gorm.DB, userID string) model.UserDivideInto {
  64. t.Helper()
  65. var row model.UserDivideInto
  66. if err := db.Where("user_id = ?", userID).First(&row).Error; err != nil {
  67. t.Fatalf("读节点(%s) 失败: %v", userID, err)
  68. }
  69. return row
  70. }
  71. // cents 金额字符串 → 分(sqlite NUMERIC 回读会丢 ".00",不得比字符串)。
  72. func cents(t *testing.T, s string) int64 {
  73. t.Helper()
  74. amt, err := money.Parse(s)
  75. if err != nil {
  76. t.Fatalf("金额解析失败 %q: %v", s, err)
  77. }
  78. return amt.Cents()
  79. }
  80. // fakeFirstCharged 首次扣费记录端口的测试替身。
  81. type fakeFirstCharged struct {
  82. recordID int64
  83. found bool
  84. err error
  85. calls int
  86. }
  87. // FirstChargedRecordID 实现 FirstChargedRecordReader。
  88. func (f *fakeFirstCharged) FirstChargedRecordID(_ context.Context, _ string) (int64, bool, error) {
  89. f.calls++
  90. return f.recordID, f.found, f.err
  91. }
  92. // TestAddSubordinateNestedSetInvariants 100 节点随机树:left<right、区间嵌套无交叉、
  93. // 节点数 = 宽度/2、值集合恰好 1..2N、父区间包含子区间。
  94. func TestAddSubordinateNestedSetInvariants(t *testing.T) {
  95. db := newDivideServiceDB(t)
  96. svc := NewDivideService(db, nil)
  97. ctx := context.Background()
  98. root := nodeID(0)
  99. seedRoot(t, db, root, model.DivideTypeOneOff, "10.00")
  100. created := []string{root}
  101. rnd := rand.New(rand.NewSource(20260109))
  102. const total = 100
  103. // 层高登记:F20 之后 AddSubordinate 有 3 层业务上限,**随机挂父会随机撞 3111**。
  104. // 本用例测的是嵌套集不变量(100 个节点),不是层数上限,
  105. // 所以把随机空间限制在「还能再挂子节点」的节点里(layer < MaxDivideBizDepth),
  106. // 保持原意:树可以很宽,但不许超过业务层数。
  107. layers := map[string]int32{root: 1}
  108. for i := 1; i < total; i++ {
  109. candidates := make([]string, 0, len(created))
  110. for _, u := range created {
  111. if layers[u] < MaxDivideBizDepth {
  112. candidates = append(candidates, u)
  113. }
  114. }
  115. if len(candidates) == 0 { // 兜底:根节点 layer=1 恒可挂,理论上不会发生
  116. t.Fatalf("没有可挂子节点的父节点(layer < %d)", MaxDivideBizDepth)
  117. }
  118. parent := candidates[rnd.Intn(len(candidates))]
  119. child := nodeID(i)
  120. if err := svc.AddSubordinate(ctx, parent, child); err != nil {
  121. t.Fatalf("AddSubordinate(%s→%s) 失败: %v", parent, child, err)
  122. }
  123. layers[child] = layers[parent] + 1
  124. created = append(created, child)
  125. }
  126. var nodes []model.UserDivideInto
  127. if err := db.Find(&nodes).Error; err != nil {
  128. t.Fatalf("读全树失败: %v", err)
  129. }
  130. if len(nodes) != total {
  131. t.Fatalf("节点数应为 %d,实得 %d", total, len(nodes))
  132. }
  133. // ① left < right 且值集合 = {1..2N}(每值恰好一次)
  134. seen := make(map[int32]string, total*2)
  135. maxRight := int32(0)
  136. for i := range nodes {
  137. n := nodes[i]
  138. if n.LeftVal >= n.RightVal {
  139. t.Fatalf("节点 %s 违反 left<right:(%d,%d)", n.UserID, n.LeftVal, n.RightVal)
  140. }
  141. for _, v := range []int32{n.LeftVal, n.RightVal} {
  142. if prev, dup := seen[v]; dup {
  143. t.Fatalf("左/右值 %d 被重复使用(%s 与 %s),嵌套集区间损坏", v, prev, n.UserID)
  144. }
  145. seen[v] = n.UserID
  146. }
  147. if n.RightVal > maxRight {
  148. maxRight = n.RightVal
  149. }
  150. }
  151. if len(seen) != total*2 || maxRight != int32(total*2) {
  152. t.Fatalf("值集合应为 1..%d(共 %d 个),实得 %d 个、max=%d", total*2, total*2, len(seen), maxRight)
  153. }
  154. // ② 节点数 = 宽度/2(Nested Set 恒等式)
  155. if got := int(maxRight / 2); got != total {
  156. t.Fatalf("节点数应 = maxRight/2 = %d,实得 %d", total, got)
  157. }
  158. // ③ 任意两节点区间:包含或相离,**绝不交叉**
  159. for i := 0; i < len(nodes); i++ {
  160. for j := i + 1; j < len(nodes); j++ {
  161. a, b := nodes[i], nodes[j]
  162. nested := (a.LeftVal < b.LeftVal && b.RightVal < a.RightVal) ||
  163. (b.LeftVal < a.LeftVal && a.RightVal < b.RightVal)
  164. disjoint := a.RightVal < b.LeftVal || b.RightVal < a.LeftVal
  165. if !nested && !disjoint {
  166. t.Fatalf("区间交叉:%s(%d,%d) vs %s(%d,%d)", a.UserID, a.LeftVal, a.RightVal, b.UserID, b.LeftVal, b.RightVal)
  167. }
  168. }
  169. }
  170. // ④ 父区间严格包含子区间,且 layer = 父 layer+1
  171. byID := make(map[string]model.UserDivideInto, len(nodes))
  172. for i := range nodes {
  173. byID[nodes[i].UserID] = nodes[i]
  174. }
  175. for i := range nodes {
  176. n := nodes[i]
  177. if n.ParentUserID == nil || *n.ParentUserID == "" {
  178. if n.UserID != root {
  179. t.Fatalf("非根节点 %s 缺少 parent", n.UserID)
  180. }
  181. continue
  182. }
  183. parent, ok := byID[*n.ParentUserID]
  184. if !ok {
  185. t.Fatalf("节点 %s 的 parent %s 不在树中", n.UserID, *n.ParentUserID)
  186. }
  187. if !(parent.LeftVal < n.LeftVal && n.RightVal < parent.RightVal) {
  188. t.Fatalf("%s 未嵌套在父 %s 区间内:父(%d,%d) 子(%d,%d)",
  189. n.UserID, parent.UserID, parent.LeftVal, parent.RightVal, n.LeftVal, n.RightVal)
  190. }
  191. if n.Layer != parent.Layer+1 {
  192. t.Fatalf("%s layer 应为父+1(%d),实得 %d", n.UserID, parent.Layer+1, n.Layer)
  193. }
  194. }
  195. }
  196. // TestAddSubordinateGuards 入参/上级缺失/自环。
  197. func TestAddSubordinateGuards(t *testing.T) {
  198. db := newDivideServiceDB(t)
  199. svc := NewDivideService(db, nil)
  200. ctx := context.Background()
  201. root := nodeID(0)
  202. seedRoot(t, db, root, model.DivideTypeOneOff, "10.00")
  203. if err := svc.AddSubordinate(ctx, "", nodeID(1)); !errors.Is(err, apperr.ErrBusinessParam) {
  204. t.Fatalf("空上级应 3140,实得 %v", err)
  205. }
  206. if err := svc.AddSubordinate(ctx, root, root); !errors.Is(err, apperr.ErrBusinessParam) {
  207. t.Fatalf("自环应 3140,实得 %v", err)
  208. }
  209. if err := svc.AddSubordinate(ctx, nodeID(99), nodeID(1)); !errors.Is(err, infraerrors.ErrNotFound) {
  210. t.Fatalf("上级不存在应 3001,实得 %v", err)
  211. }
  212. var zero *DivideService
  213. if err := zero.AddSubordinate(ctx, root, nodeID(1)); !errors.Is(err, infraerrors.ErrInternal) {
  214. t.Fatalf("未装配服务应 ErrInternal,实得 %v", err)
  215. }
  216. }
  217. // TestAddSubordinateReparentBranch 已存在节点分支:改挂父链并显式补齐 root(dump NULL 缺陷修正)。
  218. // TestAddSubordinateExistingNodeNoop 已存在 subid → **完全 no-op**(audit D4,dump 763695)。
  219. //
  220. // dump 的 `if exists(... where userid = subid) then ... end if;` 分支体内**没有任何写动作**:
  221. // 已存在即视为幂等成功,parent/root/layer/左右值一律不动。
  222. // 旧实现会"改挂父链",等于凭空移动整棵子树且不重排左右值 → 破坏嵌套集不变式(本次删除)。
  223. func TestAddSubordinateExistingNodeNoop(t *testing.T) {
  224. db := newDivideServiceDB(t)
  225. svc := NewDivideService(db, nil)
  226. ctx := context.Background()
  227. root := nodeID(0)
  228. orphan := nodeID(50)
  229. seedRoot(t, db, root, model.DivideTypeOneOff, "10.00")
  230. // 模拟 dump 脏数据:subid 已存在、parent/root 均为 NULL
  231. if err := db.Create(&model.UserDivideInto{
  232. UserID: orphan, Type: model.DivideTypeOneOff, Quota: "0.00",
  233. TotalIncome: "0.00", TotalIncomePayed: "0.00",
  234. LeftVal: 100, RightVal: 101, Layer: 1,
  235. }).Error; err != nil {
  236. t.Fatalf("seed 孤立节点失败: %v", err)
  237. }
  238. if err := svc.AddSubordinate(ctx, root, orphan); err != nil {
  239. t.Fatalf("已存在节点应幂等成功(no-op),实得 %v", err)
  240. }
  241. got := loadDivideNode(t, db, orphan)
  242. if got.ParentUserID != nil {
  243. t.Fatalf("已存在节点不得改挂父链(dump 763695 分支体无写动作),实得 parent=%v", *got.ParentUserID)
  244. }
  245. if got.RootUserID != nil {
  246. t.Fatalf("已存在节点不得写 root_user_id,实得 %v", *got.RootUserID)
  247. }
  248. if got.Layer != 1 {
  249. t.Fatalf("layer 不应变化(应 1),实得 %d", got.Layer)
  250. }
  251. if got.LeftVal != 100 || got.RightVal != 101 {
  252. t.Fatalf("左右值不应重排,实得 (%d,%d)", got.LeftVal, got.RightVal)
  253. }
  254. // 重复调用同样 no-op(幂等)
  255. if err := svc.AddSubordinate(ctx, root, orphan); err != nil {
  256. t.Fatalf("重复调用应幂等成功,实得 %v", err)
  257. }
  258. }
  259. // TestAddSubordinateBizDepthLimit 业务层级上限 3 层 → 3111(超管 → 校区主任 → 老师)。
  260. //
  261. // 边界取**恰好**:layer=1,2,3 允许(3 = MaxDivideBizDepth),第 4 层被拒。
  262. // 这条断言的产品含义:前端 `divide-into.ts:26 MAX_DIVIDE_DEPTH = 3` 只是"界面不让你点",
  263. // 若后端也允许第 4 层,绕过前端就能建出前端渲染不出来的树。
  264. func TestAddSubordinateBizDepthLimit(t *testing.T) {
  265. db := newDivideServiceDB(t)
  266. svc := NewDivideService(db, nil)
  267. ctx := context.Background()
  268. // ⚠ 这里**故意写死 3**,不用 MaxDivideBizDepth。
  269. // 原因:这条用例验的是"产品拍板的规则",规则的**值本身就是被测对象**。
  270. // 若写成 `for i := 1; i < int(MaxDivideBizDepth)`,常量被改成 100 时用例会跟着
  271. // 建到 100 层、再断言第 101 层被拒 —— 仍然通过,看起来"守住了规则",其实什么也没守
  272. // (实测过:常量改 100,用常量写法的版本仍 PASS)。这种自指断言正是空过断言的一种。
  273. const bizDepth = 3 // 硬编码:超管 → 校区主任 → 老师(拍板 2026-11-10)
  274. if MaxDivideBizDepth != bizDepth {
  275. t.Fatalf("常量 MaxDivideBizDepth=%d 与拍板值 %d 不一致", MaxDivideBizDepth, bizDepth)
  276. }
  277. root := nodeID(0)
  278. seedRoot(t, db, root, model.DivideTypeOneOff, "1.00")
  279. prev := root
  280. // **正向断言不可省**:建到 3 层,每一层都必须真建出来。
  281. // 只断言"第 4 层被拒"是不够的 —— 把上限误写成 2 时,这个用例只测被拒的那半也照样绿,
  282. // 而生产上第 3 层就再也建不出来了(存量里 MAX(layer)=2,说明第 3 层从未被验证过)。
  283. for i := 1; i < bizDepth; i++ {
  284. child := nodeID(i)
  285. if err := svc.AddSubordinate(ctx, prev, child); err != nil {
  286. t.Fatalf("建第 %d 层失败(上限 %d 应允许建到第 %d 层): %v", i+1, bizDepth, bizDepth, err)
  287. }
  288. if got := loadDivideNode(t, db, child).Layer; got != int32(i+1) {
  289. t.Fatalf("第 %d 层的 layer 应为 %d,实得 %d", i+1, i+1, got)
  290. }
  291. prev = child
  292. }
  293. if got := loadDivideNode(t, db, prev).Layer; got != bizDepth {
  294. t.Fatalf("链尾 layer 应为 %d(业务上限内),实得 %d", bizDepth, got)
  295. }
  296. // 第 4 层:必须 3111,且**中文文案指向业务上限**(不能与结构上限混淆)
  297. beforeTail := loadDivideNode(t, db, prev)
  298. err := svc.AddSubordinate(ctx, prev, nodeID(1000))
  299. if !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  300. t.Fatalf("超过 %d 层应 3111,实得 %v", bizDepth, err)
  301. }
  302. if msg := err.Error(); !strings.Contains(msg, "业务上限") {
  303. t.Fatalf("第 4 层的错误文案应指向**业务上限**,实得 %q", msg)
  304. }
  305. // 反证:被拒后不得留下任何节点(事务回滚 + 左右值未位移)
  306. if after := loadDivideNode(t, db, prev); after.RightVal != beforeTail.RightVal {
  307. t.Fatalf("被拒后父节点 right_val 不应位移:前 %d,后 %d", beforeTail.RightVal, after.RightVal)
  308. }
  309. var nodeCount int64
  310. if err := db.Model(&model.UserDivideInto{}).Count(&nodeCount).Error; err != nil {
  311. t.Fatalf("count 失败: %v", err)
  312. }
  313. if nodeCount != int64(bizDepth) {
  314. t.Fatalf("被拒后节点数应仍为 %d,实得 %d", bizDepth, nodeCount)
  315. }
  316. }
  317. // TestDivideStructuralDepthConstant 只钉一个数字:结构上限仍是 100。
  318. //
  319. // 为什么单独写:MaxDivideBizDepth(3) 上线后,"100" 看起来像是多余的历史遗留,
  320. // 很容易被下一个人当成重复常量删掉。它不是 —— 它守的是"上行 BFS 必须终止 /
  321. // 递归不能爆栈",删掉后一棵脏数据(成环/超长链)就能把服务拖死。
  322. // 这里只断言常量值,**不**去构造 100 层链(那是 TestAddLogBFSDepthBoundary 的事)。
  323. func TestDivideStructuralDepthConstant(t *testing.T) {
  324. if MaxDivideDepth != 100 {
  325. t.Fatalf("结构上限 MaxDivideDepth 必须保持 100(防 BFS 不终止/递归爆栈),实得 %d", MaxDivideDepth)
  326. }
  327. if MaxDivideBizDepth != 3 {
  328. t.Fatalf("业务上限 MaxDivideBizDepth 必须为 3(超管→校区主任→老师),实得 %d", MaxDivideBizDepth)
  329. }
  330. if MaxDivideBizDepth >= MaxDivideDepth {
  331. t.Fatalf("业务上限(%d) 必须严格小于结构上限(%d):两者不是同一个概念,也不该相等",
  332. MaxDivideBizDepth, MaxDivideDepth)
  333. }
  334. }
  335. // TestAddLogBFSThreeLevels 上行链 BFS:**从上级起算**(dump `:763744` 子查询口径),
  336. // 本人不参与分成 —— c 报课,只有 b(直接上级)与 a(根)各得一条明细。
  337. func TestAddLogBFSThreeLevels(t *testing.T) {
  338. db := newDivideServiceDB(t)
  339. svc := NewDivideService(db, nil)
  340. ctx := context.Background()
  341. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  342. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  343. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  344. t.Fatalf("建链失败: %v", err)
  345. }
  346. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  347. t.Fatalf("建链失败: %v", err)
  348. }
  349. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  350. t.Fatalf("设额度 B 失败: %v", err)
  351. }
  352. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  353. t.Fatalf("设额度 C 失败: %v", err)
  354. }
  355. stu := nodeID(900)
  356. if err := svc.AddLog(ctx, c, stu, 777, "推荐分成"); err != nil {
  357. t.Fatalf("AddLog 失败: %v", err)
  358. }
  359. var rows []model.UserDivideIntoLog
  360. if err := db.Find(&rows).Error; err != nil {
  361. t.Fatalf("读明细失败: %v", err)
  362. }
  363. if len(rows) != 2 {
  364. t.Fatalf("上行链应生成 2 条明细(本人不参与),实得 %d", len(rows))
  365. }
  366. want := map[string]int64{b: 500, a: 1000}
  367. for i := range rows {
  368. expect, ok := want[rows[i].UserID]
  369. if !ok {
  370. t.Fatalf("出现意外分成用户 %s", rows[i].UserID)
  371. }
  372. if got := cents(t, rows[i].Money); got != expect {
  373. t.Fatalf("用户 %s 分成应为 %d 分,实得 %d", rows[i].UserID, expect, got)
  374. }
  375. if rows[i].OrderNo == nil || *rows[i].OrderNo != "777" {
  376. t.Fatalf("order_no 应为 777,实得 %v", rows[i].OrderNo)
  377. }
  378. if rows[i].Remark == nil || *rows[i].Remark != "推荐分成" {
  379. t.Fatalf("remark 应为推荐分成,实得 %v", rows[i].Remark)
  380. }
  381. // 明细 type = **该节点自己的 type**:a 是预置节点(type=2),b 是 AddSubordinate 新建节点
  382. // → audit D6 规定新节点固定 1(不继承父的 2),故这里逐用户校验
  383. wantType := map[string]int8{a: model.DivideTypePerLesson, b: model.DivideTypeOneOff}
  384. if rows[i].Type != wantType[rows[i].UserID] {
  385. t.Fatalf("用户 %s 的明细 type 应为 %d(D6:新节点固定 1),实得 %d",
  386. rows[i].UserID, wantType[rows[i].UserID], rows[i].Type)
  387. }
  388. }
  389. // total_income 各自累加自己的 quota
  390. for user, expect := range want {
  391. if got := cents(t, loadDivideNode(t, db, user).TotalIncome); got != expect {
  392. t.Fatalf("%s.total_income 应为 %d 分,实得 %d", user, expect, got)
  393. }
  394. }
  395. // D1 红线:本人(c)不参与分成,任何列都不得被写入
  396. if got := cents(t, loadDivideNode(t, db, c).TotalIncome); got != 0 {
  397. t.Fatalf("本人 %s 不应获得分成(total_income 应 0),实得 %d 分", c, got)
  398. }
  399. for i := range rows {
  400. if rows[i].UserID == c {
  401. t.Fatal("本人不得生成分成明细(dump 起点是 findUserid 的上级)")
  402. }
  403. }
  404. }
  405. // TestAddLogBFSZeroQuotaMiddle 上行链**中间层 quota=0**:只跳该层,**不中断**上行(audit D2)。
  406. //
  407. // 链:A(quota 10.00, type=2) > B(quota 0.00, type=1) > C(quota 2.00, type=1),find=C。
  408. //
  409. // 期望(dump `yuansiwei_finance.sql:763760`:额度<=0 的节点不生成明细):
  410. // - 起点是 C 的上级 B(本人不参与)→ B.quota=0 → **不生成明细**、total_income 不累加;
  411. // - B 的 0 额度**不得当作断链**:上行必须继续到 A,A 照常入账 10.00。
  412. // → 明细**恰 1 条**(仅 A),B/C 的 total_income 均为 0。
  413. //
  414. // 为什么单独需要这条用例:TestAddLogBFSThreeLevels / TestAddLogBFSDepthBoundary 给链上**每个**节点
  415. // 都配了额度,恰好绕过 D2 的"零额度跳层"分支;若实现把 `quota<=0` 写成 `return err`/`break`,
  416. // 上述两条仍全绿,只有本用例会红。
  417. func TestAddLogBFSZeroQuotaMiddle(t *testing.T) {
  418. db := newDivideServiceDB(t)
  419. svc := NewDivideService(db, nil)
  420. ctx := context.Background()
  421. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  422. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  423. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  424. t.Fatalf("建链失败(%s→%s): %v", a, b, err)
  425. }
  426. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  427. t.Fatalf("建链失败(%s→%s): %v", b, c, err)
  428. }
  429. // 中间层 B 保持新建节点的默认额度 0.00(不配置)——正是本用例要覆盖的场景
  430. if got := cents(t, loadDivideNode(t, db, b).Quota); got != 0 {
  431. t.Fatalf("前置条件:B 额度应为 0.00(AddSubordinate 默认值),实得 %d 分", got)
  432. }
  433. // 链尾 C 的额度与入账无关(本人不参与分成),仅为贴合"末级也配了额度"的真实形态;
  434. // 这里直接落库而不走 UpdateQuota:后者有"子不得超父"硬上限(C 的父 B=0.00),
  435. // 配 2.00 会被 3111 拒绝,与本用例要验证的 D2 跳层逻辑无关。
  436. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", c).
  437. UpdateColumn("quota", "2.00").Error; err != nil {
  438. t.Fatalf("配置 C 额度失败: %v", err)
  439. }
  440. stu := nodeID(900)
  441. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  442. t.Fatalf("AddLog 失败(中间层零额度不得报错): %v", err)
  443. }
  444. // 恰 1 条明细(仅 A):B 被 D2 跳过,且跳过不得终止上行
  445. if count := countLogs(t, db); count != 1 {
  446. t.Fatalf("中间层 quota=0 时应恰 1 条明细(仅 A),实得 %d", count)
  447. }
  448. var rows []model.UserDivideIntoLog
  449. if err := db.Find(&rows).Error; err != nil {
  450. t.Fatalf("读明细失败: %v", err)
  451. }
  452. if len(rows) != 1 {
  453. t.Fatalf("明细应恰 1 条,实得 %d", len(rows))
  454. }
  455. if rows[0].UserID != a {
  456. t.Fatalf("唯一明细应属于 A(跨过零额度中间层后的最上级),实得 %s", rows[0].UserID)
  457. }
  458. if got := cents(t, rows[0].Money); got != 1000 {
  459. t.Fatalf("A 的分成应为 10.00(1000 分),实得 %d", got)
  460. }
  461. if rows[0].OrderNo == nil || *rows[0].OrderNo != "777" {
  462. t.Fatalf("order_no 应为 777,实得 %v", rows[0].OrderNo)
  463. }
  464. // 收入口径:只有 A 累加;B(零额度被跳过)与 C(本人)都必须为 0
  465. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 1000 {
  466. t.Fatalf("A.total_income 应为 1000 分,实得 %d", got)
  467. }
  468. for _, u := range []string{b, c} {
  469. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 0 {
  470. t.Fatalf("%s.total_income 应为 0(B 零额度不入账 / C 本人不参与),实得 %d 分", u, got)
  471. }
  472. }
  473. // 幂等不因"跳过 B"而失效:重复调用不得为 A 再写一条
  474. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  475. t.Fatalf("AddLog 重复调用应幂等成功,实得 %v", err)
  476. }
  477. if count := countLogs(t, db); count != 1 {
  478. t.Fatalf("重复调用后仍应 1 条明细(幂等),实得 %d", count)
  479. }
  480. }
  481. // TestAddLogTwoLevelIdempotency 两级幂等:type=1 忽略订单;type=2 含订单。
  482. //
  483. // 结构:root(拿分成的一方)+ child(报课/被推荐人)—— **分成只入 root**(本人不参与,dump 口径)。
  484. func TestAddLogTwoLevelIdempotency(t *testing.T) {
  485. ctx := context.Background()
  486. stu := nodeID(901)
  487. t.Run("type=1 一次付清(同 user+student 只一条)", func(t *testing.T) {
  488. db := newDivideServiceDB(t)
  489. svc := NewDivideService(db, nil)
  490. u, child := nodeID(0), nodeID(1)
  491. seedRoot(t, db, u, model.DivideTypeOneOff, "10.00")
  492. if err := svc.AddSubordinate(ctx, u, child); err != nil {
  493. t.Fatalf("建链失败: %v", err)
  494. }
  495. if err := svc.AddLog(ctx, child, stu, 777, ""); err != nil {
  496. t.Fatalf("AddLog 失败: %v", err)
  497. }
  498. if err := svc.AddLog(ctx, child, stu, 888, ""); err != nil { // 不同订单:应与 type=1 无关
  499. t.Fatalf("AddLog(第二次) 失败: %v", err)
  500. }
  501. var count int64
  502. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  503. t.Fatalf("count 失败: %v", err)
  504. }
  505. if count != 1 {
  506. t.Fatalf("type=1 应仅 1 条明细,实得 %d", count)
  507. }
  508. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 1000 {
  509. t.Fatalf("total_income 应只累加一次(1000 分),实得 %d", got)
  510. }
  511. })
  512. t.Run("type=2 按课次(同 user+student+order 只一条)", func(t *testing.T) {
  513. db := newDivideServiceDB(t)
  514. svc := NewDivideService(db, nil)
  515. u, child := nodeID(0), nodeID(1)
  516. seedRoot(t, db, u, model.DivideTypePerLesson, "10.00")
  517. if err := svc.AddSubordinate(ctx, u, child); err != nil {
  518. t.Fatalf("建链失败: %v", err)
  519. }
  520. for i := 0; i < 2; i++ { // 同一订单重复请求
  521. if err := svc.AddLog(ctx, child, stu, 777, ""); err != nil {
  522. t.Fatalf("AddLog(重复) 失败: %v", err)
  523. }
  524. }
  525. if count := countLogs(t, db); count != 1 {
  526. t.Fatalf("同订单重复请求应幂等(1 条),实得 %d", count)
  527. }
  528. if err := svc.AddLog(ctx, child, stu, 888, ""); err != nil { // 新订单:应新增
  529. t.Fatalf("AddLog(新订单) 失败: %v", err)
  530. }
  531. if count := countLogs(t, db); count != 2 {
  532. t.Fatalf("新订单应新增明细(2 条),实得 %d", count)
  533. }
  534. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 2000 {
  535. t.Fatalf("total_income 应为 2000 分,实得 %d", got)
  536. }
  537. })
  538. }
  539. // countLogs 统计分成明细行数(测试辅助)。
  540. func countLogs(t *testing.T, db *gorm.DB) int64 {
  541. t.Helper()
  542. var count int64
  543. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  544. t.Fatalf("count 失败: %v", err)
  545. }
  546. return count
  547. }
  548. // TestAddLogStartFromParentDumpSemantics 审计 P0-2(dump `yuansiwei_finance.sql:763744`):
  549. // 上行分成的起点是 **findUserid 的上级**,本人不参与;findUserid 是根 → 无明细(幂等空操作)。
  550. //
  551. // 修复前从本人开始 → 本人也记一份,整整多算一代(金额错发)。
  552. func TestAddLogStartFromParentDumpSemantics(t *testing.T) {
  553. ctx := context.Background()
  554. stu := nodeID(901)
  555. t.Run("根用户无明细(子查询为 NULL)", func(t *testing.T) {
  556. db := newDivideServiceDB(t)
  557. svc := NewDivideService(db, nil)
  558. root := nodeID(0)
  559. seedRoot(t, db, root, model.DivideTypePerLesson, "10.00")
  560. if err := svc.AddLog(ctx, root, stu, 777, ""); err != nil {
  561. t.Fatalf("根用户报课应静默不入账(不报错),实得 %v", err)
  562. }
  563. if count := countLogs(t, db); count != 0 {
  564. t.Fatalf("根用户无上级 → 不应生成明细,实得 %d", count)
  565. }
  566. if got := cents(t, loadDivideNode(t, db, root).TotalIncome); got != 0 {
  567. t.Fatalf("根用户 total_income 应保持 0,实得 %d 分", got)
  568. }
  569. })
  570. t.Run("只给上级及更高层分成、本人无明细", func(t *testing.T) {
  571. db := newDivideServiceDB(t)
  572. svc := NewDivideService(db, nil)
  573. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  574. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  575. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  576. t.Fatalf("建链失败: %v", err)
  577. }
  578. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  579. t.Fatalf("建链失败: %v", err)
  580. }
  581. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  582. t.Fatalf("设额度 B 失败: %v", err)
  583. }
  584. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  585. t.Fatalf("设额度 C 失败: %v", err)
  586. }
  587. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  588. t.Fatalf("AddLog 失败: %v", err)
  589. }
  590. var rows []model.UserDivideIntoLog
  591. if err := db.Find(&rows).Error; err != nil {
  592. t.Fatalf("读明细失败: %v", err)
  593. }
  594. got := make(map[string]int64, len(rows))
  595. for i := range rows {
  596. got[rows[i].UserID] = cents(t, rows[i].Money)
  597. }
  598. if len(got) != 2 {
  599. t.Fatalf("应只有上级 b 与根 a 两条明细,实得 %d:%v", len(got), got)
  600. }
  601. if _, ok := got[c]; ok {
  602. t.Fatal("本人 c 不得出现在分成明细中(多算一代 = 金额错发)")
  603. }
  604. if got[b] != 500 || got[a] != 1000 {
  605. t.Fatalf("分成金额不符:b=%d a=%d(期望 500/1000)", got[b], got[a])
  606. }
  607. if cents(t, loadDivideNode(t, db, c).TotalIncome) != 0 {
  608. t.Fatal("本人 c 的 total_income 必须保持 0")
  609. }
  610. })
  611. t.Run("上级已断链(不在树中)→ 无明细", func(t *testing.T) {
  612. db := newDivideServiceDB(t)
  613. svc := NewDivideService(db, nil)
  614. a, b := nodeID(0), nodeID(1)
  615. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  616. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  617. t.Fatalf("建链失败: %v", err)
  618. }
  619. // 人为把 b 的上级指向一个不存在的节点(脏数据 / 上级已退网)
  620. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  621. UpdateColumn("parent_user_id", nodeID(777)).Error; err != nil {
  622. t.Fatalf("造断链失败: %v", err)
  623. }
  624. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  625. t.Fatalf("断链应静默不入账,实得 %v", err)
  626. }
  627. if count := countLogs(t, db); count != 0 {
  628. t.Fatalf("断链不应生成明细,实得 %d", count)
  629. }
  630. })
  631. }
  632. // TestAddLogNonTreeNodeNoop 非分账树节点 → 静默不入账(不报错)。
  633. func TestAddLogNonTreeNodeNoop(t *testing.T) {
  634. db := newDivideServiceDB(t)
  635. svc := NewDivideService(db, nil)
  636. ctx := context.Background()
  637. if err := svc.AddLog(ctx, nodeID(404), nodeID(901), 777, ""); err != nil {
  638. t.Fatalf("非树节点应静默不入账,实得 %v", err)
  639. }
  640. if count := countLogs(t, db); count != 0 {
  641. t.Fatalf("非树节点不应生成明细,实得 %d", count)
  642. }
  643. if err := svc.AddLog(ctx, nodeID(1), "", 777, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  644. t.Fatalf("空学生应 3140,实得 %v", err)
  645. }
  646. if err := svc.AddLog(ctx, nodeID(1), nodeID(901), 0, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  647. t.Fatalf("recordID<=0 应 3140,实得 %v", err)
  648. }
  649. }
  650. // TestAddLogCycleGuard 数据成环 → 迭代层数兜底 3111(不死循环、不栈溢出)。
  651. func TestAddLogCycleGuard(t *testing.T) {
  652. db := newDivideServiceDB(t)
  653. svc := NewDivideService(db, nil)
  654. ctx := context.Background()
  655. a, b := nodeID(0), nodeID(1)
  656. seedRoot(t, db, a, model.DivideTypeOneOff, "10.00")
  657. seedRoot(t, db, b, model.DivideTypeOneOff, "10.00")
  658. // 人为造自环(脏数据)
  659. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", a).
  660. Updates(map[string]any{"parent_user_id": b}).Error; err != nil {
  661. t.Fatalf("造环失败: %v", err)
  662. }
  663. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  664. Updates(map[string]any{"parent_user_id": a}).Error; err != nil {
  665. t.Fatalf("造环失败: %v", err)
  666. }
  667. err := svc.AddLog(ctx, a, nodeID(901), 777, "")
  668. if !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  669. t.Fatalf("成环应 3111(层级兜底),实得 %v", err)
  670. }
  671. // 事务回滚:环上的入账不应留下
  672. if count := countLogs(t, db); count != 0 {
  673. t.Fatalf("报错后应整体回滚(0 条明细),实得 %d", count)
  674. }
  675. }
  676. // TestDeleteLogRollbackBranch 撤销分支②:无首次扣费记录 → 回滚 total_income 并删行。
  677. func TestDeleteLogRollbackBranch(t *testing.T) {
  678. db := newDivideServiceDB(t)
  679. svc := NewDivideService(db, nil) // 端口未注入 → 一律走回滚
  680. ctx := context.Background()
  681. a, b := nodeID(0), nodeID(1)
  682. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  683. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  684. t.Fatalf("建链失败: %v", err)
  685. }
  686. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  687. t.Fatalf("设额度失败: %v", err)
  688. }
  689. stu := nodeID(901)
  690. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  691. t.Fatalf("AddLog 失败: %v", err)
  692. }
  693. // b 报课 → 只有上级 a 得一条(本人不参与分成,dump 口径)
  694. if count := countLogs(t, db); count != 1 {
  695. t.Fatalf("应为 1 条明细(仅上级),实得 %d", count)
  696. }
  697. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  698. t.Fatalf("DeleteLog 失败: %v", err)
  699. }
  700. if count := countLogs(t, db); count != 0 {
  701. t.Fatalf("回滚删除后应 0 条明细,实得 %d", count)
  702. }
  703. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  704. t.Fatalf("a.total_income 应回滚为 0,实得 %d 分", got)
  705. }
  706. if got := cents(t, loadDivideNode(t, db, b).TotalIncome); got != 0 {
  707. t.Fatalf("b.total_income 应回滚为 0,实得 %d 分", got)
  708. }
  709. // 幂等:再次撤销 → 空操作
  710. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  711. t.Fatalf("重复撤销应幂等成功,实得 %v", err)
  712. }
  713. }
  714. // TestDeleteLogRebindBranch 撤销分支①:已有首次扣费记录(≠当前订单)→ 改绑保留分成。
  715. func TestDeleteLogRebindBranch(t *testing.T) {
  716. db := newDivideServiceDB(t)
  717. port := &fakeFirstCharged{recordID: 888, found: true}
  718. svc := NewDivideService(db, port)
  719. ctx := context.Background()
  720. a, b := nodeID(0), nodeID(1)
  721. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  722. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  723. t.Fatalf("建链失败: %v", err)
  724. }
  725. stu := nodeID(901)
  726. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  727. t.Fatalf("AddLog 失败: %v", err)
  728. }
  729. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  730. t.Fatalf("DeleteLog 失败: %v", err)
  731. }
  732. var rows []model.UserDivideIntoLog
  733. if err := db.Find(&rows).Error; err != nil {
  734. t.Fatalf("读明细失败: %v", err)
  735. }
  736. if len(rows) != 1 {
  737. t.Fatalf("改绑分支应保留明细(1 条),实得 %d", len(rows))
  738. }
  739. if rows[0].OrderNo == nil || *rows[0].OrderNo != "888" {
  740. t.Fatalf("order_no 应改绑为 888,实得 %v", rows[0].OrderNo)
  741. }
  742. if rows[0].Remark == nil || *rows[0].Remark != remarkRebind {
  743. t.Fatalf("remark 应为 %q,实得 %v", remarkRebind, rows[0].Remark)
  744. }
  745. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 1000 {
  746. t.Fatalf("改绑不回滚收入(应仍 1000 分),实得 %d", got)
  747. }
  748. if port.calls == 0 {
  749. t.Fatal("改绑判定应调用首次扣费端口")
  750. }
  751. }
  752. // TestDeleteLogFirstEqualsOrderRebind 首扣记录**就是**当前订单 → 仍然改绑保留(audit D11,dump 762547)。
  753. //
  754. // dump 的改绑分支不与当前 orderID 比较:撤的正是"当前这单"而它本身就是首扣记录,
  755. // 带 `first != orderID` 条件会误判成"无可改绑"→ 回滚删除,把真实产生的分成整组冲掉(少发钱)。
  756. func TestDeleteLogFirstEqualsOrderRebind(t *testing.T) {
  757. db := newDivideServiceDB(t)
  758. port := &fakeFirstCharged{recordID: 777, found: true}
  759. svc := NewDivideService(db, port)
  760. ctx := context.Background()
  761. a, b := nodeID(0), nodeID(1)
  762. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  763. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  764. t.Fatalf("建链失败: %v", err)
  765. }
  766. stu := nodeID(901)
  767. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  768. t.Fatalf("AddLog 失败: %v", err)
  769. }
  770. before := loadDivideNode(t, db, a).TotalIncome
  771. // 把改绑前的 create_time 拨到 2020:改绑要求"重置为 now()",用 2020 作参照可绕开
  772. // sqlite CURRENT_TIMESTAMP 的秒级精度(同秒内 After() 无法区分)
  773. old2020 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
  774. if err := db.Model(&model.UserDivideIntoLog{}).Where("user_id = ?", a).
  775. UpdateColumn("create_time", old2020).Error; err != nil {
  776. t.Fatalf("回拨 create_time 失败: %v", err)
  777. }
  778. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  779. t.Fatalf("DeleteLog 失败: %v", err)
  780. }
  781. if count := countLogs(t, db); count != 1 {
  782. t.Fatalf("首扣记录=当前订单 → 应改绑保留(1 条),实得 %d", count)
  783. }
  784. var rows []model.UserDivideIntoLog
  785. if err := db.Find(&rows).Error; err != nil {
  786. t.Fatalf("读明细失败: %v", err)
  787. }
  788. if rows[0].OrderNo == nil || *rows[0].OrderNo != "777" {
  789. t.Fatalf("order_no 应仍为 777(改绑到首扣记录),实得 %v", rows[0].OrderNo)
  790. }
  791. if rows[0].Remark == nil || *rows[0].Remark != remarkRebind {
  792. t.Fatalf("remark 应为 %q,实得 %v", remarkRebind, rows[0].Remark)
  793. }
  794. if got := loadDivideNode(t, db, a).TotalIncome; got != before {
  795. t.Fatalf("改绑不回滚 total_income(应仍 %q),实得 %q", before, got)
  796. }
  797. if !rows[0].CreateTime.After(old2020) {
  798. t.Fatalf("改绑后 create_time 应重置为 now()(> 2020),实得 %s", rows[0].CreateTime)
  799. }
  800. if err := svc.DeleteLog(ctx, stu, 0); !errors.Is(err, apperr.ErrBusinessParam) {
  801. t.Fatalf("orderID<=0 应 3140,实得 %v", err)
  802. }
  803. }
  804. // TestUpdateQuotaCascade 额度级联下降(子不得超父)+ 参数/缺失分支。
  805. func TestUpdateQuotaCascade(t *testing.T) {
  806. db := newDivideServiceDB(t)
  807. svc := NewDivideService(db, nil)
  808. ctx := context.Background()
  809. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  810. seedRoot(t, db, a, model.DivideTypeOneOff, "20.00")
  811. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  812. t.Fatalf("建链失败: %v", err)
  813. }
  814. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  815. t.Fatalf("建链失败: %v", err)
  816. }
  817. if err := svc.UpdateQuota(ctx, b, money.FromCents(1500)); err != nil {
  818. t.Fatalf("设额度 B 失败: %v", err)
  819. }
  820. if err := svc.UpdateQuota(ctx, c, money.FromCents(1200)); err != nil {
  821. t.Fatalf("设额度 C 失败: %v", err)
  822. }
  823. // 父 A 降到 10.00 → B(15)、C(12) 一并压到 10.00
  824. if err := svc.UpdateQuota(ctx, a, money.FromCents(1000)); err != nil {
  825. t.Fatalf("UpdateQuota(A,10) 失败: %v", err)
  826. }
  827. for _, id := range []string{a, b, c} {
  828. if got := cents(t, loadDivideNode(t, db, id).Quota); got != 1000 {
  829. t.Fatalf("%s.quota 应级联压到 1000 分,实得 %d", id, got)
  830. }
  831. }
  832. // 子节点超额(> 父)→ 3111
  833. if err := svc.UpdateQuota(ctx, b, money.FromCents(9999)); !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  834. t.Fatalf("超过上级应 3111,实得 %v", err)
  835. }
  836. // 参数/缺失
  837. if err := svc.UpdateQuota(ctx, b, money.FromCents(-1)); !errors.Is(err, apperr.ErrBusinessParam) {
  838. t.Fatalf("负额度应 3140,实得 %v", err)
  839. }
  840. if err := svc.UpdateQuota(ctx, nodeID(404), money.FromCents(100)); !errors.Is(err, infraerrors.ErrNotFound) {
  841. t.Fatalf("节点不存在应 3001,实得 %v", err)
  842. }
  843. if err := svc.UpdateQuota(ctx, "", money.FromCents(100)); !errors.Is(err, apperr.ErrBusinessParam) {
  844. t.Fatalf("空 userID 应 3140,实得 %v", err)
  845. }
  846. }
  847. // TestUpdateQuotaNoCascadeWhenOrigZero 原 quota=0 时不级联(audit A6,dump 763872 `IF (uQuota>0)`)。
  848. //
  849. // 语义:还没配置过额度的节点,被"设成某个值"时不该顺手压低子树(子树额度是独立配置的阶梯)。
  850. // 对照:节点原额度 > 0 时级联照旧生效(后半段断言)。
  851. func TestUpdateQuotaNoCascadeWhenOrigZero(t *testing.T) {
  852. db := newDivideServiceDB(t)
  853. svc := NewDivideService(db, nil)
  854. ctx := context.Background()
  855. a, b := nodeID(0), nodeID(1)
  856. seedRoot(t, db, a, model.DivideTypeOneOff, "0.00") // 原 quota = 0
  857. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  858. t.Fatalf("建链失败: %v", err)
  859. }
  860. // 直接把子节点额度设成 5.00(绕过服务,构造"父 0 / 子 5"的起始态)
  861. if err := db.Exec("UPDATE t_user_divide_into SET quota = ? WHERE user_id = ?", "5.00", b).Error; err != nil {
  862. t.Fatalf("配置子额度失败: %v", err)
  863. }
  864. // 父原 quota=0 → 设成 10.00 **不级联**:子保持 5.00
  865. if err := svc.UpdateQuota(ctx, a, money.FromCents(1000)); err != nil {
  866. t.Fatalf("UpdateQuota 失败: %v", err)
  867. }
  868. if got := cents(t, loadDivideNode(t, db, a).Quota); got != 1000 {
  869. t.Fatalf("父额度应为 10.00,实得 %d 分", got)
  870. }
  871. if got := cents(t, loadDivideNode(t, db, b).Quota); got != 500 {
  872. t.Fatalf("原 quota=0 不应级联:子应保持 5.00,实得 %d 分", got)
  873. }
  874. // 父原 quota=10.00 > 0 → 降到 3.00 **会级联**:子被压到 3.00
  875. if err := svc.UpdateQuota(ctx, a, money.FromCents(300)); err != nil {
  876. t.Fatalf("UpdateQuota(第二次) 失败: %v", err)
  877. }
  878. if got := cents(t, loadDivideNode(t, db, a).Quota); got != 300 {
  879. t.Fatalf("父额度应为 3.00,实得 %d 分", got)
  880. }
  881. if got := cents(t, loadDivideNode(t, db, b).Quota); got != 300 {
  882. t.Fatalf("原 quota>0 应级联压到 3.00,实得 %d 分", got)
  883. }
  884. }
  885. // TestDivideServiceNestedTxPassThrough 事务透传纪律:本服务在**外层事务内**被调用时
  886. // 必须经 WithTxContext 复用同一 tx(不重复 BEGIN),且随外层回滚一并撤销。
  887. func TestDivideServiceNestedTxPassThrough(t *testing.T) {
  888. db := newDivideServiceDB(t)
  889. svc := NewDivideService(db, nil)
  890. runner := repository.NewTxRunner(db)
  891. ctx := context.Background()
  892. a, b := nodeID(0), nodeID(1)
  893. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  894. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  895. t.Fatalf("建链失败: %v", err)
  896. }
  897. stu := nodeID(901)
  898. boom := errors.New("outer-rollback")
  899. err := runner.WithinTx(ctx, func(tx *gorm.DB) error {
  900. txCtx := repository.WithTxContext(ctx, tx)
  901. if aerr := svc.AddLog(txCtx, b, stu, 777, ""); aerr != nil {
  902. return aerr
  903. }
  904. // 事务内应可见刚写入的明细(说明确实跑在同一 tx 上)
  905. var inside int64
  906. if cerr := tx.Model(&model.UserDivideIntoLog{}).Count(&inside).Error; cerr != nil {
  907. return cerr
  908. }
  909. if inside != 1 {
  910. t.Fatalf("外层事务内应可见 1 条明细(仅上级,本人不参与),实得 %d", inside)
  911. }
  912. return boom
  913. })
  914. if !errors.Is(err, infraerrors.ErrDBError) {
  915. t.Fatalf("非业务错误应归一为 5002,实得 %v", err)
  916. }
  917. if count := countLogs(t, db); count != 0 {
  918. t.Fatalf("外层回滚后明细应全部消失(无独立事务提前提交),实得 %d", count)
  919. }
  920. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  921. t.Fatalf("回滚后 total_income 应为 0,实得 %d 分", got)
  922. }
  923. }
  924. // seedChain 直接落一条 layer=1..n 的**单链**,绕过 AddSubordinate。
  925. //
  926. // 为什么必须绕过:F20 之后 AddSubordinate 有 3 层业务上限,用公开接口建不出 100 层链。
  927. // 但「结构上限 / 上行 BFS 必须终止」要验的恰恰是**脏数据**(成环、超长链)下的行为,
  928. // 这种数据在现实里只能由历史迁移产生 —— 所以这里直接写库,等价于"库里已经有这么一棵树",
  929. // 与"用户用接口建出来的树"是两件事,不能混。
  930. //
  931. // 嵌套集取值(单链,n 个节点):节点 i(1-based)left = 2i-1,right = 2(n-i+1)。
  932. // **parent_user_id 必须自己连上**:上行 BFS 的唯一依据就是这列(不是 layer、不是嵌套集区间),
  933. // 只写 layer/left/right 而漏掉 parent 会造出"看似 100 层、实际 100 个孤点"的假数据,
  934. // 断言就会以"0 条明细"的形式失败 —— 空过的反面:数据没连上,测试反而更红了。
  935. func seedChain(t *testing.T, db *gorm.DB, n int32, typ int8, quota string) []string {
  936. t.Helper()
  937. if n <= 0 {
  938. t.Fatalf("seedChain 需要 n>0,实得 %d", n)
  939. }
  940. ids := make([]string, 0, n)
  941. for i := int32(1); i <= n; i++ {
  942. ids = append(ids, nodeID(int(i)))
  943. }
  944. root := ids[0]
  945. rows := make([]model.UserDivideInto, 0, n)
  946. for i := int32(1); i <= n; i++ {
  947. rootCopy := root
  948. var parent *string
  949. if i > 1 {
  950. p := ids[i-2]
  951. parent = &p
  952. }
  953. rows = append(rows, model.UserDivideInto{
  954. UserID: ids[i-1],
  955. Type: typ,
  956. Quota: quota,
  957. TotalIncome: "0.00",
  958. TotalIncomePayed: "0.00",
  959. RootUserID: &rootCopy,
  960. ParentUserID: parent,
  961. LeftVal: 2*i - 1,
  962. RightVal: 2 * (n - i + 1),
  963. Layer: i,
  964. })
  965. }
  966. if err := db.Create(&rows).Error; err != nil {
  967. t.Fatalf("seed %d 层链失败: %v", n, err)
  968. }
  969. return ids
  970. }
  971. // TestAddLogBFSDepthBoundary 100 层链(layer 1..100)恰好在上限内:BFS 必须完整走完到根
  972. // (101 级才触发 3111,见 TestAddLogCycleGuard)。同时验证"迭代不递归"在大深度下不栈溢出。
  973. //
  974. // 链由 seedChain 直接写库(F20 的 3 层业务上限不允许用 AddSubordinate 建这么深),
  975. // 语义是"库里已存在历史的超长链":**读路径不能因为链长就崩**,但**写路径不许再造新的**。
  976. //
  977. // 明细条数 = 99(链尾本人不参与分成,dump 起点是其上级,故比全链少 1 条)。
  978. func TestAddLogBFSDepthBoundary(t *testing.T) {
  979. db := newDivideServiceDB(t)
  980. svc := NewDivideService(db, nil)
  981. ctx := context.Background()
  982. // audit D2:quota<=0 的节点不生成明细 → 每节点自带 1.00 额度(seedChain 里已给),
  983. // 否则只有根节点会入账(本用例要测的是 BFS 深度边界,不是 D2)
  984. ids := seedChain(t, db, MaxDivideDepth, model.DivideTypePerLesson, "1.00")
  985. tail := ids[len(ids)-1]
  986. if got := loadDivideNode(t, db, tail).Layer; got != MaxDivideDepth {
  987. t.Fatalf("链尾 layer 应为 %d,实得 %d", MaxDivideDepth, got)
  988. }
  989. if err := svc.AddLog(ctx, tail, nodeID(901), 777, ""); err != nil {
  990. t.Fatalf("%d 层链的 BFS 入账应在限内成功,实得 %v", MaxDivideDepth, err)
  991. }
  992. // 链尾本人不参与 → 明细 = 层数 - 1
  993. if count := countLogs(t, db); count != int64(MaxDivideDepth-1) {
  994. t.Fatalf("%d 层链应生成 %d 条明细(本人不参与),实得 %d", MaxDivideDepth, MaxDivideDepth-1, count)
  995. }
  996. // 根节点收入应恰好为一次 quota
  997. if got := cents(t, loadDivideNode(t, db, ids[0]).TotalIncome); got != 100 {
  998. t.Fatalf("根节点 total_income 应为 100 分,实得 %d", got)
  999. }
  1000. }