refund_service.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. // 退费与清零服务(自定义退费双 log + 余额清零 + 取消充值活动)——AC-05。
  2. //
  3. // 依据:unified/03-migration/academic-domain-design.md §3.1 #8~#10(SP 映射与 dump 行号)
  4. // / §4.6(`CustomRefundResult` / `ClearBalanceResult` 字段契约,**逐字对齐**)
  5. // / §7.2(自定义退费时序:双账户锁 + 双 log + 活动失效 + 锁序)
  6. // / §3.8-b R1/R2(相对 dump 的两处有意强化)/ §10.3(事务)/ §10.7(金额)。
  7. //
  8. // SP 映射:
  9. //
  10. // #8 sp_user_expense_cancel_recharge_activity → CancelRechargeActivity(跨域读 t_campus.school_id)
  11. // #9 sp_user_expense_custom_refund → CustomRefund(**双 log:先 108 后 207**)
  12. // #10 sp_user_expense_school_cleared_balance → ClearBalance(★全局表扣减基数 = campusBalance)
  13. //
  14. // 三条与 dump 的**有意偏离**(设计 §3.8-b 已登记,双跑报告按 `INTENTIONAL-DEV` 归因):
  15. //
  16. // R1 校区查不到:dump 的 `IF(NULL)` 让 `campusSelfSupport` 保持 0 → 静默走**加盟**分支;
  17. // Go 硬化:`CampusReader` 取不到 → **3104**("加盟校区退费误失效本校区活动"是不可接受的静默行为)。
  18. // R2 并发:dump 读余额**无 `FOR UPDATE`**(生产存在并发超退);Go 对双账户显式加锁。
  19. // 加锁顺序 **全局 `t_user_expense` → 校区 `t_user_expense_school`**(与 §7.2 / §1.4 的写序一致)。
  20. // R-3 清零/退费前置失败:dump 静默 `LEAVE`(前端"成功但没变");Go 返回 3120 + 原因。
  21. //
  22. // 账务恒等式(CustomRefund,写进单测与 AC-17 ④,**不是各比各的**):
  23. //
  24. // requested = refunded + badDebt
  25. // 账户净变动 = -refunded = 207(−requested) + 108(+badDebt) ← 三条流水的代数和恒等于净扣减
  26. // balance_after = balance_before - refunded
  27. package service
  28. import (
  29. "context"
  30. "errors"
  31. "strings"
  32. "gorm.io/gorm"
  33. "yuansiwei/unified-backend/internal/academic/apperr"
  34. "yuansiwei/unified-backend/internal/academic/model"
  35. "yuansiwei/unified-backend/internal/academic/money"
  36. "yuansiwei/unified-backend/internal/academic/port"
  37. "yuansiwei/unified-backend/internal/academic/repository"
  38. infraerrors "yuansiwei/unified-backend/internal/infra/errors"
  39. appscope "yuansiwei/unified-backend/internal/infra/scope"
  40. )
  41. // 自定义退费 / 余额清零 / 取消充值活动的默认备注(dump `IF inputRemark=”`,逐字对齐)。
  42. const (
  43. // defaultCustomRefundRemark SP9 默认备注。
  44. defaultCustomRefundRemark = "余额退费"
  45. // defaultClearBalanceRemark SP10 默认备注。
  46. defaultClearBalanceRemark = "余额清零"
  47. // defaultCancelRechargeRemark SP8 默认备注。
  48. defaultCancelRechargeRemark = "取消充值活动"
  49. // badDebtRemarkSuffix SP9 dump 追加文案(`<br/>` 原样保留,前端按 HTML 渲染)。
  50. badDebtRemarkSuffix = "<br/>退费的金额大于可退费部分,超出部分为坏账部分。"
  51. )
  52. // RefundService 退费与清零服务(depends: 余额仓储 + 活动失效器 + 校区只读端口)。
  53. //
  54. // 字段:
  55. // - repo:余额账户仓储(全局 + 校区 + 流水);
  56. // - runner:事务运行器(顶层 BEGIN,事务内透传);
  57. // - campus:校区只读端口(跨域读 `t_campus`:self_support / institution_id,禁止跨库 SQL);
  58. // - member:成员关系校验器(可 nil:系统任务模式);
  59. // - expirer:活动失效器(与资金同事务)。
  60. type RefundService struct {
  61. repo *repository.ExpenseRepo
  62. runner *repository.TxRunner
  63. campus port.CampusReader
  64. member port.MembershipChecker
  65. expirer *ActivityExpirer
  66. }
  67. // NewRefundService 构造退费与清零服务。
  68. //
  69. // 入参:
  70. // - db *gorm.DB:数据库句柄(必填);
  71. // - sc *appscope.Scope:本次请求作用域;
  72. // - campus port.CampusReader:校区只读端口(**必须注入**:自营/加盟判定与 3104 硬化都依赖它;
  73. // 实现见 `port.NewOrgCampusReader`,事务内读取走其 `TxCampusReader` 扩展);
  74. // - member port.MembershipChecker:成员校验器(可 nil)。
  75. //
  76. // 出参:*RefundService。
  77. func NewRefundService(
  78. db *gorm.DB, sc *appscope.Scope, campus port.CampusReader, member port.MembershipChecker,
  79. ) *RefundService {
  80. return &RefundService{
  81. repo: repository.NewExpenseRepo(db, sc),
  82. runner: repository.NewTxRunner(db),
  83. campus: campus,
  84. member: member,
  85. expirer: NewActivityExpirer(db, sc),
  86. }
  87. }
  88. // ---------------------------------------------------------------- DTO(§4.6 逐字对齐)
  89. // Warning warn 级提示(HTTP 200 / body code 200,前端按 code 展示文案)。
  90. type Warning struct {
  91. // Code 31xx 业务码(当前仅 3103 可退金额不足)。
  92. Code int `json:"code"`
  93. // Message 后端出的人话文案(前端直显)。
  94. Message string `json:"message"`
  95. }
  96. // CustomRefundResult 自定义退费响应(端点 6 / SP9)。
  97. //
  98. // 业务语义(对齐 dump `sp_user_expense_custom_refund`,双 log):
  99. //
  100. // 前置 balance <= 0 → 3102(无 result);requested <= 0 → 2002(不做 no-op,因本流程含活动失效副作用)。
  101. // requested > balance:badDebt = requested - balance,扣减仅 balance;
  102. // 先写 108(+badDebt,remark 追加"退费的金额大于可退费部分,超出部分为坏账部分。"),
  103. // 再写 207(-requested,**全额**,★ 与扣减额不同,前端勿据此推导余额变化)。
  104. // requested <= balance:badDebt = 0,无 108 流水,207 = -requested。
  105. // 净资金变化 = -(requested - badDebt) = -(refunded)。
  106. type CustomRefundResult struct {
  107. Requested money.Amount `json:"requested"` // 请求退费金额(回显输入;>0)
  108. Refunded money.Amount `json:"refunded"` // 实际退出资金净额 = requested - badDebt(≥0)
  109. BadDebt money.Amount `json:"badDebt"` // 差额坏账 = max(requested-可退, 0);0 = 无坏账
  110. RefundableAmount money.Amount `json:"refundableAmount"` // 退费前可退金额快照 = max(校区 balance, 0)(本流程扣减基数;**不含**赠送额扣减,与 SP5 查询口径不同,见 FundService.RefundableAmount 注释)
  111. Balance money.Amount `json:"balance"` // 退费后校区账户余额
  112. TotalBalance money.Amount `json:"totalBalance"` // 退费后全局账户(跨校区)余额快照
  113. TotalIncome money.Amount `json:"totalIncome"` // 退费后校区账户 total_income 快照
  114. SpecialExpenses money.Amount `json:"specialExpenses"` // 退费后校区账户特殊费用累计(坏账累计口径)
  115. LogID207 int64 `json:"logId207"` // type=207 流水 ID(money = -requested 全额)
  116. LogID108 *int64 `json:"logId108"` // type=108 流水 ID(money = +badDebt);无坏账 → null
  117. ExpiredActivityIDs []int64 `json:"expiredActivityIds"` // 本次被置为 status=4 的活动 ID(空 → [])
  118. Warnings []Warning `json:"warnings"` // warn 级提示(非阻断;空 → [])
  119. Repeated bool `json:"repeated"` // true = 幂等命中,其余字段回放首次结果
  120. }
  121. // ClearBalanceResult 余额清零响应(端点 9 / SP10)。
  122. //
  123. // 三条前置校验失败(campusBalance<=0 / totalBalance<=0 / campusBalance>totalBalance)→ 3120 + reason,无 result。
  124. //
  125. // ★ 漂移项(设计 §3.1 #10):全局表 `t_user_expense` 的扣减基数是 **campusBalance**(不是 totalBalance),
  126. // 即清零只清"本校区那部分",全局钱包剩余部分保留。
  127. type ClearBalanceResult struct {
  128. Cleared money.Amount `json:"cleared"` // 已清零金额 = 清零前校区 balance(= 208 流水绝对值)
  129. CampusBalanceBefore money.Amount `json:"campusBalanceBefore"` // 清零前校区余额快照
  130. TotalBalanceBefore money.Amount `json:"totalBalanceBefore"` // 清零前全局余额快照
  131. Balance money.Amount `json:"balance"` // 清零后校区余额(恒 "0.00")
  132. TotalBalance money.Amount `json:"totalBalance"` // 清零后全局余额
  133. SpecialExpenses money.Amount `json:"specialExpenses"` // 清零后特殊费用累计
  134. LogID208 int64 `json:"logId208"` // type=208 流水 ID(money = -cleared)
  135. ExpiredActivityIDs []int64 `json:"expiredActivityIds"` // 失效活动 ID(空 → [])
  136. Repeated bool `json:"repeated"` // 幂等命中(SP10 无请求号 → 恒 false)
  137. }
  138. // CancelRechargeActivityResult 取消充值活动结果(端点 30 / SP8)。
  139. type CancelRechargeActivityResult struct {
  140. // InstitutionID 由校区反查出的机构 ID(dump 末尾 `SELECT selectSchoolid AS schoolid`)。
  141. InstitutionID int64 `json:"institutionId"`
  142. // LogID type=209 流水 ID。
  143. LogID int64 `json:"logId"`
  144. // Balance 取消后校区账户余额。
  145. Balance money.Amount `json:"balance"`
  146. // Repeated true = 幂等命中。
  147. Repeated bool `json:"repeated"`
  148. }
  149. // ---------------------------------------------------------------- 入参
  150. // CustomRefundInput 自定义退费入参(SP9 7 参;`RequestID` **必填**,作幂等键)。
  151. type CustomRefundInput struct {
  152. // UserID 退费用户(必填)。
  153. UserID string `json:"userId"`
  154. // InstitutionID 机构 ID(必填 >0)。
  155. InstitutionID int64 `json:"institutionId"`
  156. // CampusID 校区 ID(必填 >0)。
  157. CampusID int64 `json:"campusId"`
  158. // Money 请求退费金额(requested;必须 >0,允许超过可退金额 → 差额计坏账)。
  159. Money money.Amount `json:"money"`
  160. // RequestID 幂等请求号(**必填**;空则失去幂等保护,直接 2001)。
  161. RequestID string `json:"requestId"`
  162. // Remark 备注(空 → "余额退费")。
  163. Remark string `json:"remark"`
  164. // OperatorID 操作人(→ create_user_id)。
  165. OperatorID string `json:"-"`
  166. }
  167. // ClearBalanceInput 余额清零入参(SP10 5 参;**dump 无请求号**)。
  168. type ClearBalanceInput struct {
  169. // UserID 用户(必填)。
  170. UserID string `json:"userId"`
  171. // InstitutionID 机构 ID(必填 >0)。
  172. InstitutionID int64 `json:"institutionId"`
  173. // CampusID 校区 ID(必填 >0)。
  174. CampusID int64 `json:"campusId"`
  175. // Remark 备注(空 → "余额清零")。
  176. Remark string `json:"remark"`
  177. // OperatorID 操作人。
  178. OperatorID string `json:"-"`
  179. }
  180. // CancelRechargeActivityInput 取消充值活动入参(SP8 7 参)。
  181. type CancelRechargeActivityInput struct {
  182. // UserID 用户(必填)。
  183. UserID string `json:"userId"`
  184. // ActivityID 活动 ID(必填 >0)。
  185. ActivityID int64 `json:"activityId"`
  186. // CampusID 校区 ID(必填 >0;机构由 `t_campus.institution_id` 反查)。
  187. CampusID int64 `json:"campusId"`
  188. // Money 取消金额(>0;流水落 `-Money`)。
  189. Money money.Amount `json:"money"`
  190. // RequestID 幂等请求号(空 = 不享幂等)。
  191. RequestID string `json:"requestId"`
  192. // Remark 备注(空 → "取消充值活动")。
  193. Remark string `json:"remark"`
  194. // OperatorID 操作人。
  195. OperatorID string `json:"-"`
  196. }
  197. // ---------------------------------------------------------------- SP9 自定义退费
  198. // CustomRefund 自定义余额退费(SP9 `sp_user_expense_custom_refund`,**双账户锁 + 双 log + 活动失效**)。
  199. //
  200. // 时序(设计 §7.2 逐步骤,顺序不可调整):
  201. //
  202. // ① 幂等预检(207 为恒存在的主流水)→ 命中即回放首次结果(repeated=true)
  203. // ② 作用域断言(全局钱包无作用域列 → Service 显式校验)
  204. // ③ **加锁:全局 → 校区**(固定顺序,与充值写序一致,避免"充值持全局等校区 / 退费持校区等全局"死锁)
  205. // └ 校区账户不存在 或 balance<=0 → **3102**(dump "余额不能≤0")
  206. // ④ 拆分:refundable = max(balance,0);refunded = min(requested, refundable);
  207. // badDebt = requested - refunded
  208. // ⑤ 双表**同额**扣 refunded(balance−, total_income−),badDebt>0 时再 special_expenses+badDebt
  209. // ⑥ **先 108(+badDebt)再 207(−requested 全额)**(dump 顺序;扣减额 ≠ 207,两者差额恰为 108)
  210. // ⑦ 活动失效(同一事务,自营/加盟分流 → ActivityExpirer)
  211. // ⑧ 快照回填(退费后余额/累计/特殊费用)
  212. //
  213. // 与 SP10 的口径差异(**不得混淆**):本方法**不做** `campusBalance <= totalBalance` 校验——
  214. // 那是 `cleared_balance` 的规则(设计 §3.1 #9 明确标注);退费只受"本校区可退金额"约束。
  215. //
  216. // 入参:ctx / in。出参:*CustomRefundResult;错误码 2001/2002/3140/3102/3104/1004/3001/5002。
  217. func (s *RefundService) CustomRefund(ctx context.Context, in CustomRefundInput) (*CustomRefundResult, error) {
  218. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "CustomRefund", true); err != nil {
  219. return nil, err
  220. }
  221. if err := validatePositiveAmount(in.Money, "CustomRefund"); err != nil {
  222. return nil, err
  223. }
  224. if strings.TrimSpace(in.RequestID) == "" {
  225. // 本流程含"活动失效"副作用,没有幂等键就无法防重放 → 必填(设计 §4.1 端点 6)
  226. return nil, infraerrors.WithCause(infraerrors.ErrBadFormat,
  227. errString("service: CustomRefund 需要 requestId(幂等键,必填)"))
  228. }
  229. if s == nil || s.runner == nil || s.repo == nil {
  230. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: RefundService 未装配"))
  231. }
  232. remark := strings.TrimSpace(in.Remark)
  233. if remark == "" {
  234. remark = defaultCustomRefundRemark
  235. }
  236. var out CustomRefundResult
  237. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  238. txCtx := repository.WithTxContext(ctx, tx)
  239. // ① 幂等预检
  240. hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeRefund)
  241. if e != nil {
  242. return e
  243. }
  244. if hit != nil {
  245. return s.replayCustomRefund(txCtx, tx, in, &out, hit)
  246. }
  247. // ② 作用域断言
  248. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  249. return e
  250. }
  251. // ③ 加锁:**全局 → 校区**(顺序是硬约束,单测用 SQL 顺序断言钉住)
  252. if _, e := s.repo.GetForUpdate(txCtx, tx, in.UserID); e != nil {
  253. return e // 全局账户不存在 → 3001(dump 会静默 0 行更新,Go 显式失败)
  254. }
  255. school, e := s.repo.GetCampusForUpdate(txCtx, tx, in.UserID, in.CampusID)
  256. if e != nil {
  257. if errors.Is(e, infraerrors.ErrNotFound) {
  258. return infraerrors.WithCause(apperr.ErrNoBalanceToRefund,
  259. errString("service: CustomRefund 校区账户不存在,余额不能≤0"))
  260. }
  261. return e
  262. }
  263. balance, e := parseAccountAmount(school.Balance, "t_user_expense_school.balance")
  264. if e != nil {
  265. return e
  266. }
  267. if balance <= 0 {
  268. return infraerrors.WithCause(apperr.ErrNoBalanceToRefund,
  269. errString("service: CustomRefund 余额不能≤0(dump 原文文案)"))
  270. }
  271. // ④ 可退金额 + 坏账拆分
  272. refundable := balance
  273. if refundable < 0 {
  274. refundable = 0
  275. }
  276. refunded := in.Money
  277. if refunded > refundable {
  278. refunded = refundable
  279. }
  280. badDebt := in.Money.Sub(refunded)
  281. if badDebt < 0 {
  282. badDebt = 0 // 防御:refunded <= requested 恒成立,此处只为可读性
  283. }
  284. // ⑤ 双表同额扣减(badDebt>0 时同步累加 special_expenses)
  285. deltas := []repository.ColumnDelta{
  286. {Column: repository.ExpenseColumnBalance, Delta: refunded.Neg()},
  287. {Column: repository.ExpenseColumnTotalIncome, Delta: refunded.Neg()},
  288. }
  289. if badDebt > 0 {
  290. deltas = append(deltas, repository.ColumnDelta{
  291. Column: repository.ExpenseColumnSpecialExpenses, Delta: badDebt,
  292. })
  293. }
  294. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "CustomRefund", in.UserID,
  295. in.InstitutionID, in.CampusID, deltas...); e != nil {
  296. return e
  297. }
  298. after, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
  299. if e != nil {
  300. return e
  301. }
  302. balanceAfter, e := parseAccountAmount(after.Balance, "t_user_expense_school.balance")
  303. if e != nil {
  304. return e
  305. }
  306. // `balance_after` 快照口径(§3.8-f ②-bis):**全局账户**余额,写完账户后取一次,
  307. // 108 与 207 两条流水**写同一个值**(响应体的 Balance 仍是校区余额,两者语义不同)。
  308. globalSnapshot, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  309. if e != nil {
  310. return e
  311. }
  312. // ⑥ 双 log:**先 108(+badDebt)再 207(−requested 全额)**
  313. //
  314. // ★ 兼容注释:type=108 有两种来源,此处写的是**第二种**(退费差额型)——
  315. // - 差额型(本方法):只累加 special_expenses(见 ⑤),balance 净减 = refunded;
  316. // 108.money = +badDebt,207.money = **−requested 全额**,坏账部分已含在 207 内,
  317. // 故该 108 **不构成**一次独立的余额增加(判据:同 logid 存在 207);
  318. // - 独立坏账(`FundService.BadDebt`,SP7):balance 与 special_expenses **双加**,
  319. // 108.money = +m 真实对应余额增加(判据:同 logid 无 207)。
  320. // 对账口径详见 `FundService.BadDebt` 方法注释;AC-17 ④ 的恒等式判别按此落地。
  321. var logID108 *int64
  322. if badDebt > 0 {
  323. lg108 := newExpenseLog(in.UserID, model.ExpenseLogTypeBadDebt, badDebt, in.RequestID,
  324. remark+badDebtRemarkSuffix, in.OperatorID, &globalSnapshot)
  325. if e := s.insertLog(txCtx, tx, lg108); e != nil {
  326. return e
  327. }
  328. id := lg108.ID
  329. logID108 = &id
  330. }
  331. lg207 := newExpenseLog(in.UserID, model.ExpenseLogTypeRefund, in.Money.Neg(), in.RequestID,
  332. remark, in.OperatorID, &globalSnapshot)
  333. if e := s.insertLog(txCtx, tx, lg207); e != nil {
  334. return e
  335. }
  336. // ⑦ 活动失效(同事务;自营 `IN (campus,0)` / 加盟 `= campus`)
  337. expired, e := s.expireRechargeActivities(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
  338. if e != nil {
  339. return e
  340. }
  341. // ⑧ 快照回填
  342. globalAfter, e := s.repo.GetGlobalAccount(txCtx, tx, in.UserID)
  343. if e != nil {
  344. return e
  345. }
  346. totalBalance, e := parseAccountAmount(globalAfter.Balance, "t_user_expense.balance")
  347. if e != nil {
  348. return e
  349. }
  350. totalIncome, e := parseAccountAmount(after.TotalIncome, "t_user_expense_school.total_income")
  351. if e != nil {
  352. return e
  353. }
  354. special, e := parseAccountAmount(after.SpecialExpenses, "t_user_expense_school.special_expenses")
  355. if e != nil {
  356. return e
  357. }
  358. out = CustomRefundResult{
  359. Requested: in.Money,
  360. Refunded: refunded,
  361. BadDebt: badDebt,
  362. RefundableAmount: refundable,
  363. Balance: balanceAfter,
  364. TotalBalance: totalBalance,
  365. TotalIncome: totalIncome,
  366. SpecialExpenses: special,
  367. LogID207: lg207.ID,
  368. LogID108: logID108,
  369. ExpiredActivityIDs: expired,
  370. Warnings: refundWarnings(badDebt),
  371. Repeated: false,
  372. }
  373. return nil
  374. })
  375. if err != nil {
  376. // 并发幂等命中(撞 uk_request_type)→ 整笔回滚后回放首次结果
  377. if errors.Is(err, apperr.ErrRepeated) {
  378. return s.replayCustomRefundAfterRace(ctx, in)
  379. }
  380. return nil, err
  381. }
  382. return &out, nil
  383. }
  384. // replayCustomRefund 幂等回放(**事务内**路径:预检命中,未产生任何写入)。
  385. //
  386. // 入参:txCtx(含 tx)/ tx / in / out / hit(首次 207 流水)。
  387. // 出参:nil(out 已填充)/ 错误。
  388. //
  389. // 回放口径:`requested/badDebt/refunded/logId207/logId108/warnings` 由**首次流水**重建;
  390. // `balance/totalBalance/totalIncome/specialExpenses` 取**当前**账户快照
  391. // (中间若发生别的资金操作,这些快照会前进——属可接受的"当前值",不伪造历史)。
  392. func (s *RefundService) replayCustomRefund(
  393. ctx context.Context, tx *gorm.DB, in CustomRefundInput, out *CustomRefundResult, hit *model.UserExpenseLog,
  394. ) error {
  395. requested, err := money.Parse(strings.TrimPrefix(hit.Money, "-"))
  396. if err != nil {
  397. return infraerrors.WithCause(infraerrors.ErrDBError, errString("service: 首次 207 流水金额非法"))
  398. }
  399. // 使用票据金额的绝对值:207 恒为 −requested
  400. requested = absAmount(requested)
  401. var badDebt money.Amount
  402. var logID108 *int64
  403. hit108, e := s.repo.FindLogByRequest(ctx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeBadDebt)
  404. if e != nil {
  405. return e
  406. }
  407. if hit108 != nil {
  408. if v, pe := money.Parse(hit108.Money); pe == nil {
  409. badDebt = absAmount(v)
  410. id := hit108.ID
  411. logID108 = &id
  412. }
  413. }
  414. res := CustomRefundResult{
  415. Requested: requested,
  416. BadDebt: badDebt,
  417. Refunded: requested.Sub(badDebt),
  418. RefundableAmount: requested.Sub(badDebt),
  419. LogID207: hit.ID,
  420. LogID108: logID108,
  421. ExpiredActivityIDs: make([]int64, 0),
  422. Warnings: refundWarnings(badDebt),
  423. Repeated: true,
  424. }
  425. if acc, ae := s.repo.GetCampusAccount(ctx, tx, in.UserID, in.InstitutionID, in.CampusID); ae == nil {
  426. if v, pe := parseAccountAmount(acc.Balance, "t_user_expense_school.balance"); pe == nil {
  427. res.Balance = v
  428. }
  429. if v, pe := parseAccountAmount(acc.TotalIncome, "t_user_expense_school.total_income"); pe == nil {
  430. res.TotalIncome = v
  431. }
  432. if v, pe := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses"); pe == nil {
  433. res.SpecialExpenses = v
  434. }
  435. }
  436. if gl, ge := s.repo.GetGlobalAccount(ctx, tx, in.UserID); ge == nil {
  437. if v, pe := parseAccountAmount(gl.Balance, "t_user_expense.balance"); pe == nil {
  438. res.TotalBalance = v
  439. }
  440. }
  441. *out = res
  442. return nil
  443. }
  444. // replayCustomRefundAfterRace 并发幂等命中后的回放(**事务外**路径:本次事务已整笔回滚)。
  445. //
  446. // 入参:ctx / in。出参:*CustomRefundResult(Repeated=true)/ 错误。
  447. //
  448. // 为什么要等事务回滚后再查:并发对手的流水只有在它提交后才可见,
  449. // 因此这里是"先让本次事务彻底结束(回滚),再重新读首次结果"(设计 §1.4 幂等模板)。
  450. func (s *RefundService) replayCustomRefundAfterRace(
  451. ctx context.Context, in CustomRefundInput,
  452. ) (*CustomRefundResult, error) {
  453. hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeRefund)
  454. if err != nil {
  455. return nil, err
  456. }
  457. if hit == nil {
  458. return nil, infraerrors.WithCause(infraerrors.ErrInternal,
  459. errString("service: CustomRefund 幂等命中但首次流水已不可见"))
  460. }
  461. var out CustomRefundResult
  462. if err := s.replayCustomRefund(ctx, nil, in, &out, hit); err != nil {
  463. return nil, err
  464. }
  465. return &out, nil
  466. }
  467. // refundWarnings 按 badDebt 生成 warn 列表(3103 不阻断,§4.6)。
  468. //
  469. // 入参:badDebt 坏账金额。出参:[]Warning(**空时返回长度 0 的非 nil 切片**,JSON 序列化为 [])。
  470. func refundWarnings(badDebt money.Amount) []Warning {
  471. if badDebt <= 0 {
  472. return make([]Warning, 0)
  473. }
  474. return []Warning{{
  475. Code: apperr.CodeRefundableShort,
  476. Message: "可退金额不足,差额 " + badDebt.String() + " 已计入坏账",
  477. }}
  478. }
  479. // absAmount 取金额绝对值(流水方向 → 金额绝对值,回放用)。
  480. func absAmount(a money.Amount) money.Amount {
  481. if a < 0 {
  482. return a.Neg()
  483. }
  484. return a
  485. }
  486. // ---------------------------------------------------------------- SP10 余额清零
  487. // ClearBalance 余额清零(SP10 `sp_user_expense_school_cleared_balance`)。
  488. //
  489. // dump 语义(:764295,★**全局表扣减基数是 campusBalance**,不是 totalBalance,设计 §3.1 #10):
  490. //
  491. // ① 读校区余额;ISNULL 或 <=0 → LEAVE
  492. // ② 读全局余额;ISNULL 或 <=0 → LEAVE
  493. // ③ campusBalance > totalBalance → LEAVE
  494. // ④ UPDATE 校区:balance−campusBalance, special_expenses+campusBalance, spend+campusBalance
  495. // UPDATE 全局:balance−campusBalance, special_expenses+campusBalance, spend+campusBalance
  496. // ⑤ INSERT log(type=208, money=−campusBalance)
  497. // ⑥ 活动失效(与 SP9 同一段 SQL)
  498. //
  499. // Go 的差异:①②③ 失败 → **3120 + 原因**(dump 静默 LEAVE;前端会显示"成功但余额没变")。
  500. //
  501. // 幂等:SP10 **没有请求号**(dump 签名只有 5 参),因此无幂等键可落;重复调用第二次
  502. // `campusBalance=0` → 3120(天然幂等,不会重复清零)。`Repeated` 恒 false。
  503. //
  504. // 入参:ctx / in。出参:*ClearBalanceResult;错误码 2001/3140/3120/3104/1004/3001/5002。
  505. func (s *RefundService) ClearBalance(ctx context.Context, in ClearBalanceInput) (*ClearBalanceResult, error) {
  506. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "ClearBalance", true); err != nil {
  507. return nil, err
  508. }
  509. if s == nil || s.runner == nil || s.repo == nil {
  510. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: RefundService 未装配"))
  511. }
  512. remark := strings.TrimSpace(in.Remark)
  513. if remark == "" {
  514. remark = defaultClearBalanceRemark
  515. }
  516. var out ClearBalanceResult
  517. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  518. txCtx := repository.WithTxContext(ctx, tx)
  519. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  520. return e
  521. }
  522. // ① 加锁:全局 → 校区(同 §7.2 基线)
  523. global, e := s.repo.GetForUpdate(txCtx, tx, in.UserID)
  524. if e != nil {
  525. if errors.Is(e, infraerrors.ErrNotFound) {
  526. return clearBalanceRejected("全局账户不存在(totalBalance 视为 0)")
  527. }
  528. return e
  529. }
  530. school, e := s.repo.GetCampusForUpdate(txCtx, tx, in.UserID, in.CampusID)
  531. if e != nil {
  532. if errors.Is(e, infraerrors.ErrNotFound) {
  533. return clearBalanceRejected("校区账户不存在(campusBalance 视为 0)")
  534. }
  535. return e
  536. }
  537. campusBalance, e := parseAccountAmount(school.Balance, "t_user_expense_school.balance")
  538. if e != nil {
  539. return e
  540. }
  541. totalBalance, e := parseAccountAmount(global.Balance, "t_user_expense.balance")
  542. if e != nil {
  543. return e
  544. }
  545. // ② 三条前置校验(失败 → 3120 + 原因,**不做 no-op**)
  546. if campusBalance <= 0 {
  547. return clearBalanceRejected("校区余额 ≤ 0,无需清零")
  548. }
  549. if totalBalance <= 0 {
  550. return clearBalanceRejected("全局余额 ≤ 0,无需清零")
  551. }
  552. if campusBalance > totalBalance {
  553. return clearBalanceRejected("校区余额大于全局余额(数据异常,拒绝清零)")
  554. }
  555. // ③ 双表同额扣减:balance−campusBalance、special_expenses+campusBalance、spend+campusBalance
  556. // ★ 全局表扣减基数同样是 campusBalance(漂移项,不得改成 totalBalance)
  557. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "ClearBalance", in.UserID,
  558. in.InstitutionID, in.CampusID,
  559. repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: campusBalance.Neg()},
  560. repository.ColumnDelta{Column: repository.ExpenseColumnSpecialExpenses, Delta: campusBalance},
  561. repository.ColumnDelta{Column: repository.ExpenseColumnSpend, Delta: campusBalance},
  562. ); e != nil {
  563. return e
  564. }
  565. after, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
  566. if e != nil {
  567. return e
  568. }
  569. balanceAfter, e := parseAccountAmount(after.Balance, "t_user_expense_school.balance")
  570. if e != nil {
  571. return e
  572. }
  573. specialAfter, e := parseAccountAmount(after.SpecialExpenses, "t_user_expense_school.special_expenses")
  574. if e != nil {
  575. return e
  576. }
  577. // ④ 流水 type=208,money = −campusBalance(无请求号 → request_id/log_id 均为 NULL)
  578. // `balance_after` = 清零后**全局账户**余额快照(§3.8-f ②-bis;响应体 Balance 仍是校区余额 0)
  579. globalSnapshot, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  580. if e != nil {
  581. return e
  582. }
  583. lg := newExpenseLog(in.UserID, model.ExpenseLogTypeClearBalance, campusBalance.Neg(),
  584. "", remark, in.OperatorID, &globalSnapshot)
  585. if e := s.insertLog(txCtx, tx, lg); e != nil {
  586. return e
  587. }
  588. // ⑤ 活动失效(同事务,与 SP9 同源)
  589. expired, e := s.expireRechargeActivities(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
  590. if e != nil {
  591. return e
  592. }
  593. globalAfter, e := s.repo.GetGlobalAccount(txCtx, tx, in.UserID)
  594. if e != nil {
  595. return e
  596. }
  597. totalAfter, e := parseAccountAmount(globalAfter.Balance, "t_user_expense.balance")
  598. if e != nil {
  599. return e
  600. }
  601. out = ClearBalanceResult{
  602. Cleared: campusBalance,
  603. CampusBalanceBefore: campusBalance,
  604. TotalBalanceBefore: totalBalance,
  605. Balance: balanceAfter,
  606. TotalBalance: totalAfter,
  607. SpecialExpenses: specialAfter,
  608. LogID208: lg.ID,
  609. ExpiredActivityIDs: expired,
  610. Repeated: false,
  611. }
  612. return nil
  613. })
  614. if err != nil {
  615. return nil, err
  616. }
  617. return &out, nil
  618. }
  619. // clearBalanceRejected 构造 3120(前置条件不满足)+ 具体原因(设计 §3.1 #10 的显式化)。
  620. //
  621. // 入参:reason 人话原因(会进日志,不进响应体正文之外的结构)。
  622. // 出参:*infraerrors.AppError(3120)。
  623. func clearBalanceRejected(reason string) error {
  624. return infraerrors.WithCause(apperr.ErrClearBalanceRejected, errString("service: ClearBalance "+reason))
  625. }
  626. // ---------------------------------------------------------------- SP8 取消充值活动
  627. // CancelRechargeActivity 取消充值活动(SP8 `sp_user_expense_cancel_recharge_activity`)。
  628. //
  629. // dump 语义(:763935):
  630. //
  631. // ① `SELECT school_id FROM yuansiwei.t_school_campus WHERE id=inputCampusid`
  632. // → ISNULL 或 0:`msg='找不到学校信息'` + LEAVE(success=0)
  633. // ② 校区账户/全局账户不存在则建户
  634. // ③ UPDATE 校区:balance−money, total_income−money ;UPDATE 全局:同
  635. // ④ UPDATE t_courses_activity_signed SET status=**0** WHERE userid AND activityid(注意不是 4)
  636. // ⑤ INSERT log(type=209, money=**−money**)
  637. //
  638. // Go 的两处收敛:
  639. // - 跨库读 `yuansiwei.t_school_campus` → `port.CampusReader.GetSchoolID`(同事务只读,禁止跨库 SQL,§1.6);
  640. // 取不到 → **3104**(dump 返回 success=0 + 文案,无错误码);
  641. // - 幂等:`request_id + type(209)` 唯一键(dump 无幂等)。
  642. //
  643. // 归属说明:设计 §3.1 #8 把本方法挂在 `RecommendService.CancelRechargeActivity`(AC-08);
  644. // 本批(AC-05)先落在 RefundService 上——两者是同一个资金动作 + 同一句活动状态回写,
  645. // AC-08 落地时 RecommendService 可直接转调本方法(签名不变),避免同一逻辑写两份。
  646. //
  647. // 入参:ctx / in。出参:*CancelRechargeActivityResult;错误码 2001/2002/3140/3104/1004/3001/5002。
  648. func (s *RefundService) CancelRechargeActivity(
  649. ctx context.Context, in CancelRechargeActivityInput,
  650. ) (*CancelRechargeActivityResult, error) {
  651. if strings.TrimSpace(in.UserID) == "" {
  652. return nil, infraerrors.WithCause(infraerrors.ErrBadParam,
  653. errString("service: CancelRechargeActivity 需要 user_id"))
  654. }
  655. if in.CampusID <= 0 {
  656. return nil, infraerrors.WithCause(apperr.ErrBusinessParam,
  657. errString("service: CancelRechargeActivity 需要 campus_id > 0"))
  658. }
  659. if in.ActivityID <= 0 {
  660. return nil, infraerrors.WithCause(infraerrors.ErrBadFormat,
  661. errString("service: CancelRechargeActivity 需要 activity_id > 0"))
  662. }
  663. if err := validatePositiveAmount(in.Money, "CancelRechargeActivity"); err != nil {
  664. return nil, err
  665. }
  666. if s == nil || s.runner == nil || s.repo == nil || s.campus == nil {
  667. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: RefundService 未装配"))
  668. }
  669. remark := strings.TrimSpace(in.Remark)
  670. if remark == "" {
  671. remark = defaultCancelRechargeRemark
  672. }
  673. var out CancelRechargeActivityResult
  674. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  675. txCtx := repository.WithTxContext(ctx, tx)
  676. hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeCancelRechargeAct)
  677. if e != nil {
  678. return e
  679. }
  680. if hit != nil {
  681. out = CancelRechargeActivityResult{LogID: hit.ID, Repeated: true}
  682. // 响应体 Balance 是**校区**余额(流水 balance_after 自 v0.1.16 起是全局口径),
  683. // 故按"校区 → 机构 → 账户"重新回读当前值;读不到就回退 0(不伪造)。
  684. if inst, ie := s.readCampus(txCtx, tx, in.CampusID); ie == nil {
  685. out.InstitutionID = inst.SchoolID
  686. if inst.SchoolID > 0 {
  687. if bal, pe := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, inst.SchoolID, in.CampusID); pe == nil {
  688. out.Balance = bal
  689. }
  690. }
  691. }
  692. return nil
  693. }
  694. // ① 跨域读校区 → 机构 ID(失败 3104)
  695. info, e := s.readCampus(txCtx, tx, in.CampusID)
  696. if e != nil {
  697. return e
  698. }
  699. if info.SchoolID <= 0 {
  700. return infraerrors.WithCause(apperr.ErrCampusNotFound,
  701. errString("service: CancelRechargeActivity 校区未归属机构"))
  702. }
  703. if e := s.assertInScope(txCtx, in.UserID, info.SchoolID, in.CampusID); e != nil {
  704. return e
  705. }
  706. // ② 建户(dump 的 COUNT 判存在 → UPSERT)
  707. if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
  708. return e
  709. }
  710. if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
  711. UserID: in.UserID, InstitutionID: info.SchoolID, CampusID: in.CampusID,
  712. }); e != nil {
  713. return e
  714. }
  715. // ③ 余额−、总充值−
  716. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "CancelRechargeActivity", in.UserID,
  717. info.SchoolID, in.CampusID,
  718. repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money.Neg()},
  719. repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money.Neg()},
  720. ); e != nil {
  721. return e
  722. }
  723. // ④ 报名状态归 0(dump:`SET status=0`,**不是 4**)
  724. if _, e := s.expirer.SetSignedStatus(
  725. txCtx, tx, in.UserID, []int64{in.ActivityID}, model.ActivitySignedCancelled,
  726. ); e != nil {
  727. return e
  728. }
  729. acc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, info.SchoolID, in.CampusID)
  730. if e != nil {
  731. return e
  732. }
  733. bal, e := parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
  734. if e != nil {
  735. return e
  736. }
  737. // ⑤ 流水 type=209,money = −money
  738. // `balance_after` = 取消后**全局账户**余额快照(§3.8-f ②-bis;响应体 Balance 仍是校区余额)
  739. globalSnapshot, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  740. if e != nil {
  741. return e
  742. }
  743. lg := newExpenseLog(in.UserID, model.ExpenseLogTypeCancelRechargeAct, in.Money.Neg(),
  744. in.RequestID, remark, in.OperatorID, &globalSnapshot)
  745. if e := s.insertLog(txCtx, tx, lg); e != nil {
  746. return e
  747. }
  748. out = CancelRechargeActivityResult{
  749. InstitutionID: info.SchoolID,
  750. LogID: lg.ID,
  751. Balance: bal,
  752. }
  753. return nil
  754. })
  755. if err != nil {
  756. if errors.Is(err, apperr.ErrRepeated) {
  757. hit, re := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeCancelRechargeAct)
  758. if re != nil {
  759. return nil, re
  760. }
  761. if hit == nil {
  762. return nil, infraerrors.WithCause(infraerrors.ErrInternal,
  763. errString("service: CancelRechargeActivity 幂等命中但首次流水已不可见"))
  764. }
  765. bal, pe := balanceAfterOf(hit)
  766. if pe != nil {
  767. return nil, pe
  768. }
  769. return &CancelRechargeActivityResult{LogID: hit.ID, Balance: bal, Repeated: true}, nil
  770. }
  771. return nil, err
  772. }
  773. return &out, nil
  774. }
  775. // ---------------------------------------------------------------- 内部助手
  776. // assertInScope 对象级越权断言(RefundService 版本,语义同 FundService)。
  777. func (s *RefundService) assertInScope(ctx context.Context, userID string, institutionID, campusID int64) error {
  778. if s == nil || s.member == nil {
  779. return nil // 系统任务/割接脚本模式
  780. }
  781. return s.member.AssertInScope(ctx, userID, institutionID, campusID)
  782. }
  783. // insertLog 写流水(撞 `uk_request_type` → 内部幂等哨兵,语义同 FundService.insertLog)。
  784. func (s *RefundService) insertLog(txCtx context.Context, tx *gorm.DB, lg *model.UserExpenseLog) error {
  785. err := s.repo.InsertLog(txCtx, tx, lg)
  786. if err == nil {
  787. return nil
  788. }
  789. if errors.Is(err, repository.ErrDuplicateLog) {
  790. return apperr.ErrRepeated
  791. }
  792. return err
  793. }
  794. // readCampus 同事务读校区(优先 `TxCampusReader`,退化到连接池版 `CampusReader`)。
  795. //
  796. // 入参:ctx / tx / campusID(>0)。
  797. // 出参:*port.CampusInfo;3104(校区不存在)/ 3140(campusID<=0)/ 5002。
  798. //
  799. // 为什么优先 TxCampusReader:dump 是同库 JOIN(同一快照),目标态跨域读必须显式传 tx,
  800. // 否则读到的是连接池的默认隔离级别快照,与本次资金事务不一致(§1.6)。
  801. func (s *RefundService) readCampus(ctx context.Context, tx *gorm.DB, campusID int64) (*port.CampusInfo, error) {
  802. if s.campus == nil {
  803. return nil, infraerrors.WithCause(infraerrors.ErrInternal,
  804. errString("service: 未注入 port.CampusReader(无法判定自营/机构)"))
  805. }
  806. if txReader, ok := s.campus.(port.TxCampusReader); ok {
  807. return txReader.GetByIDTx(ctx, tx, campusID)
  808. }
  809. return s.campus.GetByID(ctx, campusID)
  810. }
  811. // expireRechargeActivities 判定自营/加盟并在同一事务内失效活动(SP9/SP10 共用)。
  812. //
  813. // 入参:txCtx / tx / userID / institutionID / campusID。
  814. // 出参:(失效活动 ID 列表, error);3104(校区不存在,R1 硬化)/ 5002。
  815. //
  816. // 分流(dump `IF(campusSelfSupport)`):
  817. // - 自营 true → `activity.campus_id IN (campusID, 0)`(含"全机构池"活动)
  818. // - 加盟 false → `activity.campus_id = campusID`(**不含** 0,避免误失效他校区活动)
  819. func (s *RefundService) expireRechargeActivities(
  820. ctx context.Context, tx *gorm.DB, userID string, institutionID, campusID int64,
  821. ) ([]int64, error) {
  822. info, err := s.readCampus(ctx, tx, campusID)
  823. if err != nil {
  824. return nil, err
  825. }
  826. if info.SchoolID > 0 && info.SchoolID != institutionID {
  827. // 校区归属机构与入参不一致 → 同码 3104(不泄露存在性,不误写)
  828. return nil, infraerrors.WithCause(apperr.ErrCampusNotFound,
  829. errString("service: 校区归属机构与入参 institution_id 不一致"))
  830. }
  831. return s.expirer.ExpireForUser(ctx, tx, userID, institutionID, campusID, info.SelfSupport)
  832. }