更新
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

@@ -0,0 +1,187 @@
// Package commissiondelivery 提供订单佣金与退款后处理的可靠 Outbox 事件。
package commissiondelivery
import (
"context"
"strconv"
"time"
"github.com/bytedance/sonic"
"github.com/hibiken/asynq"
"go.uber.org/zap"
"gorm.io/gorm"
"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"
"github.com/break/junhong_cmp_fiber/pkg/outboxid"
)
const (
EventCommissionCalculate = "order.commission.calculate.requested"
EventRefundCommissionDeduct = "refund.commission.deduct.requested"
EventRefundAssetProcess = "refund.asset.process.requested"
PayloadVersionV1 = 1
)
type Payload struct {
OrderID uint `json:"order_id"`
RefundID uint `json:"refund_id,omitempty"`
}
func AppendCommissionCalculate(ctx context.Context, tx *gorm.DB, repository *outbox.Repository, orderID uint) error {
return appendEvent(ctx, tx, repository, EventCommissionCalculate, "order", orderID, Payload{OrderID: orderID})
}
func AppendRefundCommissionDeduct(ctx context.Context, tx *gorm.DB, repository *outbox.Repository, refundID, orderID uint) error {
return appendEvent(ctx, tx, repository, EventRefundCommissionDeduct, "refund", refundID, Payload{OrderID: orderID, RefundID: refundID})
}
func AppendRefundAssetProcess(ctx context.Context, tx *gorm.DB, repository *outbox.Repository, refundID, orderID uint) error {
return appendEvent(ctx, tx, repository, EventRefundAssetProcess, "refund", refundID, Payload{OrderID: orderID, RefundID: refundID})
}
func appendEvent(ctx context.Context, tx *gorm.DB, repository *outbox.Repository, eventType, aggregate string, id uint, payload Payload) error {
if repository == nil {
return gorm.ErrInvalidDB
}
value := strconv.FormatUint(uint64(id), 10)
_, err := repository.AppendIdempotent(ctx, tx, outbox.Envelope{
EventID: outboxid.Stable(eventType+":", value), EventType: eventType, PayloadVersion: PayloadVersionV1,
AggregateType: aggregate, AggregateID: value, ResourceType: aggregate, ResourceID: value,
BusinessKey: eventType + ":" + value, Payload: payload,
})
return err
}
type CommissionConsumer struct {
client outbox.TaskEnqueuer
logger *zap.Logger
}
func NewCommissionConsumer(client outbox.TaskEnqueuer, logger *zap.Logger) *CommissionConsumer {
return &CommissionConsumer{client: client, logger: logger}
}
func (c *CommissionConsumer) Consume(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
var payload Payload
if err := sonic.Unmarshal(envelope.Payload, &payload); err != nil {
return outbox.Permanent(err)
}
if envelope.EventType != EventCommissionCalculate || envelope.PayloadVersion != PayloadVersionV1 || payload.OrderID == 0 {
return outbox.Permanent(gorm.ErrInvalidData)
}
if err := c.client.EnqueueTask(ctx, constants.TaskTypeCommission, map[string]any{"order_id": payload.OrderID, "request_id": envelope.RequestID, "correlation_id": envelope.CorrelationID, "parent_event_id": envelope.EventID}, asynq.Queue(constants.QueueForTaskType(constants.TaskTypeCommission))); err != nil {
return err
}
c.logger.Info("佣金计算 Outbox 已投递", zap.Uint("order_id", payload.OrderID), zap.String("event_id", envelope.EventID), zap.String("correlation_id", envelope.CorrelationID))
return nil
}
type RefundConsumer struct {
commission func(context.Context, uint) error
asset func(context.Context, uint) error
}
func NewRefundConsumer(commission func(context.Context, uint) error, asset func(context.Context, uint) error) *RefundConsumer {
return &RefundConsumer{commission: commission, asset: asset}
}
func (c *RefundConsumer) Consume(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
var payload Payload
if err := sonic.Unmarshal(envelope.Payload, &payload); err != nil {
return outbox.Permanent(err)
}
if payload.RefundID == 0 || payload.OrderID == 0 || envelope.PayloadVersion != PayloadVersionV1 {
return outbox.Permanent(gorm.ErrInvalidData)
}
ctx = auditcontext.With(ctx, auditcontext.Context{CorrelationID: envelope.CorrelationID, ParentEventID: envelope.EventID})
switch envelope.EventType {
case EventRefundCommissionDeduct:
return c.commission(ctx, payload.RefundID)
case EventRefundAssetProcess:
return c.asset(ctx, payload.RefundID)
default:
return outbox.Permanent(gorm.ErrInvalidData)
}
}
// RecoveryStats 是一次有界补偿扫描的可观察结果。
type RecoveryStats struct{ Resent, Unchanged, Failed int }
// Recover 扫描遗留订单与退款,并用稳定事件 ID 恢复投递事实。
func Recover(ctx context.Context, db *gorm.DB, repository *outbox.Repository, limit int, logger *zap.Logger) {
if limit <= 0 {
limit = 100
}
orderStats := RecoveryStats{}
refundStats := RecoveryStats{}
var orders []model.Order
if err := db.WithContext(ctx).Where("payment_status = ? AND commission_status = ?", model.PaymentStatusPaid, model.CommissionStatusPending).Order("id ASC").Limit(limit).Find(&orders).Error; err != nil {
logger.Warn("扫描待计算订单失败", zap.Error(err))
} else {
for _, order := range orders {
recoverOne(ctx, db, repository, EventCommissionCalculate, order.ID, order.ID, &orderStats, logger)
}
}
var refunds []model.RefundRequest
if err := db.WithContext(ctx).Where("status = ? AND (commission_deducted = ? OR asset_reset = ?)", model.RefundStatusApproved, false, false).Order("id ASC").Limit(limit).Find(&refunds).Error; err != nil {
logger.Warn("扫描退款后处理失败", zap.Error(err))
} else {
for _, refund := range refunds {
if !refund.CommissionDeducted {
recoverOne(ctx, db, repository, EventRefundCommissionDeduct, refund.ID, refund.OrderID, &refundStats, logger)
}
if !refund.AssetReset {
recoverOne(ctx, db, repository, EventRefundAssetProcess, refund.ID, refund.OrderID, &refundStats, logger)
}
}
}
logger.Info("佣金与退款补偿扫描完成",
zap.Int("订单已补发", orderStats.Resent), zap.Int("订单无需补发", orderStats.Unchanged), zap.Int("订单失败", orderStats.Failed),
zap.Int("退款已补发", refundStats.Resent), zap.Int("退款无需补发", refundStats.Unchanged), zap.Int("退款失败", refundStats.Failed))
}
func recoverOne(ctx context.Context, db *gorm.DB, repository *outbox.Repository, eventType string, aggregateID, orderID uint, stats *RecoveryStats, logger *zap.Logger) {
eventID := outboxid.Stable(eventType+":", strconv.FormatUint(uint64(aggregateID), 10))
var event model.OutboxEvent
err := db.WithContext(ctx).Where("event_id = ?", eventID).First(&event).Error
if err == nil {
if event.Status != constants.OutboxStatusFailed {
stats.Unchanged++
return
}
result := db.WithContext(ctx).Model(&model.OutboxEvent{}).Where("id = ? AND status = ?", event.ID, constants.OutboxStatusFailed).Updates(map[string]any{
"status": constants.OutboxStatusPending, "retry_count": 0, "next_attempt_at": time.Now().UTC(),
"last_error_code": "", "last_error_summary": "", "updated_at": time.Now().UTC(),
})
if result.Error == nil && result.RowsAffected == 1 {
stats.Resent++
return
}
if result.Error == nil {
stats.Unchanged++
return
}
stats.Failed++
logger.Warn("恢复失败 Outbox 事件失败", zap.String("event_id", eventID), zap.Error(result.Error))
return
}
if err != gorm.ErrRecordNotFound {
stats.Failed++
logger.Warn("查询补偿 Outbox 事件失败", zap.String("event_id", eventID), zap.Error(err))
return
}
err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
switch eventType {
case EventCommissionCalculate:
return AppendCommissionCalculate(ctx, tx, repository, aggregateID)
case EventRefundCommissionDeduct:
return AppendRefundCommissionDeduct(ctx, tx, repository, aggregateID, orderID)
default:
return AppendRefundAssetProcess(ctx, tx, repository, aggregateID, orderID)
}
})
if err != nil {
stats.Failed++
logger.Warn("创建补偿 Outbox 事件失败", zap.String("event_id", eventID), zap.Error(err))
return
}
stats.Resent++
}

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
}

View File

@@ -16,6 +16,8 @@ import (
cardObservationApp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
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/messaging/outbox"
"github.com/break/junhong_cmp_fiber/internal/model"
packagepkg "github.com/break/junhong_cmp_fiber/internal/service/package"
"github.com/break/junhong_cmp_fiber/internal/service/packageprice"
@@ -199,7 +201,6 @@ func (h *AutoPurchaseHandler) ProcessTask(ctx context.Context, task *asynq.Task)
}
}
var createdOrderID uint
if err := h.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
wallet, walletErr := h.walletStore.GetByID(ctx, rechargeOrder.AssetWalletID)
if walletErr != nil {
@@ -225,7 +226,6 @@ func (h *AutoPurchaseHandler) ProcessTask(ctx context.Context, task *asynq.Task)
if err = tx.Create(order).Error; err != nil {
return err
}
createdOrderID = order.ID
for _, item := range orderItems {
item.OrderID = order.ID
@@ -277,6 +277,9 @@ func (h *AutoPurchaseHandler) ProcessTask(ctx context.Context, task *asynq.Task)
if resourceID == 0 {
return pkgerrors.New(pkgerrors.CodeInvalidParam, "自动购包观测事件缺少载体")
}
if err = commissiondelivery.AppendCommissionCalculate(ctx, tx, outbox.NewRepository(), order.ID); err != nil {
return err
}
requestID := "card-observation:auto-purchase:" + strconv.FormatUint(uint64(order.ID), 10)
if err = h.observationSeriesEvents.AppendSeriesRequested(ctx, tx, cardObservationApp.SeriesRequestedEvent{
EventID: requestID, Scene: constants.CardObservationScenePackageChanged,
@@ -306,30 +309,6 @@ func (h *AutoPurchaseHandler) ProcessTask(ctx context.Context, task *asynq.Task)
return err
}
// 事务提交成功后触发佣金计算(不在事务内,防止任务提交后事务回滚的数据一致性问题)
if h.asynqClient != nil && createdOrderID > 0 {
linkage := auditcontext.From(ctx)
payloadBytes, marshalErr := sonic.Marshal(CommissionCalculationPayload{
OrderID: createdOrderID, RequestID: linkage.RequestID,
CorrelationID: linkage.CorrelationID, ParentEventID: linkage.ParentEventID,
})
if marshalErr != nil {
h.logger.Warn("佣金任务载荷序列化失败",
zap.Uint("order_id", createdOrderID),
zap.Error(marshalErr))
} else {
commissionTask := asynq.NewTask(constants.TaskTypeCommission, payloadBytes,
asynq.MaxRetry(3),
asynq.Queue(constants.QueueForTaskType(constants.TaskTypeCommission)),
)
if _, enqueueErr := h.asynqClient.EnqueueContext(ctx, commissionTask); enqueueErr != nil {
h.logger.Warn("自动购包后提交佣金任务失败",
zap.Uint("order_id", createdOrderID),
zap.Error(enqueueErr))
}
}
}
h.logger.Info("自动购包任务执行成功", zap.Uint("recharge_record_id", rechargeOrder.ID))
return nil
}