更新
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m35s

This commit is contained in:
2026-08-13 12:31:47 +08:00
parent fcfa347005
commit e134552ec5
13 changed files with 458 additions and 188 deletions

View File

@@ -14,7 +14,9 @@ import (
walletapp "github.com/break/junhong_cmp_fiber/internal/application/wallet"
packagedomain "github.com/break/junhong_cmp_fiber/internal/domain/package"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/commissiondelivery"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
packagepkg "github.com/break/junhong_cmp_fiber/internal/service/package"
@@ -510,9 +512,6 @@ func (s *Service) CreateAdminOrder(ctx context.Context, req *dto.CreateAdminOrde
if err := s.createOrderWithActivation(ctx, order, items); err != nil {
return nil, err
}
if !containsGift {
s.enqueueCommissionCalculation(ctx, order.ID)
}
s.markOrderCreated(ctx, idempotencyKey, order.ID)
return s.buildOrderResponse(ctx, order, items), nil
@@ -808,7 +807,6 @@ func (s *Service) CreateH5Order(ctx context.Context, req *dto.CreateOrderRequest
if err := s.createOrderWithActivation(ctx, order, items); err != nil {
return nil, err
}
s.enqueueCommissionCalculation(ctx, order.ID)
s.markOrderCreated(ctx, idempotencyKey, order.ID)
return s.buildOrderResponse(ctx, order, items), nil
@@ -1191,6 +1189,9 @@ func (s *Service) createOrderWithWalletPayment(ctx context.Context, order *model
if err := s.activatePackage(ctx, tx, order); err != nil {
return err
}
if err := commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入佣金计算 Outbox 事件失败")
}
if err := s.appendOrderAudit(ctx, tx, constants.AuditActionOrderCreated, "创建并使用钱包支付订单", order, nil, orderStateData(order)); err != nil {
return err
}
@@ -1209,9 +1210,6 @@ func (s *Service) createOrderWithWalletPayment(ctx context.Context, order *model
}
// 3. 事务外:所有已支付且适用差价佣金的订单都进入佣金计算
if order.CommissionStatus == model.CommissionStatusPending {
s.enqueueCommissionCalculation(ctx, order.ID)
}
return 0, nil
}
@@ -1232,6 +1230,9 @@ func (s *Service) createOrderWithActivation(ctx context.Context, order *model.Or
if err := s.activatePackage(ctx, tx, order); err != nil {
return err
}
if err := commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入佣金计算 Outbox 事件失败")
}
return s.appendOrderAudit(ctx, tx, constants.AuditActionOrderCreated, "创建并完成订单", order, nil, orderStateData(order))
})
}
@@ -1720,7 +1721,6 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
// 根据资源类型选择对应的钱包系统
now := time.Now()
actualPaidAmount := order.TotalAmount
shouldEnqueueCommission := false
if resourceType == "shop" {
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
@@ -1758,7 +1758,6 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
actualPaidAmountSnapshot := actualPaidAmount
order.ActualPaidAmount = &actualPaidAmountSnapshot
order.PaidAt = &now
shouldEnqueueCommission = true
agentWalletDebitAttempted = true
if err := s.debitAgentMainWalletInTx(ctx, tx, order, resourceID, order.TotalAmount, nil); err != nil {
@@ -1772,6 +1771,9 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
if err := s.activatePackage(ctx, tx, order); err != nil {
return err
}
if err := commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入佣金计算 Outbox 事件失败")
}
after := *order
after.PaymentStatus = model.PaymentStatusPaid
after.PaymentMethod = model.PaymentMethodWallet
@@ -1850,6 +1852,9 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
if err := s.activatePackage(ctx, tx, order); err != nil {
return err
}
if err := commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入佣金计算 Outbox 事件失败")
}
after := *order
after.PaymentStatus = model.PaymentStatusPaid
after.PaymentMethod = model.PaymentMethodWallet
@@ -1863,9 +1868,6 @@ func (s *Service) WalletPay(ctx context.Context, orderID uint, buyerType string,
return err
}
if shouldEnqueueCommission && order.CommissionStatus == model.CommissionStatusPending {
s.enqueueCommissionCalculation(ctx, orderID)
}
return nil
}
@@ -1922,7 +1924,6 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, orderNo string, pay
now := time.Now()
beforeOrder := *order
shouldResumeAfterPayment := false
shouldEnqueueCommission := false
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
result := tx.Model(&model.Order{}).
Where("id = ? AND payment_status = ?", order.ID, model.PaymentStatusPending).
@@ -1959,11 +1960,13 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, orderNo string, pay
actualPaidAmountSnapshot := actualPaidAmount
order.ActualPaidAmount = &actualPaidAmountSnapshot
shouldResumeAfterPayment = true
shouldEnqueueCommission = true
if err := s.activatePackage(ctx, tx, order); err != nil {
return err
}
if err := commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入佣金计算 Outbox 事件失败")
}
after := *order
after.PaymentStatus = model.PaymentStatusPaid
after.PaymentMethod = paymentMethod
@@ -1979,9 +1982,6 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, orderNo string, pay
if shouldResumeAfterPayment {
s.tryResumeAfterPayment(ctx, order)
}
if shouldEnqueueCommission && order.CommissionStatus == model.CommissionStatusPending {
s.enqueueCommissionCalculation(ctx, order.ID)
}
return nil
}
@@ -2010,7 +2010,6 @@ func (s *Service) HandlePaymentRecordCallback(ctx context.Context, paymentNo str
beforePayment := *payment
beforeOrder := *order
shouldResumeAfterPayment := false
shouldEnqueueCommission := false
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
paymentUpdates := map[string]any{
"status": model.PaymentRecordStatusPaid,
@@ -2069,11 +2068,13 @@ func (s *Service) HandlePaymentRecordCallback(ctx context.Context, paymentNo str
actualPaidAmountSnapshot := actualPaidAmount
order.ActualPaidAmount = &actualPaidAmountSnapshot
shouldResumeAfterPayment = true
shouldEnqueueCommission = true
if err := s.activatePackage(ctx, tx, order); err != nil {
return err
}
if err := commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入佣金计算 Outbox 事件失败")
}
afterPayment := beforePayment
afterPayment.Status = model.PaymentRecordStatusPaid
afterPayment.PaidAt = &now
@@ -2097,9 +2098,6 @@ func (s *Service) HandlePaymentRecordCallback(ctx context.Context, paymentNo str
if shouldResumeAfterPayment {
s.tryResumeAfterPayment(ctx, order)
}
if shouldEnqueueCommission && order.CommissionStatus == model.CommissionStatusPending {
s.enqueueCommissionCalculation(ctx, order.ID)
}
return nil
}
@@ -2703,30 +2701,6 @@ func (s *Service) resolvePackageTerms(ctx context.Context, tx *gorm.DB, pkg *mod
return packagepkg.ResolveTermsFromTx(ctx, tx, pkg, sellerShopID)
}
func (s *Service) enqueueCommissionCalculation(ctx context.Context, orderID uint) {
if s.queueClient == nil {
s.logger.Warn("队列客户端未初始化,跳过佣金计算任务入队", zap.Uint("order_id", orderID))
return
}
linkage := auditcontext.From(ctx)
// 直接传 map由 EnqueueTask 内部统一序列化一次(传 []byte 会导致 sonic.Marshal 二次 base64 编码)
if err := s.queueClient.EnqueueTask(ctx, constants.TaskTypeCommission, map[string]any{
"order_id": orderID, "request_id": linkage.RequestID, "correlation_id": linkage.CorrelationID,
"parent_event_id": linkage.ParentEventID,
}); err != nil {
s.logger.Error("佣金计算任务入队失败",
zap.Uint("order_id", orderID),
zap.Error(err),
zap.String("task_type", constants.TaskTypeCommission))
return
}
s.logger.Info("佣金计算任务已入队",
zap.Uint("order_id", orderID),
zap.String("task_type", constants.TaskTypeCommission))
}
func (s *Service) buildOrderResponse(ctx context.Context, order *model.Order, items []*model.OrderItem) *dto.OrderResponse {
var itemResponses []*dto.OrderItemResponse
for _, item := range items {

View File

@@ -9,6 +9,8 @@ import (
"gorm.io/gorm/clause"
approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/commissiondelivery"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/auditcontext"
"github.com/break/junhong_cmp_fiber/pkg/constants"
@@ -99,6 +101,12 @@ func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.T
if err := s.appendCompletedNotification(ctx, tx, &refund); err != nil {
return err
}
if err := commissiondelivery.AppendRefundCommissionDeduct(ctx, tx, outbox.NewRepository(), refund.ID, refund.OrderID); err != nil {
return err
}
if err := commissiondelivery.AppendRefundAssetProcess(ctx, tx, outbox.NewRepository(), refund.ID, refund.OrderID); err != nil {
return err
}
if !changed {
return nil
}
@@ -109,7 +117,7 @@ func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.T
s.recordRefundFailure(ctx, constants.AuditActionRefundApproved, "通过退款审批失败", &refund, &order, err)
return err
}
return s.ensureApprovedPostProcessing(ctx, event.BusinessID)
return nil
}
func (s *Service) applyClosedDecision(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
@@ -159,15 +167,26 @@ func (s *Service) applyClosedDecision(ctx context.Context, event approvalapp.Ter
return err
}
func (s *Service) ensureApprovedPostProcessing(ctx context.Context, refundID uint) error {
func (s *Service) ProcessCommissionDeduction(ctx context.Context, refundID uint) error {
s.deductAllCommission(ctx, refundID)
var refund model.RefundRequest
if err := s.db.WithContext(ctx).Select("commission_deducted").First(&refund, refundID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "复核退款佣金回扣状态失败")
}
if !refund.CommissionDeducted {
return errors.New(errors.CodeServiceUnavailable, "退款佣金回扣尚未完成")
}
return nil
}
func (s *Service) ProcessAssetPostProcessing(ctx context.Context, refundID uint) error {
s.handleRefundAssetProcessing(ctx, refundID)
var refund model.RefundRequest
if err := s.db.WithContext(ctx).Select("commission_deducted", "asset_reset").Where("id = ?", refundID).First(&refund).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "复核退款后处理状态失败")
if err := s.db.WithContext(ctx).Select("asset_reset").First(&refund, refundID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "复核退款资产后处理状态失败")
}
if !refund.CommissionDeducted || !refund.AssetReset {
return errors.New(errors.CodeServiceUnavailable, "退款后处理尚未全部完成,将自动重试")
if !refund.AssetReset {
return errors.New(errors.CodeServiceUnavailable, "退款资产后处理尚未完成")
}
return nil
}

View File

@@ -19,6 +19,7 @@ import (
refundapprovalapp "github.com/break/junhong_cmp_fiber/internal/application/refundapproval"
walletapp "github.com/break/junhong_cmp_fiber/internal/application/wallet"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/commissiondelivery"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
@@ -340,6 +341,12 @@ func (s *Service) Approve(ctx context.Context, id uint, req *dto.ApproveRefundRe
if err := s.appendCompletedNotification(ctx, tx, refund); err != nil {
return err
}
if err := commissiondelivery.AppendRefundCommissionDeduct(ctx, tx, outbox.NewRepository(), refund.ID, refund.OrderID); err != nil {
return err
}
if err := commissiondelivery.AppendRefundAssetProcess(ctx, tx, outbox.NewRepository(), refund.ID, refund.OrderID); err != nil {
return err
}
return s.appendRefundAudit(ctx, tx, refund.ID, constants.AuditActionRefundApproved, "通过退款审批",
"refund:"+strconv.FormatUint(uint64(refund.ID), 10)+":approved", beforeRefund, beforeOrder, "退款已通过")
})
@@ -348,24 +355,6 @@ func (s *Service) Approve(ctx context.Context, id uint, req *dto.ApproveRefundRe
return err
}
// 事务提交成功后,异步执行佣金回扣和退款后资产处理(失败不影响审批结果)
go func() {
asyncCtx := auditcontext.With(context.Background(), auditcontext.Context{
ActorKind: constants.AuditActorSystemTask, ActorID: constants.AuditActorIDRefundCommissionPostProcessing,
ActorName: "退款佣金自动回扣任务", Source: constants.AuditSourceWorker,
CorrelationID: refund.RefundNo,
})
s.deductAllCommission(asyncCtx, id)
}()
go func() {
asyncCtx := auditcontext.With(context.Background(), auditcontext.Context{
ActorKind: constants.AuditActorSystemTask, ActorID: constants.AuditActorIDRefundAssetPostProcessing,
ActorName: "退款资产自动后处理任务", Source: constants.AuditSourceWorker,
})
s.handleRefundAssetProcessing(asyncCtx, id)
}()
return nil
}