divide_service_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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:本人 + 两级上线各生成一条明细并累加 total_income。
  258. func TestAddLogBFSThreeLevels(t *testing.T) {
  259. db := newDivideServiceDB(t)
  260. svc := NewDivideService(db, nil)
  261. ctx := context.Background()
  262. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  263. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  264. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  265. t.Fatalf("建链失败: %v", err)
  266. }
  267. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  268. t.Fatalf("建链失败: %v", err)
  269. }
  270. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  271. t.Fatalf("设额度 B 失败: %v", err)
  272. }
  273. if err := svc.UpdateQuota(ctx, c, money.FromCents(200)); err != nil {
  274. t.Fatalf("设额度 C 失败: %v", err)
  275. }
  276. stu := nodeID(900)
  277. if err := svc.AddLog(ctx, c, stu, 777, "推荐分成"); err != nil {
  278. t.Fatalf("AddLog 失败: %v", err)
  279. }
  280. var rows []model.UserDivideIntoLog
  281. if err := db.Find(&rows).Error; err != nil {
  282. t.Fatalf("读明细失败: %v", err)
  283. }
  284. if len(rows) != 3 {
  285. t.Fatalf("三级链应生成 3 条明细,实得 %d", len(rows))
  286. }
  287. want := map[string]int64{c: 200, b: 500, a: 1000}
  288. for i := range rows {
  289. expect, ok := want[rows[i].UserID]
  290. if !ok {
  291. t.Fatalf("出现意外分成用户 %s", rows[i].UserID)
  292. }
  293. if got := cents(t, rows[i].Money); got != expect {
  294. t.Fatalf("用户 %s 分成应为 %d 分,实得 %d", rows[i].UserID, expect, got)
  295. }
  296. if rows[i].OrderNo == nil || *rows[i].OrderNo != "777" {
  297. t.Fatalf("order_no 应为 777,实得 %v", rows[i].OrderNo)
  298. }
  299. if rows[i].Remark == nil || *rows[i].Remark != "推荐分成" {
  300. t.Fatalf("remark 应为推荐分成,实得 %v", rows[i].Remark)
  301. }
  302. if rows[i].Type != model.DivideTypePerLesson {
  303. t.Fatalf("type 应继承节点(2),实得 %d", rows[i].Type)
  304. }
  305. }
  306. // total_income 各自累加自己的 quota
  307. for user, expect := range want {
  308. if got := cents(t, loadDivideNode(t, db, user).TotalIncome); got != expect {
  309. t.Fatalf("%s.total_income 应为 %d 分,实得 %d", user, expect, got)
  310. }
  311. }
  312. }
  313. // TestAddLogTwoLevelIdempotency 两级幂等:type=1 忽略订单;type=2 含订单。
  314. func TestAddLogTwoLevelIdempotency(t *testing.T) {
  315. ctx := context.Background()
  316. stu := nodeID(901)
  317. t.Run("type=1 一次付清(同 user+student 只一条)", func(t *testing.T) {
  318. db := newDivideServiceDB(t)
  319. svc := NewDivideService(db, nil)
  320. u := nodeID(0)
  321. seedRoot(t, db, u, model.DivideTypeOneOff, "10.00")
  322. if err := svc.AddLog(ctx, u, stu, 777, ""); err != nil {
  323. t.Fatalf("AddLog 失败: %v", err)
  324. }
  325. if err := svc.AddLog(ctx, u, stu, 888, ""); err != nil { // 不同订单:应与 type=1 无关
  326. t.Fatalf("AddLog(第二次) 失败: %v", err)
  327. }
  328. var count int64
  329. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  330. t.Fatalf("count 失败: %v", err)
  331. }
  332. if count != 1 {
  333. t.Fatalf("type=1 应仅 1 条明细,实得 %d", count)
  334. }
  335. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 1000 {
  336. t.Fatalf("total_income 应只累加一次(1000 分),实得 %d", got)
  337. }
  338. })
  339. t.Run("type=2 按课次(同 user+student+order 只一条)", func(t *testing.T) {
  340. db := newDivideServiceDB(t)
  341. svc := NewDivideService(db, nil)
  342. u := nodeID(0)
  343. seedRoot(t, db, u, model.DivideTypePerLesson, "10.00")
  344. for i := 0; i < 2; i++ { // 同一订单重复请求
  345. if err := svc.AddLog(ctx, u, stu, 777, ""); err != nil {
  346. t.Fatalf("AddLog(重复) 失败: %v", err)
  347. }
  348. }
  349. if count := countLogs(t, db); count != 1 {
  350. t.Fatalf("同订单重复请求应幂等(1 条),实得 %d", count)
  351. }
  352. if err := svc.AddLog(ctx, u, stu, 888, ""); err != nil { // 新订单:应新增
  353. t.Fatalf("AddLog(新订单) 失败: %v", err)
  354. }
  355. if count := countLogs(t, db); count != 2 {
  356. t.Fatalf("新订单应新增明细(2 条),实得 %d", count)
  357. }
  358. if got := cents(t, loadDivideNode(t, db, u).TotalIncome); got != 2000 {
  359. t.Fatalf("total_income 应为 2000 分,实得 %d", got)
  360. }
  361. })
  362. }
  363. // countLogs 统计分成明细行数(测试辅助)。
  364. func countLogs(t *testing.T, db *gorm.DB) int64 {
  365. t.Helper()
  366. var count int64
  367. if err := db.Model(&model.UserDivideIntoLog{}).Count(&count).Error; err != nil {
  368. t.Fatalf("count 失败: %v", err)
  369. }
  370. return count
  371. }
  372. // TestAddLogNonTreeNodeNoop 非分账树节点 → 静默不入账(不报错)。
  373. func TestAddLogNonTreeNodeNoop(t *testing.T) {
  374. db := newDivideServiceDB(t)
  375. svc := NewDivideService(db, nil)
  376. ctx := context.Background()
  377. if err := svc.AddLog(ctx, nodeID(404), nodeID(901), 777, ""); err != nil {
  378. t.Fatalf("非树节点应静默不入账,实得 %v", err)
  379. }
  380. if count := countLogs(t, db); count != 0 {
  381. t.Fatalf("非树节点不应生成明细,实得 %d", count)
  382. }
  383. if err := svc.AddLog(ctx, nodeID(1), "", 777, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  384. t.Fatalf("空学生应 3140,实得 %v", err)
  385. }
  386. if err := svc.AddLog(ctx, nodeID(1), nodeID(901), 0, ""); !errors.Is(err, apperr.ErrBusinessParam) {
  387. t.Fatalf("recordID<=0 应 3140,实得 %v", err)
  388. }
  389. }
  390. // TestAddLogCycleGuard 数据成环 → 迭代层数兜底 3111(不死循环、不栈溢出)。
  391. func TestAddLogCycleGuard(t *testing.T) {
  392. db := newDivideServiceDB(t)
  393. svc := NewDivideService(db, nil)
  394. ctx := context.Background()
  395. a, b := nodeID(0), nodeID(1)
  396. seedRoot(t, db, a, model.DivideTypeOneOff, "10.00")
  397. seedRoot(t, db, b, model.DivideTypeOneOff, "10.00")
  398. // 人为造自环(脏数据)
  399. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", a).
  400. Updates(map[string]any{"parent_user_id": b}).Error; err != nil {
  401. t.Fatalf("造环失败: %v", err)
  402. }
  403. if err := db.Model(&model.UserDivideInto{}).Where("user_id = ?", b).
  404. Updates(map[string]any{"parent_user_id": a}).Error; err != nil {
  405. t.Fatalf("造环失败: %v", err)
  406. }
  407. err := svc.AddLog(ctx, a, nodeID(901), 777, "")
  408. if !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  409. t.Fatalf("成环应 3111(层级兜底),实得 %v", err)
  410. }
  411. // 事务回滚:环上的入账不应留下
  412. if count := countLogs(t, db); count != 0 {
  413. t.Fatalf("报错后应整体回滚(0 条明细),实得 %d", count)
  414. }
  415. }
  416. // TestDeleteLogRollbackBranch 撤销分支②:无首次扣费记录 → 回滚 total_income 并删行。
  417. func TestDeleteLogRollbackBranch(t *testing.T) {
  418. db := newDivideServiceDB(t)
  419. svc := NewDivideService(db, nil) // 端口未注入 → 一律走回滚
  420. ctx := context.Background()
  421. a, b := nodeID(0), nodeID(1)
  422. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  423. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  424. t.Fatalf("建链失败: %v", err)
  425. }
  426. if err := svc.UpdateQuota(ctx, b, money.FromCents(500)); err != nil {
  427. t.Fatalf("设额度失败: %v", err)
  428. }
  429. stu := nodeID(901)
  430. if err := svc.AddLog(ctx, b, stu, 777, ""); err != nil {
  431. t.Fatalf("AddLog 失败: %v", err)
  432. }
  433. if count := countLogs(t, db); count != 2 {
  434. t.Fatalf("应为 2 条明细,实得 %d", count)
  435. }
  436. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  437. t.Fatalf("DeleteLog 失败: %v", err)
  438. }
  439. if count := countLogs(t, db); count != 0 {
  440. t.Fatalf("回滚删除后应 0 条明细,实得 %d", count)
  441. }
  442. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  443. t.Fatalf("a.total_income 应回滚为 0,实得 %d 分", got)
  444. }
  445. if got := cents(t, loadDivideNode(t, db, b).TotalIncome); got != 0 {
  446. t.Fatalf("b.total_income 应回滚为 0,实得 %d 分", got)
  447. }
  448. // 幂等:再次撤销 → 空操作
  449. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  450. t.Fatalf("重复撤销应幂等成功,实得 %v", err)
  451. }
  452. }
  453. // TestDeleteLogRebindBranch 撤销分支①:已有首次扣费记录(≠当前订单)→ 改绑保留分成。
  454. func TestDeleteLogRebindBranch(t *testing.T) {
  455. db := newDivideServiceDB(t)
  456. port := &fakeFirstCharged{recordID: 888, found: true}
  457. svc := NewDivideService(db, port)
  458. ctx := context.Background()
  459. a := nodeID(0)
  460. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  461. stu := nodeID(901)
  462. if err := svc.AddLog(ctx, a, stu, 777, ""); err != nil {
  463. t.Fatalf("AddLog 失败: %v", err)
  464. }
  465. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  466. t.Fatalf("DeleteLog 失败: %v", err)
  467. }
  468. var rows []model.UserDivideIntoLog
  469. if err := db.Find(&rows).Error; err != nil {
  470. t.Fatalf("读明细失败: %v", err)
  471. }
  472. if len(rows) != 1 {
  473. t.Fatalf("改绑分支应保留明细(1 条),实得 %d", len(rows))
  474. }
  475. if rows[0].OrderNo == nil || *rows[0].OrderNo != "888" {
  476. t.Fatalf("order_no 应改绑为 888,实得 %v", rows[0].OrderNo)
  477. }
  478. if rows[0].Remark == nil || *rows[0].Remark != remarkRebind {
  479. t.Fatalf("remark 应为 %q,实得 %v", remarkRebind, rows[0].Remark)
  480. }
  481. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 1000 {
  482. t.Fatalf("改绑不回滚收入(应仍 1000 分),实得 %d", got)
  483. }
  484. if port.calls == 0 {
  485. t.Fatal("改绑判定应调用首次扣费端口")
  486. }
  487. }
  488. // TestDeleteLogFirstEqualsOrder 首次扣费记录 = 当前订单 → 不属改绑场景,走回滚删除。
  489. func TestDeleteLogFirstEqualsOrder(t *testing.T) {
  490. db := newDivideServiceDB(t)
  491. port := &fakeFirstCharged{recordID: 777, found: true}
  492. svc := NewDivideService(db, port)
  493. ctx := context.Background()
  494. a := nodeID(0)
  495. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  496. stu := nodeID(901)
  497. if err := svc.AddLog(ctx, a, stu, 777, ""); err != nil {
  498. t.Fatalf("AddLog 失败: %v", err)
  499. }
  500. if err := svc.DeleteLog(ctx, stu, 777); err != nil {
  501. t.Fatalf("DeleteLog 失败: %v", err)
  502. }
  503. if count := countLogs(t, db); count != 0 {
  504. t.Fatalf("首次记录即当前订单 → 应回滚删除(0 条),实得 %d", count)
  505. }
  506. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  507. t.Fatalf("total_income 应回滚为 0,实得 %d 分", got)
  508. }
  509. if err := svc.DeleteLog(ctx, stu, 0); !errors.Is(err, apperr.ErrBusinessParam) {
  510. t.Fatalf("orderID<=0 应 3140,实得 %v", err)
  511. }
  512. }
  513. // TestUpdateQuotaCascade 额度级联下降(子不得超父)+ 参数/缺失分支。
  514. func TestUpdateQuotaCascade(t *testing.T) {
  515. db := newDivideServiceDB(t)
  516. svc := NewDivideService(db, nil)
  517. ctx := context.Background()
  518. a, b, c := nodeID(0), nodeID(1), nodeID(2)
  519. seedRoot(t, db, a, model.DivideTypeOneOff, "20.00")
  520. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  521. t.Fatalf("建链失败: %v", err)
  522. }
  523. if err := svc.AddSubordinate(ctx, b, c); err != nil {
  524. t.Fatalf("建链失败: %v", err)
  525. }
  526. if err := svc.UpdateQuota(ctx, b, money.FromCents(1500)); err != nil {
  527. t.Fatalf("设额度 B 失败: %v", err)
  528. }
  529. if err := svc.UpdateQuota(ctx, c, money.FromCents(1200)); err != nil {
  530. t.Fatalf("设额度 C 失败: %v", err)
  531. }
  532. // 父 A 降到 10.00 → B(15)、C(12) 一并压到 10.00
  533. if err := svc.UpdateQuota(ctx, a, money.FromCents(1000)); err != nil {
  534. t.Fatalf("UpdateQuota(A,10) 失败: %v", err)
  535. }
  536. for _, id := range []string{a, b, c} {
  537. if got := cents(t, loadDivideNode(t, db, id).Quota); got != 1000 {
  538. t.Fatalf("%s.quota 应级联压到 1000 分,实得 %d", id, got)
  539. }
  540. }
  541. // 子节点超额(> 父)→ 3111
  542. if err := svc.UpdateQuota(ctx, b, money.FromCents(9999)); !errors.Is(err, apperr.ErrDivideQuotaExceeded) {
  543. t.Fatalf("超过上级应 3111,实得 %v", err)
  544. }
  545. // 参数/缺失
  546. if err := svc.UpdateQuota(ctx, b, money.FromCents(-1)); !errors.Is(err, apperr.ErrBusinessParam) {
  547. t.Fatalf("负额度应 3140,实得 %v", err)
  548. }
  549. if err := svc.UpdateQuota(ctx, nodeID(404), money.FromCents(100)); !errors.Is(err, infraerrors.ErrNotFound) {
  550. t.Fatalf("节点不存在应 3001,实得 %v", err)
  551. }
  552. if err := svc.UpdateQuota(ctx, "", money.FromCents(100)); !errors.Is(err, apperr.ErrBusinessParam) {
  553. t.Fatalf("空 userID 应 3140,实得 %v", err)
  554. }
  555. }
  556. // TestDivideServiceNestedTxPassThrough 事务透传纪律:本服务在**外层事务内**被调用时
  557. // 必须经 WithTxContext 复用同一 tx(不重复 BEGIN),且随外层回滚一并撤销。
  558. func TestDivideServiceNestedTxPassThrough(t *testing.T) {
  559. db := newDivideServiceDB(t)
  560. svc := NewDivideService(db, nil)
  561. runner := repository.NewTxRunner(db)
  562. ctx := context.Background()
  563. a, b := nodeID(0), nodeID(1)
  564. seedRoot(t, db, a, model.DivideTypePerLesson, "10.00")
  565. if err := svc.AddSubordinate(ctx, a, b); err != nil {
  566. t.Fatalf("建链失败: %v", err)
  567. }
  568. stu := nodeID(901)
  569. boom := errors.New("outer-rollback")
  570. err := runner.WithinTx(ctx, func(tx *gorm.DB) error {
  571. txCtx := repository.WithTxContext(ctx, tx)
  572. if aerr := svc.AddLog(txCtx, b, stu, 777, ""); aerr != nil {
  573. return aerr
  574. }
  575. // 事务内应可见刚写入的明细(说明确实跑在同一 tx 上)
  576. var inside int64
  577. if cerr := tx.Model(&model.UserDivideIntoLog{}).Count(&inside).Error; cerr != nil {
  578. return cerr
  579. }
  580. if inside != 2 {
  581. t.Fatalf("外层事务内应可见 2 条明细,实得 %d", inside)
  582. }
  583. return boom
  584. })
  585. if !errors.Is(err, infraerrors.ErrDBError) {
  586. t.Fatalf("非业务错误应归一为 5002,实得 %v", err)
  587. }
  588. if count := countLogs(t, db); count != 0 {
  589. t.Fatalf("外层回滚后明细应全部消失(无独立事务提前提交),实得 %d", count)
  590. }
  591. if got := cents(t, loadDivideNode(t, db, a).TotalIncome); got != 0 {
  592. t.Fatalf("回滚后 total_income 应为 0,实得 %d 分", got)
  593. }
  594. }
  595. // TestAddLogBFSDepthBoundary 100 层链(layer 1..100)恰好在上限内:BFS 必须完整走完 100 级
  596. // (101 级才触发 3111,见 TestAddLogCycleGuard)。同时验证"迭代不递归"在大深度下不栈溢出。
  597. func TestAddLogBFSDepthBoundary(t *testing.T) {
  598. db := newDivideServiceDB(t)
  599. svc := NewDivideService(db, nil)
  600. ctx := context.Background()
  601. root := nodeID(0)
  602. seedRoot(t, db, root, model.DivideTypePerLesson, "1.00")
  603. prev := root
  604. for i := 1; i <= 99; i++ {
  605. child := nodeID(i)
  606. if err := svc.AddSubordinate(ctx, prev, child); err != nil {
  607. t.Fatalf("建链失败(%s→%s): %v", prev, child, err)
  608. }
  609. prev = child
  610. }
  611. tail := prev
  612. if got := loadDivideNode(t, db, tail).Layer; got != MaxDivideDepth {
  613. t.Fatalf("链尾 layer 应为 %d,实得 %d", MaxDivideDepth, got)
  614. }
  615. if err := svc.AddLog(ctx, tail, nodeID(901), 777, ""); err != nil {
  616. t.Fatalf("%d 层链的 BFS 入账应在限内成功,实得 %v", MaxDivideDepth, err)
  617. }
  618. if count := countLogs(t, db); count != int64(MaxDivideDepth) {
  619. t.Fatalf("%d 层链应生成 %d 条明细,实得 %d", MaxDivideDepth, MaxDivideDepth, count)
  620. }
  621. // 根节点收入应恰好为一次 quota
  622. if got := cents(t, loadDivideNode(t, db, root).TotalIncome); got != 100 {
  623. t.Fatalf("根节点 total_income 应为 100 分,实得 %d", got)
  624. }
  625. }