fund_service.go 56 KB

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