fund_service.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. // 余额核心服务(8 个余额类 SP 的 Go 化落点)——AC-04。
  2. //
  3. // 依据:unified/03-migration/academic-domain-design.md §3.1(余额 11 SP 映射,本文件覆盖 #1~#7 + #11)
  4. // / §1.4(事务模板)/ §1.5(幂等键 uk_request_type)/ §7.1(充值时序)/ §10.2(type 编码与方向)
  5. // / §10.3(事务边界只在 Service)/ §10.7(金额溢出与量级上限)。
  6. //
  7. // SP 映射(dump 行号见 §3.1,**顺序与方向一律按 dump,不得"顺手修正"**):
  8. //
  9. // #1 sp_user_expense_recharge → Recharge(8 参、**双表更新**:全局 + 校区同事务)
  10. // #2 sp_user_expense_school_recharge → Recharge(同构合并,仅默认备注不同 → RechargeKind)
  11. // #3 sp_user_expense_school_expenditure → Expenditure(type 由调用方传,白名单校验)
  12. // #4 sp_user_expense_school_refund → Refund(**补 institution_id 参数**,BUG#2 修正)
  13. // #5 sp_user_expense_school_get_refundable_amount → RefundableAmount(只读,无事务;**两步修正**)
  14. // #6 sp_user_expense_school_transfer_expenditure → Transfer(**不动 balance**;106=+m / 206=−m)
  15. // #7 sp_user_expense_baddebt → BadDebt(SP 头注释即「余额+,特殊费用+」→ **双加**)
  16. // #11 sp_user_expense_school_spend → AccumulateSpend(只更新 spend,不动 balance;BUG#1)
  17. //
  18. // 两条不可违反的纪律(评审逐处检查):
  19. //
  20. // 1. **事务边界只在 Service**:写路径一律 `s.runner.WithinTx`;仓储方法不开事务,
  21. // 事务内下游调用一律经 `repository.WithTxContext(ctx, tx)` 注入的 ctx(§10.3)。
  22. // 2. **固定写序「全局 → 校区」**:所有双表写都收敛到
  23. // `ExpenseRepo.AddColumnsGlobalThenCampus`(一条表一条 UPDATE,全局在前),
  24. // 与 RefundService 的**加锁**顺序保持一致,否则与并发充值交叉即成环(§1.4 / §7.2)。
  25. //
  26. // 金额纪律:全链路 `money.Amount`(int64 分),入参先过 `validatePositiveAmount`
  27. // (业务量级 + `Validate()`),落库前再由仓储的 `amountLiteral` 二次 `Validate()`(§10.7 兜底网)。
  28. package service
  29. import (
  30. "context"
  31. "errors"
  32. "sort"
  33. "strings"
  34. "gorm.io/gorm"
  35. "yuansiwei/unified-backend/internal/academic/apperr"
  36. "yuansiwei/unified-backend/internal/academic/model"
  37. "yuansiwei/unified-backend/internal/academic/money"
  38. "yuansiwei/unified-backend/internal/academic/port"
  39. "yuansiwei/unified-backend/internal/academic/repository"
  40. infraerrors "yuansiwei/unified-backend/internal/infra/errors"
  41. appscope "yuansiwei/unified-backend/internal/infra/scope"
  42. )
  43. // 默认备注文案(dump 的 `IF inputRemark=”` 分支,**逐字对齐**,双跑会比对 log.remark)。
  44. const (
  45. // defaultRechargeRemark SP1 `sp_user_expense_recharge` 默认备注。
  46. defaultRechargeRemark = "余额充值"
  47. // defaultSchoolRechargeRemark SP2 `sp_user_expense_school_recharge` 默认备注(与 SP1 不同)。
  48. defaultSchoolRechargeRemark = "充值缴费"
  49. // defaultExpenditureRemark SP3 `sp_user_expense_school_expenditure` 默认备注。
  50. defaultExpenditureRemark = "历史扣费"
  51. // defaultRefundRemark SP4 `sp_user_expense_school_refund` 默认备注。
  52. defaultRefundRemark = "报课的费用退回"
  53. // defaultBadDebtRemark SP7 `sp_user_expense_baddebt` 默认备注。
  54. defaultBadDebtRemark = "坏账处理"
  55. )
  56. // maxSingleAmount 单笔金额业务上限(1,000,000.00 元)。
  57. //
  58. // 依据设计 §10.7「配套纪律 2」:Service 入口对 money 做业务量级断言,把"脏数据放大"挡在运算前
  59. // (超出 → 2002)。注意与 `money.MaxAmount`(decimal(12,2) 全域 ±99.99 亿元)不是一回事:
  60. // 前者是**业务**天花板,后者是**存储**天花板,两者都必须校验。
  61. const maxSingleAmount money.Amount = 100_000_000
  62. // RechargeKind 充值 SP 形态(#1 与 #2 的**唯一差异**是默认备注,合并后用它区分双跑映射)。
  63. type RechargeKind int
  64. const (
  65. // RechargeKindDefault 对应 SP1 `sp_user_expense_recharge`(默认备注"余额充值")。
  66. RechargeKindDefault RechargeKind = iota
  67. // RechargeKindSchool 对应 SP2 `sp_user_expense_school_recharge`(默认备注"充值缴费")。
  68. RechargeKindSchool
  69. )
  70. // FundService 余额核心服务(充值/消费/退费/转结/坏账/累计消费/可退金额)。
  71. //
  72. // 字段:
  73. // - repo:余额账户仓储(全局 + 校区 + 流水;校区账户走机构作用域);
  74. // - requests:余额工单仓储(**只读**用途:SP5 可退额需要按「充值工单 × 活动报名」汇总已用赠送额,
  75. // 设计 §3.1 #5 的第二步修正,`SumRechargeActivityUsedGift`);
  76. // - runner:事务运行器(顶层 BEGIN,事务内透传);
  77. // - campus:校区只读端口(**只读**:转结转入方建户需要"权威机构 ID",见 R4-bis);
  78. // - member:成员关系校验器(可 nil:系统任务/割接脚本模式不做对象级越权断言)。
  79. type FundService struct {
  80. repo *repository.ExpenseRepo
  81. requests *repository.BalanceRequestRepo
  82. runner *repository.TxRunner
  83. campus port.CampusReader
  84. member port.MembershipChecker
  85. }
  86. // NewFundService 构造余额核心服务(repo 与 runner 绑定同一 DB 句柄,避免跨连接池事务失效)。
  87. //
  88. // 入参:
  89. // - db *gorm.DB:数据库句柄(必填);
  90. // - sc *appscope.Scope:本次请求作用域(校区账户读写必需;系统任务可 nil,
  91. // 此时**只能**调用全局/流水方法,触达校区账户会 panic fail-fast);
  92. // - member port.MembershipChecker:成员校验器(可 nil)。
  93. //
  94. // 出参:*FundService。
  95. //
  96. // 说明:`campus` 端口由本构造函数内部用同一 db 装配(`port.NewOrgCampusReader`),
  97. // 因此**签名保持不变**(既有调用方无需改动);需要注入 mock 的用例可用 `WithCampusReader`。
  98. func NewFundService(db *gorm.DB, sc *appscope.Scope, member port.MembershipChecker) *FundService {
  99. return &FundService{
  100. repo: repository.NewExpenseRepo(db, sc),
  101. requests: repository.NewBalanceRequestRepo(db, sc),
  102. runner: repository.NewTxRunner(db),
  103. campus: port.NewOrgCampusReader(db),
  104. member: member,
  105. }
  106. }
  107. // WithCampusReader 替换校区只读端口(单测注入 mock 用;nil 时忽略)。
  108. //
  109. // 入参:reader port.CampusReader。出参:*FundService(链式,原地修改后返回自身)。
  110. func (s *FundService) WithCampusReader(reader port.CampusReader) *FundService {
  111. if s != nil && reader != nil {
  112. s.campus = reader
  113. }
  114. return s
  115. }
  116. // ---------------------------------------------------------------- 入参 / 出参
  117. // RechargeInput 充值入参(SP1 `sp_user_expense_recharge` 8 参 / SP2 同构 7 参)。
  118. //
  119. // 入参纪律:`Money` 已由 Handler 用 `money.Parse` 解析(**拒绝 float**,§10.6),
  120. // 本层不再解析字符串,只校验量级与业务规则。
  121. type RechargeInput struct {
  122. // UserID 充值用户(canonical_user_id ULID;必填)。
  123. UserID string `json:"userId"`
  124. // InstitutionID 机构 ID(必填 >0;dump 的 inputSchoolid)。
  125. InstitutionID int64 `json:"institutionId"`
  126. // CampusID 校区 ID(必填 >0;dump 的 inputCampusid)。
  127. CampusID int64 `json:"campusId"`
  128. // Money 充值金额(>0;dump 的 inputMoney)。
  129. Money money.Amount `json:"money"`
  130. // Type 流水类型(dump 的 inputType;<100 一律归 100,对齐 dump `IF inputType<100`)。
  131. Type int32 `json:"type"`
  132. // RequestID 幂等请求号(→ request_id 幂等键 + log_id 业务单号;空 = 不享幂等)。
  133. RequestID string `json:"requestId"`
  134. // Remark 备注(空 → 按 Kind 取默认文案)。
  135. Remark string `json:"remark"`
  136. // OperatorID 操作人(→ create_user_id;空 → NULL)。
  137. OperatorID string `json:"-"`
  138. // Kind SP 形态(默认 RechargeKindDefault)。
  139. Kind RechargeKind `json:"-"`
  140. }
  141. // RechargeResult 充值结果(端点 3 响应 `{logId,balance,repeated}`)。
  142. type RechargeResult struct {
  143. // LogID 流水 ID(幂等命中时为**首次**流水 ID)。
  144. LogID int64 `json:"logId"`
  145. // Balance 充值后校区账户余额(balance_after 口径)。
  146. Balance money.Amount `json:"balance"`
  147. // Repeated true = 幂等命中(requestId 已处理),未重复入账。
  148. Repeated bool `json:"repeated"`
  149. }
  150. // ExpenditureInput 消费入参(SP3 `sp_user_expense_school_expenditure` 8 参)。
  151. type ExpenditureInput 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 消费金额(>0;流水落 `-Money`)。
  159. Money money.Amount `json:"money"`
  160. // Type 消费类型(101/104/105/200/201/204/205,白名单;非法 → 2002)。
  161. Type int32 `json:"type"`
  162. // RequestID 幂等请求号(空 = 不享幂等)。
  163. RequestID string `json:"requestId"`
  164. // Remark 备注(空 → "历史扣费")。
  165. Remark string `json:"remark"`
  166. // OperatorID 操作人。
  167. OperatorID string `json:"-"`
  168. }
  169. // ExpenditureResult 消费结果(端点 4 响应 `{logId,balance}`)。
  170. type ExpenditureResult struct {
  171. // LogID 流水 ID。
  172. LogID int64 `json:"logId"`
  173. // Balance 消费后校区账户余额。
  174. Balance money.Amount `json:"balance"`
  175. // Repeated true = 幂等命中。
  176. Repeated bool `json:"repeated"`
  177. }
  178. // RefundInput 退费入参(SP4 `sp_user_expense_school_refund` 7 参 + **补 institution_id**)。
  179. type RefundInput struct {
  180. // UserID 用户(必填)。
  181. UserID string `json:"userId"`
  182. // InstitutionID 机构 ID(必填 >0;**dump 无此参数 = BUG#2**,见 Refund 方法注释)。
  183. InstitutionID int64 `json:"institutionId"`
  184. // CampusID 校区 ID(必填 >0)。
  185. CampusID int64 `json:"campusId"`
  186. // Money 退费金额(>0 才生效;<=0 → changed=false 的 no-op,对齐 dump `IF inputMoney>0`)。
  187. Money money.Amount `json:"money"`
  188. // Type 流水类型(dump 的 inputType;必须属 model.ExpenseLogType* 白名单)。
  189. Type int32 `json:"type"`
  190. // RequestID 幂等请求号(空 = 不享幂等)。
  191. RequestID string `json:"requestId"`
  192. // Remark 备注(空 → "报课的费用退回")。
  193. Remark string `json:"remark"`
  194. // OperatorID 操作人。
  195. OperatorID string `json:"-"`
  196. }
  197. // RefundResult 退费结果(端点 5 响应 `{logId,balance,changed}`)。
  198. type RefundResult struct {
  199. // LogID 流水 ID(恒 > 0:money<=0 已在入口按 R6 拒为 2002)。
  200. LogID int64 `json:"logId"`
  201. // Balance 退费后校区账户余额。
  202. Balance money.Amount `json:"balance"`
  203. // Changed 成功即发生账户写入 ⇒ **恒 true**(R6 定稿:金额<=0 一律入口 2002,不存在 no-op 分支)。
  204. // 字段仅为 DTO 契约兼容保留;**前端不得用 changed=false 作为正常分支**判断(不会有该取值)。
  205. // 幂等命中用 Repeated 表达。
  206. Changed bool `json:"changed"`
  207. // Repeated true = 幂等命中。
  208. Repeated bool `json:"repeated"`
  209. }
  210. // TransferInput 转结入参(SP6 `sp_user_expense_school_transfer_expenditure` 8 参)。
  211. type TransferInput struct {
  212. // UserID 用户(必填)。
  213. UserID string `json:"userId"`
  214. // FromInstitutionID 转出机构 ID(必填 >0)。
  215. FromInstitutionID int64 `json:"fromInstitutionId"`
  216. // FromCampusID 转出校区 ID(必填 >0)。
  217. FromCampusID int64 `json:"fromCampusId"`
  218. // ToInstitutionID 转入机构 ID(必填 >0)。
  219. ToInstitutionID int64 `json:"toInstitutionId"`
  220. // ToCampusID 转入校区 ID(必填 >0)。
  221. ToCampusID int64 `json:"toCampusId"`
  222. // Money 转结金额(>0)。
  223. Money money.Amount `json:"money"`
  224. // RequestID 幂等请求号(**两条流水共用**同一 request_id,type 不同故不撞键)。
  225. RequestID string `json:"requestId"`
  226. // Remark 备注(dump 无默认值)。
  227. Remark string `json:"remark"`
  228. // OperatorID 操作人。
  229. OperatorID string `json:"-"`
  230. }
  231. // TransferResult 转结结果(端点 7 响应 `{logId106,logId206}`)。
  232. type TransferResult struct {
  233. // LogID106 type=106 转结出流水 ID(dump: money = **+Money**)。
  234. LogID106 int64 `json:"logId106"`
  235. // LogID206 type=206 转结入流水 ID(dump: money = **−Money**)。
  236. LogID206 int64 `json:"logId206"`
  237. // FromBalance 转出校区账户余额(转结**不动 balance**,故与转结前相同)。
  238. FromBalance money.Amount `json:"fromBalance"`
  239. // ToBalance 转入校区账户余额(同上)。
  240. ToBalance money.Amount `json:"toBalance"`
  241. // Repeated true = 幂等命中。
  242. Repeated bool `json:"repeated"`
  243. }
  244. // BadDebtInput 坏账入参(SP7 `sp_user_expense_baddebt` 7 参)。
  245. type BadDebtInput struct {
  246. // UserID 用户(必填)。
  247. UserID string `json:"userId"`
  248. // InstitutionID 机构 ID(必填 >0)。
  249. InstitutionID int64 `json:"institutionId"`
  250. // CampusID 校区 ID(必填 >0)。
  251. CampusID int64 `json:"campusId"`
  252. // Money 坏账金额(>0)。
  253. Money money.Amount `json:"money"`
  254. // RequestID 幂等请求号(空 = 不享幂等)。
  255. RequestID string `json:"requestId"`
  256. // Remark 备注(空 → "坏账处理")。
  257. Remark string `json:"remark"`
  258. // OperatorID 操作人。
  259. OperatorID string `json:"-"`
  260. }
  261. // BadDebtResult 坏账结果(端点 8 响应 `{logId,specialExpenses}`)。
  262. type BadDebtResult struct {
  263. // LogID type=108 流水 ID。
  264. LogID int64 `json:"logId"`
  265. // SpecialExpenses 处理后校区账户特殊费用累计。
  266. SpecialExpenses money.Amount `json:"specialExpenses"`
  267. // Balance 处理后校区账户余额(**dump 口径:坏账双加,故已 +Money**)。
  268. Balance money.Amount `json:"balance"`
  269. // Repeated true = 幂等命中。
  270. Repeated bool `json:"repeated"`
  271. }
  272. // SpendInput 累计消费入参(SP11 `sp_user_expense_school_spend` 4 参)。
  273. type SpendInput struct {
  274. // UserID 用户(必填)。
  275. UserID string `json:"userId"`
  276. // InstitutionID 机构 ID(必填 >0)。
  277. InstitutionID int64 `json:"institutionId"`
  278. // CampusID 校区 ID(必填 >0)。
  279. CampusID int64 `json:"campusId"`
  280. // SpendMoney 本次累加的课费单价之和(元;**负数一律归 0**,dump INSERT 分支同口径)。
  281. SpendMoney money.Amount `json:"spendMoney"`
  282. }
  283. // SpendResult 累计消费结果(端点 10 响应 `{spend}`)。
  284. type SpendResult struct {
  285. // Spend 累加后校区账户 spend 列(**不是** balance)。
  286. Spend money.Amount `json:"spend"`
  287. }
  288. // ---------------------------------------------------------------- 校验助手
  289. // validateUserScope 校验"用户 + 机构 + 校区"三元组(资金方法入口统一形状)。
  290. //
  291. // 入参:userID / institutionID / campusID;op 操作名(错误文案定位);campusRequired 是否要求校区>0。
  292. // 出参:nil 合法;2001(缺 user_id)/ 3140(校区或机构缺失,对齐设计 §1.6「campusid<=0 → 3140」)。
  293. func validateUserScope(userID string, institutionID, campusID int64, op string, campusRequired bool) error {
  294. if strings.TrimSpace(userID) == "" {
  295. return infraerrors.WithCause(infraerrors.ErrBadParam, errString("service: "+op+" 需要 user_id"))
  296. }
  297. if institutionID <= 0 {
  298. return infraerrors.WithCause(apperr.ErrBusinessParam,
  299. errString("service: "+op+" 需要 institution_id > 0"))
  300. }
  301. if campusRequired && campusID <= 0 {
  302. // dump:`IF (inputSchoolid<1 || inputCampusid<1) THEN LEAVE`(静默 no-op)
  303. // Go:显式 3140,避免"调用成功但什么都没做"
  304. return infraerrors.WithCause(apperr.ErrBusinessParam,
  305. errString("service: "+op+" 需要 campus_id > 0(dump:必须有校区信息)"))
  306. }
  307. if campusID < 0 {
  308. return infraerrors.WithCause(apperr.ErrBusinessParam,
  309. errString("service: "+op+" 的 campus_id 不得为负"))
  310. }
  311. return nil
  312. }
  313. // validatePositiveAmount 校验金额为正且不超业务/存储天花板(§10.7)。
  314. //
  315. // 入参:amount 金额(分);op 操作名。
  316. // 出参:nil 合法;2002(<=0 / 超业务上限 / 超 decimal(12,2) 全域)。
  317. //
  318. // 与 dump 的差异(登记为有意偏离):dump 对负数是 `IF inputMoney<0 THEN SET inputMoney=0`
  319. // **静默归零后继续记账**,会留下 money=0 的流水并占住幂等键;Go 显式拒绝(2002)。
  320. func validatePositiveAmount(amount money.Amount, op string) error {
  321. if amount <= 0 {
  322. return infraerrors.WithCause(infraerrors.ErrBadFormat,
  323. errString("service: "+op+" 金额必须 > 0(dump 静默归零 → Go 显式拒绝)"))
  324. }
  325. if amount > maxSingleAmount {
  326. return infraerrors.WithCause(infraerrors.ErrBadFormat,
  327. errString("service: "+op+" 金额超出单笔业务上限"))
  328. }
  329. if err := amount.Validate(); err != nil {
  330. return infraerrors.WithCause(infraerrors.ErrBadFormat, err)
  331. }
  332. return nil
  333. }
  334. // parseAccountAmount 把账户 decimal 字符串列解析为 money.Amount。
  335. //
  336. // 入参:raw 列原文(如 "12.34");col 列名(错误文案定位)。
  337. // 出参:money.Amount;ErrDBError(历史脏值/格式非法——属数据问题,不是入参问题)。
  338. func parseAccountAmount(raw, col string) (money.Amount, error) {
  339. amount, err := money.Parse(raw)
  340. if err != nil {
  341. return 0, infraerrors.WithCause(infraerrors.ErrDBError,
  342. errString("service: 账户列 "+col+" 金额非法("+raw+")"))
  343. }
  344. return amount, nil
  345. }
  346. // globalBalanceAfter 取「该笔操作完成后**全局账户**(t_user_expense)余额」快照。
  347. //
  348. // 用途(唯一):流水列 `t_user_expense_log.balance_after` 的取值口径(设计 §3.8-f ②-bis 裁定):
  349. // - 语义 = **全局账户余额**,不是校区余额(`t_user_expense_log` 上没有 `campus_id`,
  350. // 只有 user 级全局链才能做 `balance_after(op_n) = balance_after(op_{n−1}) + Σ(money of op_n)` 校验);
  351. // - 取值时机 = **写完账户、写第一条流水之前取一次**,同一操作的多行流水(转结 106/206、
  352. // 退费 108/207)**复用同一个值**;**禁止逐条重算**(并发下会取到不同值,链式校验必乱)。
  353. //
  354. // 入参:ctx / repo / tx(**必传**:必须与本操作的账户写入同事务同快照)/ userID。
  355. // 出参:(全局余额, error);ErrNotFound(账户不存在,属调用顺序错误)/ ErrDBError。
  356. func globalBalanceAfter(
  357. ctx context.Context, repo *repository.ExpenseRepo, tx *gorm.DB, userID string,
  358. ) (money.Amount, error) {
  359. global, err := repo.GetGlobalAccount(ctx, tx, userID)
  360. if err != nil {
  361. return 0, err
  362. }
  363. return parseAccountAmount(global.Balance, "t_user_expense.balance")
  364. }
  365. // campusBalanceAfter 取「该笔操作完成后**校区账户**余额」快照。
  366. //
  367. // 用途(唯一):**API 响应体的 `Balance` 字段**(各 Result.Balance 的契约是"校区账户余额",
  368. // 与流水的 `balance_after` 语义不同,**不得**混用同一个值)。
  369. //
  370. // 入参:ctx / repo / tx / userID / institutionID / campusID。
  371. // 出参:(校区余额, error);ErrNotFound / ErrDBError。
  372. func campusBalanceAfter(
  373. ctx context.Context, repo *repository.ExpenseRepo, tx *gorm.DB,
  374. userID string, institutionID, campusID int64,
  375. ) (money.Amount, error) {
  376. acc, err := repo.GetCampusAccount(ctx, tx, userID, institutionID, campusID)
  377. if err != nil {
  378. return 0, err
  379. }
  380. return parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
  381. }
  382. // optString 把空串转成 nil 指针(*string 列的 NULL 语义:request_id 为空时"不享幂等")。
  383. func optString(s string) *string {
  384. s = strings.TrimSpace(s)
  385. if s == "" {
  386. return nil
  387. }
  388. return &s
  389. }
  390. // amountPtr 返回金额两位小数字符串的指针(`balance_after` 等可空金额列用)。
  391. func amountPtr(a money.Amount) *string {
  392. s := a.String()
  393. return &s
  394. }
  395. // newExpenseLog 组装一条余额变更流水(字段口径收口,避免各方法重复拼装)。
  396. //
  397. // 入参:userID/typ/money 金额/requestID/remark/operatorID/**balanceAfter = 该操作完成后全局账户余额快照**
  398. // (nil = 不写快照;同一操作的多行流水必须传**同一个值**,见 `globalBalanceAfter` 的口径说明)。
  399. // 出参:*model.UserExpenseLog(未落库;Create 后 ID 由 GORM 回填)。
  400. func newExpenseLog(userID string, typ int32, amount money.Amount, requestID, remark, operatorID string,
  401. balanceAfter *money.Amount) *model.UserExpenseLog {
  402. lg := &model.UserExpenseLog{
  403. UserID: userID,
  404. Type: typ,
  405. Money: amount.String(),
  406. RequestID: optString(requestID),
  407. LogID: optString(requestID), // dump:logid = 外部单号(SP1 的 inputOrder / SP2 的 inputRequestid)
  408. CreateUserID: optString(operatorID),
  409. Remark: optString(remark),
  410. }
  411. if balanceAfter != nil {
  412. lg.BalanceAfter = amountPtr(*balanceAfter)
  413. }
  414. return lg
  415. }
  416. // assertInScope 对象级越权断言(全局钱包无作用域列,只能由 Service 显式校验,设计 §1.7 例外一)。
  417. //
  418. // 入参:ctx / userID / institutionID / campusID。
  419. // 出参:nil 通过(或未注入 checker 的系统任务模式);1004 越权;5002 DB 异常。
  420. func (s *FundService) assertInScope(ctx context.Context, userID string, institutionID, campusID int64) error {
  421. if s == nil || s.member == nil {
  422. return nil // 系统任务/割接脚本模式:不注入 checker 即不做对象级断言(装配层责任)
  423. }
  424. return s.member.AssertInScope(ctx, userID, institutionID, campusID)
  425. }
  426. // ---------------------------------------------------------------- SP1 / SP2 充值
  427. // Recharge 余额充值(SP1 `sp_user_expense_recharge` + SP2 `sp_user_expense_school_recharge`)。
  428. //
  429. // dump 语义(yuansiwei_finance.sql:764247,★8 参 + **双表更新**):
  430. //
  431. // ① inputMoney<0 → 0;inputType<100 → 100;inputRemark='' → 默认备注;
  432. // ② schoolid<1 || campusid<1 → LEAVE(静默 no-op);
  433. // ③ 校区账户不存在则 INSERT;全局账户不存在则 INSERT;
  434. // ④ UPDATE 校区:balance+, total_income+ ;UPDATE 全局:balance+, total_income+;
  435. // ⑤ INSERT log(type=inputType, logid=inputOrder, money=inputMoney)。
  436. //
  437. // Go 的三处**有意强化**(不改变资金结果):
  438. // - 建户合并为一次 UPSERT(`ON CONFLICT DO NOTHING`),替代 dump 的 `COUNT` 判存在(§1.5);
  439. // - 写序固定为 **全局 → 校区**(dump 是校区 → 全局;顺序不同但结果一致,
  440. // 统一顺序是**死锁预防**的硬要求,见 §1.4 与 §7.2 的加锁基线);
  441. // - 幂等:`request_id + type` 唯一键,并发重复提交只落 1 条流水(dump 无幂等,会重复入账)。
  442. //
  443. // 入参:ctx / in(见 RechargeInput;Kind 决定默认备注)。
  444. // 出参:*RechargeResult(logId/balance/repeated);错误码 2001/2002/3140/1004/5002。
  445. func (s *FundService) Recharge(ctx context.Context, in RechargeInput) (*RechargeResult, error) {
  446. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "Recharge", true); err != nil {
  447. return nil, err
  448. }
  449. if err := validatePositiveAmount(in.Money, "Recharge"); err != nil {
  450. return nil, err
  451. }
  452. if in.Type < 100 {
  453. // dump:`IF inputType<100 THEN SET inputType=100`(充值流水类型下限)
  454. in.Type = model.ExpenseLogTypeRecharge
  455. }
  456. if s == nil || s.runner == nil || s.repo == nil {
  457. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  458. }
  459. remark := strings.TrimSpace(in.Remark)
  460. if remark == "" {
  461. if in.Kind == RechargeKindSchool {
  462. remark = defaultSchoolRechargeRemark
  463. } else {
  464. remark = defaultRechargeRemark
  465. }
  466. }
  467. var out RechargeResult
  468. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  469. txCtx := repository.WithTxContext(ctx, tx)
  470. // ① 幂等预检(`uk_request_type`):命中 → 返回首次结果,不重复入账
  471. hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, in.Type)
  472. if e != nil {
  473. return e
  474. }
  475. if hit != nil {
  476. bal, pe := balanceAfterOf(hit)
  477. if pe != nil {
  478. return pe
  479. }
  480. out = RechargeResult{LogID: hit.ID, Balance: bal, Repeated: true}
  481. return nil
  482. }
  483. // ② 作用域断言(全局钱包无作用域列 → Service 层显式校验)
  484. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  485. return e
  486. }
  487. // ③ 建户(两个 UPSERT,**不动已有余额**)
  488. if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
  489. return e
  490. }
  491. if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
  492. UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
  493. }); e != nil {
  494. return e
  495. }
  496. // ④ 原子增减(固定「全局 → 校区」,两列合并为每表一条 UPDATE)
  497. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "Recharge", in.UserID,
  498. in.InstitutionID, in.CampusID,
  499. repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money},
  500. repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money},
  501. ); e != nil {
  502. return e
  503. }
  504. // ⑤ 流水(`balance_after` = **充值后全局账户余额**快照;响应体 Balance 仍是校区余额)
  505. globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  506. if e != nil {
  507. return e
  508. }
  509. bal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.InstitutionID, in.CampusID)
  510. if e != nil {
  511. return e
  512. }
  513. lg := newExpenseLog(in.UserID, in.Type, in.Money, in.RequestID, remark, in.OperatorID, &globalAfter)
  514. if e := s.insertLog(txCtx, tx, lg); e != nil {
  515. return e
  516. }
  517. out = RechargeResult{LogID: lg.ID, Balance: bal}
  518. return nil
  519. })
  520. if err != nil {
  521. return nil, s.mapIdempotentHit(err, func() error {
  522. return s.replayRecharge(ctx, in, &out)
  523. })
  524. }
  525. return &out, nil
  526. }
  527. // ---------------------------------------------------------------- SP3 消费
  528. // Expenditure 余额消费扣费(SP3 `sp_user_expense_school_expenditure`)。
  529. //
  530. // dump 语义(:764364,**type 决定列组合,方向不可改**):
  531. //
  532. // inputType=200(历史扣费) → balance−, total_expenditure+, spend+
  533. // inputType=207(余额退费) → balance−, total_income−
  534. // 其余(101/104/105/201/204/205)→ balance−, total_expenditure+
  535. // 两条 UPDATE(校区 + 全局)+ log(money = **−inputMoney**)
  536. //
  537. // Go 的口径选择(**与 dump 的两处差异,均为设计 §3.1 #3 明确要求**):
  538. // - type 白名单校验:`101/104/105/200/201/204/205`(非法 → 2002)。dump 会把
  539. // `type<200 或 >299` **静默改成 200**,把"调用方传错类型"变成"记成历史扣费";
  540. // - dump 的 `type=207` 分支**不开放**给本方法(退费走 `Refund`/`CustomRefund`,
  541. // 否则同一语义有两条写入口,流水方向难以对账)。
  542. //
  543. // 入参:ctx / in。出参:*ExpenditureResult;错误码 2001/2002/3140/1004/5002。
  544. func (s *FundService) Expenditure(ctx context.Context, in ExpenditureInput) (*ExpenditureResult, error) {
  545. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "Expenditure", true); err != nil {
  546. return nil, err
  547. }
  548. if err := validatePositiveAmount(in.Money, "Expenditure"); err != nil {
  549. return nil, err
  550. }
  551. if !isExpenditureType(in.Type) {
  552. return nil, infraerrors.WithCause(infraerrors.ErrBadFormat,
  553. errString("service: Expenditure 的 type 非法(白名单 101/104/105/200/201/204/205)"))
  554. }
  555. if s == nil || s.runner == nil || s.repo == nil {
  556. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  557. }
  558. remark := strings.TrimSpace(in.Remark)
  559. if remark == "" {
  560. remark = defaultExpenditureRemark
  561. }
  562. deltas := expenditureDeltas(in.Type, in.Money)
  563. var out ExpenditureResult
  564. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  565. txCtx := repository.WithTxContext(ctx, tx)
  566. hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, in.Type)
  567. if e != nil {
  568. return e
  569. }
  570. if hit != nil {
  571. bal, pe := balanceAfterOf(hit)
  572. if pe != nil {
  573. return pe
  574. }
  575. out = ExpenditureResult{LogID: hit.ID, Balance: bal, Repeated: true}
  576. return nil
  577. }
  578. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  579. return e
  580. }
  581. if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
  582. return e
  583. }
  584. if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
  585. UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
  586. }); e != nil {
  587. return e
  588. }
  589. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "Expenditure", in.UserID,
  590. in.InstitutionID, in.CampusID, deltas...); e != nil {
  591. return e
  592. }
  593. // `balance_after` = 扣费后**全局账户余额**快照;响应体 Balance 仍是校区余额
  594. globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  595. if e != nil {
  596. return e
  597. }
  598. bal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.InstitutionID, in.CampusID)
  599. if e != nil {
  600. return e
  601. }
  602. // dump:INSERT log(money = **−inputMoney**)
  603. lg := newExpenseLog(in.UserID, in.Type, in.Money.Neg(), in.RequestID, remark, in.OperatorID, &globalAfter)
  604. if e := s.insertLog(txCtx, tx, lg); e != nil {
  605. return e
  606. }
  607. out = ExpenditureResult{LogID: lg.ID, Balance: bal}
  608. return nil
  609. })
  610. if err != nil {
  611. return nil, s.mapIdempotentHit(err, func() error {
  612. return s.replayExpenditure(ctx, in, &out)
  613. })
  614. }
  615. return &out, nil
  616. }
  617. // expenditureDeltas 按 type 生成列增量(dump 三个分支的逐列对应,**顺序/方向不得改**)。
  618. //
  619. // 入参:typ 消费类型(已过白名单);amount 消费金额(>0)。
  620. // 出参:[]repository.ColumnDelta(balance 恒为 −amount)。
  621. func expenditureDeltas(typ int32, amount money.Amount) []repository.ColumnDelta {
  622. switch typ {
  623. case model.ExpenseLogTypeHistoryDeduct:
  624. // dump:`balance-`,`total_expenditure+`,`spend+`(历史扣费同时计入消费统计)
  625. return []repository.ColumnDelta{
  626. {Column: repository.ExpenseColumnBalance, Delta: amount.Neg()},
  627. {Column: repository.ExpenseColumnTotalExpenditure, Delta: amount},
  628. {Column: repository.ExpenseColumnSpend, Delta: amount},
  629. }
  630. default:
  631. // dump:`balance-`,`total_expenditure+`(报课学费 / 学校消费)
  632. return []repository.ColumnDelta{
  633. {Column: repository.ExpenseColumnBalance, Delta: amount.Neg()},
  634. {Column: repository.ExpenseColumnTotalExpenditure, Delta: amount},
  635. }
  636. }
  637. }
  638. // isExpenditureType 消费类型白名单(设计 §3.1 #3:101/104/105/200/201/204/205)。
  639. func isExpenditureType(typ int32) bool {
  640. switch typ {
  641. case model.ExpenseLogTypeCourseCampus, // 101
  642. model.ExpenseLogTypeCourseSchoolA, // 104
  643. model.ExpenseLogTypeCourseSchoolB, // 105
  644. model.ExpenseLogTypeHistoryDeduct, // 200
  645. model.ExpenseLogTypeCourseCampusB, // 201
  646. model.ExpenseLogTypeCourseSchoolC, // 204
  647. model.ExpenseLogTypeCourseSchoolD: // 205
  648. return true
  649. default:
  650. return false
  651. }
  652. }
  653. // ---------------------------------------------------------------- SP4 退费
  654. // Refund 余额退费(SP4 `sp_user_expense_school_refund`)。
  655. //
  656. // dump 语义(:764576):`IF inputMoney>0` 才动作(<=0 静默 no-op);
  657. // 校区账户已存在才 UPDATE(balance+, total_expenditure−);全局账户已存在才 UPDATE;
  658. // 任一更新成功才写 log(money = **+inputMoney**,type = inputType)。
  659. //
  660. // **BUG#2 修正(设计 §3.1 #4)**:dump 的定位条件是 `userid + campusid`,**没有 schoolid**——
  661. // 同一 campus_id 若在多机构复用(历史数据/跨库迁移期),会误更新别的机构的账户行。
  662. // Go 侧补 `institution_id` 参数并进 WHERE,定位三元组精确到 `(user, institution, campus)`。
  663. //
  664. // **R6(设计 §3.8-b)强化**:`money <= 0` → **2002**(与 recharge/expenditure/baddebt/transfer 五处统一)。
  665. // 与 dump 的差异是**有意偏离**:dump 对 <=0 是"静默不动作",前端会显示"成功但余额没变";
  666. // Go 显式拒绝。注:本处 dump 分支**不写流水**、不占幂等键,与另三处"归 0 仍写 0 元流水"不同,
  667. // 但对外统一成 2002 更不易被误用(前端不会把"没退钱"当成功)。
  668. //
  669. // 入参:ctx / in。出参:*RefundResult;
  670. // 错误码 2001/2002/3140/1004/3001/5002。
  671. func (s *FundService) Refund(ctx context.Context, in RefundInput) (*RefundResult, error) {
  672. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "Refund", true); err != nil {
  673. return nil, err
  674. }
  675. if in.Type <= 0 {
  676. return nil, infraerrors.WithCause(infraerrors.ErrBadFormat, errString("service: Refund 需要 type"))
  677. }
  678. if !isKnownLogType(in.Type) {
  679. return nil, infraerrors.WithCause(infraerrors.ErrBadFormat,
  680. errString("service: Refund 的 type 不在流水类型白名单内"))
  681. }
  682. // R6:金额 <= 0 一律 2002(dump 是 `IF inputMoney>0` 静默跳过;Go 显式拒绝)
  683. if err := validatePositiveAmount(in.Money, "Refund"); err != nil {
  684. return nil, err
  685. }
  686. if s == nil || s.runner == nil || s.repo == nil {
  687. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  688. }
  689. remark := strings.TrimSpace(in.Remark)
  690. if remark == "" {
  691. remark = defaultRefundRemark
  692. }
  693. var out RefundResult
  694. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  695. txCtx := repository.WithTxContext(ctx, tx)
  696. hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, in.Type)
  697. if e != nil {
  698. return e
  699. }
  700. if hit != nil {
  701. bal, pe := balanceAfterOf(hit)
  702. if pe != nil {
  703. return pe
  704. }
  705. out = RefundResult{LogID: hit.ID, Balance: bal, Changed: true, Repeated: true}
  706. return nil
  707. }
  708. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  709. return e
  710. }
  711. // dump 不建户(account 不存在则什么都不做);Go 显式 3001,避免"调用成功但没退钱"
  712. if _, e := s.repo.GetCampusForUpdateExact(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  713. return e
  714. }
  715. // dump:`balance+`,`total_expenditure-`
  716. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "Refund", in.UserID,
  717. in.InstitutionID, in.CampusID,
  718. repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money},
  719. repository.ColumnDelta{Column: repository.ExpenseColumnTotalExpenditure, Delta: in.Money.Neg()},
  720. ); e != nil {
  721. return e
  722. }
  723. globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  724. if e != nil {
  725. return e
  726. }
  727. bal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.InstitutionID, in.CampusID)
  728. if e != nil {
  729. return e
  730. }
  731. lg := newExpenseLog(in.UserID, in.Type, in.Money, in.RequestID, remark, in.OperatorID, &globalAfter)
  732. if e := s.insertLog(txCtx, tx, lg); e != nil {
  733. return e
  734. }
  735. out = RefundResult{LogID: lg.ID, Balance: bal, Changed: true}
  736. return nil
  737. })
  738. if err != nil {
  739. return nil, s.mapIdempotentHit(err, func() error {
  740. return s.replayRefund(ctx, in, &out)
  741. })
  742. }
  743. return &out, nil
  744. }
  745. // ---------------------------------------------------------------- SP5 可退金额(只读)
  746. // RefundableAmount 查询校区账户可退金额(SP5 `sp_user_expense_school_get_refundable_amount`,**只读**)。
  747. //
  748. // dump 语义(:764421,**三步修正,缺一不可**;dump 里的游标段整段被 `/* */` 注释掉,实际只生效下面的 SUM):
  749. //
  750. // ① 读 campusBalance(t_user_expense_school.balance)与 totalBalance(t_user_expense.balance);
  751. // 任一 <= 0(含 NULL/账户不存在)→ 0;
  752. // ② **截断**:`IF campusBalance > totalBalance THEN campusBalance = totalBalance`,
  753. // 截断后再早退一次(`campusBalance <= 0 → 0`,dump 真有这句,最易漏);
  754. // ③ **减已使用赠送额**(`t_user_balance_request × t_courses_activity_signed` 关联汇总,
  755. // 口径见 `BalanceRequestRepo.SumRechargeActivityUsedGift`):
  756. // refundable = campusBalance − usedGift,**下限 0**(SUM 为 NULL → 视作 0)。
  757. //
  758. // 两个**别复原**的陷阱(设计 §3.8-b 明确登记,评审逐处检查):
  759. // - 同一 SP 里还把 `SUM(activity_money)` 存进 `totalDiscountAmount`,但**全文再未引用**(死变量)
  760. // → **不得**据此加"赠送额上限/赠送额不可超余额"之类的额外约束;
  761. // - 那段按 `response_time DESC` 逐笔累加的游标(`DECLARE cur` / `OPEN` / 循环)**整段被注释掉**
  762. // → **不得**照注释补回逐笔逻辑,实际口径就是一条聚合 SUM。
  763. //
  764. // Go 的显式化(不改变资金结果,只把 dump 的静默分支显式化):
  765. // - 校区账户不存在 → (0, nil)(dump:ISNULL → 0);
  766. // - `campusBalance <= 0`(欠费)或 `totalBalance <= 0` → 0(dump 下负数参与减法后取 max(…,0) 亦为 0,
  767. // 这里提前返回是同结果的短路,避免把"欠费"当成"可退");
  768. // - 全局账户不存在 → 0(totalBalance 视为 0 → 截断后必为 0)。
  769. //
  770. // 只读且**无事务**:本方法不写任何表,故不开事务、也不加行锁(加锁只属于资金写路径,§10.3)。
  771. // 与之配套的调用纪律:可退额是"查询口径",**不得**用它做写路径的扣减基数——
  772. // 退费扣减基数由 `CustomRefund` 在事务内用加锁读的校区余额决定(§7.2 R2)。
  773. //
  774. // 与 SP9 的关系(**勿互相复用**):`custom_refund` **不调用**本方法,它内部的坏账基数是
  775. // **校区 `balance` 本身**;两者数值天然不同(本方法扣赠送额与全局截断,SP9 不扣不截)。
  776. //
  777. // 入参:ctx / userID / institutionID / campusID。
  778. // 出参:(可退金额, error);账户不存在 / 余额非正 → (0, nil);错误码 2001/3140/1004/5002。
  779. func (s *FundService) RefundableAmount(
  780. ctx context.Context, userID string, institutionID, campusID int64,
  781. ) (money.Amount, error) {
  782. if err := validateUserScope(userID, institutionID, campusID, "RefundableAmount", true); err != nil {
  783. return 0, err
  784. }
  785. if s == nil || s.repo == nil || s.requests == nil {
  786. return 0, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  787. }
  788. if err := s.assertInScope(ctx, userID, institutionID, campusID); err != nil {
  789. return 0, err
  790. }
  791. // ① 校区余额(读不到 = 账户不存在 → 0,dump 的 ISNULL 分支)
  792. acc, err := s.repo.GetCampusAccount(ctx, nil, userID, institutionID, campusID)
  793. if err != nil {
  794. if errors.Is(err, infraerrors.ErrNotFound) {
  795. return 0, nil // dump:账户不存在 → 0
  796. }
  797. return 0, err
  798. }
  799. campusBalance, err := parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
  800. if err != nil {
  801. return 0, err
  802. }
  803. if campusBalance <= 0 {
  804. return 0, nil
  805. }
  806. // ② 全局余额(跨校区总余额;这是 dump 的"截断上界")
  807. global, err := s.repo.GetGlobalAccount(ctx, nil, userID)
  808. if err != nil {
  809. if errors.Is(err, infraerrors.ErrNotFound) {
  810. return 0, nil // totalBalance 视为 0 → 截断后必为 0
  811. }
  812. return 0, err
  813. }
  814. totalBalance, err := parseAccountAmount(global.Balance, "t_user_expense.balance")
  815. if err != nil {
  816. return 0, err
  817. }
  818. if totalBalance <= 0 {
  819. return 0, nil
  820. }
  821. // ③ **第一步修正**:校区余额按全局余额截断(dump:campusBalance > totalBalance → 取 totalBalance)
  822. if campusBalance > totalBalance {
  823. campusBalance = totalBalance
  824. }
  825. // ③-b 截断后再早退一次(dump 里真有这句,最容易被"省掉"):截断后仍非正 → 0,
  826. // 不要在非正基数上继续做减项(否则 -- 与 max(…,0) 的结果虽同,语义却把"欠费/脏数据"当成可退基数)。
  827. if campusBalance <= 0 {
  828. return 0, nil
  829. }
  830. // ④ **第二步修正**:扣掉已使用的充值赠送额(赠送额不可退)
  831. usedGift, err := s.requests.SumRechargeActivityUsedGift(ctx, userID, institutionID, campusID)
  832. if err != nil {
  833. return 0, err
  834. }
  835. refundable := campusBalance.Sub(usedGift)
  836. if refundable <= 0 {
  837. return 0, nil // dump:max(…, 0)
  838. }
  839. return refundable, nil
  840. }
  841. // ---------------------------------------------------------------- SP6 课费转结
  842. // Transfer 课费转结(SP6 `sp_user_expense_school_transfer_expenditure`)。
  843. //
  844. // dump 语义(:764661,★**与 P0-04 规格相反,以 dump 为准**,设计 §3.1 #6 / §10.2):
  845. //
  846. // IF inputMoney>0:
  847. // 源校区账户存在 →
  848. // 目标校区账户不存在则 INSERT;
  849. // UPDATE 源:total_expenditure−m, total_income−m
  850. // UPDATE 目标:total_expenditure+m, total_income+m
  851. // INSERT log(type=106, money=**+m**) ← 转结出
  852. // INSERT log(type=206, money=**−m**) ← 转结入
  853. //
  854. // **四个"不得改动"的点**:
  855. // 1. **不动 balance**(dump 全程没有 balance 赋值)——转结只调"总消费/总充值"两个统计口径;
  856. // 2. 106 记 **+m**、206 记 **−m**(与"出/入"的直觉相反,dump 原文如此,§11-6 #6);
  857. // 3. 两条流水的 `request_id` **相同**、`type` 不同 → 不撞 `uk_request_type`(唯一键含 type);
  858. // 4. 目标账户不存在时**建户**(dump 的 INSERT),源账户不存在时**不动**(dump 的 `IF campusLogid1>0`)。
  859. //
  860. // **两处 dump 既有事实(已核全文,**不得"顺手补齐"**)**:
  861. // - 转结**只更新两张校区表**的 `total_expenditure` / `total_income`,**完全不碰全局表**
  862. // (整段没有 `UPDATE t_user_expense`)⇒ 全局的 `total_*` 与"各校区之和"**本来就不相等**,
  863. // 这是旧库既有口径,谁去"补齐全局"谁就把双跑对账搞乱;
  864. // - 转出/转入账户定位**只按 `userid + campusid`、没有 schoolid** ⇒ 同一 campus_id 在多机构复用时
  865. // 会误命中别家账户(BUG#2 同源)⇒ Go 一律按 `(user, institution, campus)` 三元组定位。
  866. //
  867. // 边界码(§3.8 R4 / R4-bis):
  868. //
  869. // refund 校区账户缺失 / refund 全局账户缺失 → **3001**(dump 只更单边 + 照写流水 = 双表撕裂)
  870. // transfer 转出方(源)账户缺失 → **3001**(dump `IF campusLogid1>0` 包整笔 → 静默 no-op)
  871. // transfer 转入方(目标)账户缺失 → **建户**(正常路径,见 `resolveTargetInstitution` 的 R4-bis)
  872. // transfer 转入校区查不到 / 未归属机构 → **3104**
  873. // transfer 入参机构 ≠ 校区归属机构 → **3140**(不建户、不落行,防机构错配僵尸户)
  874. // 同校区自转(净效应为零) → **3140**
  875. //
  876. // 入参:ctx / in。出参:*TransferResult{logId106,logId206};错误码 2001/2002/3104/3140/1004/3001/5002。
  877. func (s *FundService) Transfer(ctx context.Context, in TransferInput) (*TransferResult, error) {
  878. if err := validateUserScope(in.UserID, in.FromInstitutionID, in.FromCampusID, "Transfer(from)", true); err != nil {
  879. return nil, err
  880. }
  881. if err := validateUserScope(in.UserID, in.ToInstitutionID, in.ToCampusID, "Transfer(to)", true); err != nil {
  882. return nil, err
  883. }
  884. if err := validatePositiveAmount(in.Money, "Transfer"); err != nil {
  885. return nil, err
  886. }
  887. if in.FromInstitutionID == in.ToInstitutionID && in.FromCampusID == in.ToCampusID {
  888. return nil, infraerrors.WithCause(apperr.ErrBusinessParam,
  889. errString("service: Transfer 的转出与转入校区不能相同"))
  890. }
  891. if s == nil || s.runner == nil || s.repo == nil {
  892. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  893. }
  894. var out TransferResult
  895. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  896. txCtx := repository.WithTxContext(ctx, tx)
  897. // ① 幂等预检:106 是"转结出"主流水(必然存在),用它做命中判定
  898. hit106, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeTransferOut)
  899. if e != nil {
  900. return e
  901. }
  902. if hit106 != nil {
  903. out = TransferResult{LogID106: hit106.ID, Repeated: true}
  904. if bal, pe := balanceAfterOf(hit106); pe == nil {
  905. out.FromBalance = bal
  906. }
  907. hit206, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeTransferIn)
  908. if e != nil {
  909. return e
  910. }
  911. if hit206 != nil {
  912. out.LogID206 = hit206.ID
  913. if bal, pe := balanceAfterOf(hit206); pe == nil {
  914. out.ToBalance = bal
  915. }
  916. }
  917. return nil
  918. }
  919. // ② 作用域断言(两侧机构都必须可见)
  920. if e := s.assertInScope(txCtx, in.UserID, in.FromInstitutionID, in.FromCampusID); e != nil {
  921. return e
  922. }
  923. if in.ToInstitutionID != in.FromInstitutionID {
  924. if e := s.assertInScope(txCtx, in.UserID, in.ToInstitutionID, in.ToCampusID); e != nil {
  925. return e
  926. }
  927. }
  928. // ③ 加锁:两个校区账户**按 campus_id ASC 排序**后依次加锁(§1.4 多账户场景防死锁)
  929. refs := []campusRef{
  930. {InstitutionID: in.FromInstitutionID, CampusID: in.FromCampusID},
  931. {InstitutionID: in.ToInstitutionID, CampusID: in.ToCampusID},
  932. }
  933. sort.Slice(refs, func(i, j int) bool { return refs[i].CampusID < refs[j].CampusID })
  934. locked := make(map[campusRef]bool, len(refs))
  935. for _, ref := range refs {
  936. _, le := s.repo.GetCampusForUpdateExact(txCtx, tx, in.UserID, ref.InstitutionID, ref.CampusID)
  937. if le != nil {
  938. if errors.Is(le, infraerrors.ErrNotFound) {
  939. locked[ref] = false
  940. continue
  941. }
  942. return le
  943. }
  944. locked[ref] = true
  945. }
  946. fromRef := campusRef{InstitutionID: in.FromInstitutionID, CampusID: in.FromCampusID}
  947. toRef := campusRef{InstitutionID: in.ToInstitutionID, CampusID: in.ToCampusID}
  948. if !locked[fromRef] {
  949. // dump:源账户不存在 → `IF campusLogid1>0` 不成立 → 静默什么都不做
  950. return infraerrors.WithCause(infraerrors.ErrNotFound,
  951. errString("service: Transfer 转出校区账户不存在"))
  952. }
  953. if !locked[toRef] {
  954. // dump:目标账户不存在 → **INSERT 建户**(R4 ④:建户是**正常路径**,不是 3001——
  955. // 转结的语义就是"把钱挪到还没有账户的校区",改成 3001 会让首次跨校区转结全部失败)。
  956. //
  957. // **R4-bis(§3.8-R4-bis / §5.7 #18b、#19b)**:dump 建户用的是入参 `inputSchoolid2`,
  958. // 入参校区与机构不匹配时会建出**机构错配的僵尸户**;而 UK(user,institution,campus)
  959. // 一旦机构写错,后续按正确机构查不到 → 再建第二个 → 同校区双账户 → 差值冻结直接破。
  960. // 故建户的机构**只认校区表的权威值**,不用入参:
  961. // ① inst := 校区表里的 institution_id(同事务只读) ② 取不到 → 3104
  962. // ③ 入参 toInstitutionId ≠ inst → 3140(不建户、不落任何行) ④ 用 inst 建户
  963. // 正常数据下 ②③ 恒不触发(两值相同),只在非法入参时拒绝。
  964. inst, ie := s.resolveTargetInstitution(txCtx, tx, in.ToCampusID, in.ToInstitutionID)
  965. if ie != nil {
  966. return ie
  967. }
  968. if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
  969. UserID: in.UserID, InstitutionID: inst, CampusID: in.ToCampusID,
  970. }); e != nil {
  971. return e
  972. }
  973. }
  974. // ④ 4 次 UPDATE → 2 条语句(每表两列),**balance 一律不动**
  975. if _, e := s.repo.AddCampusColumns(txCtx, tx, "Transfer(out)", in.UserID,
  976. in.FromInstitutionID, in.FromCampusID,
  977. repository.ColumnDelta{Column: repository.ExpenseColumnTotalExpenditure, Delta: in.Money.Neg()},
  978. repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money.Neg()},
  979. ); e != nil {
  980. return e
  981. }
  982. if _, e := s.repo.AddCampusColumns(txCtx, tx, "Transfer(in)", in.UserID,
  983. in.ToInstitutionID, in.ToCampusID,
  984. repository.ColumnDelta{Column: repository.ExpenseColumnTotalExpenditure, Delta: in.Money},
  985. repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money},
  986. ); e != nil {
  987. return e
  988. }
  989. // ⑤ 两条流水(106 在前、206 在后;方向 ★dump 口径)
  990. //
  991. // `balance_after` 口径(§3.8-f ②-bis):转结**不动 balance**,故 106 与 206 **写同一个全局快照**;
  992. // 响应体的 FromBalance / ToBalance 才是两个校区各自的余额(两列语义不同,勿混用)。
  993. globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  994. if e != nil {
  995. return e
  996. }
  997. fromBal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.FromInstitutionID, in.FromCampusID)
  998. if e != nil {
  999. return e
  1000. }
  1001. toBal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.ToInstitutionID, in.ToCampusID)
  1002. if e != nil {
  1003. return e
  1004. }
  1005. lg106 := newExpenseLog(in.UserID, model.ExpenseLogTypeTransferOut, in.Money,
  1006. in.RequestID, in.Remark, in.OperatorID, &globalAfter)
  1007. if e := s.insertLog(txCtx, tx, lg106); e != nil {
  1008. return e
  1009. }
  1010. lg206 := newExpenseLog(in.UserID, model.ExpenseLogTypeTransferIn, in.Money.Neg(),
  1011. in.RequestID, in.Remark, in.OperatorID, &globalAfter)
  1012. if e := s.insertLog(txCtx, tx, lg206); e != nil {
  1013. return e
  1014. }
  1015. out = TransferResult{
  1016. LogID106: lg106.ID, LogID206: lg206.ID,
  1017. FromBalance: fromBal, ToBalance: toBal,
  1018. }
  1019. return nil
  1020. })
  1021. if err != nil {
  1022. return nil, s.mapIdempotentHit(err, func() error {
  1023. return s.replayTransfer(ctx, in, &out)
  1024. })
  1025. }
  1026. return &out, nil
  1027. }
  1028. // campusRef 校区账户定位三元组的"机构 + 校区"部分(转结加锁排序用)。
  1029. type campusRef struct {
  1030. // InstitutionID 机构 ID。
  1031. InstitutionID int64
  1032. // CampusID 校区 ID。
  1033. CampusID int64
  1034. }
  1035. // resolveTargetInstitution 解析转结**转入方**的权威机构 ID(R4-bis 的三道校验)。
  1036. //
  1037. // 入参:
  1038. // - ctx 请求上下文(含 tx);
  1039. // - tx 事务句柄(**必传**:与本次资金事务同一快照,禁止走连接池读到旧值);
  1040. // - campusID 转入校区(>0,已由 validateUserScope 校验);
  1041. // - inputInstitutionID 调用方声明的转入机构。
  1042. //
  1043. // 出参:
  1044. // - int64:**权威**机构 ID(= t_campus.institution_id),调用方必须用它建户;
  1045. // - 3104(校区不存在 / 校区未归属机构)/ 3140(入参与权威值矛盾)/ 5002。
  1046. //
  1047. // 为什么必须校验(§3.8-R4-bis):dump 建户用入参机构,入参错就会建出机构错配的僵尸账户,
  1048. // 之后按正确机构再也查不到它 → 同校区出现两个账户 → "差值冻结"恒等式破。
  1049. // 正常调用方两值一致,本校验零影响;只有入参矛盾时才拒绝(比"按解析值静默建户"安全:
  1050. // 后者管理员看不到任何提示,事故后极难归因)。
  1051. func (s *FundService) resolveTargetInstitution(
  1052. ctx context.Context, tx *gorm.DB, campusID, inputInstitutionID int64,
  1053. ) (int64, error) {
  1054. if s == nil || s.campus == nil {
  1055. return 0, infraerrors.WithCause(infraerrors.ErrInternal,
  1056. errString("service: 未注入 port.CampusReader(无法解析转入校区机构)"))
  1057. }
  1058. info, err := s.readCampusInfo(ctx, tx, campusID)
  1059. if err != nil {
  1060. return 0, err
  1061. }
  1062. if info == nil || info.SchoolID <= 0 {
  1063. return 0, infraerrors.WithCause(apperr.ErrCampusNotFound,
  1064. errString("service: Transfer 转入校区未归属机构,拒绝建户"))
  1065. }
  1066. if inputInstitutionID != info.SchoolID {
  1067. return 0, infraerrors.WithCause(apperr.ErrBusinessParam,
  1068. errString("service: Transfer 的转入机构与校区归属机构不一致(拒绝建户,防僵尸账户)"))
  1069. }
  1070. return info.SchoolID, nil
  1071. }
  1072. // readCampusInfo 同事务读校区(优先 TxCampusReader,退化到连接池版 CampusReader)。
  1073. //
  1074. // 入参:ctx / tx / campusID(>0)。出参:*port.CampusInfo;3104(校区不存在)/ 5002。
  1075. func (s *FundService) readCampusInfo(ctx context.Context, tx *gorm.DB, campusID int64) (*port.CampusInfo, error) {
  1076. if s == nil || s.campus == nil {
  1077. return nil, infraerrors.WithCause(infraerrors.ErrInternal,
  1078. errString("service: 未注入 port.CampusReader(无法判定校区归属)"))
  1079. }
  1080. if txReader, ok := s.campus.(port.TxCampusReader); ok {
  1081. return txReader.GetByIDTx(ctx, tx, campusID)
  1082. }
  1083. return s.campus.GetByID(ctx, campusID)
  1084. }
  1085. // ---------------------------------------------------------------- SP7 坏账
  1086. // BadDebt 坏账处理(SP7 `sp_user_expense_baddebt`)。
  1087. //
  1088. // dump 语义(:763890,SP 头注释即「用户坏账处理(余额+,特殊费用+)」,**双加**):
  1089. //
  1090. // UPDATE t_user_expense_school SET balance = balance + inputMoney,
  1091. // special_expenses = special_expenses + inputMoney
  1092. // WHERE userid AND schoolid AND campusid;
  1093. // UPDATE t_user_expense SET balance = balance + inputMoney,
  1094. // special_expenses = special_expenses + inputMoney
  1095. // WHERE userid;
  1096. // INSERT t_user_expense_log(..., type = 108, money = +inputMoney, ...);
  1097. //
  1098. // 即:**全局 + 校区都同时加 `balance` 与 `special_expenses`**(两列同增,金额相同),
  1099. // 流水 type=108、money=+Money。Go 侧严格照做(不做"只统计特殊费用"的收敛)。
  1100. //
  1101. // ★ type=108 的**两种来源**(对账/恒等式判别的唯一依据,AC-17 ④ 按此落地):
  1102. //
  1103. // ① **独立坏账**(本 SP):`balance += m` **且** `special_expenses += m`,108.money = +m;
  1104. // —— 108 上记的 +m **真实对应余额增加**,**参与**"balance 增量 = Σ流水"的归因。
  1105. // ② **退费差额**(`RefundService.CustomRefund` 的 `requested > 可退` 分支):
  1106. // 只 `special_expenses += m`(余额净减 = refunded),108.money = +badDebt,
  1107. // 而同一请求的 207.money = **−requested(全额)**——坏账部分已含在 207 里;
  1108. // —— 该 108 **不再构成一次独立的余额增加**,**不参与**"108 → balance 增量"的归因
  1109. // (否则会与 207 重复计入)。
  1110. //
  1111. // **判别式(唯一、可机械执行,设计 §3.8-b (f) A18)**:取该 108 流水的 `logid`
  1112. // (= `request_id`,`newExpenseLog` 对两者写同一值)——
  1113. // **同 `logid` 存在 type=207 且 `logid <> ''`(非 NULL/空)= 差额型(②)**;
  1114. // **不存在(含 logid 为空)= 独立坏账(①)**。可直接落地的判定 SQL(AC-17 ④ 可照抄):
  1115. //
  1116. // SELECT l.id, l.money,
  1117. // (l.log_id IS NOT NULL AND l.log_id <> ''
  1118. // AND EXISTS (SELECT 1 FROM t_user_expense_log r
  1119. // WHERE r.user_id = l.user_id AND r.type = 207 AND r.log_id = l.log_id)) AS differential
  1120. // FROM t_user_expense_log l
  1121. // WHERE l.user_id = ? AND l.type = 108;
  1122. //
  1123. // · 两条来源都存在时,"balance = Σ全部流水" 仍恒成立(②里 108 与 207 的代数和恰为净扣减
  1124. // −(requested−badDebt) = −refunded),但"逐条 108 是否代表一次余额增加"必须用上面的判别式区分;
  1125. // **禁止**用一条 `SUM(money) WHERE type=108` 把两种语义混算。
  1126. //
  1127. // 幂等:`request_id + type(108)` 唯一键;无 requestId 时不享幂等(dump 同口径)。
  1128. //
  1129. // 入参:ctx / in。出参:*BadDebtResult;错误码 2001/2002/3140/1004/5002。
  1130. func (s *FundService) BadDebt(ctx context.Context, in BadDebtInput) (*BadDebtResult, error) {
  1131. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "BadDebt", true); err != nil {
  1132. return nil, err
  1133. }
  1134. if err := validatePositiveAmount(in.Money, "BadDebt"); err != nil {
  1135. return nil, err
  1136. }
  1137. if s == nil || s.runner == nil || s.repo == nil {
  1138. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  1139. }
  1140. remark := strings.TrimSpace(in.Remark)
  1141. if remark == "" {
  1142. remark = defaultBadDebtRemark
  1143. }
  1144. var out BadDebtResult
  1145. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  1146. txCtx := repository.WithTxContext(ctx, tx)
  1147. hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeBadDebt)
  1148. if e != nil {
  1149. return e
  1150. }
  1151. if hit != nil {
  1152. out = BadDebtResult{LogID: hit.ID, Repeated: true}
  1153. if acc, ae := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID); ae == nil {
  1154. if spec, pe := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses"); pe == nil {
  1155. out.SpecialExpenses = spec
  1156. }
  1157. if bal, pe := parseAccountAmount(acc.Balance, "t_user_expense_school.balance"); pe == nil {
  1158. out.Balance = bal
  1159. }
  1160. }
  1161. return nil
  1162. }
  1163. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  1164. return e
  1165. }
  1166. if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
  1167. return e
  1168. }
  1169. if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
  1170. UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
  1171. }); e != nil {
  1172. return e
  1173. }
  1174. // dump:两条 UPDATE 都是 `balance + inputMoney, special_expenses + inputMoney` → **双加**
  1175. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "BadDebt", in.UserID,
  1176. in.InstitutionID, in.CampusID,
  1177. repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money},
  1178. repository.ColumnDelta{Column: repository.ExpenseColumnSpecialExpenses, Delta: in.Money},
  1179. ); e != nil {
  1180. return e
  1181. }
  1182. acc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
  1183. if e != nil {
  1184. return e
  1185. }
  1186. bal, e := parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
  1187. if e != nil {
  1188. return e
  1189. }
  1190. spec, e := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses")
  1191. if e != nil {
  1192. return e
  1193. }
  1194. // `balance_after` = 坏账后**全局账户余额**快照(响应体 Balance 是校区余额,两者此时数值相同但口径不同)
  1195. globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
  1196. if e != nil {
  1197. return e
  1198. }
  1199. lg := newExpenseLog(in.UserID, model.ExpenseLogTypeBadDebt, in.Money,
  1200. in.RequestID, remark, in.OperatorID, &globalAfter)
  1201. if e := s.insertLog(txCtx, tx, lg); e != nil {
  1202. return e
  1203. }
  1204. out = BadDebtResult{LogID: lg.ID, SpecialExpenses: spec, Balance: bal}
  1205. return nil
  1206. })
  1207. if err != nil {
  1208. return nil, s.mapIdempotentHit(err, func() error {
  1209. return s.replayBadDebt(ctx, in, &out)
  1210. })
  1211. }
  1212. return &out, nil
  1213. }
  1214. // ---------------------------------------------------------------- SP11 累计消费(spend)
  1215. // AccumulateSpend 累计消费金额(SP11 `sp_user_expense_school_spend`)。
  1216. //
  1217. // 口径(设计 §3.1 #11):**只更新 `spend`,不动 `balance`**;无流水(dump 不写 log)。
  1218. //
  1219. // **BUG#1 修正**:dump 的全局分支 `INSERT INTO t_user_expense(userid, spend) VALUES(inputUserid,
  1220. // inputMoney, inputSpendMoney)` 是 **3 个值对 2 列**(且 inputMoney 在该 SP 里根本未声明)→ 必报错。
  1221. // Go 修正为"UPSERT 建户 + `spend = spend + ?`",列数与列名对齐 DDL。
  1222. //
  1223. // 负值处理:dump 仅在 **INSERT 分支**把负数归 0(UPDATE 分支会照减);本实现统一归 0
  1224. // (`spend` 是"只增"的统计口径列,model 注释亦如此约定),并回显当前值。
  1225. //
  1226. // 幂等:dump 的 SP11 **没有请求号**(签名只有 4 参),因此本方法不参与 `uk_request_type` 幂等;
  1227. // 重复调用会重复累加 `spend`——这是 dump 的既有语义(调用方为"结束上课"链路,每次课一条),
  1228. // 不做"按 requestId 去重"的加法,以免与 dump 的双跑口径分叉。
  1229. //
  1230. // 入参:ctx / in。出参:*SpendResult{spend};错误码 2001/3140/5002。
  1231. func (s *FundService) AccumulateSpend(ctx context.Context, in SpendInput) (*SpendResult, error) {
  1232. if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "AccumulateSpend", true); err != nil {
  1233. return nil, err
  1234. }
  1235. if err := in.SpendMoney.Validate(); err != nil {
  1236. return nil, infraerrors.WithCause(infraerrors.ErrBadFormat, err)
  1237. }
  1238. if in.SpendMoney < 0 {
  1239. in.SpendMoney = 0 // dump INSERT 分支:负数归 0(spend 只增)
  1240. }
  1241. if s == nil || s.runner == nil || s.repo == nil {
  1242. return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
  1243. }
  1244. var out SpendResult
  1245. err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
  1246. txCtx := repository.WithTxContext(ctx, tx)
  1247. if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
  1248. return e
  1249. }
  1250. if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
  1251. return e
  1252. }
  1253. if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
  1254. UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
  1255. }); e != nil {
  1256. return e
  1257. }
  1258. if !in.SpendMoney.IsZero() {
  1259. if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "AccumulateSpend", in.UserID,
  1260. in.InstitutionID, in.CampusID,
  1261. repository.ColumnDelta{Column: repository.ExpenseColumnSpend, Delta: in.SpendMoney},
  1262. ); e != nil {
  1263. return e
  1264. }
  1265. }
  1266. acc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
  1267. if e != nil {
  1268. return e
  1269. }
  1270. spend, e := parseAccountAmount(acc.Spend, "t_user_expense_school.spend")
  1271. if e != nil {
  1272. return e
  1273. }
  1274. out = SpendResult{Spend: spend}
  1275. return nil
  1276. })
  1277. if err != nil {
  1278. return nil, err
  1279. }
  1280. return &out, nil
  1281. }
  1282. // ---------------------------------------------------------------- 幂等公共形状
  1283. // insertLog 写流水并把"撞 uk_request_type"翻译成内部幂等哨兵(`apperr.ErrRepeated`)。
  1284. //
  1285. // 入参:txCtx(含 tx 的 ctx)/ tx / lg 流水行。
  1286. // 出参:nil 成功;apperr.ErrRepeated(**并发幂等命中**,调用方据此回放首次结果);
  1287. // 其余错误原样上抛(ErrBadParam/ErrDBError)。
  1288. //
  1289. // 为什么用 ErrRepeated 作为事务内哨兵:它是 *AppError,`TxRunner.wrapTxErr` 会原样透传
  1290. // (不降级成 5002),且它是设计里"仅内部日志用"的码(§10.1),不会泄漏给前端。
  1291. func (s *FundService) insertLog(txCtx context.Context, tx *gorm.DB, lg *model.UserExpenseLog) error {
  1292. err := s.repo.InsertLog(txCtx, tx, lg)
  1293. if err == nil {
  1294. return nil
  1295. }
  1296. if errors.Is(err, repository.ErrDuplicateLog) {
  1297. return apperr.ErrRepeated
  1298. }
  1299. return err
  1300. }
  1301. // mapIdempotentHit 把"并发幂等命中"从错误路径转成"回放首次结果"的成功路径。
  1302. //
  1303. // 入参:
  1304. // - err:WithinTx 返回的错误;
  1305. // - replay:回放函数(重新查询首次流水并填充 out)。
  1306. //
  1307. // 出参:nil(回放成功)/ 回放错误 / 原错误(非幂等命中)。
  1308. //
  1309. // 语义(§1.5):`uk_request_type` 撞键 = 同一请求号 + 同一 type 的第二次写入,
  1310. // **不是错误**(code 仍 200,data.repeated=true)。实现上先整笔回滚(本次零残留),再回放。
  1311. func (s *FundService) mapIdempotentHit(err error, replay func() error) error {
  1312. if err == nil {
  1313. return nil
  1314. }
  1315. if errors.Is(err, apperr.ErrRepeated) {
  1316. return replay()
  1317. }
  1318. return err
  1319. }
  1320. // balanceAfterOf 从流水行取 balance_after 快照(NULL → 0)。
  1321. //
  1322. // ⚠ 口径提醒:`balance_after` 自 v0.1.16 起是「该操作完成后**全局账户**余额」(§3.8-f ②-bis),
  1323. // 而各 `Result.Balance` 的契约是**校区**余额 —— 因此**响应体不得再用本函数填充**(会串口径),
  1324. // 回放一律走 `campusBalanceAfter` 读当前校区账户。本函数仅保留给"确实要读全局快照"的对账/排障用途。
  1325. //
  1326. // 入参:lg 流水行(可 nil)。出参:(金额, error);balance_after 为 NULL 时返回 0 且无错
  1327. // (历史行没有快照列,调用方需能接受 0)。
  1328. func balanceAfterOf(lg *model.UserExpenseLog) (money.Amount, error) {
  1329. if lg == nil || lg.BalanceAfter == nil {
  1330. return 0, nil
  1331. }
  1332. return parseAccountAmount(*lg.BalanceAfter, "t_user_expense_log.balance_after")
  1333. }
  1334. // replayRecharge 幂等回放(充值)。
  1335. func (s *FundService) replayRecharge(ctx context.Context, in RechargeInput, out *RechargeResult) error {
  1336. hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, in.Type)
  1337. if err != nil {
  1338. return err
  1339. }
  1340. if hit == nil {
  1341. return infraerrors.WithCause(infraerrors.ErrInternal,
  1342. errString("service: Recharge 幂等命中但首次流水已不可见"))
  1343. }
  1344. // 响应体 Balance 是**校区**余额(与流水的 balance_after 全局口径不同),回放按当前校区账户取值
  1345. bal, err := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.InstitutionID, in.CampusID)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. *out = RechargeResult{LogID: hit.ID, Balance: bal, Repeated: true}
  1350. return nil
  1351. }
  1352. // replayExpenditure 幂等回放(消费)。
  1353. func (s *FundService) replayExpenditure(ctx context.Context, in ExpenditureInput, out *ExpenditureResult) error {
  1354. hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, in.Type)
  1355. if err != nil {
  1356. return err
  1357. }
  1358. if hit == nil {
  1359. return infraerrors.WithCause(infraerrors.ErrInternal,
  1360. errString("service: Expenditure 幂等命中但首次流水已不可见"))
  1361. }
  1362. // 响应体 Balance 是**校区**余额(与流水的 balance_after 全局口径不同),回放按当前校区账户取值
  1363. bal, err := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.InstitutionID, in.CampusID)
  1364. if err != nil {
  1365. return err
  1366. }
  1367. *out = ExpenditureResult{LogID: hit.ID, Balance: bal, Repeated: true}
  1368. return nil
  1369. }
  1370. // replayRefund 幂等回放(退费)。
  1371. func (s *FundService) replayRefund(ctx context.Context, in RefundInput, out *RefundResult) error {
  1372. hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, in.Type)
  1373. if err != nil {
  1374. return err
  1375. }
  1376. if hit == nil {
  1377. return infraerrors.WithCause(infraerrors.ErrInternal,
  1378. errString("service: Refund 幂等命中但首次流水已不可见"))
  1379. }
  1380. // 响应体 Balance 是**校区**余额(与流水的 balance_after 全局口径不同),回放按当前校区账户取值
  1381. bal, err := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.InstitutionID, in.CampusID)
  1382. if err != nil {
  1383. return err
  1384. }
  1385. *out = RefundResult{LogID: hit.ID, Balance: bal, Changed: true, Repeated: true}
  1386. return nil
  1387. }
  1388. // replayBadDebt 幂等回放(坏账)。
  1389. func (s *FundService) replayBadDebt(ctx context.Context, in BadDebtInput, out *BadDebtResult) error {
  1390. hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeBadDebt)
  1391. if err != nil {
  1392. return err
  1393. }
  1394. if hit == nil {
  1395. return infraerrors.WithCause(infraerrors.ErrInternal,
  1396. errString("service: BadDebt 幂等命中但首次流水已不可见"))
  1397. }
  1398. var spec, bal money.Amount
  1399. if acc, ae := s.repo.GetCampusAccount(ctx, nil, in.UserID, in.InstitutionID, in.CampusID); ae == nil {
  1400. if v, pe := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses"); pe == nil {
  1401. spec = v
  1402. }
  1403. if v, pe := parseAccountAmount(acc.Balance, "t_user_expense_school.balance"); pe == nil {
  1404. bal = v
  1405. }
  1406. }
  1407. *out = BadDebtResult{LogID: hit.ID, SpecialExpenses: spec, Balance: bal, Repeated: true}
  1408. return nil
  1409. }
  1410. // replayTransfer 幂等回放(转结)。
  1411. func (s *FundService) replayTransfer(ctx context.Context, in TransferInput, out *TransferResult) error {
  1412. hit106, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeTransferOut)
  1413. if err != nil {
  1414. return err
  1415. }
  1416. if hit106 == nil {
  1417. return infraerrors.WithCause(infraerrors.ErrInternal,
  1418. errString("service: Transfer 幂等命中但首次流水已不可见"))
  1419. }
  1420. // FromBalance / ToBalance 是两个**校区**各自余额(流水 balance_after 是全局口径,不能拿来充两个值)
  1421. res := TransferResult{LogID106: hit106.ID, Repeated: true}
  1422. if bal, pe := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.FromInstitutionID, in.FromCampusID); pe == nil {
  1423. res.FromBalance = bal
  1424. }
  1425. hit206, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeTransferIn)
  1426. if err != nil {
  1427. return err
  1428. }
  1429. if hit206 != nil {
  1430. res.LogID206 = hit206.ID
  1431. if bal, pe := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.ToInstitutionID, in.ToCampusID); pe == nil {
  1432. res.ToBalance = bal
  1433. }
  1434. }
  1435. *out = res
  1436. return nil
  1437. }
  1438. // isKnownLogType 流水类型白名单(`model.ExpenseLogType*` 全集,§10.2)。
  1439. //
  1440. // 用途:`Refund` 的 type 来自调用方(dump 透传),必须落在已知编码内,
  1441. // 否则会污染流水表并让"按 type 汇总"的对账口径失效。
  1442. func isKnownLogType(typ int32) bool {
  1443. switch typ {
  1444. case model.ExpenseLogTypeRecharge,
  1445. model.ExpenseLogTypeCourseCampus,
  1446. model.ExpenseLogTypeCourseSchoolA,
  1447. model.ExpenseLogTypeCourseSchoolB,
  1448. model.ExpenseLogTypeTransferOut,
  1449. model.ExpenseLogTypeRecommend,
  1450. model.ExpenseLogTypeBadDebt,
  1451. model.ExpenseLogTypeHistoryDeduct,
  1452. model.ExpenseLogTypeCourseCampusB,
  1453. model.ExpenseLogTypeCourseSchoolC,
  1454. model.ExpenseLogTypeCourseSchoolD,
  1455. model.ExpenseLogTypeTransferIn,
  1456. model.ExpenseLogTypeRefund,
  1457. model.ExpenseLogTypeClearBalance,
  1458. model.ExpenseLogTypeCancelRechargeAct:
  1459. return true
  1460. default:
  1461. return false
  1462. }
  1463. }