divide_service_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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. "testing"
  13. gormsqlite "github.com/glebarez/sqlite"
  14. "gorm.io/gorm"
  15. "yuansiwei/unified-backend/internal/academic/apperr"
  16. "yuansiwei/unified-backend/internal/academic/model"
  17. "yuansiwei/unified-backend/internal/academic/money"
  18. "yuansiwei/unified-backend/internal/academic/repository"
  19. infraerrors "yuansiwei/unified-backend/internal/infra/errors"
  20. )
  21. // newDivideServiceDB 分账域真实库(2 表 AutoMigrate)。
  22. func newDivideServiceDB(t *testing.T) *gorm.DB {
  23. t.Helper()
  24. dsn := filepath.Join(t.TempDir(), "academic_divide_service_test.db")
  25. db, err := gorm.Open(gormsqlite.Open(dsn), &gorm.Config{})
  26. if err != nil {
  27. t.Fatalf("gorm.Open(分账服务文件库) 失败: %v", err)
  28. }
  29. t.Cleanup(func() {
  30. if sqlDB, e := db.DB(); e == nil {
  31. _ = sqlDB.Close()
  32. }
  33. })
  34. if err := db.AutoMigrate(&model.UserDivideInto{}, &model.UserDivideIntoLog{}); err != nil {
  35. t.Fatalf("AutoMigrate(分账 2 表) 失败: %v", err)
  36. }
  37. return db
  38. }
  39. // nodeID 生成 26 位类 ULID 的测试用户 ID(t_user_divide_into.user_id 为 VARCHAR(26))。
  40. func nodeID(i int) string { return fmt.Sprintf("01H%023d", i) }
  41. // seedRoot 直接落一棵树的根节点(dump 中根节点由后台/迁移建立,不在 4 个 SP 范围内)。
  42. func seedRoot(t *testing.T, db *gorm.DB, userID string, typ int8, quota string) {
  43. t.Helper()
  44. root := userID
  45. row := &model.UserDivideInto{
  46. UserID: userID,
  47. Type: typ,
  48. Quota: quota,
  49. TotalIncome: "0.00",
  50. TotalIncomePayed: "0.00",
  51. RootUserID: &root,
  52. LeftVal: 1,
  53. RightVal: 2,
  54. Layer: 1,
  55. }
  56. if err := db.Create(row).Error; err != nil {
  57. t.Fatalf("seed 根节点(%s) 失败: %v", userID, err)
  58. }
  59. }
  60. // loadDivideNode 读节点。
  61. func loadDivideNode(t *testing.T, db *gorm.DB, userID string) model.UserDivideInto {
  62. t.Helper()
  63. var row model.UserDivideInto
  64. if err := db.Where("user_id = ?", userID).First(&row).Error; err != nil {
  65. t.Fatalf("读节点(%s) 失败: %v", userID, err)
  66. }
  67. return row
  68. }
  69. // cents 金额字符串 → 分(sqlite NUMERIC 回读会丢 ".00",不得比字符串)。
  70. func cents(t *testing.T, s string) int64 {
  71. t.Helper()
  72. amt, err := money.Parse(s)
  73. if err != nil {
  74. t.Fatalf("金额解析失败 %q: %v", s, err)
  75. }
  76. return amt.Cents()
  77. }
  78. // fakeFirstCharged 首次扣费记录端口的测试替身。
  79. type fakeFirstCharged struct {
  80. recordID int64
  81. found bool
  82. err error
  83. calls int
  84. }
  85. // FirstChargedRecordID 实现 FirstChargedRecordReader。
  86. func (f *fakeFirstCharged) FirstChargedRecordID(_ context.Context, _ string) (int64, bool, error) {
  87. f.calls++
  88. return f.recordID, f.found, f.err
  89. }
  90. // TestAddSubordinateNestedSetInvariants 100 节点随机树:left<right、区间嵌套无交叉、
  91. // 节点数 = 宽度/2、值集合恰好 1..2N、父区间包含子区间。
  92. func TestAddSubordinateNestedSetInvariants(t *testing.T) {
  93. db := newDivideServiceDB(t)
  94. svc := NewDivideService(db, nil)
  95. ctx := context.Background()
  96. root := nodeID(0)
  97. seedRoot(t, db, root, model.DivideTypeOneOff, "10.00")
  98. created := []string{root}
  99. rnd := rand.New(rand.NewSource(20260109))
  100. const total = 100
  101. for i := 1; i < total; i++ {
  102. parent := created[rnd.Intn(len(created))]
  103. child := nodeID(i)
  104. if err := svc.AddSubordinate(ctx, parent, child); err != nil {
  105. t.Fatalf("AddSubordinate(%s→%s) 失败: %v", parent, child, err)
  106. }
  107. created = append(created, child)
  108. }
  109. var nodes []model.UserDivideInto
  110. if err := db.Find(&nodes).Error; err != nil {
  111. t.Fatalf("读全树失败: %v", err)
  112. }
  113. if len(nodes) != total {
  114. t.Fatalf("节点数应为 %d,实得 %d", total, len(nodes))
  115. }
  116. // ① left < right 且值集合 = {1..2N}(每值恰好一次)
  117. seen := make(map[int32]string, total*2)
  118. maxRight := int32(0)
  119. for i := range nodes {
  120. n := nodes[i]
  121. if n.LeftVal >= n.RightVal {
  122. t.Fatalf("节点 %s 违反 left<right:(%d,%d)", n.UserID, n.LeftVal, n.RightVal)
  123. }
  124. for _, v := range []int32{n.LeftVal, n.RightVal} {
  125. if prev, dup := seen[v]; dup {
  126. t.Fatalf("左/右值 %d 被重复使用(%s 与 %s),嵌套集区间损坏", v, prev, n.UserID)
  127. }
  128. seen[v] = n.UserID
  129. }
  130. if n.RightVal > maxRight {
  131. maxRight = n.RightVal
  132. }
  133. }
  134. if len(seen) != total*2 || maxRight != int32(total*2) {
  135. t.Fatalf("值集合应为 1..%d(共 %d 个),实得 %d 个、max=%d", total*2, total*2, len(seen), maxRight)
  136. }
  137. // ② 节点数 = 宽度/2(Nested Set 恒等式)
  138. if got := int(maxRight / 2); got != total {
  139. t.Fatalf("节点数应 = maxRight/2 = %d,实得 %d", total, got)
  140. }
  141. // ③ 任意两节点区间:包含或相离,**绝不交叉**
  142. for i := 0; i < len(nodes); i++ {
  143. for j := i + 1; j < len(nodes); j++ {
  144. a, b := nodes[i], nodes[j]
  145. nested := (a.LeftVal < b.LeftVal && b.RightVal < a.RightVal) ||
  146. (b.LeftVal < a.LeftVal && a.RightVal < b.RightVal)
  147. disjoint := a.RightVal < b.LeftVal || b.RightVal < a.LeftVal
  148. if !nested && !disjoint {
  149. t.Fatalf("区间交叉:%s(%d,%d) vs %s(%d,%d)", a.UserID, a.LeftVal, a.RightVal, b.UserID, b.LeftVal, b.RightVal)
  150. }
  151. }
  152. }
  153. // ④ 父区间严格包含子区间,且 layer = 父 layer+1
  154. byID := make(map[string]model.UserDivideInto, len(nodes))
  155. for i := range nodes {
  156. byID[nodes[i].UserID] = nodes[i]
  157. }
  158. for i := range nodes {
  159. n := nodes[i]
  160. if n.ParentUserID == nil || *n.ParentUserID == "" {
  161. if n.UserID != root {
  162. t.Fatalf("非根节点 %s 缺少 parent", n.UserID)
  163. }
  164. continue
  165. }
  166. parent, ok := byID[*n.ParentUserID]
  167. if !ok {
  168. t.Fatalf("节点 %s 的 parent %s 不在树中", n.UserID, *n.ParentUserID)
  169. }
  170. if !(parent.LeftVal < n.LeftVal && n.RightVal < parent.RightVal) {
  171. t.Fatalf("%s 未嵌套在父 %s 区间内:父(%d,%d) 子(%d,%d)",
  172. n.UserID, parent.UserID, parent.LeftVal, parent.RightVal, n.LeftVal, n.RightVal)
  173. }
  174. if n.Layer != parent.Layer+1 {
  175. t.Fatalf("%s layer 应为父+1(%d),实得 %d", n.UserID, parent.Layer+1, n.Layer)
  176. }
  177. }
  178. }
  179. // TestAddSubordinateGuards 入参/上级缺失/自环。
  180. func TestAddSubordinateGuards(t *testing.T) {
  181. db := newDivideServiceDB(t)
  182. svc := NewDivideService(db, nil)
  183. ctx := context.Background()
  184. root := nodeID(0)
  185. seedRoot(t, db, root, model.DivideTypeOneOff, "10.00")
  186. if err := svc.AddSubordinate(ctx, "", nodeID(1)); !errors.Is(err, apperr.ErrBusinessParam) {
  187. t.Fatalf("空上级应 3140,实得 %v", err)
  188. }
  189. if err := svc.AddSubordinate(ctx, root, root); !errors.Is(err, apperr.ErrBusinessParam) {
  190. t.Fatalf("自环应 3140,实得 %v", err)
  191. }
  192. if err := svc.AddSubordinate(ctx, nodeID(99), nodeID(1)); !errors.Is(err, infraerrors.ErrNotFound) {
  193. t.Fatalf("上级不存在应 3001,实得 %v", err)
  194. }
  195. var zero *DivideService
  196. if err := zero.AddSubordinate(ctx, root, nodeID(1)); !errors.Is(err, infraerrors.ErrInternal) {
  197. t.Fatalf("未装配服务应 ErrInternal,实得 %v", err)
  198. }
  199. }
  200. // TestAddSubordinateReparentBranch 已存在节点分支:改挂父链并显式补齐 root(dump NULL 缺陷修正)。
  201. func TestAddSubordinateReparentBranch(t *testing.T) {
  202. db := newDivideServiceDB(t)
  203. svc := NewDivideService(db, nil)
  204. ctx := context.Background()
  205. root := nodeID(0)
  206. orphan := nodeID(50)
  207. seedRoot(t, db, root, model.DivideTypeOneOff, "10.00")
  208. // 模拟 dump 脏数据:subid 已存在、parent/root 均为 NULL
  209. if err := db.Create(&model.UserDivideInto{
  210. UserID: orphan, Type: model.DivideTypeOneOff, Quota: "0.00",
  211. TotalIncome: "0.00", TotalIncomePayed: "0.00",
  212. LeftVal: 100, RightVal: 101, Layer: 1,
  213. }).Error; err != nil {
  214. t.Fatalf("seed 孤立节点失败: %v", err)
  215. }
  216. if err := svc.AddSubordinate(ctx, root, orphan); err != nil {
  217. t.Fatalf("改挂分支失败: %v", err)
  218. }
  219. got := loadDivideNode(t, db, orphan)
  220. if got.ParentUserID == nil || *got.ParentUserID != root {
  221. t.Fatalf("parent 应改为 %s,实得 %v", root, got.ParentUserID)
  222. }
  223. if got.RootUserID == nil || *got.RootUserID != root {
  224. t.Fatalf("root_user_id 必须补齐为 %s(dump 缺陷修正),实得 %v", root, got.RootUserID)
  225. }
  226. if got.Layer != 2 {
  227. t.Fatalf("layer 应为 2,实得 %d", got.Layer)
  228. }
  229. // 不重排左右值(与原 SP 对齐)→ 值保持不变
  230. if got.LeftVal != 100 || got.RightVal != 101 {
  231. t.Fatalf("改挂分支不应重排左右值,实得 (%d,%d)", got.LeftVal, got.RightVal)
  232. }
  233. }
  234. // TestAddSubordinateDepthLimit 层级上限 100 → 3111。
  235. func TestAddSubordinateDepthLimit(t *testing.T) {
  236. db := newDivideServiceDB(t)
  237. svc := NewDivideService(db, nil)
  238. ctx := context.Background()
  239. root := nodeID(0)
  240. seedRoot(t, db, root, model.DivideTypeOneOff, "1.00")
  241. prev := root
  242. // 链到 layer=100
  243. for i := 1; i <= 99; i++ {
  244. child := nodeID(i)
  245. if err := svc.AddSubordinate(ctx, prev, child); err != nil {
  246. t.Fatalf("建链 AddSubordinate(%s→%s) 失败: %v", prev, child, err)
  247. }
  248. prev = child
  249. }
  250. if got := loadDivideNode(t, db, prev); got.Layer != 100 {
  251. t.Fatalf("链尾 layer 应为 100,实得 %d", got.Layer)
  252. }
  253. if err := svc.AddSubordinate(ctx, prev, nodeID(1000)); !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  254. t.Fatalf("超过 100 层应 3111,实得 %v", err)
  255. }
  256. }
  257. // TestAddLogBFSThreeLevels 上行链 BFS:**从上级起算**(dump `:763744` 子查询口径),
  258. // 本人不参与分成 —— c 报课,只有 b(直接上级)与 a(根)各得一条明细。
  259. func TestAddLogBFSThreeLevels(t *testing.T) {
  260. db := newDivideServiceDB(t)
  261. svc := NewDivideService(db, nil)
  262. ctx := context.Background()
  263. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  264. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  265. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  266. t.Fatalf("建链失败: %v", err)
  267. }
  268. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  269. t.Fatalf("建链失败: %v", err)
  270. }
  271. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  272. t.Fatalf("设额度 B 失败: %v", err)
  273. }
  274. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  275. t.Fatalf("设额度 C 失败: %v", err)
  276. }
  277. stu := nodeID(900)
  278. if err := svc.AddLog(ctx, c, stu, 777, "推荐分成"); err != nil {
  279. t.Fatalf("AddLog 失败: %v", err)
  280. }
  281. var rows []model.UserDivideIntoLog
  282. if err := db.Find(&rows).Error; err != nil {
  283. t.Fatalf("读明细失败: %v", err)
  284. }
  285. if len(rows) != 2 {
  286. t.Fatalf("上行链应生成 2 条明细(本人不参与),实得 %d", len(rows))
  287. }
  288. want := map[string]int64{b: 500, a: 1000}
  289. for i := range rows {
  290. expect, ok := want[rows[i].UserID]
  291. if !ok {
  292. t.Fatalf("出现意外分成用户 %s", rows[i].UserID)
  293. }
  294. if got := cents(t, rows[i].Money); got != expect {
  295. t.Fatalf("用户 %s 分成应为 %d 分,实得 %d", rows[i].UserID, expect, got)
  296. }
  297. if rows[i].OrderNo == nil || *rows[i].OrderNo != "777" {
  298. t.Fatalf("order_no 应为 777,实得 %v", rows[i].OrderNo)
  299. }
  300. if rows[i].Remark == nil || *rows[i].Remark != "推荐分成" {
  301. t.Fatalf("remark 应为推荐分成,实得 %v", rows[i].Remark)
  302. }
  303. if rows[i].Type != model.DivideTypePerLesson {
  304. t.Fatalf("type 应继承节点(2),实得 %d", rows[i].Type)
  305. }
  306. }
  307. // total_income 各自累加自己的 quota
  308. for user, expect := range want {
  309. if got := cents(t, loadDivideNode(t, db, user).TotalIncome); got != expect {
  310. t.Fatalf("%s.total_income 应为 %d 分,实得 %d", user, expect, got)
  311. }
  312. }
  313. // D1 红线:本人(c)不参与分成,任何列都不得被写入
  314. if got := cents(t, loadDivideNode(t, db, c).TotalIncome); got != 0 {
  315. t.Fatalf("本人 %s 不应获得分成(total_income 应 0),实得 %d 分", c, got)
  316. }
  317. for i := range rows {
  318. if rows[i].UserID == c {
  319. t.Fatal("本人不得生成分成明细(dump 起点是 findUserid 的上级)")
  320. }
  321. }
  322. }
  323. // TestAddLogTwoLevelIdempotency 两级幂等:type=1 忽略订单;type=2 含订单。
  324. //
  325. // 结构:root(拿分成的一方)+ child(报课/被推荐人)—— **分成只入 root**(本人不参与,dump 口径)。
  326. func TestAddLogTwoLevelIdempotency(t *testing.T) {
  327. ctx := context.Background()
  328. stu := nodeID(901)
  329. t.Run("type=1 一次付清(同 user+student 只一条)", func(t *testing.T) {
  330. db := newDivideServiceDB(t)
  331. svc := NewDivideService(db, nil)
  332. u, child := nodeID(0), nodeID(1)
  333. seedRoot(t, db, u, model.DivideTypeOneOff, "10.00")
  334. if err := svc.AddSubordinate(ctx, u, child); err != nil {
  335. t.Fatalf("建链失败: %v", err)
  336. }
  337. if err := svc.AddLog(ctx, child, stu, 777, ""); err != nil {
  338. t.Fatalf("AddLog 失败: %v", err)
  339. }
  340. if err := svc.AddLog(ctx, child, stu, 888, ""); err != nil { // 不同订单:应与 type=1 无关
  341. t.Fatalf("AddLog(第二次) 失败: %v", err)
  342. }
  343. var count int64
  344. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  345. t.Fatalf("count 失败: %v", err)
  346. }
  347. if count != 1 {
  348. t.Fatalf("type=1 应仅 1 条明细,实得 %d", count)
  349. }
  350. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 1000 {
  351. t.Fatalf("total_income 应只累加一次(1000 分),实得 %d", got)
  352. }
  353. })
  354. t.Run("type=2 按课次(同 user+student+order 只一条)", func(t *testing.T) {
  355. db := newDivideServiceDB(t)
  356. svc := NewDivideService(db, nil)
  357. u, child := nodeID(0), nodeID(1)
  358. seedRoot(t, db, u, model.DivideTypePerLesson, "10.00")
  359. if err := svc.AddSubordinate(ctx, u, child); err != nil {
  360. t.Fatalf("建链失败: %v", err)
  361. }
  362. for i := 0; i < 2; i++ { // 同一订单重复请求
  363. if err := svc.AddLog(ctx, child, stu, 777, ""); err != nil {
  364. t.Fatalf("AddLog(重复) 失败: %v", err)
  365. }
  366. }
  367. if count := countLogs(t, db); count != 1 {
  368. t.Fatalf("同订单重复请求应幂等(1 条),实得 %d", count)
  369. }
  370. if err := svc.AddLog(ctx, child, stu, 888, ""); err != nil { // 新订单:应新增
  371. t.Fatalf("AddLog(新订单) 失败: %v", err)
  372. }
  373. if count := countLogs(t, db); count != 2 {
  374. t.Fatalf("新订单应新增明细(2 条),实得 %d", count)
  375. }
  376. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 2000 {
  377. t.Fatalf("total_income 应为 2000 分,实得 %d", got)
  378. }
  379. })
  380. }
  381. // countLogs 统计分成明细行数(测试辅助)。
  382. func countLogs(t *testing.T, db *gorm.DB) int64 {
  383. t.Helper()
  384. var count int64
  385. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  386. t.Fatalf("count 失败: %v", err)
  387. }
  388. return count
  389. }
  390. // TestAddLogStartFromParentDumpSemantics 审计 P0-2(dump `yuansiwei_finance.sql:763744`):
  391. // 上行分成的起点是 **findUserid 的上级**,本人不参与;findUserid 是根 → 无明细(幂等空操作)。
  392. //
  393. // 修复前从本人开始 → 本人也记一份,整整多算一代(金额错发)。
  394. func TestAddLogStartFromParentDumpSemantics(t *testing.T) {
  395. ctx := context.Background()
  396. stu := nodeID(901)
  397. t.Run("根用户无明细(子查询为 NULL)", func(t *testing.T) {
  398. db := newDivideServiceDB(t)
  399. svc := NewDivideService(db, nil)
  400. root := nodeID(0)
  401. seedRoot(t, db, root, model.DivideTypePerLesson, "10.00")
  402. if err := svc.AddLog(ctx, root, stu, 777, ""); err != nil {
  403. t.Fatalf("根用户报课应静默不入账(不报错),实得 %v", err)
  404. }
  405. if count := countLogs(t, db); count != 0 {
  406. t.Fatalf("根用户无上级 → 不应生成明细,实得 %d", count)
  407. }
  408. if got := cents(t, loadDivideNode(t, db, root).TotalIncome); got != 0 {
  409. t.Fatalf("根用户 total_income 应保持 0,实得 %d 分", got)
  410. }
  411. })
  412. t.Run("只给上级及更高层分成、本人无明细", func(t *testing.T) {
  413. db := newDivideServiceDB(t)
  414. svc := NewDivideService(db, nil)
  415. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  416. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  417. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  418. t.Fatalf("建链失败: %v", err)
  419. }
  420. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  421. t.Fatalf("建链失败: %v", err)
  422. }
  423. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  424. t.Fatalf("设额度 B 失败: %v", err)
  425. }
  426. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  427. t.Fatalf("设额度 C 失败: %v", err)
  428. }
  429. if err := svc.AddLog(ctx, c, stu, 777, ""); err != nil {
  430. t.Fatalf("AddLog 失败: %v", err)
  431. }
  432. var rows []model.UserDivideIntoLog
  433. if err := db.Find(&rows).Error; err != nil {
  434. t.Fatalf("读明细失败: %v", err)
  435. }
  436. got := make(map[string]int64, len(rows))
  437. for i := range rows {
  438. got[rows[i].UserID] = cents(t, rows[i].Money)
  439. }
  440. if len(got) != 2 {
  441. t.Fatalf("应只有上级 b 与根 a 两条明细,实得 %d:%v", len(got), got)
  442. }
  443. if _, ok := got[c]; ok {
  444. t.Fatal("本人 c 不得出现在分成明细中(多算一代 = 金额错发)")
  445. }
  446. if got[b] != 500 || got[a] != 1000 {
  447. t.Fatalf("分成金额不符:b=%d a=%d(期望 500/1000)", got[b], got[a])
  448. }
  449. if cents(t, loadDivideNode(t, db, c).TotalIncome) != 0 {
  450. t.Fatal("本人 c 的 total_income 必须保持 0")
  451. }
  452. })
  453. t.Run("上级已断链(不在树中)→ 无明细", func(t *testing.T) {
  454. db := newDivideServiceDB(t)
  455. svc := NewDivideService(db, nil)
  456. a, b := nodeID(0), nodeID(1)
  457. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  458. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  459. t.Fatalf("建链失败: %v", err)
  460. }
  461. // 人为把 b 的上级指向一个不存在的节点(脏数据 / 上级已退网)
  462. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  463. UpdateColumn("parent_user_id", nodeID(777)).Error; err != nil {
  464. t.Fatalf("造断链失败: %v", err)
  465. }
  466. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  467. t.Fatalf("断链应静默不入账,实得 %v", err)
  468. }
  469. if count := countLogs(t, db); count != 0 {
  470. t.Fatalf("断链不应生成明细,实得 %d", count)
  471. }
  472. })
  473. }
  474. // TestAddLogNonTreeNodeNoop 非分账树节点 → 静默不入账(不报错)。
  475. func TestAddLogNonTreeNodeNoop(t *testing.T) {
  476. db := newDivideServiceDB(t)
  477. svc := NewDivideService(db, nil)
  478. ctx := context.Background()
  479. if err := svc.AddLog(ctx, nodeID(404), nodeID(901), 777, ""); err != nil {
  480. t.Fatalf("非树节点应静默不入账,实得 %v", err)
  481. }
  482. if count := countLogs(t, db); count != 0 {
  483. t.Fatalf("非树节点不应生成明细,实得 %d", count)
  484. }
  485. if err := svc.AddLog(ctx, nodeID(1), "", 777, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  486. t.Fatalf("空学生应 3140,实得 %v", err)
  487. }
  488. if err := svc.AddLog(ctx, nodeID(1), nodeID(901), 0, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  489. t.Fatalf("recordID<=0 应 3140,实得 %v", err)
  490. }
  491. }
  492. // TestAddLogCycleGuard 数据成环 → 迭代层数兜底 3111(不死循环、不栈溢出)。
  493. func TestAddLogCycleGuard(t *testing.T) {
  494. db := newDivideServiceDB(t)
  495. svc := NewDivideService(db, nil)
  496. ctx := context.Background()
  497. a, b := nodeID(0), nodeID(1)
  498. seedRoot(t, db, a, model.DivideTypeOneOff, "10.00")
  499. seedRoot(t, db, b, model.DivideTypeOneOff, "10.00")
  500. // 人为造自环(脏数据)
  501. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", a).
  502. Updates(map[string]any{"parent_user_id": b}).Error; err != nil {
  503. t.Fatalf("造环失败: %v", err)
  504. }
  505. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  506. Updates(map[string]any{"parent_user_id": a}).Error; err != nil {
  507. t.Fatalf("造环失败: %v", err)
  508. }
  509. err := svc.AddLog(ctx, a, nodeID(901), 777, "")
  510. if !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  511. t.Fatalf("成环应 3111(层级兜底),实得 %v", err)
  512. }
  513. // 事务回滚:环上的入账不应留下
  514. if count := countLogs(t, db); count != 0 {
  515. t.Fatalf("报错后应整体回滚(0 条明细),实得 %d", count)
  516. }
  517. }
  518. // TestDeleteLogRollbackBranch 撤销分支②:无首次扣费记录 → 回滚 total_income 并删行。
  519. func TestDeleteLogRollbackBranch(t *testing.T) {
  520. db := newDivideServiceDB(t)
  521. svc := NewDivideService(db, nil) // 端口未注入 → 一律走回滚
  522. ctx := context.Background()
  523. a, b := nodeID(0), nodeID(1)
  524. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  525. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  526. t.Fatalf("建链失败: %v", err)
  527. }
  528. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  529. t.Fatalf("设额度失败: %v", err)
  530. }
  531. stu := nodeID(901)
  532. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  533. t.Fatalf("AddLog 失败: %v", err)
  534. }
  535. // b 报课 → 只有上级 a 得一条(本人不参与分成,dump 口径)
  536. if count := countLogs(t, db); count != 1 {
  537. t.Fatalf("应为 1 条明细(仅上级),实得 %d", count)
  538. }
  539. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  540. t.Fatalf("DeleteLog 失败: %v", err)
  541. }
  542. if count := countLogs(t, db); count != 0 {
  543. t.Fatalf("回滚删除后应 0 条明细,实得 %d", count)
  544. }
  545. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  546. t.Fatalf("a.total_income 应回滚为 0,实得 %d 分", got)
  547. }
  548. if got := cents(t, loadDivideNode(t, db, b).TotalIncome); got != 0 {
  549. t.Fatalf("b.total_income 应回滚为 0,实得 %d 分", got)
  550. }
  551. // 幂等:再次撤销 → 空操作
  552. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  553. t.Fatalf("重复撤销应幂等成功,实得 %v", err)
  554. }
  555. }
  556. // TestDeleteLogRebindBranch 撤销分支①:已有首次扣费记录(≠当前订单)→ 改绑保留分成。
  557. func TestDeleteLogRebindBranch(t *testing.T) {
  558. db := newDivideServiceDB(t)
  559. port := &fakeFirstCharged{recordID: 888, found: true}
  560. svc := NewDivideService(db, port)
  561. ctx := context.Background()
  562. a, b := nodeID(0), nodeID(1)
  563. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  564. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  565. t.Fatalf("建链失败: %v", err)
  566. }
  567. stu := nodeID(901)
  568. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  569. t.Fatalf("AddLog 失败: %v", err)
  570. }
  571. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  572. t.Fatalf("DeleteLog 失败: %v", err)
  573. }
  574. var rows []model.UserDivideIntoLog
  575. if err := db.Find(&rows).Error; err != nil {
  576. t.Fatalf("读明细失败: %v", err)
  577. }
  578. if len(rows) != 1 {
  579. t.Fatalf("改绑分支应保留明细(1 条),实得 %d", len(rows))
  580. }
  581. if rows[0].OrderNo == nil || *rows[0].OrderNo != "888" {
  582. t.Fatalf("order_no 应改绑为 888,实得 %v", rows[0].OrderNo)
  583. }
  584. if rows[0].Remark == nil || *rows[0].Remark != remarkRebind {
  585. t.Fatalf("remark 应为 %q,实得 %v", remarkRebind, rows[0].Remark)
  586. }
  587. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 1000 {
  588. t.Fatalf("改绑不回滚收入(应仍 1000 分),实得 %d", got)
  589. }
  590. if port.calls == 0 {
  591. t.Fatal("改绑判定应调用首次扣费端口")
  592. }
  593. }
  594. // TestDeleteLogFirstEqualsOrder 首次扣费记录 = 当前订单 → 不属改绑场景,走回滚删除。
  595. func TestDeleteLogFirstEqualsOrder(t *testing.T) {
  596. db := newDivideServiceDB(t)
  597. port := &fakeFirstCharged{recordID: 777, found: true}
  598. svc := NewDivideService(db, port)
  599. ctx := context.Background()
  600. a, b := nodeID(0), nodeID(1)
  601. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  602. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  603. t.Fatalf("建链失败: %v", err)
  604. }
  605. stu := nodeID(901)
  606. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  607. t.Fatalf("AddLog 失败: %v", err)
  608. }
  609. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  610. t.Fatalf("DeleteLog 失败: %v", err)
  611. }
  612. if count := countLogs(t, db); count != 0 {
  613. t.Fatalf("首次记录即当前订单 → 应回滚删除(0 条),实得 %d", count)
  614. }
  615. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  616. t.Fatalf("total_income 应回滚为 0,实得 %d 分", got)
  617. }
  618. if err := svc.DeleteLog(ctx, stu, 0); !errors.Is(err, apperr.ErrBusinessParam) {
  619. t.Fatalf("orderID<=0 应 3140,实得 %v", err)
  620. }
  621. }
  622. // TestUpdateQuotaCascade 额度级联下降(子不得超父)+ 参数/缺失分支。
  623. func TestUpdateQuotaCascade(t *testing.T) {
  624. db := newDivideServiceDB(t)
  625. svc := NewDivideService(db, nil)
  626. ctx := context.Background()
  627. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  628. seedRoot(t, db, a, model.DivideTypeOneOff, "20.00")
  629. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  630. t.Fatalf("建链失败: %v", err)
  631. }
  632. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  633. t.Fatalf("建链失败: %v", err)
  634. }
  635. if err := svc.UpdateQuota(ctx, b, money.FromCents(1500)); err != nil {
  636. t.Fatalf("设额度 B 失败: %v", err)
  637. }
  638. if err := svc.UpdateQuota(ctx, c, money.FromCents(1200)); err != nil {
  639. t.Fatalf("设额度 C 失败: %v", err)
  640. }
  641. // 父 A 降到 10.00 → B(15)、C(12) 一并压到 10.00
  642. if err := svc.UpdateQuota(ctx, a, money.FromCents(1000)); err != nil {
  643. t.Fatalf("UpdateQuota(A,10) 失败: %v", err)
  644. }
  645. for _, id := range []string{a, b, c} {
  646. if got := cents(t, loadDivideNode(t, db, id).Quota); got != 1000 {
  647. t.Fatalf("%s.quota 应级联压到 1000 分,实得 %d", id, got)
  648. }
  649. }
  650. // 子节点超额(> 父)→ 3111
  651. if err := svc.UpdateQuota(ctx, b, money.FromCents(9999)); !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  652. t.Fatalf("超过上级应 3111,实得 %v", err)
  653. }
  654. // 参数/缺失
  655. if err := svc.UpdateQuota(ctx, b, money.FromCents(-1)); !errors.Is(err, apperr.ErrBusinessParam) {
  656. t.Fatalf("负额度应 3140,实得 %v", err)
  657. }
  658. if err := svc.UpdateQuota(ctx, nodeID(404), money.FromCents(100)); !errors.Is(err, infraerrors.ErrNotFound) {
  659. t.Fatalf("节点不存在应 3001,实得 %v", err)
  660. }
  661. if err := svc.UpdateQuota(ctx, "", money.FromCents(100)); !errors.Is(err, apperr.ErrBusinessParam) {
  662. t.Fatalf("空 userID 应 3140,实得 %v", err)
  663. }
  664. }
  665. // TestDivideServiceNestedTxPassThrough 事务透传纪律:本服务在**外层事务内**被调用时
  666. // 必须经 WithTxContext 复用同一 tx(不重复 BEGIN),且随外层回滚一并撤销。
  667. func TestDivideServiceNestedTxPassThrough(t *testing.T) {
  668. db := newDivideServiceDB(t)
  669. svc := NewDivideService(db, nil)
  670. runner := repository.NewTxRunner(db)
  671. ctx := context.Background()
  672. a, b := nodeID(0), nodeID(1)
  673. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  674. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  675. t.Fatalf("建链失败: %v", err)
  676. }
  677. stu := nodeID(901)
  678. boom := errors.New("outer-rollback")
  679. err := runner.WithinTx(ctx, func(tx *gorm.DB) error {
  680. txCtx := repository.WithTxContext(ctx, tx)
  681. if aerr := svc.AddLog(txCtx, b, stu, 777, ""); aerr != nil {
  682. return aerr
  683. }
  684. // 事务内应可见刚写入的明细(说明确实跑在同一 tx 上)
  685. var inside int64
  686. if cerr := tx.Model(&model.UserDivideIntoLog{}).Count(&inside).Error; cerr != nil {
  687. return cerr
  688. }
  689. if inside != 1 {
  690. t.Fatalf("外层事务内应可见 1 条明细(仅上级,本人不参与),实得 %d", inside)
  691. }
  692. return boom
  693. })
  694. if !errors.Is(err, infraerrors.ErrDBError) {
  695. t.Fatalf("非业务错误应归一为 5002,实得 %v", err)
  696. }
  697. if count := countLogs(t, db); count != 0 {
  698. t.Fatalf("外层回滚后明细应全部消失(无独立事务提前提交),实得 %d", count)
  699. }
  700. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  701. t.Fatalf("回滚后 total_income 应为 0,实得 %d 分", got)
  702. }
  703. }
  704. // TestAddLogBFSDepthBoundary 100 层链(layer 1..100)恰好在上限内:BFS 必须完整走完到根
  705. // (101 级才触发 3111,见 TestAddLogCycleGuard)。同时验证"迭代不递归"在大深度下不栈溢出。
  706. //
  707. // 明细条数 = 99(链尾本人不参与分成,dump 起点是其上级,故比全链少 1 条)。
  708. func TestAddLogBFSDepthBoundary(t *testing.T) {
  709. db := newDivideServiceDB(t)
  710. svc := NewDivideService(db, nil)
  711. ctx := context.Background()
  712. root := nodeID(0)
  713. seedRoot(t, db, root, model.DivideTypePerLesson, "1.00")
  714. prev := root
  715. for i := 1; i <= 99; i++ {
  716. child := nodeID(i)
  717. if err := svc.AddSubordinate(ctx, prev, child); err != nil {
  718. t.Fatalf("建链失败(%s→%s): %v", prev, child, err)
  719. }
  720. prev = child
  721. }
  722. tail := prev
  723. if got := loadDivideNode(t, db, tail).Layer; got != MaxDivideDepth {
  724. t.Fatalf("链尾 layer 应为 %d,实得 %d", MaxDivideDepth, got)
  725. }
  726. if err := svc.AddLog(ctx, tail, nodeID(901), 777, ""); err != nil {
  727. t.Fatalf("%d 层链的 BFS 入账应在限内成功,实得 %v", MaxDivideDepth, err)
  728. }
  729. // 链尾本人不参与 → 明细 = 层数 - 1
  730. if count := countLogs(t, db); count != int64(MaxDivideDepth-1) {
  731. t.Fatalf("%d 层链应生成 %d 条明细(本人不参与),实得 %d", MaxDivideDepth, MaxDivideDepth-1, count)
  732. }
  733. // 根节点收入应恰好为一次 quota
  734. if got := cents(t, loadDivideNode(t, db, root).TotalIncome); got != 100 {
  735. t.Fatalf("根节点 total_income 应为 100 分,实得 %d", got)
  736. }
  737. }