| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400 |
- // 余额核心服务(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,事务内透传);
- // - member:成员关系校验器(可 nil:系统任务/割接脚本模式不做对象级越权断言)。
- type FundService struct {
- repo *repository.ExpenseRepo
- requests *repository.BalanceRequestRepo
- runner *repository.TxRunner
- member port.MembershipChecker
- }
- // NewFundService 构造余额核心服务(repo 与 runner 绑定同一 DB 句柄,避免跨连接池事务失效)。
- //
- // 入参:
- // - db *gorm.DB:数据库句柄(必填);
- // - sc *appscope.Scope:本次请求作用域(校区账户读写必需;系统任务可 nil,
- // 此时**只能**调用全局/流水方法,触达校区账户会 panic fail-fast);
- // - member port.MembershipChecker:成员校验器(可 nil)。
- //
- // 出参:*FundService。
- 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),
- member: member,
- }
- }
- // ---------------------------------------------------------------- 入参 / 出参
- // 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:money<=0 由 R6 在入口拒为 2002(不再有 no-op 分支),
- // 幂等命中用 Repeated 表达(字段保留是为兼容既有响应契约,不再有 false 的业务分支)。
- 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
- }
- // 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 = 不写快照)。
- // 出参:*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 = 充值后校区余额快照,供对账/双跑逐字段比对)
- 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
- }
- lg := newExpenseLog(in.UserID, in.Type, in.Money, in.RequestID, remark, in.OperatorID, &bal)
- 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
- }
- 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
- }
- // dump:INSERT log(money = **−inputMoney**)
- lg := newExpenseLog(in.UserID, in.Type, in.Money.Neg(), in.RequestID, remark, in.OperatorID, &bal)
- 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
- }
- 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
- }
- lg := newExpenseLog(in.UserID, in.Type, in.Money, in.RequestID, remark, in.OperatorID, &bal)
- 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`)。
- //
- // Go 的两处显式化:源账户不存在 → 3001(不静默);同校区自转 → 3140(净效应为零的无意义操作)。
- //
- // 入参:ctx / in。出参:*TransferResult{logId106,logId206};错误码 2001/2002/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 建户
- if e := s.repo.UpsertCampus(txCtx, tx, &model.UserExpenseSchool{
- UserID: in.UserID, InstitutionID: in.ToInstitutionID, 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 口径)
- fromAcc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.FromInstitutionID, in.FromCampusID)
- if e != nil {
- return e
- }
- fromBal, e := parseAccountAmount(fromAcc.Balance, "t_user_expense_school.balance")
- if e != nil {
- return e
- }
- toAcc, e := s.repo.GetCampusAccount(txCtx, tx, in.UserID, in.ToInstitutionID, in.ToCampusID)
- if e != nil {
- return e
- }
- toBal, e := parseAccountAmount(toAcc.Balance, "t_user_expense_school.balance")
- if e != nil {
- return e
- }
- lg106 := newExpenseLog(in.UserID, model.ExpenseLogTypeTransferOut, in.Money,
- in.RequestID, in.Remark, in.OperatorID, &fromBal)
- 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, &toBal)
- 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
- }
- // ---------------------------------------------------------------- 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
- }
- lg := newExpenseLog(in.UserID, model.ExpenseLogTypeBadDebt, in.Money,
- in.RequestID, remark, in.OperatorID, &bal)
- 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,幂等回放用)。
- //
- // 入参:lg 流水行(可 nil)。出参:(金额, error);balance_after 为 NULL 时返回 0 且无错
- // (历史行没有快照列,回放时余额字段退化为 0 并保持 repeated=true)。
- 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 幂等命中但首次流水已不可见"))
- }
- bal, err := balanceAfterOf(hit)
- 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 幂等命中但首次流水已不可见"))
- }
- bal, err := balanceAfterOf(hit)
- 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 幂等命中但首次流水已不可见"))
- }
- bal, err := balanceAfterOf(hit)
- 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 幂等命中但首次流水已不可见"))
- }
- res := TransferResult{LogID106: hit106.ID, Repeated: true}
- if bal, pe := balanceAfterOf(hit106); 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 := balanceAfterOf(hit206); 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
- }
- }
|