divide_service.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. // 分账服务(Nested Set 树维护 + 上行分成 + 撤销 + 额度级联)——AC-09。
  2. //
  3. // 依据:unified/03-migration/academic-domain-design.md §3.3 #22~#25(分账 4 SP)
  4. // / §1.7(全局无作用域表)/ §10.3(事务边界只在 Service)/ §11.1 拍板 11-12。
  5. //
  6. // 四个 SP 的 Go 化落点:
  7. //
  8. // divide_into_add → AddSubordinate(**服务端算左右值**,dump 2 参语义:只传上下级)
  9. // divide_into_log_add → AddLog(上行链入账;**递归改迭代 BFS**,深度上限 100)
  10. // divide_into_log_delete → DeleteLog(两分支:改绑 / 回滚删除,dump 2 参语义:studentid + orderid)
  11. // divide_into_update_quota → UpdateQuota(改额度 + 子树级联下降,子不得超父 → 3111)
  12. //
  13. // 事务纪律:所有写路径走 `repository.TxRunner.WithinTx`;事务内下游调用一律传
  14. // `repository.WithTxContext(ctx, tx)` 注入的 ctx(读方法自动复用同一 tx,见仓储 db(ctx))。
  15. // 禁止在本服务内直接调用 `db.Transaction`(嵌套只允许经 TxRunner 透传)。
  16. //
  17. // 金额纪律:库里 quota / total_income / money 均为 decimal(12,2) 字符串列,
  18. // 一律 `money.Parse` 转 money.Amount(int64 分)后运算,**零 float64**。
  19. package service
  20. import (
  21. "context"
  22. "errors"
  23. "strconv"
  24. "strings"
  25. "gorm.io/gorm"
  26. "yuansiwei/unified-backend/internal/academic/apperr"
  27. "yuansiwei/unified-backend/internal/academic/model"
  28. "yuansiwei/unified-backend/internal/academic/money"
  29. "yuansiwei/unified-backend/internal/academic/repository"
  30. infraerrors "yuansiwei/unified-backend/internal/infra/errors"
  31. )
  32. // MaxDivideDepth 分账树深度上限(根 layer=1;超限 → apperr.ErrDivideQuotaExceeded 3111)。
  33. //
  34. // 依据:模型注释 layer「深度上限 100(超限 → 3111,防递归栈溢出)」+ dump 的层数保护。
  35. // BFS 迭代在本上限内必然终止(即使数据成环也不会死循环)。
  36. const MaxDivideDepth int32 = 100
  37. // remarkRebind 撤销改绑分支写入的备注文案(dump 原样:"推广分成")。
  38. const remarkRebind = "推广分成"
  39. // FirstChargedRecordReader 首次扣费上课记录只读端口(跨聚合依赖,本服务**只定义契约**)。
  40. //
  41. // 为什么用端口而不是直接 JOIN:`log_delete` 的改绑分支需要判断"学生是否已有首次扣费上课记录",
  42. // 该判定属于课次/打卡聚合(AC-05/AC-10 范围)。AC-09 不实现它,只声明只读契约 + 允许注入;
  43. // 未注入时**所有撤销走回滚删除分支**(保守:不让分成悬空在多订单上)。
  44. //
  45. // 契约:
  46. // - 只读,禁止写任何表;
  47. // - 返回 (recordID, found, err):found=false 表示学生尚无扣费记录 → 走回滚删除分支;
  48. // - err 仅 DB 异常(infraerrors.ErrDBError),不得返回业务错误。
  49. type FirstChargedRecordReader interface {
  50. // FirstChargedRecordID 取该学生"首次扣费上课记录"的 ID。
  51. //
  52. // 入参:ctx 请求上下文;studentID 报课学生(canonical_user_id ULID)。
  53. // 出参:recordID int64(上课记录 ID);found bool;error。
  54. FirstChargedRecordID(ctx context.Context, studentID string) (recordID int64, found bool, err error)
  55. }
  56. // DivideService 分账服务(全局推广体系;越权防线在 Handler 角色白名单,本服务不做租户裁剪)。
  57. type DivideService struct {
  58. // repo 分账树仓储(全局数据,不继承 BaseRepo)。
  59. repo *repository.DivideRepo
  60. // runner 事务运行器(顶层开事务,事务内透传)。
  61. runner *repository.TxRunner
  62. // firstCharged 首次扣费记录端口(可 nil:未注入时撤销一律走回滚删除)。
  63. firstCharged FirstChargedRecordReader
  64. }
  65. // NewDivideService 构造分账服务(repo 与 runner 绑定同一 DB 句柄,避免跨连接池事务失效)。
  66. //
  67. // 入参:
  68. // - db *gorm.DB:数据库句柄(必填)。
  69. // - firstCharged FirstChargedRecordReader:首次扣费记录端口(可 nil)。
  70. //
  71. // 出参:*DivideService。
  72. func NewDivideService(db *gorm.DB, firstCharged FirstChargedRecordReader) *DivideService {
  73. return &DivideService{
  74. repo: repository.NewDivideRepo(db),
  75. runner: repository.NewTxRunner(db),
  76. firstCharged: firstCharged,
  77. }
  78. }
  79. // AddSubordinate 把 subUserID 挂为 parentUserID 的下级(dump `divide_into_add` 2 参语义)。
  80. //
  81. // 入参:
  82. // - ctx 请求上下文;
  83. // - parentUserID 上级用户(ULID;必须已是树节点,否则 3001);
  84. // - subUserID 下级用户(ULID;== parentUserID → 3140,禁止自环)。
  85. //
  86. // 出参:
  87. // - nil:成功(新建节点,或"已存在节点"分支改挂成功);
  88. // - ErrNotFound(3001):上级不存在或不在分账体系;
  89. // - ErrDivideQuotaExceeded(3111):层级超上限(父 layer+1 > 100);
  90. // - ErrBusinessParam(3140):入参非法。
  91. //
  92. // 左右值算法(Nested Set 插入最右子节点,**服务端计算**,调用方不传 left/right):
  93. //
  94. // ① 父节点右值 R = parent.right_val(插入点)
  95. // ② ShiftRight(R, +2):right_val >= R 全体 +2 → 父节点及其**全部祖先**区间右移
  96. // ③ ShiftLeft (R, +2):left_val >= R 全体 +2 → 位于插入点右侧的兄弟及其后代右移
  97. // ④ 新节点 (left, right) = (R, R+1),layer = parent.layer+1,root = 父的树根
  98. //
  99. // 不变式:①②③④ 必须在同一事务内完成(否则中间态树不可用);完成后恒有 left < right。
  100. //
  101. // 已存在节点分支(dump `if exists(select 1 from ... where userid = subid)`):
  102. //
  103. // dump 仅改 parent,**漏写 root_user_id**(留 NULL → 子树/级联查询失效)。
  104. // 本实现按模型注释的修正要求显式写入父树根,且**不重排左右值**(与原 SP 一致,
  105. // 区间重排会与迁移期数据冲突,登记为遗留项)。
  106. func (s *DivideService) AddSubordinate(ctx context.Context, parentUserID, subUserID string) error {
  107. parentUserID = strings.TrimSpace(parentUserID)
  108. subUserID = strings.TrimSpace(subUserID)
  109. if parentUserID == "" || subUserID == "" {
  110. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: AddSubordinate 需要 parent/sub user id"))
  111. }
  112. if parentUserID == subUserID {
  113. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: 下级不能是自身(禁止成环)"))
  114. }
  115. if err := s.assertReady(); err != nil {
  116. return err
  117. }
  118. return s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  119. txCtx := repository.WithTxContext(ctx, tx)
  120. parent, err := s.repo.GetByUserID(txCtx, parentUserID)
  121. if err != nil {
  122. return err // ErrNotFound(3001) 原样上抛:上级未加入分账体系
  123. }
  124. nextLayer := parent.Layer + 1
  125. if nextLayer > MaxDivideDepth {
  126. return infraerrors.WithCause(apperr.ErrDivideQuotaExceeded,
  127. errString("service: 分账层级超上限 "+strconv.Itoa(int(MaxDivideDepth))))
  128. }
  129. rootID := resolveRoot(parent)
  130. existing, err := s.repo.GetByUserID(txCtx, subUserID)
  131. switch {
  132. case err == nil:
  133. // ── 已存在节点分支:只改挂父链(补齐 root,dump 缺陷修正)
  134. if existing.UserID == parentUserID {
  135. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: 上下级相同"))
  136. }
  137. if _, uerr := s.repo.UpdateNodeParent(txCtx, tx, subUserID, parentUserID, rootID, nextLayer); uerr != nil {
  138. return uerr
  139. }
  140. return nil
  141. case !errors.Is(err, infraerrors.ErrNotFound):
  142. return err
  143. }
  144. // ── 新建节点分支:嵌套集"插入最右子节点"
  145. insertAt := parent.RightVal
  146. if _, serr := s.repo.ShiftRight(txCtx, tx, insertAt, 2); serr != nil {
  147. return serr
  148. }
  149. if _, serr := s.repo.ShiftLeft(txCtx, tx, insertAt, 2); serr != nil {
  150. return serr
  151. }
  152. parentID := parentUserID
  153. node := &model.UserDivideInto{
  154. UserID: subUserID,
  155. Type: parent.Type,
  156. Quota: "0.00", // 新节点额度由后台 UpdateQuota 配置(默认 0,且不得超父)
  157. TotalIncome: "0.00",
  158. TotalIncomePayed: "0.00",
  159. RootUserID: &rootID,
  160. ParentUserID: &parentID,
  161. LeftVal: insertAt,
  162. RightVal: insertAt + 1,
  163. Layer: nextLayer,
  164. }
  165. if ierr := s.repo.InsertNode(txCtx, tx, node); ierr != nil {
  166. return ierr
  167. }
  168. return nil
  169. })
  170. }
  171. // AddLog 上行分成入账(dump `divide_into_log_add`;**递归改迭代 BFS**)。
  172. //
  173. // 入参:
  174. // - ctx 请求上下文;
  175. // - findUserID 起始用户(ULID;通常是直接推荐人);
  176. // - stuID 报课学生(ULID;幂等键组成列);
  177. // - recordID 上课记录 ID(int64;写入 order_no 作为 type=2 的幂等键,dump 传 orderid 语义);
  178. // - remark 备注(可空;空则落 NULL)。
  179. //
  180. // 出参:
  181. // - nil:成功(含"起始用户不是树节点 → 不入账"的空操作、以及幂等命中);
  182. // - ErrDivideQuotaExceeded(3111):上行层数超 100(数据成环/异常链);
  183. // - ErrBusinessParam / ErrDBError;
  184. // - 若节点 quota 金额被写坏(非十进制)→ ErrDBError(数据异常,不静默归零)。
  185. //
  186. // 上行链语义(dump):从 findUserID 开始,逐级上溯 parent_user_id,每级生成一条明细
  187. // (money = 该级节点的 quota 快照),并累加该节点 total_income;到根(parent 为 NULL)终止。
  188. //
  189. // 幂等(两级,设计 §3.3 #22,**同事务内逐级判定**):
  190. // - 节点 type=1(一次付清):同 (user, student) 只生成一条 → 后续不同 recordID 也不重复入账;
  191. // - 节点 type=2(按课次) :同 (user, student, order_no) 只生成一条。
  192. //
  193. // 为什么用迭代:链深可达 100,递归在极端脏数据下会栈溢出;迭代 + 显式层数计数可兜底成环。
  194. func (s *DivideService) AddLog(ctx context.Context, findUserID, stuID string, recordID int64, remark string) error {
  195. findUserID = strings.TrimSpace(findUserID)
  196. stuID = strings.TrimSpace(stuID)
  197. if findUserID == "" || stuID == "" {
  198. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: AddLog 需要 findUserID/stuID"))
  199. }
  200. if recordID <= 0 {
  201. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: AddLog 需要 recordID > 0"))
  202. }
  203. if err := s.assertReady(); err != nil {
  204. return err
  205. }
  206. orderNo := strconv.FormatInt(recordID, 10)
  207. return s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  208. txCtx := repository.WithTxContext(ctx, tx)
  209. cur, err := s.repo.GetByUserID(txCtx, findUserID)
  210. if errors.Is(err, infraerrors.ErrNotFound) {
  211. // 红线(模型注释):必须是分账树节点才入账;非节点 → 静默不入账(不是错误)
  212. return nil
  213. }
  214. if err != nil {
  215. return err
  216. }
  217. for depth := int32(0); cur != nil; depth++ {
  218. if depth >= MaxDivideDepth {
  219. return infraerrors.WithCause(apperr.ErrDivideQuotaExceeded,
  220. errString("service: 上行分成层级超上限(疑似成环) "+strconv.Itoa(int(MaxDivideDepth))))
  221. }
  222. if err := s.appendShare(txCtx, tx, cur, stuID, orderNo, remark); err != nil {
  223. return err
  224. }
  225. if cur.ParentUserID == nil || strings.TrimSpace(*cur.ParentUserID) == "" {
  226. break // 到根
  227. }
  228. parentID := strings.TrimSpace(*cur.ParentUserID)
  229. if parentID == cur.UserID {
  230. return infraerrors.WithCause(apperr.ErrDivideQuotaExceeded,
  231. errString("service: 分账树自环(parent 指向自身)"))
  232. }
  233. next, perr := s.repo.GetByUserID(txCtx, parentID)
  234. if errors.Is(perr, infraerrors.ErrNotFound) {
  235. break // 断链(上级已不在树中):终止上行,已入账部分保留
  236. }
  237. if perr != nil {
  238. return perr
  239. }
  240. cur = next
  241. }
  242. return nil
  243. })
  244. }
  245. // appendShare 为单个节点生成分成明细并累加 total_income(AddLog 的迭代体)。
  246. //
  247. // 入参:txCtx(含 tx 的 ctx);tx;node 当前节点;stuID 学生;orderNo 订单号;remark 备注。
  248. // 出参:nil 成功/幂等命中;ErrDBError。
  249. //
  250. // 幂等判定经 repository.FindLog(两级键口径唯一入口),命中即跳过(**不返回错误**,
  251. // 对外语义是"重复请求幂等成功",与设计 §10.1 的 3114 仅内部日志口径一致)。
  252. func (s *DivideService) appendShare(txCtx context.Context, tx *gorm.DB, node *model.UserDivideInto, stuID, orderNo, remark string) error {
  253. if node == nil {
  254. return nil
  255. }
  256. _, err := s.repo.FindLog(txCtx, node.UserID, stuID, node.Type, orderNo)
  257. switch {
  258. case err == nil:
  259. return nil // 幂等命中:该 (user, student[, order]) 已有分成
  260. case !errors.Is(err, infraerrors.ErrNotFound):
  261. return err
  262. }
  263. amount, perr := parseAmount(node.Quota)
  264. if perr != nil {
  265. return perr
  266. }
  267. row := &model.UserDivideIntoLog{
  268. Type: node.Type,
  269. UserID: node.UserID,
  270. StudentID: stuID,
  271. OrderNo: stringPtr(orderNo),
  272. Money: amount.String(),
  273. Remark: optionalString(remark),
  274. }
  275. if ierr := s.repo.InsertLog(txCtx, tx, row); ierr != nil {
  276. return ierr
  277. }
  278. if _, ierr := s.repo.IncTotalIncome(txCtx, tx, node.UserID, amount); ierr != nil {
  279. return ierr
  280. }
  281. return nil
  282. }
  283. // DeleteLog 撤销某「学生 + 订单」产生的全部分成(dump `divide_into_log_delete` 2 参语义)。
  284. //
  285. // 入参:
  286. // - ctx 请求上下文;
  287. // - stuID 报课学生(ULID);
  288. // - orderID 订单/上课记录 ID(int64;dump 传 orderid)。
  289. //
  290. // 出参:
  291. // - nil:成功(含"无对应明细"的幂等空操作);
  292. // - ErrBusinessParam / ErrDBError(含端口返回的 DB 异常)。
  293. //
  294. // 两分支(设计 §3.3 #23,**顺序不可颠倒**):
  295. //
  296. // ① 改绑(保留分成):学生已有首次扣费上课记录 first,且 first != orderID
  297. // → 该组明细的 order_no 改为 first,备注写"推广分成",total_income **不回滚**;
  298. // ② 回滚删除:否则 → total_income -= money(冲正)并物理删除明细行。
  299. //
  300. // 说明:同一订单的分成会沿上行链生成多行(本人 + 各级上线),故按 (student, order) 取全量
  301. // 逐行处理,而不是只处理一行(否则上级分成会悬空)。
  302. func (s *DivideService) DeleteLog(ctx context.Context, stuID string, orderID int64) error {
  303. stuID = strings.TrimSpace(stuID)
  304. if stuID == "" || orderID <= 0 {
  305. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: DeleteLog 需要 stuID/orderID"))
  306. }
  307. if err := s.assertReady(); err != nil {
  308. return err
  309. }
  310. orderNo := strconv.FormatInt(orderID, 10)
  311. return s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  312. txCtx := repository.WithTxContext(ctx, tx)
  313. rows, err := s.repo.ListLogsByStudentOrder(txCtx, stuID, orderNo)
  314. if err != nil {
  315. return err
  316. }
  317. if len(rows) == 0 {
  318. return nil // 已撤销/从未生成:幂等空操作
  319. }
  320. // 首次扣费记录(端口未注入 → 一律走回滚删除分支)
  321. var firstID int64
  322. var hasFirst bool
  323. if s.firstCharged != nil {
  324. firstID, hasFirst, err = s.firstCharged.FirstChargedRecordID(txCtx, stuID)
  325. if err != nil {
  326. return err
  327. }
  328. }
  329. rebindTo := ""
  330. if hasFirst && firstID > 0 && firstID != orderID {
  331. rebindTo = strconv.FormatInt(firstID, 10)
  332. }
  333. for i := range rows {
  334. row := &rows[i]
  335. if rebindTo != "" {
  336. // ① 改绑分支:保留分成,仅改幂等键指向首次扣费订单
  337. if _, uerr := s.repo.UpdateLogOrderNo(txCtx, tx, row.ID, rebindTo, remarkRebind); uerr != nil {
  338. return uerr
  339. }
  340. continue
  341. }
  342. // ② 回滚删除分支:冲正 total_income 后物理删除
  343. amount, perr := parseAmount(row.Money)
  344. if perr != nil {
  345. return perr
  346. }
  347. if _, ierr := s.repo.IncTotalIncome(txCtx, tx, row.UserID, amount.Neg()); ierr != nil {
  348. return ierr
  349. }
  350. if derr := s.repo.DeleteLog(txCtx, tx, row.ID); derr != nil {
  351. return derr
  352. }
  353. }
  354. return nil
  355. })
  356. }
  357. // UpdateQuota 修改节点分成额度并级联下降子树(dump `divide_into_update_quota`)。
  358. //
  359. // 入参:
  360. // - ctx 请求上下文;
  361. // - userID 节点用户(ULID;必须是树节点,否则 3001);
  362. // - quota 新额度(单位:分;负值/越界 → 3140)。
  363. //
  364. // 出参:
  365. // - nil:成功(含"子树内无超标节点"的空更新);
  366. // - ErrNotFound(3001):节点不存在;
  367. // - ErrDivideQuotaExceeded(3111):新额度**超过上级**额度(子不得超父);
  368. // - ErrBusinessParam / ErrDBError。
  369. //
  370. // 级联规则("只降不升"):
  371. //
  372. // 本节点 quota := 新值;
  373. // 子树中 quota > 新值的节点 → 压到新值(低于新值的阶梯额度保持不变)。
  374. //
  375. // 事务:本节点更新与子树压制**同事务**(否则出现"父已降、子仍高于父"的越权窗口)。
  376. func (s *DivideService) UpdateQuota(ctx context.Context, userID string, quota money.Amount) error {
  377. userID = strings.TrimSpace(userID)
  378. if userID == "" {
  379. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: UpdateQuota 需要 userID"))
  380. }
  381. if quota.IsNegative() {
  382. return infraerrors.WithCause(apperr.ErrBusinessParam, errString("service: 分成额度不能为负"))
  383. }
  384. if verr := quota.Validate(); verr != nil {
  385. return infraerrors.WithCause(apperr.ErrBusinessParam, verr)
  386. }
  387. if err := s.assertReady(); err != nil {
  388. return err
  389. }
  390. return s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  391. txCtx := repository.WithTxContext(ctx, tx)
  392. node, err := s.repo.GetByUserID(txCtx, userID)
  393. if err != nil {
  394. return err // ErrNotFound(3001) 原样上抛
  395. }
  396. // 上限校验:子不得超父(父额度是硬上限,超限 → 3111)
  397. if node.ParentUserID != nil && strings.TrimSpace(*node.ParentUserID) != "" {
  398. parent, perr := s.repo.GetByUserID(txCtx, strings.TrimSpace(*node.ParentUserID))
  399. if perr == nil {
  400. parentQuota, aerr := parseAmount(parent.Quota)
  401. if aerr != nil {
  402. return aerr
  403. }
  404. if quota.GreaterThan(parentQuota) {
  405. return infraerrors.WithCause(apperr.ErrDivideQuotaExceeded,
  406. errString("service: 分成额度不得超过上级("+quota.String()+" > "+parentQuota.String()+")"))
  407. }
  408. } else if !errors.Is(perr, infraerrors.ErrNotFound) {
  409. return perr
  410. }
  411. // 上级不在树中(断链)→ 不做上限校验(不阻断后台修复数据)
  412. }
  413. if _, uerr := s.repo.UpdateNodeQuota(txCtx, tx, userID, quota); uerr != nil {
  414. return uerr
  415. }
  416. if _, cerr := s.repo.ClampSubtreeQuota(txCtx, tx, node.LeftVal, node.RightVal, quota); cerr != nil {
  417. return cerr
  418. }
  419. return nil
  420. })
  421. }
  422. // assertReady 装配期自检(repo/runner 未构造 → ErrInternal,避免 nil 解引用)。
  423. func (s *DivideService) assertReady() error {
  424. if s == nil || s.repo == nil || s.runner == nil {
  425. return infraerrors.WithCause(infraerrors.ErrInternal, errString("service: DivideService 未装配 repo/runner"))
  426. }
  427. return nil
  428. }
  429. // resolveRoot 解析节点的所属树根(自身为根时返回自身 user_id)。
  430. //
  431. // 入参:node 分账节点(可 nil)。出参:根 user_id 字符串。
  432. //
  433. // 修正点(模型注释 ★):旧 SP 在"subid 已存在"分支可能留下 root_user_id = NULL,
  434. // 因此这里必须容忍 nil/空串并回退到节点自身,再回退到 parent(由调用方兜底)。
  435. func resolveRoot(node *model.UserDivideInto) string {
  436. if node == nil {
  437. return ""
  438. }
  439. if node.RootUserID != nil && strings.TrimSpace(*node.RootUserID) != "" {
  440. return strings.TrimSpace(*node.RootUserID)
  441. }
  442. return node.UserID
  443. }
  444. // parseAmount 把库里的 decimal(12,2) 字符串转 money.Amount(空串视为 0.00,容错迁移期脏值)。
  445. //
  446. // 入参:s 十进制"元"字符串。出参:money.Amount;解析失败 → ErrDBError(数据异常不静默归零)。
  447. func parseAmount(s string) (money.Amount, error) {
  448. trimmed := strings.TrimSpace(s)
  449. if trimmed == "" {
  450. return 0, nil
  451. }
  452. amount, err := money.Parse(trimmed)
  453. if err != nil {
  454. return 0, infraerrors.WithCause(infraerrors.ErrDBError, err)
  455. }
  456. return amount, nil
  457. }
  458. // stringPtr 返回字符串指针(空串返回 nil,便于落 NULL)。
  459. func stringPtr(s string) *string {
  460. trimmed := strings.TrimSpace(s)
  461. if trimmed == "" {
  462. return nil
  463. }
  464. return &trimmed
  465. }
  466. // optionalString 空串返回 nil 的指针构造(备注列语义:空 → NULL)。
  467. func optionalString(s string) *string { return stringPtr(s) }
  468. // errString 实现 error 的最小字符串类型(本包不引入额外依赖,语义同 repository.errString)。
  469. type errString string
  470. // Error 实现 error 接口。
  471. func (e errString) Error() string { return string(e) }