Files
junhong_cmp_fiber/internal/service/commission_withdrawal/service.go
break 62419d4b17
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 13m40s
feat(导出时间筛选): AUG26-014 统一时间筛选与临期导出,归档并同步主 Spec 与证据链
统一时间筛选:新增共享严格解析器 pkg/utils/time_range.go,只接受带显式时区的 RFC3339 秒级时间(拒绝小数秒、无时区、date-only、空格分隔、±hhmm、未补零、非法日期与越界偏移),闭区间含两端、归一为 UTC 瞬时,创建期与执行期共用同一份实现。

端点改造(13 个入口):IoT 卡导入任务、设备导入任务、导出任务列表、订单列表参数名不变仅收紧解析;换货、分配记录、代理充值、临期列表改名 start_time/end_time(旧参数名显式拒绝);提现记录两处删除解析失败静默跳过,非法参数一律 1001;授权记录由起始闭结束开改为闭区间含两端;临期列表改按当前生效主套餐最终到期时刻比较,保留剩余天数上下限与既有粗放窗口。

临期导出新建:新场景 expiring_asset 与受控入口 POST /api/admin/expiring-assets/export,复用列表候选预筛与最终到期推算,一行一资产、加油包不单独成行,列序与 111 §18.1 逐列一致,店铺/业务员/用户组按执行时当前归属补充且不超出创建时冻结范围。

佣金明细导出新增按创建时间闭区间筛选(原佣金与回溯两条分支各自创建时间列),记录粒度、列定义与余额口径不变。

冻结与遗留任务:创建期把筛选与时间边界规范化为 UTC RFC3339 秒级串写入既有 query_json,无新列无迁移;执行期只按冻结值严格解析,非法冻结值在任何分片与文件动作前落任务失败并写安全摘要,不放行全量;重试沿用原快照。达量预警导出执行期同样纳入严格解析(其入口契约、列定义与触发快照口径不变)。

归档 add-export-time-filter-standards 并新建主 Spec openspec/specs/export-time-filter/spec.md,同步 requirement-evidence.json 与入口能力矩阵,README 导出场景清单更新为 11 个场景。

验证:junhong_cmp_test + 本地隔离 Redis(DB7,测试部署共享队列 DB6 未被占用)实跑 85 PASS / 0 FAIL(接受/拒绝集合、区间与顺序语义、列表与导出同筛选行集一致、代理 HTTP 全链路与范围冻结、遗留旧格式任务安全失败、列与余额口径回归、表头逐字),门禁 gofmt/go build/gendocs 两次一致/openspec validate/doctor/context-health 全绿;无 Schema 变更、无迁移、无运行时开关。
2026-09-17 18:37:02 +08:00

435 lines
14 KiB
Go

package commission_withdrawal
import (
"context"
"encoding/json"
"time"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
"github.com/break/junhong_cmp_fiber/internal/store"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"gorm.io/gorm"
)
type Service struct {
db *gorm.DB
shopStore *postgres.ShopStore
accountStore *postgres.AccountStore
agentWalletStore *postgres.AgentWalletStore
agentWalletTransactionStore *postgres.AgentWalletTransactionStore
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore
auditWriter *audit.Writer
}
// SetAuditWriter 注入佣金提现审批统一审计 Writer。
func (s *Service) SetAuditWriter(writer *audit.Writer) {
s.auditWriter = writer
}
func New(
db *gorm.DB,
shopStore *postgres.ShopStore,
accountStore *postgres.AccountStore,
agentWalletStore *postgres.AgentWalletStore,
agentWalletTransactionStore *postgres.AgentWalletTransactionStore,
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore,
) *Service {
return &Service{
db: db,
shopStore: shopStore,
accountStore: accountStore,
agentWalletStore: agentWalletStore,
agentWalletTransactionStore: agentWalletTransactionStore,
commissionWithdrawalReqStore: commissionWithdrawalReqStore,
}
}
func (s *Service) ListWithdrawalRequests(ctx context.Context, req *dto.WithdrawalRequestListReq, startTime, endTime *time.Time) (*dto.WithdrawalRequestPageResult, error) {
opts := &store.QueryOptions{
Page: req.Page,
PageSize: req.PageSize,
OrderBy: "created_at DESC",
}
if opts.Page == 0 {
opts.Page = 1
}
if opts.PageSize == 0 {
opts.PageSize = constants.DefaultPageSize
}
filters := &postgres.WithdrawalRequestListFilters{
WithdrawalNo: req.WithdrawalNo,
Status: req.Status,
StartTime: startTime,
EndTime: endTime,
}
requests, total, err := s.commissionWithdrawalReqStore.List(ctx, opts, filters)
if err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "查询提现申请列表失败")
}
shopIDs := make([]uint, 0)
applicantIDs := make([]uint, 0)
processorIDs := make([]uint, 0)
for _, r := range requests {
if r.ShopID > 0 {
shopIDs = append(shopIDs, r.ShopID)
}
if r.ApplicantID > 0 {
applicantIDs = append(applicantIDs, r.ApplicantID)
}
if r.ProcessorID > 0 {
processorIDs = append(processorIDs, r.ProcessorID)
}
}
shopMap := make(map[uint]*model.Shop)
for _, id := range shopIDs {
shop, err := s.shopStore.GetByID(ctx, id)
if err == nil {
shopMap[id] = shop
}
}
applicantMap := make(map[uint]string)
processorMap := make(map[uint]string)
if len(applicantIDs) > 0 {
accounts, _ := s.accountStore.GetByIDs(ctx, applicantIDs)
for _, acc := range accounts {
applicantMap[acc.ID] = acc.Username
}
}
if len(processorIDs) > 0 {
accounts, _ := s.accountStore.GetByIDs(ctx, processorIDs)
for _, acc := range accounts {
processorMap[acc.ID] = acc.Username
}
}
items := make([]dto.WithdrawalRequestItem, 0, len(requests))
for _, r := range requests {
shop := shopMap[r.ShopID]
shopName := ""
shopHierarchy := ""
if shop != nil {
shopName = shop.ShopName
shopHierarchy = s.buildShopHierarchyPath(ctx, shop)
if req.ShopName != "" && !containsSubstring(shopName, req.ShopName) {
total--
continue
}
}
item := s.buildWithdrawalRequestItem(r, shopName, shopHierarchy, applicantMap, processorMap)
items = append(items, item)
}
return &dto.WithdrawalRequestPageResult{
Items: items,
Total: total,
Page: opts.Page,
Size: opts.PageSize,
}, nil
}
func (s *Service) Approve(ctx context.Context, id uint, req *dto.ApproveWithdrawalReq) (*dto.WithdrawalApprovalResp, error) {
currentUserID := middleware.GetUserIDFromContext(ctx)
if currentUserID == 0 {
return nil, errors.New(errors.CodeUnauthorized, "未授权访问")
}
withdrawal, err := s.commissionWithdrawalReqStore.GetByID(ctx, id)
if err != nil {
return nil, errors.New(errors.CodeNotFound, "提现申请不存在")
}
if withdrawal.ApprovalInstanceID != nil {
// 已关联企业微信审批实例的申请只接受渠道终审,本地人工终审一律拒绝且不改动任何事实。
businessErr := errors.New(errors.CodeConflict, "提现申请已接入企业微信终审,不支持本地人工处理")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", businessErr)
return nil, businessErr
}
if withdrawal.Status != constants.WithdrawalStatusPending {
businessErr := errors.New(errors.CodeInvalidStatus, "申请状态不允许此操作")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", businessErr)
return nil, businessErr
}
// 获取店铺分佣钱包
wallet, err := s.agentWalletStore.GetCommissionWallet(ctx, withdrawal.ShopID)
if err != nil {
businessErr := errors.New(errors.CodeNotFound, "店铺佣金钱包不存在")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", businessErr)
return nil, businessErr
}
amount := withdrawal.Amount
if req.Amount != nil {
amount = *req.Amount
}
if wallet.FrozenBalance < amount {
businessErr := errors.New(errors.CodeInsufficientBalance, "钱包冻结余额不足")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, wallet, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", businessErr)
return nil, businessErr
}
now := time.Now()
err = s.db.Transaction(func(tx *gorm.DB) error {
// 从冻结余额扣款
if err := s.agentWalletStore.DeductFrozenBalanceWithTx(ctx, tx, wallet.ID, amount); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "扣除冻结余额失败")
}
// 创建代理钱包交易记录
refType := "withdrawal"
refID := withdrawal.ID
transaction := &model.AgentWalletTransaction{
AgentWalletID: wallet.ID,
ShopID: withdrawal.ShopID,
UserID: currentUserID,
TransactionType: "withdrawal",
Amount: -amount,
BalanceBefore: wallet.Balance,
BalanceAfter: wallet.Balance,
Status: 1,
ReferenceType: &refType,
ReferenceID: &refID,
Creator: currentUserID,
ShopIDTag: withdrawal.ShopID,
}
if err := s.agentWalletTransactionStore.CreateWithTx(ctx, tx, transaction); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建交易流水失败")
}
updates := map[string]interface{}{
"status": constants.WithdrawalStatusApproved,
"processor_id": currentUserID,
"processed_at": now,
"payment_type": req.PaymentType,
"remark": req.Remark,
}
if req.Amount != nil {
feeRate := withdrawal.FeeRate
fee := amount * feeRate / 10000
actualAmount := amount - fee
updates["amount"] = amount
updates["fee"] = fee
updates["actual_amount"] = actualAmount
}
if req.WithdrawalMethod != nil {
updates["withdrawal_method"] = *req.WithdrawalMethod
}
if req.AccountName != nil || req.AccountNumber != nil {
accountInfo := make(map[string]interface{})
if withdrawal.AccountInfo != nil {
_ = json.Unmarshal(withdrawal.AccountInfo, &accountInfo)
}
if req.AccountName != nil {
accountInfo["account_name"] = *req.AccountName
}
if req.AccountNumber != nil {
accountInfo["account_number"] = *req.AccountNumber
}
infoBytes, _ := json.Marshal(accountInfo)
updates["account_info"] = infoBytes
}
if err := s.commissionWithdrawalReqStore.UpdateStatusWithTx(ctx, tx, id, updates); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "更新提现申请状态失败")
}
return s.appendWithdrawalDecisionAudit(ctx, tx, withdrawal, wallet, transaction, constants.AuditActionCommissionWithdrawalApproved, "佣金提现申请已通过", amount)
})
if err != nil {
s.recordWithdrawalDecisionFailure(ctx, withdrawal, wallet, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", err)
return nil, err
}
return &dto.WithdrawalApprovalResp{
ID: withdrawal.ID,
WithdrawalNo: withdrawal.WithdrawalNo,
Status: constants.WithdrawalStatusApproved,
StatusName: "已通过",
ProcessedAt: now.Format("2006-01-02 15:04:05"),
}, nil
}
func (s *Service) Reject(ctx context.Context, id uint, req *dto.RejectWithdrawalReq) (*dto.WithdrawalApprovalResp, error) {
currentUserID := middleware.GetUserIDFromContext(ctx)
if currentUserID == 0 {
return nil, errors.New(errors.CodeUnauthorized, "未授权访问")
}
withdrawal, err := s.commissionWithdrawalReqStore.GetByID(ctx, id)
if err != nil {
return nil, errors.New(errors.CodeNotFound, "提现申请不存在")
}
if withdrawal.ApprovalInstanceID != nil {
// 已关联企业微信审批实例的申请只接受渠道终审,本地人工终审一律拒绝且不改动任何事实。
businessErr := errors.New(errors.CodeConflict, "提现申请已接入企业微信终审,不支持本地人工处理")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalRejected, "驳回佣金提现申请失败", businessErr)
return nil, businessErr
}
if withdrawal.Status != constants.WithdrawalStatusPending {
businessErr := errors.New(errors.CodeInvalidStatus, "申请状态不允许此操作")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalRejected, "驳回佣金提现申请失败", businessErr)
return nil, businessErr
}
wallet, err := s.agentWalletStore.GetCommissionWallet(ctx, withdrawal.ShopID)
if err != nil {
businessErr := errors.New(errors.CodeNotFound, "店铺佣金钱包不存在")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalRejected, "驳回佣金提现申请失败", businessErr)
return nil, businessErr
}
now := time.Now()
err = s.db.Transaction(func(tx *gorm.DB) error {
if err := s.agentWalletStore.UnfreezeBalanceWithTx(ctx, tx, wallet.ID, withdrawal.Amount); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "解冻余额失败")
}
refType := "withdrawal"
refID := withdrawal.ID
transaction := &model.AgentWalletTransaction{
AgentWalletID: wallet.ID,
ShopID: withdrawal.ShopID,
UserID: currentUserID,
TransactionType: "refund",
Amount: withdrawal.Amount,
BalanceBefore: wallet.Balance,
BalanceAfter: wallet.Balance + withdrawal.Amount,
Status: 1,
ReferenceType: &refType,
ReferenceID: &refID,
Creator: currentUserID,
ShopIDTag: withdrawal.ShopID,
}
if err := s.agentWalletTransactionStore.CreateWithTx(ctx, tx, transaction); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建交易流水失败")
}
updates := map[string]interface{}{
"status": constants.WithdrawalStatusRejected,
"processor_id": currentUserID,
"processed_at": now,
"reject_reason": req.Remark,
"remark": req.Remark,
}
if err := s.commissionWithdrawalReqStore.UpdateStatusWithTx(ctx, tx, id, updates); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "更新提现申请状态失败")
}
return s.appendWithdrawalDecisionAudit(ctx, tx, withdrawal, wallet, transaction, constants.AuditActionCommissionWithdrawalRejected, "佣金提现申请已驳回", withdrawal.Amount)
})
if err != nil {
s.recordWithdrawalDecisionFailure(ctx, withdrawal, wallet, constants.AuditActionCommissionWithdrawalRejected, "驳回佣金提现申请失败", err)
return nil, err
}
return &dto.WithdrawalApprovalResp{
ID: withdrawal.ID,
WithdrawalNo: withdrawal.WithdrawalNo,
Status: constants.WithdrawalStatusRejected,
StatusName: "已拒绝",
ProcessedAt: now.Format("2006-01-02 15:04:05"),
}, nil
}
func (s *Service) buildShopHierarchyPath(ctx context.Context, shop *model.Shop) string {
if shop == nil {
return ""
}
path := shop.ShopName
current := shop
depth := 0
for current.ParentID != nil && depth < 2 {
parent, err := s.shopStore.GetByID(ctx, *current.ParentID)
if err != nil {
break
}
path = parent.ShopName + "_" + path
current = parent
depth++
}
return path
}
func (s *Service) buildWithdrawalRequestItem(r *model.CommissionWithdrawalRequest, shopName, shopHierarchy string, applicantMap, processorMap map[uint]string) dto.WithdrawalRequestItem {
var processorID *uint
if r.ProcessorID > 0 {
processorID = &r.ProcessorID
}
var accountName, accountNumber, bankName string
if len(r.AccountInfo) > 0 {
var info map[string]interface{}
if err := json.Unmarshal(r.AccountInfo, &info); err == nil {
if v, ok := info["account_name"].(string); ok {
accountName = v
}
if v, ok := info["account_number"].(string); ok {
accountNumber = v
}
if v, ok := info["bank_name"].(string); ok {
bankName = v
}
}
}
var processedAt string
if r.ProcessedAt != nil {
processedAt = r.ProcessedAt.Format("2006-01-02 15:04:05")
}
return dto.WithdrawalRequestItem{
ID: r.ID,
WithdrawalNo: r.WithdrawalNo,
Amount: r.Amount,
FeeRate: r.FeeRate,
Fee: r.Fee,
ActualAmount: r.ActualAmount,
Status: r.Status,
StatusName: constants.GetWithdrawalStatusName(r.Status),
ShopID: r.ShopID,
ShopName: shopName,
ShopHierarchy: shopHierarchy,
ApplicantID: r.ApplicantID,
ApplicantName: applicantMap[r.ApplicantID],
ProcessorID: processorID,
ProcessorName: processorMap[r.ProcessorID],
WithdrawalMethod: r.WithdrawalMethod,
PaymentType: r.PaymentType,
AccountName: accountName,
AccountNumber: accountNumber,
BankName: bankName,
RejectReason: r.RejectReason,
Remark: r.Remark,
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
ProcessedAt: processedAt,
}
}
func containsSubstring(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}