divide_service_test.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. // 建到 layer=3(3 层 = 超管 / 校区主任 / 老师)
  281. for i := 1; i < bizDepth; i++ {
  282. child := nodeID(i)
  283. if err := svc.AddSubordinate(ctx, prev, child); err != nil {
  284. t.Fatalf("建链 AddSubordinate(%s→%s) 失败: %v", prev, child, err)
  285. }
  286. prev = child
  287. }
  288. if got := loadDivideNode(t, db, prev).Layer; got != bizDepth {
  289. t.Fatalf("链尾 layer 应为 %d(业务上限内),实得 %d", bizDepth, got)
  290. }
  291. // 第 4 层:必须 3111,且**中文文案指向业务上限**(不能与结构上限混淆)
  292. beforeTail := loadDivideNode(t, db, prev)
  293. err := svc.AddSubordinate(ctx, prev, nodeID(1000))
  294. if !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  295. t.Fatalf("超过 %d 层应 3111,实得 %v", bizDepth, err)
  296. }
  297. if msg := err.Error(); !strings.Contains(msg, "业务上限") {
  298. t.Fatalf("第 4 层的错误文案应指向**业务上限**,实得 %q", msg)
  299. }
  300. // 反证:被拒后不得留下任何节点(事务回滚 + 左右值未位移)
  301. if after := loadDivideNode(t, db, prev); after.RightVal != beforeTail.RightVal {
  302. t.Fatalf("被拒后父节点 right_val 不应位移:前 %d,后 %d", beforeTail.RightVal, after.RightVal)
  303. }
  304. var nodeCount int64
  305. if err := db.Model(&model.UserDivideInto{}).Count(&nodeCount).Error; err != nil {
  306. t.Fatalf("count 失败: %v", err)
  307. }
  308. if nodeCount != int64(bizDepth) {
  309. t.Fatalf("被拒后节点数应仍为 %d,实得 %d", bizDepth, nodeCount)
  310. }
  311. }
  312. // TestDivideStructuralDepthConstant 只钉一个数字:结构上限仍是 100。
  313. //
  314. // 为什么单独写:MaxDivideBizDepth(3) 上线后,"100" 看起来像是多余的历史遗留,
  315. // 很容易被下一个人当成重复常量删掉。它不是 —— 它守的是"上行 BFS 必须终止 /
  316. // 递归不能爆栈",删掉后一棵脏数据(成环/超长链)就能把服务拖死。
  317. // 这里只断言常量值,**不**去构造 100 层链(那是 TestAddLogBFSDepthBoundary 的事)。
  318. func TestDivideStructuralDepthConstant(t *testing.T) {
  319. if MaxDivideDepth != 100 {
  320. t.Fatalf("结构上限 MaxDivideDepth 必须保持 100(防 BFS 不终止/递归爆栈),实得 %d", MaxDivideDepth)
  321. }
  322. if MaxDivideBizDepth != 3 {
  323. t.Fatalf("业务上限 MaxDivideBizDepth 必须为 3(超管→校区主任→老师),实得 %d", MaxDivideBizDepth)
  324. }
  325. if MaxDivideBizDepth >= MaxDivideDepth {
  326. t.Fatalf("业务上限(%d) 必须严格小于结构上限(%d):两者不是同一个概念,也不该相等",
  327. MaxDivideBizDepth, MaxDivideDepth)
  328. }
  329. }
  330. // TestAddLogBFSThreeLevels 上行链 BFS:**从上级起算**(dump `:763744` 子查询口径),
  331. // 本人不参与分成 —— c 报课,只有 b(直接上级)与 a(根)各得一条明细。
  332. func TestAddLogBFSThreeLevels(t *testing.T) {
  333. db := newDivideServiceDB(t)
  334. svc := NewDivideService(db, nil)
  335. ctx := context.Background()
  336. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  337. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  338. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  339. t.Fatalf("建链失败: %v", err)
  340. }
  341. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  342. t.Fatalf("建链失败: %v", err)
  343. }
  344. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  345. t.Fatalf("设额度 B 失败: %v", err)
  346. }
  347. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  348. t.Fatalf("设额度 C 失败: %v", err)
  349. }
  350. stu := nodeID(900)
  351. if err := svc.AddLog(ctx, c, stu, 777, "推荐分成"); err != nil {
  352. t.Fatalf("AddLog 失败: %v", err)
  353. }
  354. var rows []model.UserDivideIntoLog
  355. if err := db.Find(&rows).Error; err != nil {
  356. t.Fatalf("读明细失败: %v", err)
  357. }
  358. if len(rows) != 2 {
  359. t.Fatalf("上行链应生成 2 条明细(本人不参与),实得 %d", len(rows))
  360. }
  361. want := map[string]int64{b: 500, a: 1000}
  362. for i := range rows {
  363. expect, ok := want[rows[i].UserID]
  364. if !ok {
  365. t.Fatalf("出现意外分成用户 %s", rows[i].UserID)
  366. }
  367. if got := cents(t, rows[i].Money); got != expect {
  368. t.Fatalf("用户 %s 分成应为 %d 分,实得 %d", rows[i].UserID, expect, got)
  369. }
  370. if rows[i].OrderNo == nil || *rows[i].OrderNo != "777" {
  371. t.Fatalf("order_no 应为 777,实得 %v", rows[i].OrderNo)
  372. }
  373. if rows[i].Remark == nil || *rows[i].Remark != "推荐分成" {
  374. t.Fatalf("remark 应为推荐分成,实得 %v", rows[i].Remark)
  375. }
  376. // 明细 type = **该节点自己的 type**:a 是预置节点(type=2),b 是 AddSubordinate 新建节点
  377. // → audit D6 规定新节点固定 1(不继承父的 2),故这里逐用户校验
  378. wantType := map[string]int8{a: model.DivideTypePerLesson, b: model.DivideTypeOneOff}
  379. if rows[i].Type != wantType[rows[i].UserID] {
  380. t.Fatalf("用户 %s 的明细 type 应为 %d(D6:新节点固定 1),实得 %d",
  381. rows[i].UserID, wantType[rows[i].UserID], rows[i].Type)
  382. }
  383. }
  384. // total_income 各自累加自己的 quota
  385. for user, expect := range want {
  386. if got := cents(t, loadDivideNode(t, db, user).TotalIncome); got != expect {
  387. t.Fatalf("%s.total_income 应为 %d 分,实得 %d", user, expect, got)
  388. }
  389. }
  390. // D1 红线:本人(c)不参与分成,任何列都不得被写入
  391. if got := cents(t, loadDivideNode(t, db, c).TotalIncome); got != 0 {
  392. t.Fatalf("本人 %s 不应获得分成(total_income 应 0),实得 %d 分", c, got)
  393. }
  394. for i := range rows {
  395. if rows[i].UserID == c {
  396. t.Fatal("本人不得生成分成明细(dump 起点是 findUserid 的上级)")
  397. }
  398. }
  399. }
  400. // TestAddLogBFSZeroQuotaMiddle 上行链**中间层 quota=0**:只跳该层,**不中断**上行(audit D2)。
  401. //
  402. // 链:A(quota 10.00, type=2) > B(quota 0.00, type=1) > C(quota 2.00, type=1),find=C。
  403. //
  404. // 期望(dump `yuansiwei_finance.sql:763760`:额度<=0 的节点不生成明细):
  405. // - 起点是 C 的上级 B(本人不参与)→ B.quota=0 → **不生成明细**、total_income 不累加;
  406. // - B 的 0 额度**不得当作断链**:上行必须继续到 A,A 照常入账 10.00。
  407. // → 明细**恰 1 条**(仅 A),B/C 的 total_income 均为 0。
  408. //
  409. // 为什么单独需要这条用例:TestAddLogBFSThreeLevels / TestAddLogBFSDepthBoundary 给链上**每个**节点
  410. // 都配了额度,恰好绕过 D2 的"零额度跳层"分支;若实现把 `quota<=0` 写成 `return err`/`break`,
  411. // 上述两条仍全绿,只有本用例会红。
  412. func TestAddLogBFSZeroQuotaMiddle(t *testing.T) {
  413. db := newDivideServiceDB(t)
  414. svc := NewDivideService(db, nil)
  415. ctx := context.Background()
  416. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  417. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  418. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  419. t.Fatalf("建链失败(%s→%s): %v", a, b, err)
  420. }
  421. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  422. t.Fatalf("建链失败(%s→%s): %v", b, c, err)
  423. }
  424. // 中间层 B 保持新建节点的默认额度 0.00(不配置)——正是本用例要覆盖的场景
  425. if got := cents(t, loadDivideNode(t, db, b).Quota); got != 0 {
  426. t.Fatalf("前置条件:B 额度应为 0.00(AddSubordinate 默认值),实得 %d 分", got)
  427. }
  428. // 链尾 C 的额度与入账无关(本人不参与分成),仅为贴合"末级也配了额度"的真实形态;
  429. // 这里直接落库而不走 UpdateQuota:后者有"子不得超父"硬上限(C 的父 B=0.00),
  430. // 配 2.00 会被 3111 拒绝,与本用例要验证的 D2 跳层逻辑无关。
  431. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", c).
  432. UpdateColumn("quota", "2.00").Error; err != nil {
  433. t.Fatalf("配置 C 额度失败: %v", err)
  434. }
  435. stu := nodeID(900)
  436. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  437. t.Fatalf("AddLog 失败(中间层零额度不得报错): %v", err)
  438. }
  439. // 恰 1 条明细(仅 A):B 被 D2 跳过,且跳过不得终止上行
  440. if count := countLogs(t, db); count != 1 {
  441. t.Fatalf("中间层 quota=0 时应恰 1 条明细(仅 A),实得 %d", count)
  442. }
  443. var rows []model.UserDivideIntoLog
  444. if err := db.Find(&rows).Error; err != nil {
  445. t.Fatalf("读明细失败: %v", err)
  446. }
  447. if len(rows) != 1 {
  448. t.Fatalf("明细应恰 1 条,实得 %d", len(rows))
  449. }
  450. if rows[0].UserID != a {
  451. t.Fatalf("唯一明细应属于 A(跨过零额度中间层后的最上级),实得 %s", rows[0].UserID)
  452. }
  453. if got := cents(t, rows[0].Money); got != 1000 {
  454. t.Fatalf("A 的分成应为 10.00(1000 分),实得 %d", got)
  455. }
  456. if rows[0].OrderNo == nil || *rows[0].OrderNo != "777" {
  457. t.Fatalf("order_no 应为 777,实得 %v", rows[0].OrderNo)
  458. }
  459. // 收入口径:只有 A 累加;B(零额度被跳过)与 C(本人)都必须为 0
  460. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 1000 {
  461. t.Fatalf("A.total_income 应为 1000 分,实得 %d", got)
  462. }
  463. for _, u := range []string{b, c} {
  464. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 0 {
  465. t.Fatalf("%s.total_income 应为 0(B 零额度不入账 / C 本人不参与),实得 %d 分", u, got)
  466. }
  467. }
  468. // 幂等不因"跳过 B"而失效:重复调用不得为 A 再写一条
  469. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  470. t.Fatalf("AddLog 重复调用应幂等成功,实得 %v", err)
  471. }
  472. if count := countLogs(t, db); count != 1 {
  473. t.Fatalf("重复调用后仍应 1 条明细(幂等),实得 %d", count)
  474. }
  475. }
  476. // TestAddLogTwoLevelIdempotency 两级幂等:type=1 忽略订单;type=2 含订单。
  477. //
  478. // 结构:root(拿分成的一方)+ child(报课/被推荐人)—— **分成只入 root**(本人不参与,dump 口径)。
  479. func TestAddLogTwoLevelIdempotency(t *testing.T) {
  480. ctx := context.Background()
  481. stu := nodeID(901)
  482. t.Run("type=1 一次付清(同 user+student 只一条)", func(t *testing.T) {
  483. db := newDivideServiceDB(t)
  484. svc := NewDivideService(db, nil)
  485. u, child := nodeID(0), nodeID(1)
  486. seedRoot(t, db, u, model.DivideTypeOneOff, "10.00")
  487. if err := svc.AddSubordinate(ctx, u, child); err != nil {
  488. t.Fatalf("建链失败: %v", err)
  489. }
  490. if err := svc.AddLog(ctx, child, stu, 777, ""); err != nil {
  491. t.Fatalf("AddLog 失败: %v", err)
  492. }
  493. if err := svc.AddLog(ctx, child, stu, 888, ""); err != nil { // 不同订单:应与 type=1 无关
  494. t.Fatalf("AddLog(第二次) 失败: %v", err)
  495. }
  496. var count int64
  497. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  498. t.Fatalf("count 失败: %v", err)
  499. }
  500. if count != 1 {
  501. t.Fatalf("type=1 应仅 1 条明细,实得 %d", count)
  502. }
  503. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 1000 {
  504. t.Fatalf("total_income 应只累加一次(1000 分),实得 %d", got)
  505. }
  506. })
  507. t.Run("type=2 按课次(同 user+student+order 只一条)", func(t *testing.T) {
  508. db := newDivideServiceDB(t)
  509. svc := NewDivideService(db, nil)
  510. u, child := nodeID(0), nodeID(1)
  511. seedRoot(t, db, u, model.DivideTypePerLesson, "10.00")
  512. if err := svc.AddSubordinate(ctx, u, child); err != nil {
  513. t.Fatalf("建链失败: %v", err)
  514. }
  515. for i := 0; i < 2; i++ { // 同一订单重复请求
  516. if err := svc.AddLog(ctx, child, stu, 777, ""); err != nil {
  517. t.Fatalf("AddLog(重复) 失败: %v", err)
  518. }
  519. }
  520. if count := countLogs(t, db); count != 1 {
  521. t.Fatalf("同订单重复请求应幂等(1 条),实得 %d", count)
  522. }
  523. if err := svc.AddLog(ctx, child, stu, 888, ""); err != nil { // 新订单:应新增
  524. t.Fatalf("AddLog(新订单) 失败: %v", err)
  525. }
  526. if count := countLogs(t, db); count != 2 {
  527. t.Fatalf("新订单应新增明细(2 条),实得 %d", count)
  528. }
  529. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 2000 {
  530. t.Fatalf("total_income 应为 2000 分,实得 %d", got)
  531. }
  532. })
  533. }
  534. // countLogs 统计分成明细行数(测试辅助)。
  535. func countLogs(t *testing.T, db *gorm.DB) int64 {
  536. t.Helper()
  537. var count int64
  538. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  539. t.Fatalf("count 失败: %v", err)
  540. }
  541. return count
  542. }
  543. // TestAddLogStartFromParentDumpSemantics 审计 P0-2(dump `yuansiwei_finance.sql:763744`):
  544. // 上行分成的起点是 **findUserid 的上级**,本人不参与;findUserid 是根 → 无明细(幂等空操作)。
  545. //
  546. // 修复前从本人开始 → 本人也记一份,整整多算一代(金额错发)。
  547. func TestAddLogStartFromParentDumpSemantics(t *testing.T) {
  548. ctx := context.Background()
  549. stu := nodeID(901)
  550. t.Run("根用户无明细(子查询为 NULL)", func(t *testing.T) {
  551. db := newDivideServiceDB(t)
  552. svc := NewDivideService(db, nil)
  553. root := nodeID(0)
  554. seedRoot(t, db, root, model.DivideTypePerLesson, "10.00")
  555. if err := svc.AddLog(ctx, root, stu, 777, ""); err != nil {
  556. t.Fatalf("根用户报课应静默不入账(不报错),实得 %v", err)
  557. }
  558. if count := countLogs(t, db); count != 0 {
  559. t.Fatalf("根用户无上级 → 不应生成明细,实得 %d", count)
  560. }
  561. if got := cents(t, loadDivideNode(t, db, root).TotalIncome); got != 0 {
  562. t.Fatalf("根用户 total_income 应保持 0,实得 %d 分", got)
  563. }
  564. })
  565. t.Run("只给上级及更高层分成、本人无明细", func(t *testing.T) {
  566. db := newDivideServiceDB(t)
  567. svc := NewDivideService(db, nil)
  568. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  569. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  570. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  571. t.Fatalf("建链失败: %v", err)
  572. }
  573. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  574. t.Fatalf("建链失败: %v", err)
  575. }
  576. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  577. t.Fatalf("设额度 B 失败: %v", err)
  578. }
  579. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  580. t.Fatalf("设额度 C 失败: %v", err)
  581. }
  582. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  583. t.Fatalf("AddLog 失败: %v", err)
  584. }
  585. var rows []model.UserDivideIntoLog
  586. if err := db.Find(&rows).Error; err != nil {
  587. t.Fatalf("读明细失败: %v", err)
  588. }
  589. got := make(map[string]int64, len(rows))
  590. for i := range rows {
  591. got[rows[i].UserID] = cents(t, rows[i].Money)
  592. }
  593. if len(got) != 2 {
  594. t.Fatalf("应只有上级 b 与根 a 两条明细,实得 %d:%v", len(got), got)
  595. }
  596. if _, ok := got[c]; ok {
  597. t.Fatal("本人 c 不得出现在分成明细中(多算一代 = 金额错发)")
  598. }
  599. if got[b] != 500 || got[a] != 1000 {
  600. t.Fatalf("分成金额不符:b=%d a=%d(期望 500/1000)", got[b], got[a])
  601. }
  602. if cents(t, loadDivideNode(t, db, c).TotalIncome) != 0 {
  603. t.Fatal("本人 c 的 total_income 必须保持 0")
  604. }
  605. })
  606. t.Run("上级已断链(不在树中)→ 无明细", func(t *testing.T) {
  607. db := newDivideServiceDB(t)
  608. svc := NewDivideService(db, nil)
  609. a, b := nodeID(0), nodeID(1)
  610. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  611. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  612. t.Fatalf("建链失败: %v", err)
  613. }
  614. // 人为把 b 的上级指向一个不存在的节点(脏数据 / 上级已退网)
  615. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  616. UpdateColumn("parent_user_id", nodeID(777)).Error; err != nil {
  617. t.Fatalf("造断链失败: %v", err)
  618. }
  619. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  620. t.Fatalf("断链应静默不入账,实得 %v", err)
  621. }
  622. if count := countLogs(t, db); count != 0 {
  623. t.Fatalf("断链不应生成明细,实得 %d", count)
  624. }
  625. })
  626. }
  627. // TestAddLogNonTreeNodeNoop 非分账树节点 → 静默不入账(不报错)。
  628. func TestAddLogNonTreeNodeNoop(t *testing.T) {
  629. db := newDivideServiceDB(t)
  630. svc := NewDivideService(db, nil)
  631. ctx := context.Background()
  632. if err := svc.AddLog(ctx, nodeID(404), nodeID(901), 777, ""); err != nil {
  633. t.Fatalf("非树节点应静默不入账,实得 %v", err)
  634. }
  635. if count := countLogs(t, db); count != 0 {
  636. t.Fatalf("非树节点不应生成明细,实得 %d", count)
  637. }
  638. if err := svc.AddLog(ctx, nodeID(1), "", 777, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  639. t.Fatalf("空学生应 3140,实得 %v", err)
  640. }
  641. if err := svc.AddLog(ctx, nodeID(1), nodeID(901), 0, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  642. t.Fatalf("recordID<=0 应 3140,实得 %v", err)
  643. }
  644. }
  645. // TestAddLogCycleGuard 数据成环 → 迭代层数兜底 3111(不死循环、不栈溢出)。
  646. func TestAddLogCycleGuard(t *testing.T) {
  647. db := newDivideServiceDB(t)
  648. svc := NewDivideService(db, nil)
  649. ctx := context.Background()
  650. a, b := nodeID(0), nodeID(1)
  651. seedRoot(t, db, a, model.DivideTypeOneOff, "10.00")
  652. seedRoot(t, db, b, model.DivideTypeOneOff, "10.00")
  653. // 人为造自环(脏数据)
  654. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", a).
  655. Updates(map[string]any{"parent_user_id": b}).Error; err != nil {
  656. t.Fatalf("造环失败: %v", err)
  657. }
  658. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  659. Updates(map[string]any{"parent_user_id": a}).Error; err != nil {
  660. t.Fatalf("造环失败: %v", err)
  661. }
  662. err := svc.AddLog(ctx, a, nodeID(901), 777, "")
  663. if !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  664. t.Fatalf("成环应 3111(层级兜底),实得 %v", err)
  665. }
  666. // 事务回滚:环上的入账不应留下
  667. if count := countLogs(t, db); count != 0 {
  668. t.Fatalf("报错后应整体回滚(0 条明细),实得 %d", count)
  669. }
  670. }
  671. // TestDeleteLogRollbackBranch 撤销分支②:无首次扣费记录 → 回滚 total_income 并删行。
  672. func TestDeleteLogRollbackBranch(t *testing.T) {
  673. db := newDivideServiceDB(t)
  674. svc := NewDivideService(db, nil) // 端口未注入 → 一律走回滚
  675. ctx := context.Background()
  676. a, b := nodeID(0), nodeID(1)
  677. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  678. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  679. t.Fatalf("建链失败: %v", err)
  680. }
  681. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  682. t.Fatalf("设额度失败: %v", err)
  683. }
  684. stu := nodeID(901)
  685. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  686. t.Fatalf("AddLog 失败: %v", err)
  687. }
  688. // b 报课 → 只有上级 a 得一条(本人不参与分成,dump 口径)
  689. if count := countLogs(t, db); count != 1 {
  690. t.Fatalf("应为 1 条明细(仅上级),实得 %d", count)
  691. }
  692. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  693. t.Fatalf("DeleteLog 失败: %v", err)
  694. }
  695. if count := countLogs(t, db); count != 0 {
  696. t.Fatalf("回滚删除后应 0 条明细,实得 %d", count)
  697. }
  698. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  699. t.Fatalf("a.total_income 应回滚为 0,实得 %d 分", got)
  700. }
  701. if got := cents(t, loadDivideNode(t, db, b).TotalIncome); got != 0 {
  702. t.Fatalf("b.total_income 应回滚为 0,实得 %d 分", got)
  703. }
  704. // 幂等:再次撤销 → 空操作
  705. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  706. t.Fatalf("重复撤销应幂等成功,实得 %v", err)
  707. }
  708. }
  709. // TestDeleteLogRebindBranch 撤销分支①:已有首次扣费记录(≠当前订单)→ 改绑保留分成。
  710. func TestDeleteLogRebindBranch(t *testing.T) {
  711. db := newDivideServiceDB(t)
  712. port := &fakeFirstCharged{recordID: 888, found: true}
  713. svc := NewDivideService(db, port)
  714. ctx := context.Background()
  715. a, b := nodeID(0), nodeID(1)
  716. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  717. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  718. t.Fatalf("建链失败: %v", err)
  719. }
  720. stu := nodeID(901)
  721. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  722. t.Fatalf("AddLog 失败: %v", err)
  723. }
  724. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  725. t.Fatalf("DeleteLog 失败: %v", err)
  726. }
  727. var rows []model.UserDivideIntoLog
  728. if err := db.Find(&rows).Error; err != nil {
  729. t.Fatalf("读明细失败: %v", err)
  730. }
  731. if len(rows) != 1 {
  732. t.Fatalf("改绑分支应保留明细(1 条),实得 %d", len(rows))
  733. }
  734. if rows[0].OrderNo == nil || *rows[0].OrderNo != "888" {
  735. t.Fatalf("order_no 应改绑为 888,实得 %v", rows[0].OrderNo)
  736. }
  737. if rows[0].Remark == nil || *rows[0].Remark != remarkRebind {
  738. t.Fatalf("remark 应为 %q,实得 %v", remarkRebind, rows[0].Remark)
  739. }
  740. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 1000 {
  741. t.Fatalf("改绑不回滚收入(应仍 1000 分),实得 %d", got)
  742. }
  743. if port.calls == 0 {
  744. t.Fatal("改绑判定应调用首次扣费端口")
  745. }
  746. }
  747. // TestDeleteLogFirstEqualsOrderRebind 首扣记录**就是**当前订单 → 仍然改绑保留(audit D11,dump 762547)。
  748. //
  749. // dump 的改绑分支不与当前 orderID 比较:撤的正是"当前这单"而它本身就是首扣记录,
  750. // 带 `first != orderID` 条件会误判成"无可改绑"→ 回滚删除,把真实产生的分成整组冲掉(少发钱)。
  751. func TestDeleteLogFirstEqualsOrderRebind(t *testing.T) {
  752. db := newDivideServiceDB(t)
  753. port := &fakeFirstCharged{recordID: 777, found: true}
  754. svc := NewDivideService(db, port)
  755. ctx := context.Background()
  756. a, b := nodeID(0), nodeID(1)
  757. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  758. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  759. t.Fatalf("建链失败: %v", err)
  760. }
  761. stu := nodeID(901)
  762. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  763. t.Fatalf("AddLog 失败: %v", err)
  764. }
  765. before := loadDivideNode(t, db, a).TotalIncome
  766. // 把改绑前的 create_time 拨到 2020:改绑要求"重置为 now()",用 2020 作参照可绕开
  767. // sqlite CURRENT_TIMESTAMP 的秒级精度(同秒内 After() 无法区分)
  768. old2020 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
  769. if err := db.Model(&model.UserDivideIntoLog{}).Where("user_id = ?", a).
  770. UpdateColumn("create_time", old2020).Error; err != nil {
  771. t.Fatalf("回拨 create_time 失败: %v", err)
  772. }
  773. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  774. t.Fatalf("DeleteLog 失败: %v", err)
  775. }
  776. if count := countLogs(t, db); count != 1 {
  777. t.Fatalf("首扣记录=当前订单 → 应改绑保留(1 条),实得 %d", count)
  778. }
  779. var rows []model.UserDivideIntoLog
  780. if err := db.Find(&rows).Error; err != nil {
  781. t.Fatalf("读明细失败: %v", err)
  782. }
  783. if rows[0].OrderNo == nil || *rows[0].OrderNo != "777" {
  784. t.Fatalf("order_no 应仍为 777(改绑到首扣记录),实得 %v", rows[0].OrderNo)
  785. }
  786. if rows[0].Remark == nil || *rows[0].Remark != remarkRebind {
  787. t.Fatalf("remark 应为 %q,实得 %v", remarkRebind, rows[0].Remark)
  788. }
  789. if got := loadDivideNode(t, db, a).TotalIncome; got != before {
  790. t.Fatalf("改绑不回滚 total_income(应仍 %q),实得 %q", before, got)
  791. }
  792. if !rows[0].CreateTime.After(old2020) {
  793. t.Fatalf("改绑后 create_time 应重置为 now()(> 2020),实得 %s", rows[0].CreateTime)
  794. }
  795. if err := svc.DeleteLog(ctx, stu, 0); !errors.Is(err, apperr.ErrBusinessParam) {
  796. t.Fatalf("orderID<=0 应 3140,实得 %v", err)
  797. }
  798. }
  799. // TestUpdateQuotaCascade 额度级联下降(子不得超父)+ 参数/缺失分支。
  800. func TestUpdateQuotaCascade(t *testing.T) {
  801. db := newDivideServiceDB(t)
  802. svc := NewDivideService(db, nil)
  803. ctx := context.Background()
  804. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  805. seedRoot(t, db, a, model.DivideTypeOneOff, "20.00")
  806. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  807. t.Fatalf("建链失败: %v", err)
  808. }
  809. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  810. t.Fatalf("建链失败: %v", err)
  811. }
  812. if err := svc.UpdateQuota(ctx, b, money.FromCents(1500)); err != nil {
  813. t.Fatalf("设额度 B 失败: %v", err)
  814. }
  815. if err := svc.UpdateQuota(ctx, c, money.FromCents(1200)); err != nil {
  816. t.Fatalf("设额度 C 失败: %v", err)
  817. }
  818. // 父 A 降到 10.00 → B(15)、C(12) 一并压到 10.00
  819. if err := svc.UpdateQuota(ctx, a, money.FromCents(1000)); err != nil {
  820. t.Fatalf("UpdateQuota(A,10) 失败: %v", err)
  821. }
  822. for _, id := range []string{a, b, c} {
  823. if got := cents(t, loadDivideNode(t, db, id).Quota); got != 1000 {
  824. t.Fatalf("%s.quota 应级联压到 1000 分,实得 %d", id, got)
  825. }
  826. }
  827. // 子节点超额(> 父)→ 3111
  828. if err := svc.UpdateQuota(ctx, b, money.FromCents(9999)); !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  829. t.Fatalf("超过上级应 3111,实得 %v", err)
  830. }
  831. // 参数/缺失
  832. if err := svc.UpdateQuota(ctx, b, money.FromCents(-1)); !errors.Is(err, apperr.ErrBusinessParam) {
  833. t.Fatalf("负额度应 3140,实得 %v", err)
  834. }
  835. if err := svc.UpdateQuota(ctx, nodeID(404), money.FromCents(100)); !errors.Is(err, infraerrors.ErrNotFound) {
  836. t.Fatalf("节点不存在应 3001,实得 %v", err)
  837. }
  838. if err := svc.UpdateQuota(ctx, "", money.FromCents(100)); !errors.Is(err, apperr.ErrBusinessParam) {
  839. t.Fatalf("空 userID 应 3140,实得 %v", err)
  840. }
  841. }
  842. // TestUpdateQuotaNoCascadeWhenOrigZero 原 quota=0 时不级联(audit A6,dump 763872 `IF (uQuota>0)`)。
  843. //
  844. // 语义:还没配置过额度的节点,被"设成某个值"时不该顺手压低子树(子树额度是独立配置的阶梯)。
  845. // 对照:节点原额度 > 0 时级联照旧生效(后半段断言)。
  846. func TestUpdateQuotaNoCascadeWhenOrigZero(t *testing.T) {
  847. db := newDivideServiceDB(t)
  848. svc := NewDivideService(db, nil)
  849. ctx := context.Background()
  850. a, b := nodeID(0), nodeID(1)
  851. seedRoot(t, db, a, model.DivideTypeOneOff, "0.00") // 原 quota = 0
  852. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  853. t.Fatalf("建链失败: %v", err)
  854. }
  855. // 直接把子节点额度设成 5.00(绕过服务,构造"父 0 / 子 5"的起始态)
  856. if err := db.Exec("UPDATE t_user_divide_into SET quota = ? WHERE user_id = ?", "5.00", b).Error; err != nil {
  857. t.Fatalf("配置子额度失败: %v", err)
  858. }
  859. // 父原 quota=0 → 设成 10.00 **不级联**:子保持 5.00
  860. if err := svc.UpdateQuota(ctx, a, money.FromCents(1000)); err != nil {
  861. t.Fatalf("UpdateQuota 失败: %v", err)
  862. }
  863. if got := cents(t, loadDivideNode(t, db, a).Quota); got != 1000 {
  864. t.Fatalf("父额度应为 10.00,实得 %d 分", got)
  865. }
  866. if got := cents(t, loadDivideNode(t, db, b).Quota); got != 500 {
  867. t.Fatalf("原 quota=0 不应级联:子应保持 5.00,实得 %d 分", got)
  868. }
  869. // 父原 quota=10.00 > 0 → 降到 3.00 **会级联**:子被压到 3.00
  870. if err := svc.UpdateQuota(ctx, a, money.FromCents(300)); err != nil {
  871. t.Fatalf("UpdateQuota(第二次) 失败: %v", err)
  872. }
  873. if got := cents(t, loadDivideNode(t, db, a).Quota); got != 300 {
  874. t.Fatalf("父额度应为 3.00,实得 %d 分", got)
  875. }
  876. if got := cents(t, loadDivideNode(t, db, b).Quota); got != 300 {
  877. t.Fatalf("原 quota>0 应级联压到 3.00,实得 %d 分", got)
  878. }
  879. }
  880. // TestDivideServiceNestedTxPassThrough 事务透传纪律:本服务在**外层事务内**被调用时
  881. // 必须经 WithTxContext 复用同一 tx(不重复 BEGIN),且随外层回滚一并撤销。
  882. func TestDivideServiceNestedTxPassThrough(t *testing.T) {
  883. db := newDivideServiceDB(t)
  884. svc := NewDivideService(db, nil)
  885. runner := repository.NewTxRunner(db)
  886. ctx := context.Background()
  887. a, b := nodeID(0), nodeID(1)
  888. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  889. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  890. t.Fatalf("建链失败: %v", err)
  891. }
  892. stu := nodeID(901)
  893. boom := errors.New("outer-rollback")
  894. err := runner.WithinTx(ctx, func(tx *gorm.DB) error {
  895. txCtx := repository.WithTxContext(ctx, tx)
  896. if aerr := svc.AddLog(txCtx, b, stu, 777, ""); aerr != nil {
  897. return aerr
  898. }
  899. // 事务内应可见刚写入的明细(说明确实跑在同一 tx 上)
  900. var inside int64
  901. if cerr := tx.Model(&model.UserDivideIntoLog{}).Count(&inside).Error; cerr != nil {
  902. return cerr
  903. }
  904. if inside != 1 {
  905. t.Fatalf("外层事务内应可见 1 条明细(仅上级,本人不参与),实得 %d", inside)
  906. }
  907. return boom
  908. })
  909. if !errors.Is(err, infraerrors.ErrDBError) {
  910. t.Fatalf("非业务错误应归一为 5002,实得 %v", err)
  911. }
  912. if count := countLogs(t, db); count != 0 {
  913. t.Fatalf("外层回滚后明细应全部消失(无独立事务提前提交),实得 %d", count)
  914. }
  915. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  916. t.Fatalf("回滚后 total_income 应为 0,实得 %d 分", got)
  917. }
  918. }
  919. // seedChain 直接落一条 layer=1..n 的**单链**,绕过 AddSubordinate。
  920. //
  921. // 为什么必须绕过:F20 之后 AddSubordinate 有 3 层业务上限,用公开接口建不出 100 层链。
  922. // 但「结构上限 / 上行 BFS 必须终止」要验的恰恰是**脏数据**(成环、超长链)下的行为,
  923. // 这种数据在现实里只能由历史迁移产生 —— 所以这里直接写库,等价于"库里已经有这么一棵树",
  924. // 与"用户用接口建出来的树"是两件事,不能混。
  925. //
  926. // 嵌套集取值(单链,n 个节点):节点 i(1-based)left = 2i-1,right = 2(n-i+1)。
  927. // **parent_user_id 必须自己连上**:上行 BFS 的唯一依据就是这列(不是 layer、不是嵌套集区间),
  928. // 只写 layer/left/right 而漏掉 parent 会造出"看似 100 层、实际 100 个孤点"的假数据,
  929. // 断言就会以"0 条明细"的形式失败 —— 空过的反面:数据没连上,测试反而更红了。
  930. func seedChain(t *testing.T, db *gorm.DB, n int32, typ int8, quota string) []string {
  931. t.Helper()
  932. if n <= 0 {
  933. t.Fatalf("seedChain 需要 n>0,实得 %d", n)
  934. }
  935. ids := make([]string, 0, n)
  936. for i := int32(1); i <= n; i++ {
  937. ids = append(ids, nodeID(int(i)))
  938. }
  939. root := ids[0]
  940. rows := make([]model.UserDivideInto, 0, n)
  941. for i := int32(1); i <= n; i++ {
  942. rootCopy := root
  943. var parent *string
  944. if i > 1 {
  945. p := ids[i-2]
  946. parent = &p
  947. }
  948. rows = append(rows, model.UserDivideInto{
  949. UserID: ids[i-1],
  950. Type: typ,
  951. Quota: quota,
  952. TotalIncome: "0.00",
  953. TotalIncomePayed: "0.00",
  954. RootUserID: &rootCopy,
  955. ParentUserID: parent,
  956. LeftVal: 2*i - 1,
  957. RightVal: 2 * (n - i + 1),
  958. Layer: i,
  959. })
  960. }
  961. if err := db.Create(&rows).Error; err != nil {
  962. t.Fatalf("seed %d 层链失败: %v", n, err)
  963. }
  964. return ids
  965. }
  966. // TestAddLogBFSDepthBoundary 100 层链(layer 1..100)恰好在上限内:BFS 必须完整走完到根
  967. // (101 级才触发 3111,见 TestAddLogCycleGuard)。同时验证"迭代不递归"在大深度下不栈溢出。
  968. //
  969. // 链由 seedChain 直接写库(F20 的 3 层业务上限不允许用 AddSubordinate 建这么深),
  970. // 语义是"库里已存在历史的超长链":**读路径不能因为链长就崩**,但**写路径不许再造新的**。
  971. //
  972. // 明细条数 = 99(链尾本人不参与分成,dump 起点是其上级,故比全链少 1 条)。
  973. func TestAddLogBFSDepthBoundary(t *testing.T) {
  974. db := newDivideServiceDB(t)
  975. svc := NewDivideService(db, nil)
  976. ctx := context.Background()
  977. // audit D2:quota<=0 的节点不生成明细 → 每节点自带 1.00 额度(seedChain 里已给),
  978. // 否则只有根节点会入账(本用例要测的是 BFS 深度边界,不是 D2)
  979. ids := seedChain(t, db, MaxDivideDepth, model.DivideTypePerLesson, "1.00")
  980. tail := ids[len(ids)-1]
  981. if got := loadDivideNode(t, db, tail).Layer; got != MaxDivideDepth {
  982. t.Fatalf("链尾 layer 应为 %d,实得 %d", MaxDivideDepth, got)
  983. }
  984. if err := svc.AddLog(ctx, tail, nodeID(901), 777, ""); err != nil {
  985. t.Fatalf("%d 层链的 BFS 入账应在限内成功,实得 %v", MaxDivideDepth, err)
  986. }
  987. // 链尾本人不参与 → 明细 = 层数 - 1
  988. if count := countLogs(t, db); count != int64(MaxDivideDepth-1) {
  989. t.Fatalf("%d 层链应生成 %d 条明细(本人不参与),实得 %d", MaxDivideDepth, MaxDivideDepth-1, count)
  990. }
  991. // 根节点收入应恰好为一次 quota
  992. if got := cents(t, loadDivideNode(t, db, ids[0]).TotalIncome); got != 100 {
  993. t.Fatalf("根节点 total_income 应为 100 分,实得 %d", got)
  994. }
  995. }