From ec8a1558b8c731976e653d63ccb1cad94d83939f Mon Sep 17 00:00:00 2001 From: Rogee Date: Tue, 13 May 2025 09:03:30 +0800 Subject: [PATCH] feat: fix pay by balance --- backend/app/http/posts.go | 4 ---- backend/app/jobs/balance_pay_notify.go | 20 ++++++++++++++++++++ backend/database/fields/orders.go | 1 + 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/backend/app/http/posts.go b/backend/app/http/posts.go index 66d473f..830697e 100644 --- a/backend/app/http/posts.go +++ b/backend/app/http/posts.go @@ -280,10 +280,6 @@ func (ctl *posts) Buy(ctx fiber.Ctx, id int64, user *model.Users) (*wechat.JSAPI payPrice := post.Price * int64(post.Discount) / 100 if user.Balance >= payPrice { - err = models.Users.SetBalance(ctx.Context(), user.ID, user.Balance-payPrice) - if err != nil { - return nil, errors.Wrap(err, "余额支付失败") - } if err := ctl.job.Add(&jobs.BalancePayNotify{OrderNo: order.OrderNo}); err != nil { log.Errorf("add job error:%v", err) diff --git a/backend/app/jobs/balance_pay_notify.go b/backend/app/jobs/balance_pay_notify.go index 23cdc7a..57541c6 100644 --- a/backend/app/jobs/balance_pay_notify.go +++ b/backend/app/jobs/balance_pay_notify.go @@ -56,8 +56,21 @@ func (w *BalancePayNotifyWorker) Work(ctx context.Context, job *Job[BalancePayNo return JobCancel(fmt.Errorf("Order already paid, currently status: %d", order.Status)) } + user, err := models.Users.GetByID(context.Background(), order.UserID) + if err != nil { + log.Errorf("GetByID error:%v", err) + return errors.Wrap(err, "get user error") + } + + payPrice := order.Price * int64(order.Discount) / 100 + order.PaymentMethod = "balance" order.Status = fields.OrderStatusCompleted + + meta := order.Meta.Data + meta.CostBalance = payPrice + order.Meta = fields.ToJson(meta) + log.Infof("Updated order details: %+v", order) tx, err := models.Transaction(ctx) if err != nil { @@ -65,6 +78,13 @@ func (w *BalancePayNotifyWorker) Work(ctx context.Context, job *Job[BalancePayNo } defer tx.Rollback() + // update user balance + err = models.Users.SetBalance(ctx, user.ID, user.Balance-payPrice) + if err != nil { + log.WithError(err).Error("SetBalance error") + return JobCancel(errors.Wrap(err, "set user balance failed")) + } + if err := models.Users.BuyPosts(context.Background(), order.UserID, order.PostID, order.Price); err != nil { log.Errorf("BuyPosts error:%v", err) return errors.Wrap(err, "BuyPosts error") diff --git a/backend/database/fields/orders.go b/backend/database/fields/orders.go index 4900ac5..d154966 100644 --- a/backend/database/fields/orders.go +++ b/backend/database/fields/orders.go @@ -12,4 +12,5 @@ type OrderMeta struct { PayNotify *wechat.V3DecryptPayResult `json:"pay_notify"` RefundResp *wechat.RefundOrderResponse `json:"refund_resp"` RefundNotify *wechat.V3DecryptRefundResult `json:"refund_notify"` + CostBalance int64 `json:"cost_balance"` // 余额支付的金额 }