| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555 |
- // 余额核心服务(8 个余额类 SP 的 Go 化落点)——AC-04。
- //
- // 依据:unified/03-migration/academic-domain-design.md §3.1(余额 11 SP 映射,本文件覆盖 #1~#7 + #11)
- // / §1.4(事务模板)/ §1.5(幂等键 uk_request_type)/ §7.1(充值时序)/ §10.2(type 编码与方向)
- // / §10.3(事务边界只在 Service)/ §10.7(金额溢出与量级上限)。
- //
- // SP 映射(dump 行号见 §3.1,**顺序与方向一律按 dump,不得"顺手修正"**):
- //
- // #1 sp_user_expense_recharge → Recharge(8 参、**双表更新**:全局 + 校区同事务)
- // #2 sp_user_expense_school_recharge → Recharge(同构合并,仅默认备注不同 → RechargeKind)
- // #3 sp_user_expense_school_expenditure → Expenditure(type 由调用方传,白名单校验)
- // #4 sp_user_expense_school_refund → Refund(**补 institution_id 参数**,BUG#2 修正)
- // #5 sp_user_expense_school_get_refundable_amount → RefundableAmount(只读,无事务;**两步修正**)
- // #6 sp_user_expense_school_transfer_expenditure → Transfer(**不动 balance**;106=+m / 206=−m)
- // #7 sp_user_expense_baddebt → BadDebt(SP 头注释即「余额+,特殊费用+」→ **双加**)
- // #11 sp_user_expense_school_spend → AccumulateSpend(只更新 spend,不动 balance;BUG#1)
- //
- // 两条不可违反的纪律(评审逐处检查):
- //
- // 1. **事务边界只在 Service**:写路径一律 `s.runner.WithinTx`;仓储方法不开事务,
- // 事务内下游调用一律经 `repository.WithTxContext(ctx, tx)` 注入的 ctx(§10.3)。
- // 2. **固定写序「全局 → 校区」**:所有双表写都收敛到
- // `ExpenseRepo.AddColumnsGlobalThenCampus`(一条表一条 UPDATE,全局在前),
- // 与 RefundService 的**加锁**顺序保持一致,否则与并发充值交叉即成环(§1.4 / §7.2)。
- //
- // 金额纪律:全链路 `money.Amount`(int64 分),入参先过 `validatePositiveAmount`
- // (业务量级 + `Validate()`),落库前再由仓储的 `amountLiteral` 二次 `Validate()`(§10.7 兜底网)。
- package service
- import (
- "context"
- "errors"
- "sort"
- "strings"
- "gorm.io/gorm"
- "yuansiwei/unified-backend/internal/academic/apperr"
- "yuansiwei/unified-backend/internal/academic/model"
- "yuansiwei/unified-backend/internal/academic/money"
- "yuansiwei/unified-backend/internal/academic/port"
- "yuansiwei/unified-backend/internal/academic/repository"
- infraerrors "yuansiwei/unified-backend/internal/infra/errors"
- appscope "yuansiwei/unified-backend/internal/infra/scope"
- )
- // 默认备注文案(dump 的 `IF inputRemark=”` 分支,**逐字对齐**,双跑会比对 log.remark)。
- const (
- // defaultRechargeRemark SP1 `sp_user_expense_recharge` 默认备注。
- defaultRechargeRemark = "余额充值"
- // defaultSchoolRechargeRemark SP2 `sp_user_expense_school_recharge` 默认备注(与 SP1 不同)。
- defaultSchoolRechargeRemark = "充值缴费"
- // defaultExpenditureRemark SP3 `sp_user_expense_school_expenditure` 默认备注。
- defaultExpenditureRemark = "历史扣费"
- // defaultRefundRemark SP4 `sp_user_expense_school_refund` 默认备注。
- defaultRefundRemark = "报课的费用退回"
- // defaultBadDebtRemark SP7 `sp_user_expense_baddebt` 默认备注。
- defaultBadDebtRemark = "坏账处理"
- )
- // maxSingleAmount 单笔金额业务上限(1,000,000.00 元)。
- //
- // 依据设计 §10.7「配套纪律 2」:Service 入口对 money 做业务量级断言,把"脏数据放大"挡在运算前
- // (超出 → 2002)。注意与 `money.MaxAmount`(decimal(12,2) 全域 ±99.99 亿元)不是一回事:
- // 前者是**业务**天花板,后者是**存储**天花板,两者都必须校验。
- const maxSingleAmount money.Amount = 100_000_000
- // RechargeKind 充值 SP 形态(#1 与 #2 的**唯一差异**是默认备注,合并后用它区分双跑映射)。
- type RechargeKind int
- const (
- // RechargeKindDefault 对应 SP1 `sp_user_expense_recharge`(默认备注"余额充值")。
- RechargeKindDefault RechargeKind = iota
- // RechargeKindSchool 对应 SP2 `sp_user_expense_school_recharge`(默认备注"充值缴费")。
- RechargeKindSchool
- )
- // FundService 余额核心服务(充值/消费/退费/转结/坏账/累计消费/可退金额)。
- //
- // 字段:
- // - repo:余额账户仓储(全局 + 校区 + 流水;校区账户走机构作用域);
- // - requests:余额工单仓储(**只读**用途:SP5 可退额需要按「充值工单 × 活动报名」汇总已用赠送额,
- // 设计 §3.1 #5 的第二步修正,`SumRechargeActivityUsedGift`);
- // - runner:事务运行器(顶层 BEGIN,事务内透传);
- // - campus:校区只读端口(**只读**:转结转入方建户需要"权威机构 ID",见 R4-bis);
- // - member:成员关系校验器(可 nil:系统任务/割接脚本模式不做对象级越权断言)。
- type FundService struct {
- repo *repository.ExpenseRepo
- requests *repository.BalanceRequestRepo
- runner *repository.TxRunner
- campus port.CampusReader
- member port.MembershipChecker
- }
- // NewFundService 构造余额核心服务(repo 与 runner 绑定同一 DB 句柄,避免跨连接池事务失效)。
- //
- // 入参:
- // - db *gorm.DB:数据库句柄(必填);
- // - sc *appscope.Scope:本次请求作用域(校区账户读写必需;系统任务可 nil,
- // 此时**只能**调用全局/流水方法,触达校区账户会 panic fail-fast);
- // - member port.MembershipChecker:成员校验器(可 nil)。
- //
- // 出参:*FundService。
- //
- // 说明:`campus` 端口由本构造函数内部用同一 db 装配(`port.NewOrgCampusReader`),
- // 因此**签名保持不变**(既有调用方无需改动);需要注入 mock 的用例可用 `WithCampusReader`。
- func NewFundService(db *gorm.DB, sc *appscope.Scope, member port.MembershipChecker) *FundService {
- return &FundService{
- repo: repository.NewExpenseRepo(db, sc),
- requests: repository.NewBalanceRequestRepo(db, sc),
- runner: repository.NewTxRunner(db),
- campus: port.NewOrgCampusReader(db),
- member: member,
- }
- }
- // WithCampusReader 替换校区只读端口(单测注入 mock 用;nil 时忽略)。
- //
- // 入参:reader port.CampusReader。出参:*FundService(链式,原地修改后返回自身)。
- func (s *FundService) WithCampusReader(reader port.CampusReader) *FundService {
- if s != nil && reader != nil {
- s.campus = reader
- }
- return s
- }
- // ---------------------------------------------------------------- 入参 / 出参
- // RechargeInput 充值入参(SP1 `sp_user_expense_recharge` 8 参 / SP2 同构 7 参)。
- //
- // 入参纪律:`Money` 已由 Handler 用 `money.Parse` 解析(**拒绝 float**,§10.6),
- // 本层不再解析字符串,只校验量级与业务规则。
- type RechargeInput struct {
- // UserID 充值用户(canonical_user_id ULID;必填)。
- UserID string `json:"userId"`
- // InstitutionID 机构 ID(必填 >0;dump 的 inputSchoolid)。
- InstitutionID int64 `json:"institutionId"`
- // CampusID 校区 ID(必填 >0;dump 的 inputCampusid)。
- CampusID int64 `json:"campusId"`
- // Money 充值金额(>0;dump 的 inputMoney)。
- Money money.Amount `json:"money"`
- // Type 流水类型(dump 的 inputType;<100 一律归 100,对齐 dump `IF inputType<100`)。
- Type int32 `json:"type"`
- // RequestID 幂等请求号(→ request_id 幂等键 + log_id 业务单号;空 = 不享幂等)。
- RequestID string `json:"requestId"`
- // Remark 备注(空 → 按 Kind 取默认文案)。
- Remark string `json:"remark"`
- // OperatorID 操作人(→ create_user_id;空 → NULL)。
- OperatorID string `json:"-"`
- // Kind SP 形态(默认 RechargeKindDefault)。
- Kind RechargeKind `json:"-"`
- }
- // RechargeResult 充值结果(端点 3 响应 `{logId,balance,repeated}`)。
- type RechargeResult struct {
- // LogID 流水 ID(幂等命中时为**首次**流水 ID)。
- LogID int64 `json:"logId"`
- // Balance 充值后校区账户余额(balance_after 口径)。
- Balance money.Amount `json:"balance"`
- // Repeated true = 幂等命中(requestId 已处理),未重复入账。
- Repeated bool `json:"repeated"`
- }
- // ExpenditureInput 消费入参(SP3 `sp_user_expense_school_expenditure` 8 参)。
- type ExpenditureInput struct {
- // UserID 用户(必填)。
- UserID string `json:"userId"`
- // InstitutionID 机构 ID(必填 >0)。
- InstitutionID int64 `json:"institutionId"`
- // CampusID 校区 ID(必填 >0)。
- CampusID int64 `json:"campusId"`
- // Money 消费金额(>0;流水落 `-Money`)。
- Money money.Amount `json:"money"`
- // Type 消费类型(101/104/105/200/201/204/205,白名单;非法 → 2002)。
- Type int32 `json:"type"`
- // RequestID 幂等请求号(空 = 不享幂等)。
- RequestID string `json:"requestId"`
- // Remark 备注(空 → "历史扣费")。
- Remark string `json:"remark"`
- // OperatorID 操作人。
- OperatorID string `json:"-"`
- }
- // ExpenditureResult 消费结果(端点 4 响应 `{logId,balance}`)。
- type ExpenditureResult struct {
- // LogID 流水 ID。
- LogID int64 `json:"logId"`
- // Balance 消费后校区账户余额。
- Balance money.Amount `json:"balance"`
- // Repeated true = 幂等命中。
- Repeated bool `json:"repeated"`
- }
- // RefundInput 退费入参(SP4 `sp_user_expense_school_refund` 7 参 + **补 institution_id**)。
- type RefundInput struct {
- // UserID 用户(必填)。
- UserID string `json:"userId"`
- // InstitutionID 机构 ID(必填 >0;**dump 无此参数 = BUG#2**,见 Refund 方法注释)。
- InstitutionID int64 `json:"institutionId"`
- // CampusID 校区 ID(必填 >0)。
- CampusID int64 `json:"campusId"`
- // Money 退费金额(>0 才生效;<=0 → changed=false 的 no-op,对齐 dump `IF inputMoney>0`)。
- Money money.Amount `json:"money"`
- // Type 流水类型(dump 的 inputType;必须属 model.ExpenseLogType* 白名单)。
- Type int32 `json:"type"`
- // RequestID 幂等请求号(空 = 不享幂等)。
- RequestID string `json:"requestId"`
- // Remark 备注(空 → "报课的费用退回")。
- Remark string `json:"remark"`
- // OperatorID 操作人。
- OperatorID string `json:"-"`
- }
- // RefundResult 退费结果(端点 5 响应 `{logId,balance,changed}`)。
- type RefundResult struct {
- // LogID 流水 ID(恒 > 0:money<=0 已在入口按 R6 拒为 2002)。
- LogID int64 `json:"logId"`
- // Balance 退费后校区账户余额。
- Balance money.Amount `json:"balance"`
- // Changed 成功即发生账户写入 ⇒ **恒 true**(R6 定稿:金额<=0 一律入口 2002,不存在 no-op 分支)。
- // 字段仅为 DTO 契约兼容保留;**前端不得用 changed=false 作为正常分支**判断(不会有该取值)。
- // 幂等命中用 Repeated 表达。
- Changed bool `json:"changed"`
- // Repeated true = 幂等命中。
- Repeated bool `json:"repeated"`
- }
- // TransferInput 转结入参(SP6 `sp_user_expense_school_transfer_expenditure` 8 参)。
- type TransferInput struct {
- // UserID 用户(必填)。
- UserID string `json:"userId"`
- // FromInstitutionID 转出机构 ID(必填 >0)。
- FromInstitutionID int64 `json:"fromInstitutionId"`
- // FromCampusID 转出校区 ID(必填 >0)。
- FromCampusID int64 `json:"fromCampusId"`
- // ToInstitutionID 转入机构 ID(必填 >0)。
- ToInstitutionID int64 `json:"toInstitutionId"`
- // ToCampusID 转入校区 ID(必填 >0)。
- ToCampusID int64 `json:"toCampusId"`
- // Money 转结金额(>0)。
- Money money.Amount `json:"money"`
- // RequestID 幂等请求号(**两条流水共用**同一 request_id,type 不同故不撞键)。
- RequestID string `json:"requestId"`
- // Remark 备注(dump 无默认值)。
- Remark string `json:"remark"`
- // OperatorID 操作人。
- OperatorID string `json:"-"`
- }
- // TransferResult 转结结果(端点 7 响应 `{logId106,logId206}`)。
- type TransferResult struct {
- // LogID106 type=106 转结出流水 ID(dump: money = **+Money**)。
- LogID106 int64 `json:"logId106"`
- // LogID206 type=206 转结入流水 ID(dump: money = **−Money**)。
- LogID206 int64 `json:"logId206"`
- // FromBalance 转出校区账户余额(转结**不动 balance**,故与转结前相同)。
- FromBalance money.Amount `json:"fromBalance"`
- // ToBalance 转入校区账户余额(同上)。
- ToBalance money.Amount `json:"toBalance"`
- // Repeated true = 幂等命中。
- Repeated bool `json:"repeated"`
- }
- // BadDebtInput 坏账入参(SP7 `sp_user_expense_baddebt` 7 参)。
- type BadDebtInput struct {
- // UserID 用户(必填)。
- UserID string `json:"userId"`
- // InstitutionID 机构 ID(必填 >0)。
- InstitutionID int64 `json:"institutionId"`
- // CampusID 校区 ID(必填 >0)。
- CampusID int64 `json:"campusId"`
- // Money 坏账金额(>0)。
- Money money.Amount `json:"money"`
- // RequestID 幂等请求号(空 = 不享幂等)。
- RequestID string `json:"requestId"`
- // Remark 备注(空 → "坏账处理")。
- Remark string `json:"remark"`
- // OperatorID 操作人。
- OperatorID string `json:"-"`
- }
- // BadDebtResult 坏账结果(端点 8 响应 `{logId,specialExpenses}`)。
- type BadDebtResult struct {
- // LogID type=108 流水 ID。
- LogID int64 `json:"logId"`
- // SpecialExpenses 处理后校区账户特殊费用累计。
- SpecialExpenses money.Amount `json:"specialExpenses"`
- // Balance 处理后校区账户余额(**dump 口径:坏账双加,故已 +Money**)。
- Balance money.Amount `json:"balance"`
- // Repeated true = 幂等命中。
- Repeated bool `json:"repeated"`
- }
- // SpendInput 累计消费入参(SP11 `sp_user_expense_school_spend` 4 参)。
- type SpendInput struct {
- // UserID 用户(必填)。
- UserID string `json:"userId"`
- // InstitutionID 机构 ID(必填 >0)。
- InstitutionID int64 `json:"institutionId"`
- // CampusID 校区 ID(必填 >0)。
- CampusID int64 `json:"campusId"`
- // SpendMoney 本次累加的课费单价之和(元;**负数一律归 0**,dump INSERT 分支同口径)。
- SpendMoney money.Amount `json:"spendMoney"`
- }
- // SpendResult 累计消费结果(端点 10 响应 `{spend}`)。
- type SpendResult struct {
- // Spend 累加后校区账户 spend 列(**不是** balance)。
- Spend money.Amount `json:"spend"`
- }
- // ---------------------------------------------------------------- 校验助手
- // validateUserScope 校验"用户 + 机构 + 校区"三元组(资金方法入口统一形状)。
- //
- // 入参:userID / institutionID / campusID;op 操作名(错误文案定位);campusRequired 是否要求校区>0。
- // 出参:nil 合法;2001(缺 user_id)/ 3140(校区或机构缺失,对齐设计 §1.6「campusid<=0 → 3140」)。
- func validateUserScope(userID string, institutionID, campusID int64, op string, campusRequired bool) error {
- if strings.TrimSpace(userID) == "" {
- return infraerrors.WithCause(infraerrors.ErrBadParam, errString("service: "+op+" 需要 user_id"))
- }
- if institutionID <= 0 {
- return infraerrors.WithCause(apperr.ErrBusinessParam,
- errString("service: "+op+" 需要 institution_id > 0"))
- }
- if campusRequired && campusID <= 0 {
- // dump:`IF (inputSchoolid<1 || inputCampusid<1) THEN LEAVE`(静默 no-op)
- // Go:显式 3140,避免"调用成功但什么都没做"
- return infraerrors.WithCause(apperr.ErrBusinessParam,
- errString("service: "+op+" 需要 campus_id > 0(dump:必须有校区信息)"))
- }
- if campusID < 0 {
- return infraerrors.WithCause(apperr.ErrBusinessParam,
- errString("service: "+op+" 的 campus_id 不得为负"))
- }
- return nil
- }
- // validatePositiveAmount 校验金额为正且不超业务/存储天花板(§10.7)。
- //
- // 入参:amount 金额(分);op 操作名。
- // 出参:nil 合法;2002(<=0 / 超业务上限 / 超 decimal(12,2) 全域)。
- //
- // 与 dump 的差异(登记为有意偏离):dump 对负数是 `IF inputMoney<0 THEN SET inputMoney=0`
- // **静默归零后继续记账**,会留下 money=0 的流水并占住幂等键;Go 显式拒绝(2002)。
- func validatePositiveAmount(amount money.Amount, op string) error {
- if amount <= 0 {
- return infraerrors.WithCause(infraerrors.ErrBadFormat,
- errString("service: "+op+" 金额必须 > 0(dump 静默归零 → Go 显式拒绝)"))
- }
- if amount > maxSingleAmount {
- return infraerrors.WithCause(infraerrors.ErrBadFormat,
- errString("service: "+op+" 金额超出单笔业务上限"))
- }
- if err := amount.Validate(); err != nil {
- return infraerrors.WithCause(infraerrors.ErrBadFormat, err)
- }
- return nil
- }
- // parseAccountAmount 把账户 decimal 字符串列解析为 money.Amount。
- //
- // 入参:raw 列原文(如 "12.34");col 列名(错误文案定位)。
- // 出参:money.Amount;ErrDBError(历史脏值/格式非法——属数据问题,不是入参问题)。
- func parseAccountAmount(raw, col string) (money.Amount, error) {
- amount, err := money.Parse(raw)
- if err != nil {
- return 0, infraerrors.WithCause(infraerrors.ErrDBError,
- errString("service: 账户列 "+col+" 金额非法("+raw+")"))
- }
- return amount, nil
- }
- // globalBalanceAfter 取「该笔操作完成后**全局账户**(t_user_expense)余额」快照。
- //
- // ⚠ **与 `campusBalanceAfter` 不得合并**(后人最容易"优化"成同一个函数):两者是**两列不同的列**、
- // 服务于**两个不同的消费者**,且在"多校区"场景下数值本来就不相等——
- // - 本函数 → 流水 `t_user_expense_log.balance_after`(对账链,全局口径);
- // - 另一个 → API 响应体 `Result.Balance`(用户体验,校区口径)。
- //
- // 用途(唯一):流水列 `t_user_expense_log.balance_after` 的取值口径(设计 §3.8-f ②-bis 裁定):
- // - 语义 = **全局账户余额**,不是校区余额(`t_user_expense_log` 上没有 `campus_id`,
- // 只有 user 级全局链才能做 `balance_after(op_n) = balance_after(op_{n−1}) + Σ(money of op_n)` 校验);
- // - 取值时机 = **写完账户、写第一条流水之前取一次**,同一操作的多行流水(转结 106/206、
- // 退费 108/207)**复用同一个值**;**禁止逐条重算**(并发下会取到不同值,链式校验必乱)。
- //
- // 入参:ctx / repo / tx(**必传**:必须与本操作的账户写入同事务同快照)/ userID。
- // 出参:(全局余额, error);ErrNotFound(账户不存在,属调用顺序错误)/ ErrDBError。
- func globalBalanceAfter(
- ctx context.Context, repo *repository.ExpenseRepo, tx *gorm.DB, userID string,
- ) (money.Amount, error) {
- global, err := repo.GetGlobalAccount(ctx, tx, userID)
- if err != nil {
- return 0, err
- }
- return parseAccountAmount(global.Balance, "t_user_expense.balance")
- }
- // campusBalanceAfter 取「该笔操作完成后**校区账户**余额」快照。
- //
- // ⚠ **与 `globalBalanceAfter` 不得合并**:见后者头注释(两个消费者、两列、多校区下数值本就不等)。
- //
- // 用途(唯一):**API 响应体的 `Balance` 字段**(各 Result.Balance 的契约是"校区账户余额",
- // 与流水的 `balance_after` 语义不同,**不得**混用同一个值)。
- //
- // 入参:ctx / repo / tx / userID / institutionID / campusID。
- // 出参:(校区余额, error);ErrNotFound / ErrDBError。
- func campusBalanceAfter(
- ctx context.Context, repo *repository.ExpenseRepo, tx *gorm.DB,
- userID string, institutionID, campusID int64,
- ) (money.Amount, error) {
- acc, err := repo.GetCampusAccount(ctx, tx, userID, institutionID, campusID)
- if err != nil {
- return 0, err
- }
- return parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
- }
- // optString 把空串转成 nil 指针(*string 列的 NULL 语义:request_id 为空时"不享幂等")。
- func optString(s string) *string {
- s = strings.TrimSpace(s)
- if s == "" {
- return nil
- }
- return &s
- }
- // amountPtr 返回金额两位小数字符串的指针(`balance_after` 等可空金额列用)。
- func amountPtr(a money.Amount) *string {
- s := a.String()
- return &s
- }
- // newExpenseLog 组装一条余额变更流水(字段口径收口,避免各方法重复拼装)。
- //
- // 入参:userID/typ/money 金额/requestID/remark/operatorID/**balanceAfter = 该操作完成后全局账户余额快照**
- // (nil = 不写快照;同一操作的多行流水必须传**同一个值**,见 `globalBalanceAfter` 的口径说明)。
- // 出参:*model.UserExpenseLog(未落库;Create 后 ID 由 GORM 回填)。
- func newExpenseLog(userID string, typ int32, amount money.Amount, requestID, remark, operatorID string,
- balanceAfter *money.Amount) *model.UserExpenseLog {
- lg := &model.UserExpenseLog{
- UserID: userID,
- Type: typ,
- Money: amount.String(),
- RequestID: optString(requestID),
- LogID: optString(requestID), // dump:logid = 外部单号(SP1 的 inputOrder / SP2 的 inputRequestid)
- CreateUserID: optString(operatorID),
- Remark: optString(remark),
- }
- if balanceAfter != nil {
- lg.BalanceAfter = amountPtr(*balanceAfter)
- }
- return lg
- }
- // assertInScope 对象级越权断言(全局钱包无作用域列,只能由 Service 显式校验,设计 §1.7 例外一)。
- //
- // 入参:ctx / userID / institutionID / campusID。
- // 出参:nil 通过(或未注入 checker 的系统任务模式);1004 越权;5002 DB 异常。
- func (s *FundService) assertInScope(ctx context.Context, userID string, institutionID, campusID int64) error {
- if s == nil || s.member == nil {
- return nil // 系统任务/割接脚本模式:不注入 checker 即不做对象级断言(装配层责任)
- }
- return s.member.AssertInScope(ctx, userID, institutionID, campusID)
- }
- // ---------------------------------------------------------------- SP1 / SP2 充值
- // Recharge 余额充值(SP1 `sp_user_expense_recharge` + SP2 `sp_user_expense_school_recharge`)。
- //
- // dump 语义(yuansiwei_finance.sql:764247,★8 参 + **双表更新**):
- //
- // ① inputMoney<0 → 0;inputType<100 → 100;inputRemark='' → 默认备注;
- // ② schoolid<1 || campusid<1 → LEAVE(静默 no-op);
- // ③ 校区账户不存在则 INSERT;全局账户不存在则 INSERT;
- // ④ UPDATE 校区:balance+, total_income+ ;UPDATE 全局:balance+, total_income+;
- // ⑤ INSERT log(type=inputType, logid=inputOrder, money=inputMoney)。
- //
- // Go 的三处**有意强化**(不改变资金结果):
- // - 建户合并为一次 UPSERT(`ON CONFLICT DO NOTHING`),替代 dump 的 `COUNT` 判存在(§1.5);
- // - 写序固定为 **全局 → 校区**(dump 是校区 → 全局;顺序不同但结果一致,
- // 统一顺序是**死锁预防**的硬要求,见 §1.4 与 §7.2 的加锁基线);
- // - 幂等:`request_id + type` 唯一键,并发重复提交只落 1 条流水(dump 无幂等,会重复入账)。
- //
- // 入参:ctx / in(见 RechargeInput;Kind 决定默认备注)。
- // 出参:*RechargeResult(logId/balance/repeated);错误码 2001/2002/3140/1004/5002。
- func (s *FundService) Recharge(ctx context.Context, in RechargeInput) (*RechargeResult, error) {
- if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "Recharge", true); err != nil {
- return nil, err
- }
- if err := validatePositiveAmount(in.Money, "Recharge"); err != nil {
- return nil, err
- }
- if in.Type < 100 {
- // dump:`IF inputType<100 THEN SET inputType=100`(充值流水类型下限)
- in.Type = model.ExpenseLogTypeRecharge
- }
- if s == nil || s.runner == nil || s.repo == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- remark := strings.TrimSpace(in.Remark)
- if remark == "" {
- if in.Kind == RechargeKindSchool {
- remark = defaultSchoolRechargeRemark
- } else {
- remark = defaultRechargeRemark
- }
- }
- var out RechargeResult
- err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
- txCtx := repository.WithTxContext(ctx, tx)
- // ① 幂等预检(`uk_request_type`):命中 → 返回首次结果,不重复入账
- hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, in.Type)
- if e != nil {
- return e
- }
- if hit != nil {
- bal, pe := balanceAfterOf(hit)
- if pe != nil {
- return pe
- }
- out = RechargeResult{LogID: hit.ID, Balance: bal, Repeated: true}
- return nil
- }
- // ② 作用域断言(全局钱包无作用域列 → Service 层显式校验)
- if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
- return e
- }
- // ③ 建户(两个 UPSERT,**不动已有余额**)
- if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
- return e
- }
- if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
- UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
- }); e != nil {
- return e
- }
- // ④ 原子增减(固定「全局 → 校区」,两列合并为每表一条 UPDATE)
- if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "Recharge", in.UserID,
- in.InstitutionID, in.CampusID,
- repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money},
- repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money},
- ); e != nil {
- return e
- }
- // ⑤ 流水(`balance_after` = **充值后全局账户余额**快照;响应体 Balance 仍是校区余额)
- globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
- if e != nil {
- return e
- }
- bal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.InstitutionID, in.CampusID)
- if e != nil {
- return e
- }
- lg := newExpenseLog(in.UserID, in.Type, in.Money, in.RequestID, remark, in.OperatorID, &globalAfter)
- if e := s.insertLog(txCtx, tx, lg); e != nil {
- return e
- }
- out = RechargeResult{LogID: lg.ID, Balance: bal}
- return nil
- })
- if err != nil {
- return nil, s.mapIdempotentHit(err, func() error {
- return s.replayRecharge(ctx, in, &out)
- })
- }
- return &out, nil
- }
- // ---------------------------------------------------------------- SP3 消费
- // Expenditure 余额消费扣费(SP3 `sp_user_expense_school_expenditure`)。
- //
- // dump 语义(:764364,**type 决定列组合,方向不可改**):
- //
- // inputType=200(历史扣费) → balance−, total_expenditure+, spend+
- // inputType=207(余额退费) → balance−, total_income−
- // 其余(101/104/105/201/204/205)→ balance−, total_expenditure+
- // 两条 UPDATE(校区 + 全局)+ log(money = **−inputMoney**)
- //
- // Go 的口径选择(**与 dump 的两处差异,均为设计 §3.1 #3 明确要求**):
- // - type 白名单校验:`101/104/105/200/201/204/205`(非法 → 2002)。dump 会把
- // `type<200 或 >299` **静默改成 200**,把"调用方传错类型"变成"记成历史扣费";
- // - dump 的 `type=207` 分支**不开放**给本方法(退费走 `Refund`/`CustomRefund`,
- // 否则同一语义有两条写入口,流水方向难以对账)。
- //
- // 入参:ctx / in。出参:*ExpenditureResult;错误码 2001/2002/3140/1004/5002。
- func (s *FundService) Expenditure(ctx context.Context, in ExpenditureInput) (*ExpenditureResult, error) {
- if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "Expenditure", true); err != nil {
- return nil, err
- }
- if err := validatePositiveAmount(in.Money, "Expenditure"); err != nil {
- return nil, err
- }
- if !isExpenditureType(in.Type) {
- return nil, infraerrors.WithCause(infraerrors.ErrBadFormat,
- errString("service: Expenditure 的 type 非法(白名单 101/104/105/200/201/204/205)"))
- }
- if s == nil || s.runner == nil || s.repo == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- remark := strings.TrimSpace(in.Remark)
- if remark == "" {
- remark = defaultExpenditureRemark
- }
- deltas := expenditureDeltas(in.Type, in.Money)
- var out ExpenditureResult
- err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
- txCtx := repository.WithTxContext(ctx, tx)
- hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, in.Type)
- if e != nil {
- return e
- }
- if hit != nil {
- bal, pe := balanceAfterOf(hit)
- if pe != nil {
- return pe
- }
- out = ExpenditureResult{LogID: hit.ID, Balance: bal, Repeated: true}
- return nil
- }
- if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
- return e
- }
- if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
- return e
- }
- if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
- UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
- }); e != nil {
- return e
- }
- if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "Expenditure", in.UserID,
- in.InstitutionID, in.CampusID, deltas...); e != nil {
- return e
- }
- // `balance_after` = 扣费后**全局账户余额**快照;响应体 Balance 仍是校区余额
- globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
- if e != nil {
- return e
- }
- bal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.InstitutionID, in.CampusID)
- if e != nil {
- return e
- }
- // dump:INSERT log(money = **−inputMoney**)
- lg := newExpenseLog(in.UserID, in.Type, in.Money.Neg(), in.RequestID, remark, in.OperatorID, &globalAfter)
- if e := s.insertLog(txCtx, tx, lg); e != nil {
- return e
- }
- out = ExpenditureResult{LogID: lg.ID, Balance: bal}
- return nil
- })
- if err != nil {
- return nil, s.mapIdempotentHit(err, func() error {
- return s.replayExpenditure(ctx, in, &out)
- })
- }
- return &out, nil
- }
- // expenditureDeltas 按 type 生成列增量(dump 三个分支的逐列对应,**顺序/方向不得改**)。
- //
- // 入参:typ 消费类型(已过白名单);amount 消费金额(>0)。
- // 出参:[]repository.ColumnDelta(balance 恒为 −amount)。
- func expenditureDeltas(typ int32, amount money.Amount) []repository.ColumnDelta {
- switch typ {
- case model.ExpenseLogTypeHistoryDeduct:
- // dump:`balance-`,`total_expenditure+`,`spend+`(历史扣费同时计入消费统计)
- return []repository.ColumnDelta{
- {Column: repository.ExpenseColumnBalance, Delta: amount.Neg()},
- {Column: repository.ExpenseColumnTotalExpenditure, Delta: amount},
- {Column: repository.ExpenseColumnSpend, Delta: amount},
- }
- default:
- // dump:`balance-`,`total_expenditure+`(报课学费 / 学校消费)
- return []repository.ColumnDelta{
- {Column: repository.ExpenseColumnBalance, Delta: amount.Neg()},
- {Column: repository.ExpenseColumnTotalExpenditure, Delta: amount},
- }
- }
- }
- // isExpenditureType 消费类型白名单(设计 §3.1 #3:101/104/105/200/201/204/205)。
- func isExpenditureType(typ int32) bool {
- switch typ {
- case model.ExpenseLogTypeCourseCampus, // 101
- model.ExpenseLogTypeCourseSchoolA, // 104
- model.ExpenseLogTypeCourseSchoolB, // 105
- model.ExpenseLogTypeHistoryDeduct, // 200
- model.ExpenseLogTypeCourseCampusB, // 201
- model.ExpenseLogTypeCourseSchoolC, // 204
- model.ExpenseLogTypeCourseSchoolD: // 205
- return true
- default:
- return false
- }
- }
- // ---------------------------------------------------------------- SP4 退费
- // Refund 余额退费(SP4 `sp_user_expense_school_refund`)。
- //
- // dump 语义(:764576):`IF inputMoney>0` 才动作(<=0 静默 no-op);
- // 校区账户已存在才 UPDATE(balance+, total_expenditure−);全局账户已存在才 UPDATE;
- // 任一更新成功才写 log(money = **+inputMoney**,type = inputType)。
- //
- // **BUG#2 修正(设计 §3.1 #4)**:dump 的定位条件是 `userid + campusid`,**没有 schoolid**——
- // 同一 campus_id 若在多机构复用(历史数据/跨库迁移期),会误更新别的机构的账户行。
- // Go 侧补 `institution_id` 参数并进 WHERE,定位三元组精确到 `(user, institution, campus)`。
- //
- // **R6(设计 §3.8-b)强化**:`money <= 0` → **2002**(与 recharge/expenditure/baddebt/transfer 五处统一)。
- // 与 dump 的差异是**有意偏离**:dump 对 <=0 是"静默不动作",前端会显示"成功但余额没变";
- // Go 显式拒绝。注:本处 dump 分支**不写流水**、不占幂等键,与另三处"归 0 仍写 0 元流水"不同,
- // 但对外统一成 2002 更不易被误用(前端不会把"没退钱"当成功)。
- //
- // 入参:ctx / in。出参:*RefundResult;
- // 错误码 2001/2002/3140/1004/3001/5002。
- func (s *FundService) Refund(ctx context.Context, in RefundInput) (*RefundResult, error) {
- if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "Refund", true); err != nil {
- return nil, err
- }
- if in.Type <= 0 {
- return nil, infraerrors.WithCause(infraerrors.ErrBadFormat, errString("service: Refund 需要 type"))
- }
- if !isKnownLogType(in.Type) {
- return nil, infraerrors.WithCause(infraerrors.ErrBadFormat,
- errString("service: Refund 的 type 不在流水类型白名单内"))
- }
- // R6:金额 <= 0 一律 2002(dump 是 `IF inputMoney>0` 静默跳过;Go 显式拒绝)
- if err := validatePositiveAmount(in.Money, "Refund"); err != nil {
- return nil, err
- }
- if s == nil || s.runner == nil || s.repo == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- remark := strings.TrimSpace(in.Remark)
- if remark == "" {
- remark = defaultRefundRemark
- }
- var out RefundResult
- err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
- txCtx := repository.WithTxContext(ctx, tx)
- hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, in.Type)
- if e != nil {
- return e
- }
- if hit != nil {
- bal, pe := balanceAfterOf(hit)
- if pe != nil {
- return pe
- }
- out = RefundResult{LogID: hit.ID, Balance: bal, Changed: true, Repeated: true}
- return nil
- }
- if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
- return e
- }
- // dump 不建户(account 不存在则什么都不做);Go 显式 3001,避免"调用成功但没退钱"
- if _, e := s.repo.GetCampusForUpdateExact(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
- return e
- }
- // dump:`balance+`,`total_expenditure-`
- if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "Refund", in.UserID,
- in.InstitutionID, in.CampusID,
- repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money},
- repository.ColumnDelta{Column: repository.ExpenseColumnTotalExpenditure, Delta: in.Money.Neg()},
- ); e != nil {
- return e
- }
- globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
- if e != nil {
- return e
- }
- bal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.InstitutionID, in.CampusID)
- if e != nil {
- return e
- }
- lg := newExpenseLog(in.UserID, in.Type, in.Money, in.RequestID, remark, in.OperatorID, &globalAfter)
- if e := s.insertLog(txCtx, tx, lg); e != nil {
- return e
- }
- out = RefundResult{LogID: lg.ID, Balance: bal, Changed: true}
- return nil
- })
- if err != nil {
- return nil, s.mapIdempotentHit(err, func() error {
- return s.replayRefund(ctx, in, &out)
- })
- }
- return &out, nil
- }
- // ---------------------------------------------------------------- SP5 可退金额(只读)
- // RefundableAmount 查询校区账户可退金额(SP5 `sp_user_expense_school_get_refundable_amount`,**只读**)。
- //
- // dump 语义(:764421,**三步修正,缺一不可**;dump 里的游标段整段被 `/* */` 注释掉,实际只生效下面的 SUM):
- //
- // ① 读 campusBalance(t_user_expense_school.balance)与 totalBalance(t_user_expense.balance);
- // 任一 <= 0(含 NULL/账户不存在)→ 0;
- // ② **截断**:`IF campusBalance > totalBalance THEN campusBalance = totalBalance`,
- // 截断后再早退一次(`campusBalance <= 0 → 0`,dump 真有这句,最易漏);
- // ③ **减已使用赠送额**(`t_user_balance_request × t_courses_activity_signed` 关联汇总,
- // 口径见 `BalanceRequestRepo.SumRechargeActivityUsedGift`):
- // refundable = campusBalance − usedGift,**下限 0**(SUM 为 NULL → 视作 0)。
- //
- // 两个**别复原**的陷阱(设计 §3.8-b 明确登记,评审逐处检查):
- // - 同一 SP 里还把 `SUM(activity_money)` 存进 `totalDiscountAmount`,但**全文再未引用**(死变量)
- // → **不得**据此加"赠送额上限/赠送额不可超余额"之类的额外约束;
- // - 那段按 `response_time DESC` 逐笔累加的游标(`DECLARE cur` / `OPEN` / 循环)**整段被注释掉**
- // → **不得**照注释补回逐笔逻辑,实际口径就是一条聚合 SUM。
- //
- // Go 的显式化(不改变资金结果,只把 dump 的静默分支显式化):
- // - 校区账户不存在 → (0, nil)(dump:ISNULL → 0);
- // - `campusBalance <= 0`(欠费)或 `totalBalance <= 0` → 0(dump 下负数参与减法后取 max(…,0) 亦为 0,
- // 这里提前返回是同结果的短路,避免把"欠费"当成"可退");
- // - 全局账户不存在 → 0(totalBalance 视为 0 → 截断后必为 0)。
- //
- // 只读且**无事务**:本方法不写任何表,故不开事务、也不加行锁(加锁只属于资金写路径,§10.3)。
- // 与之配套的调用纪律:可退额是"查询口径",**不得**用它做写路径的扣减基数——
- // 退费扣减基数由 `CustomRefund` 在事务内用加锁读的校区余额决定(§7.2 R2)。
- //
- // 与 SP9 的关系(**勿互相复用**):`custom_refund` **不调用**本方法,它内部的坏账基数是
- // **校区 `balance` 本身**;两者数值天然不同(本方法扣赠送额与全局截断,SP9 不扣不截)。
- //
- // 入参:ctx / userID / institutionID / campusID。
- // 出参:(可退金额, error);账户不存在 / 余额非正 → (0, nil);错误码 2001/3140/1004/5002。
- func (s *FundService) RefundableAmount(
- ctx context.Context, userID string, institutionID, campusID int64,
- ) (money.Amount, error) {
- if err := validateUserScope(userID, institutionID, campusID, "RefundableAmount", true); err != nil {
- return 0, err
- }
- if s == nil || s.repo == nil || s.requests == nil {
- return 0, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- if err := s.assertInScope(ctx, userID, institutionID, campusID); err != nil {
- return 0, err
- }
- // ① 校区余额(读不到 = 账户不存在 → 0,dump 的 ISNULL 分支)
- acc, err := s.repo.GetCampusAccount(ctx, nil, userID, institutionID, campusID)
- if err != nil {
- if errors.Is(err, infraerrors.ErrNotFound) {
- return 0, nil // dump:账户不存在 → 0
- }
- return 0, err
- }
- campusBalance, err := parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
- if err != nil {
- return 0, err
- }
- if campusBalance <= 0 {
- return 0, nil
- }
- // ② 全局余额(跨校区总余额;这是 dump 的"截断上界")
- global, err := s.repo.GetGlobalAccount(ctx, nil, userID)
- if err != nil {
- if errors.Is(err, infraerrors.ErrNotFound) {
- return 0, nil // totalBalance 视为 0 → 截断后必为 0
- }
- return 0, err
- }
- totalBalance, err := parseAccountAmount(global.Balance, "t_user_expense.balance")
- if err != nil {
- return 0, err
- }
- if totalBalance <= 0 {
- return 0, nil
- }
- // ③ **第一步修正**:校区余额按全局余额截断(dump:campusBalance > totalBalance → 取 totalBalance)
- if campusBalance > totalBalance {
- campusBalance = totalBalance
- }
- // ③-b 截断后再早退一次(dump 里真有这句,最容易被"省掉"):截断后仍非正 → 0,
- // 不要在非正基数上继续做减项(否则 -- 与 max(…,0) 的结果虽同,语义却把"欠费/脏数据"当成可退基数)。
- if campusBalance <= 0 {
- return 0, nil
- }
- // ④ **第二步修正**:扣掉已使用的充值赠送额(赠送额不可退)
- usedGift, err := s.requests.SumRechargeActivityUsedGift(ctx, userID, institutionID, campusID)
- if err != nil {
- return 0, err
- }
- refundable := campusBalance.Sub(usedGift)
- if refundable <= 0 {
- return 0, nil // dump:max(…, 0)
- }
- return refundable, nil
- }
- // ---------------------------------------------------------------- SP6 课费转结
- // Transfer 课费转结(SP6 `sp_user_expense_school_transfer_expenditure`)。
- //
- // dump 语义(:764661,★**与 P0-04 规格相反,以 dump 为准**,设计 §3.1 #6 / §10.2):
- //
- // IF inputMoney>0:
- // 源校区账户存在 →
- // 目标校区账户不存在则 INSERT;
- // UPDATE 源:total_expenditure−m, total_income−m
- // UPDATE 目标:total_expenditure+m, total_income+m
- // INSERT log(type=106, money=**+m**) ← 转结出
- // INSERT log(type=206, money=**−m**) ← 转结入
- //
- // **四个"不得改动"的点**:
- // 1. **不动 balance**(dump 全程没有 balance 赋值)——转结只调"总消费/总充值"两个统计口径;
- // 2. 106 记 **+m**、206 记 **−m**(与"出/入"的直觉相反,dump 原文如此,§11-6 #6);
- // 3. 两条流水的 `request_id` **相同**、`type` 不同 → 不撞 `uk_request_type`(唯一键含 type);
- // 4. 目标账户不存在时**建户**(dump 的 INSERT),源账户不存在时**不动**(dump 的 `IF campusLogid1>0`)。
- //
- // **两处 dump 既有事实(已核全文,**不得"顺手补齐"**)**:
- // - 转结**只更新两张校区表**的 `total_expenditure` / `total_income`,**完全不碰全局表**
- // (整段没有 `UPDATE t_user_expense`)⇒ 全局的 `total_*` 与"各校区之和"**本来就不相等**,
- // 这是旧库既有口径,谁去"补齐全局"谁就把双跑对账搞乱;
- // - 转出/转入账户定位**只按 `userid + campusid`、没有 schoolid** ⇒ 同一 campus_id 在多机构复用时
- // 会误命中别家账户(BUG#2 同源)⇒ Go 一律按 `(user, institution, campus)` 三元组定位。
- //
- // 边界码(§3.8 R4 / R4-bis):
- //
- // refund 校区账户缺失 / refund 全局账户缺失 → **3001**(dump 只更单边 + 照写流水 = 双表撕裂)
- // transfer 转出方(源)账户缺失 → **3001**(dump `IF campusLogid1>0` 包整笔 → 静默 no-op)
- // transfer 转入方(目标)账户缺失 → **建户**(正常路径,见 `resolveTargetInstitution` 的 R4-bis)
- // transfer 转入校区查不到 / 未归属机构 → **3104**
- // transfer 入参机构 ≠ 校区归属机构 → **3140**(不建户、不落行,防机构错配僵尸户)
- // 同校区自转(净效应为零) → **3140**
- //
- // 入参:ctx / in。出参:*TransferResult{logId106,logId206};错误码 2001/2002/3104/3140/1004/3001/5002。
- func (s *FundService) Transfer(ctx context.Context, in TransferInput) (*TransferResult, error) {
- if err := validateUserScope(in.UserID, in.FromInstitutionID, in.FromCampusID, "Transfer(from)", true); err != nil {
- return nil, err
- }
- if err := validateUserScope(in.UserID, in.ToInstitutionID, in.ToCampusID, "Transfer(to)", true); err != nil {
- return nil, err
- }
- if err := validatePositiveAmount(in.Money, "Transfer"); err != nil {
- return nil, err
- }
- if in.FromInstitutionID == in.ToInstitutionID && in.FromCampusID == in.ToCampusID {
- return nil, infraerrors.WithCause(apperr.ErrBusinessParam,
- errString("service: Transfer 的转出与转入校区不能相同"))
- }
- if s == nil || s.runner == nil || s.repo == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- var out TransferResult
- err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
- txCtx := repository.WithTxContext(ctx, tx)
- // ① 幂等预检:106 是"转结出"主流水(必然存在),用它做命中判定
- hit106, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeTransferOut)
- if e != nil {
- return e
- }
- if hit106 != nil {
- out = TransferResult{LogID106: hit106.ID, Repeated: true}
- if bal, pe := balanceAfterOf(hit106); pe == nil {
- out.FromBalance = bal
- }
- hit206, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeTransferIn)
- if e != nil {
- return e
- }
- if hit206 != nil {
- out.LogID206 = hit206.ID
- if bal, pe := balanceAfterOf(hit206); pe == nil {
- out.ToBalance = bal
- }
- }
- return nil
- }
- // ② 作用域断言(两侧机构都必须可见)
- if e := s.assertInScope(txCtx, in.UserID, in.FromInstitutionID, in.FromCampusID); e != nil {
- return e
- }
- if in.ToInstitutionID != in.FromInstitutionID {
- if e := s.assertInScope(txCtx, in.UserID, in.ToInstitutionID, in.ToCampusID); e != nil {
- return e
- }
- }
- // ③ 加锁:两个校区账户**按 campus_id ASC 排序**后依次加锁(§1.4 多账户场景防死锁)
- refs := []campusRef{
- {InstitutionID: in.FromInstitutionID, CampusID: in.FromCampusID},
- {InstitutionID: in.ToInstitutionID, CampusID: in.ToCampusID},
- }
- sort.Slice(refs, func(i, j int) bool { return refs[i].CampusID < refs[j].CampusID })
- locked := make(map[campusRef]bool, len(refs))
- for _, ref := range refs {
- _, le := s.repo.GetCampusForUpdateExact(txCtx, tx, in.UserID, ref.InstitutionID, ref.CampusID)
- if le != nil {
- if errors.Is(le, infraerrors.ErrNotFound) {
- locked[ref] = false
- continue
- }
- return le
- }
- locked[ref] = true
- }
- fromRef := campusRef{InstitutionID: in.FromInstitutionID, CampusID: in.FromCampusID}
- toRef := campusRef{InstitutionID: in.ToInstitutionID, CampusID: in.ToCampusID}
- if !locked[fromRef] {
- // dump:源账户不存在 → `IF campusLogid1>0` 不成立 → 静默什么都不做
- return infraerrors.WithCause(infraerrors.ErrNotFound,
- errString("service: Transfer 转出校区账户不存在"))
- }
- if !locked[toRef] {
- // dump:目标账户不存在 → **INSERT 建户**(R4 ④:建户是**正常路径**,不是 3001——
- // 转结的语义就是"把钱挪到还没有账户的校区",改成 3001 会让首次跨校区转结全部失败)。
- //
- // **R4-bis(§3.8-R4-bis / §5.7 #18b、#19b)**:dump 建户用的是入参 `inputSchoolid2`,
- // 入参校区与机构不匹配时会建出**机构错配的僵尸户**;而 UK(user,institution,campus)
- // 一旦机构写错,后续按正确机构查不到 → 再建第二个 → 同校区双账户 → 差值冻结直接破。
- // 故建户的机构**只认校区表的权威值**,不用入参:
- // ① inst := 校区表里的 institution_id(同事务只读) ② 取不到 → 3104
- // ③ 入参 toInstitutionId ≠ inst → 3140(不建户、不落任何行) ④ 用 inst 建户
- // 正常数据下 ②③ 恒不触发(两值相同),只在非法入参时拒绝。
- inst, ie := s.resolveTargetInstitution(txCtx, tx, in.ToCampusID, in.ToInstitutionID)
- if ie != nil {
- return ie
- }
- if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
- UserID: in.UserID, InstitutionID: inst, CampusID: in.ToCampusID,
- }); e != nil {
- return e
- }
- }
- // ④ 4 次 UPDATE → 2 条语句(每表两列),**balance 一律不动**
- if _, e := s.repo.AddCampusColumns(txCtx, tx, "Transfer(out)", in.UserID,
- in.FromInstitutionID, in.FromCampusID,
- repository.ColumnDelta{Column: repository.ExpenseColumnTotalExpenditure, Delta: in.Money.Neg()},
- repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money.Neg()},
- ); e != nil {
- return e
- }
- if _, e := s.repo.AddCampusColumns(txCtx, tx, "Transfer(in)", in.UserID,
- in.ToInstitutionID, in.ToCampusID,
- repository.ColumnDelta{Column: repository.ExpenseColumnTotalExpenditure, Delta: in.Money},
- repository.ColumnDelta{Column: repository.ExpenseColumnTotalIncome, Delta: in.Money},
- ); e != nil {
- return e
- }
- // ⑤ 两条流水(106 在前、206 在后;方向 ★dump 口径)
- //
- // `balance_after` 口径(§3.8-f ②-bis):转结**不动 balance**,故 106 与 206 **写同一个全局快照**;
- // 响应体的 FromBalance / ToBalance 才是两个校区各自的余额(两列语义不同,勿混用)。
- globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
- if e != nil {
- return e
- }
- fromBal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.FromInstitutionID, in.FromCampusID)
- if e != nil {
- return e
- }
- toBal, e := campusBalanceAfter(txCtx, s.repo, tx, in.UserID, in.ToInstitutionID, in.ToCampusID)
- if e != nil {
- return e
- }
- lg106 := newExpenseLog(in.UserID, model.ExpenseLogTypeTransferOut, in.Money,
- in.RequestID, in.Remark, in.OperatorID, &globalAfter)
- if e := s.insertLog(txCtx, tx, lg106); e != nil {
- return e
- }
- lg206 := newExpenseLog(in.UserID, model.ExpenseLogTypeTransferIn, in.Money.Neg(),
- in.RequestID, in.Remark, in.OperatorID, &globalAfter)
- if e := s.insertLog(txCtx, tx, lg206); e != nil {
- return e
- }
- out = TransferResult{
- LogID106: lg106.ID, LogID206: lg206.ID,
- FromBalance: fromBal, ToBalance: toBal,
- }
- return nil
- })
- if err != nil {
- return nil, s.mapIdempotentHit(err, func() error {
- return s.replayTransfer(ctx, in, &out)
- })
- }
- return &out, nil
- }
- // campusRef 校区账户定位三元组的"机构 + 校区"部分(转结加锁排序用)。
- type campusRef struct {
- // InstitutionID 机构 ID。
- InstitutionID int64
- // CampusID 校区 ID。
- CampusID int64
- }
- // resolveTargetInstitution 解析转结**转入方**的权威机构 ID(R4-bis 的三道校验)。
- //
- // 入参:
- // - ctx 请求上下文(含 tx);
- // - tx 事务句柄(**必传**:与本次资金事务同一快照,禁止走连接池读到旧值);
- // - campusID 转入校区(>0,已由 validateUserScope 校验);
- // - inputInstitutionID 调用方声明的转入机构。
- //
- // 出参:
- // - int64:**权威**机构 ID(= t_campus.institution_id),调用方必须用它建户;
- // - 3104(校区不存在 / 校区未归属机构)/ 3140(入参与权威值矛盾)/ 5002。
- //
- // 为什么必须校验(§3.8-R4-bis):dump 建户用入参机构,入参错就会建出机构错配的僵尸账户,
- // 之后按正确机构再也查不到它 → 同校区出现两个账户 → "差值冻结"恒等式破。
- // 正常调用方两值一致,本校验零影响;只有入参矛盾时才拒绝(比"按解析值静默建户"安全:
- // 后者管理员看不到任何提示,事故后极难归因)。
- func (s *FundService) resolveTargetInstitution(
- ctx context.Context, tx *gorm.DB, campusID, inputInstitutionID int64,
- ) (int64, error) {
- if s == nil || s.campus == nil {
- return 0, infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: 未注入 port.CampusReader(无法解析转入校区机构)"))
- }
- info, err := s.readCampusInfo(ctx, tx, campusID)
- if err != nil {
- return 0, err
- }
- if info == nil || info.SchoolID <= 0 {
- return 0, infraerrors.WithCause(apperr.ErrCampusNotFound,
- errString("service: Transfer 转入校区未归属机构,拒绝建户"))
- }
- if inputInstitutionID != info.SchoolID {
- return 0, infraerrors.WithCause(apperr.ErrBusinessParam,
- errString("service: Transfer 的转入机构与校区归属机构不一致(拒绝建户,防僵尸账户)"))
- }
- return info.SchoolID, nil
- }
- // readCampusInfo 同事务读校区(优先 TxCampusReader,退化到连接池版 CampusReader)。
- //
- // 入参:ctx / tx / campusID(>0)。出参:*port.CampusInfo;3104(校区不存在)/ 5002。
- func (s *FundService) readCampusInfo(ctx context.Context, tx *gorm.DB, campusID int64) (*port.CampusInfo, error) {
- if s == nil || s.campus == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: 未注入 port.CampusReader(无法判定校区归属)"))
- }
- if txReader, ok := s.campus.(port.TxCampusReader); ok {
- return txReader.GetByIDTx(ctx, tx, campusID)
- }
- return s.campus.GetByID(ctx, campusID)
- }
- // ---------------------------------------------------------------- SP7 坏账
- // BadDebt 坏账处理(SP7 `sp_user_expense_baddebt`)。
- //
- // dump 语义(:763890,SP 头注释即「用户坏账处理(余额+,特殊费用+)」,**双加**):
- //
- // UPDATE t_user_expense_school SET balance = balance + inputMoney,
- // special_expenses = special_expenses + inputMoney
- // WHERE userid AND schoolid AND campusid;
- // UPDATE t_user_expense SET balance = balance + inputMoney,
- // special_expenses = special_expenses + inputMoney
- // WHERE userid;
- // INSERT t_user_expense_log(..., type = 108, money = +inputMoney, ...);
- //
- // 即:**全局 + 校区都同时加 `balance` 与 `special_expenses`**(两列同增,金额相同),
- // 流水 type=108、money=+Money。Go 侧严格照做(不做"只统计特殊费用"的收敛)。
- //
- // ★ type=108 的**两种来源**(对账/恒等式判别的唯一依据,AC-17 ④ 按此落地):
- //
- // ① **独立坏账**(本 SP):`balance += m` **且** `special_expenses += m`,108.money = +m;
- // —— 108 上记的 +m **真实对应余额增加**,**参与**"balance 增量 = Σ流水"的归因。
- // ② **退费差额**(`RefundService.CustomRefund` 的 `requested > 可退` 分支):
- // 只 `special_expenses += m`(余额净减 = refunded),108.money = +badDebt,
- // 而同一请求的 207.money = **−requested(全额)**——坏账部分已含在 207 里;
- // —— 该 108 **不再构成一次独立的余额增加**,**不参与**"108 → balance 增量"的归因
- // (否则会与 207 重复计入)。
- //
- // **判别式(唯一、可机械执行,设计 §3.8-b (f) A18)**:取该 108 流水的 `logid`
- // (= `request_id`,`newExpenseLog` 对两者写同一值)——
- // **同 `logid` 存在 type=207 且 `logid <> ''`(非 NULL/空)= 差额型(②)**;
- // **不存在(含 logid 为空)= 独立坏账(①)**。可直接落地的判定 SQL(AC-17 ④ 可照抄):
- //
- // SELECT l.id, l.money,
- // (l.log_id IS NOT NULL AND l.log_id <> ''
- // AND EXISTS (SELECT 1 FROM t_user_expense_log r
- // WHERE r.user_id = l.user_id AND r.type = 207 AND r.log_id = l.log_id)) AS differential
- // FROM t_user_expense_log l
- // WHERE l.user_id = ? AND l.type = 108;
- //
- // · 两条来源都存在时,"balance = Σ全部流水" 仍恒成立(②里 108 与 207 的代数和恰为净扣减
- // −(requested−badDebt) = −refunded),但"逐条 108 是否代表一次余额增加"必须用上面的判别式区分;
- // **禁止**用一条 `SUM(money) WHERE type=108` 把两种语义混算。
- //
- // 幂等:`request_id + type(108)` 唯一键;无 requestId 时不享幂等(dump 同口径)。
- //
- // 入参:ctx / in。出参:*BadDebtResult;错误码 2001/2002/3140/1004/5002。
- func (s *FundService) BadDebt(ctx context.Context, in BadDebtInput) (*BadDebtResult, error) {
- if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "BadDebt", true); err != nil {
- return nil, err
- }
- if err := validatePositiveAmount(in.Money, "BadDebt"); err != nil {
- return nil, err
- }
- if s == nil || s.runner == nil || s.repo == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- remark := strings.TrimSpace(in.Remark)
- if remark == "" {
- remark = defaultBadDebtRemark
- }
- var out BadDebtResult
- err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
- txCtx := repository.WithTxContext(ctx, tx)
- hit, e := s.repo.FindLogByRequest(txCtx, tx, in.UserID, in.RequestID, model.ExpenseLogTypeBadDebt)
- if e != nil {
- return e
- }
- if hit != nil {
- out = BadDebtResult{LogID: hit.ID, Repeated: true}
- if acc, ae := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID); ae == nil {
- if spec, pe := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses"); pe == nil {
- out.SpecialExpenses = spec
- }
- if bal, pe := parseAccountAmount(acc.Balance, "t_user_expense_school.balance"); pe == nil {
- out.Balance = bal
- }
- }
- return nil
- }
- if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
- return e
- }
- if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
- return e
- }
- if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
- UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
- }); e != nil {
- return e
- }
- // dump:两条 UPDATE 都是 `balance + inputMoney, special_expenses + inputMoney` → **双加**
- if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "BadDebt", in.UserID,
- in.InstitutionID, in.CampusID,
- repository.ColumnDelta{Column: repository.ExpenseColumnBalance, Delta: in.Money},
- repository.ColumnDelta{Column: repository.ExpenseColumnSpecialExpenses, Delta: in.Money},
- ); e != nil {
- return e
- }
- acc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
- if e != nil {
- return e
- }
- bal, e := parseAccountAmount(acc.Balance, "t_user_expense_school.balance")
- if e != nil {
- return e
- }
- spec, e := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses")
- if e != nil {
- return e
- }
- // `balance_after` = 坏账后**全局账户余额**快照(响应体 Balance 是校区余额,两者此时数值相同但口径不同)
- globalAfter, e := globalBalanceAfter(txCtx, s.repo, tx, in.UserID)
- if e != nil {
- return e
- }
- lg := newExpenseLog(in.UserID, model.ExpenseLogTypeBadDebt, in.Money,
- in.RequestID, remark, in.OperatorID, &globalAfter)
- if e := s.insertLog(txCtx, tx, lg); e != nil {
- return e
- }
- out = BadDebtResult{LogID: lg.ID, SpecialExpenses: spec, Balance: bal}
- return nil
- })
- if err != nil {
- return nil, s.mapIdempotentHit(err, func() error {
- return s.replayBadDebt(ctx, in, &out)
- })
- }
- return &out, nil
- }
- // ---------------------------------------------------------------- SP11 累计消费(spend)
- // AccumulateSpend 累计消费金额(SP11 `sp_user_expense_school_spend`)。
- //
- // 口径(设计 §3.1 #11):**只更新 `spend`,不动 `balance`**;无流水(dump 不写 log)。
- //
- // **BUG#1 修正**:dump 的全局分支 `INSERT INTO t_user_expense(userid, spend) VALUES(inputUserid,
- // inputMoney, inputSpendMoney)` 是 **3 个值对 2 列**(且 inputMoney 在该 SP 里根本未声明)→ 必报错。
- // Go 修正为"UPSERT 建户 + `spend = spend + ?`",列数与列名对齐 DDL。
- //
- // 负值处理:dump 仅在 **INSERT 分支**把负数归 0(UPDATE 分支会照减);本实现统一归 0
- // (`spend` 是"只增"的统计口径列,model 注释亦如此约定),并回显当前值。
- //
- // 幂等:dump 的 SP11 **没有请求号**(签名只有 4 参),因此本方法不参与 `uk_request_type` 幂等;
- // 重复调用会重复累加 `spend`——这是 dump 的既有语义(调用方为"结束上课"链路,每次课一条),
- // 不做"按 requestId 去重"的加法,以免与 dump 的双跑口径分叉。
- //
- // 入参:ctx / in。出参:*SpendResult{spend};错误码 2001/3140/5002。
- func (s *FundService) AccumulateSpend(ctx context.Context, in SpendInput) (*SpendResult, error) {
- if err := validateUserScope(in.UserID, in.InstitutionID, in.CampusID, "AccumulateSpend", true); err != nil {
- return nil, err
- }
- if err := in.SpendMoney.Validate(); err != nil {
- return nil, infraerrors.WithCause(infraerrors.ErrBadFormat, err)
- }
- if in.SpendMoney < 0 {
- in.SpendMoney = 0 // dump INSERT 分支:负数归 0(spend 只增)
- }
- if s == nil || s.runner == nil || s.repo == nil {
- return nil, infraerrors.WithCause(infraerrors.ErrInternal, errString("service: FundService 未装配"))
- }
- var out SpendResult
- err := s.runner.WithinTx(ctx, func(tx *gorm.DB) error {
- txCtx := repository.WithTxContext(ctx, tx)
- if e := s.assertInScope(txCtx, in.UserID, in.InstitutionID, in.CampusID); e != nil {
- return e
- }
- if e := s.repo.UpsertGlobal(txCtx, tx, &model.UserExpense{UserID: in.UserID}); e != nil {
- return e
- }
- if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
- UserID: in.UserID, InstitutionID: in.InstitutionID, CampusID: in.CampusID,
- }); e != nil {
- return e
- }
- if !in.SpendMoney.IsZero() {
- if _, e := s.repo.AddColumnsGlobalThenCampus(txCtx, tx, "AccumulateSpend", in.UserID,
- in.InstitutionID, in.CampusID,
- repository.ColumnDelta{Column: repository.ExpenseColumnSpend, Delta: in.SpendMoney},
- ); e != nil {
- return e
- }
- }
- acc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.InstitutionID, in.CampusID)
- if e != nil {
- return e
- }
- spend, e := parseAccountAmount(acc.Spend, "t_user_expense_school.spend")
- if e != nil {
- return e
- }
- out = SpendResult{Spend: spend}
- return nil
- })
- if err != nil {
- return nil, err
- }
- return &out, nil
- }
- // ---------------------------------------------------------------- 幂等公共形状
- // insertLog 写流水并把"撞 uk_request_type"翻译成内部幂等哨兵(`apperr.ErrRepeated`)。
- //
- // 入参:txCtx(含 tx 的 ctx)/ tx / lg 流水行。
- // 出参:nil 成功;apperr.ErrRepeated(**并发幂等命中**,调用方据此回放首次结果);
- // 其余错误原样上抛(ErrBadParam/ErrDBError)。
- //
- // 为什么用 ErrRepeated 作为事务内哨兵:它是 *AppError,`TxRunner.wrapTxErr` 会原样透传
- // (不降级成 5002),且它是设计里"仅内部日志用"的码(§10.1),不会泄漏给前端。
- func (s *FundService) insertLog(txCtx context.Context, tx *gorm.DB, lg *model.UserExpenseLog) error {
- err := s.repo.InsertLog(txCtx, tx, lg)
- if err == nil {
- return nil
- }
- if errors.Is(err, repository.ErrDuplicateLog) {
- return apperr.ErrRepeated
- }
- return err
- }
- // mapIdempotentHit 把"并发幂等命中"从错误路径转成"回放首次结果"的成功路径。
- //
- // 入参:
- // - err:WithinTx 返回的错误;
- // - replay:回放函数(重新查询首次流水并填充 out)。
- //
- // 出参:nil(回放成功)/ 回放错误 / 原错误(非幂等命中)。
- //
- // 语义(§1.5):`uk_request_type` 撞键 = 同一请求号 + 同一 type 的第二次写入,
- // **不是错误**(code 仍 200,data.repeated=true)。实现上先整笔回滚(本次零残留),再回放。
- func (s *FundService) mapIdempotentHit(err error, replay func() error) error {
- if err == nil {
- return nil
- }
- if errors.Is(err, apperr.ErrRepeated) {
- return replay()
- }
- return err
- }
- // balanceAfterOf 从流水行取 balance_after 快照(NULL → 0)。
- //
- // ⚠ 口径提醒:`balance_after` 自 v0.1.16 起是「该操作完成后**全局账户**余额」(§3.8-f ②-bis),
- // 而各 `Result.Balance` 的契约是**校区**余额 —— 因此**响应体不得再用本函数填充**(会串口径),
- // 回放一律走 `campusBalanceAfter` 读当前校区账户。本函数仅保留给"确实要读全局快照"的对账/排障用途。
- //
- // 入参:lg 流水行(可 nil)。出参:(金额, error);balance_after 为 NULL 时返回 0 且无错
- // (历史行没有快照列,调用方需能接受 0)。
- func balanceAfterOf(lg *model.UserExpenseLog) (money.Amount, error) {
- if lg == nil || lg.BalanceAfter == nil {
- return 0, nil
- }
- return parseAccountAmount(*lg.BalanceAfter, "t_user_expense_log.balance_after")
- }
- // replayRecharge 幂等回放(充值)。
- func (s *FundService) replayRecharge(ctx context.Context, in RechargeInput, out *RechargeResult) error {
- hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, in.Type)
- if err != nil {
- return err
- }
- if hit == nil {
- return infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: Recharge 幂等命中但首次流水已不可见"))
- }
- // 响应体 Balance 是**校区**余额(与流水的 balance_after 全局口径不同),回放按当前校区账户取值
- bal, err := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.InstitutionID, in.CampusID)
- if err != nil {
- return err
- }
- *out = RechargeResult{LogID: hit.ID, Balance: bal, Repeated: true}
- return nil
- }
- // replayExpenditure 幂等回放(消费)。
- func (s *FundService) replayExpenditure(ctx context.Context, in ExpenditureInput, out *ExpenditureResult) error {
- hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, in.Type)
- if err != nil {
- return err
- }
- if hit == nil {
- return infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: Expenditure 幂等命中但首次流水已不可见"))
- }
- // 响应体 Balance 是**校区**余额(与流水的 balance_after 全局口径不同),回放按当前校区账户取值
- bal, err := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.InstitutionID, in.CampusID)
- if err != nil {
- return err
- }
- *out = ExpenditureResult{LogID: hit.ID, Balance: bal, Repeated: true}
- return nil
- }
- // replayRefund 幂等回放(退费)。
- func (s *FundService) replayRefund(ctx context.Context, in RefundInput, out *RefundResult) error {
- hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, in.Type)
- if err != nil {
- return err
- }
- if hit == nil {
- return infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: Refund 幂等命中但首次流水已不可见"))
- }
- // 响应体 Balance 是**校区**余额(与流水的 balance_after 全局口径不同),回放按当前校区账户取值
- bal, err := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.InstitutionID, in.CampusID)
- if err != nil {
- return err
- }
- *out = RefundResult{LogID: hit.ID, Balance: bal, Changed: true, Repeated: true}
- return nil
- }
- // replayBadDebt 幂等回放(坏账)。
- func (s *FundService) replayBadDebt(ctx context.Context, in BadDebtInput, out *BadDebtResult) error {
- hit, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeBadDebt)
- if err != nil {
- return err
- }
- if hit == nil {
- return infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: BadDebt 幂等命中但首次流水已不可见"))
- }
- var spec, bal money.Amount
- if acc, ae := s.repo.GetCampusAccount(ctx, nil, in.UserID, in.InstitutionID, in.CampusID); ae == nil {
- if v, pe := parseAccountAmount(acc.SpecialExpenses, "t_user_expense_school.special_expenses"); pe == nil {
- spec = v
- }
- if v, pe := parseAccountAmount(acc.Balance, "t_user_expense_school.balance"); pe == nil {
- bal = v
- }
- }
- *out = BadDebtResult{LogID: hit.ID, SpecialExpenses: spec, Balance: bal, Repeated: true}
- return nil
- }
- // replayTransfer 幂等回放(转结)。
- func (s *FundService) replayTransfer(ctx context.Context, in TransferInput, out *TransferResult) error {
- hit106, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeTransferOut)
- if err != nil {
- return err
- }
- if hit106 == nil {
- return infraerrors.WithCause(infraerrors.ErrInternal,
- errString("service: Transfer 幂等命中但首次流水已不可见"))
- }
- // FromBalance / ToBalance 是两个**校区**各自余额(流水 balance_after 是全局口径,不能拿来充两个值)
- res := TransferResult{LogID106: hit106.ID, Repeated: true}
- if bal, pe := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.FromInstitutionID, in.FromCampusID); pe == nil {
- res.FromBalance = bal
- }
- hit206, err := s.repo.FindLogByRequest(ctx, nil, in.UserID, in.RequestID, model.ExpenseLogTypeTransferIn)
- if err != nil {
- return err
- }
- if hit206 != nil {
- res.LogID206 = hit206.ID
- if bal, pe := campusBalanceAfter(ctx, s.repo, nil, in.UserID, in.ToInstitutionID, in.ToCampusID); pe == nil {
- res.ToBalance = bal
- }
- }
- *out = res
- return nil
- }
- // isKnownLogType 流水类型白名单(`model.ExpenseLogType*` 全集,§10.2)。
- //
- // 用途:`Refund` 的 type 来自调用方(dump 透传),必须落在已知编码内,
- // 否则会污染流水表并让"按 type 汇总"的对账口径失效。
- func isKnownLogType(typ int32) bool {
- switch typ {
- case model.ExpenseLogTypeRecharge,
- model.ExpenseLogTypeCourseCampus,
- model.ExpenseLogTypeCourseSchoolA,
- model.ExpenseLogTypeCourseSchoolB,
- model.ExpenseLogTypeTransferOut,
- model.ExpenseLogTypeRecommend,
- model.ExpenseLogTypeBadDebt,
- model.ExpenseLogTypeHistoryDeduct,
- model.ExpenseLogTypeCourseCampusB,
- model.ExpenseLogTypeCourseSchoolC,
- model.ExpenseLogTypeCourseSchoolD,
- model.ExpenseLogTypeTransferIn,
- model.ExpenseLogTypeRefund,
- model.ExpenseLogTypeClearBalance,
- model.ExpenseLogTypeCancelRechargeAct:
- return true
- default:
- return false
- }
- }
|