You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
2.3 KiB
94 lines
2.3 KiB
package logic
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"healthapi/internal/model"
|
|
"healthapi/internal/svc"
|
|
"healthapi/internal/types"
|
|
"healthapi/pkg/errorx"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type CancelOrderLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewCancelOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelOrderLogic {
|
|
return &CancelOrderLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *CancelOrderLogic) CancelOrder(req *types.CancelOrderReq) (resp *types.CommonResp, err error) {
|
|
userID, err := GetUserIDFromCtx(l.ctx)
|
|
if err != nil {
|
|
return nil, errorx.ErrUnauthorized
|
|
}
|
|
|
|
var order model.Order
|
|
if err := l.svcCtx.DB.Where("id = ? AND user_id = ?", req.Id, userID).First(&order).Error; err != nil {
|
|
return nil, errorx.NewCodeError(404, "订单不存在")
|
|
}
|
|
|
|
if order.Status != model.OrderStatusPending {
|
|
return nil, errorx.NewCodeError(400, "只能取消待支付订单")
|
|
}
|
|
|
|
err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
|
// 更新订单状态
|
|
if err := tx.Model(&order).Updates(map[string]interface{}{
|
|
"status": model.OrderStatusCancelled,
|
|
"cancel_reason": req.Reason,
|
|
}).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
// 恢复库存
|
|
var items []model.OrderItem
|
|
tx.Where("order_id = ?", order.ID).Find(&items)
|
|
for _, item := range items {
|
|
if item.SkuID > 0 {
|
|
tx.Model(&model.ProductSku{}).Where("id = ?", item.SkuID).
|
|
Update("stock", gorm.Expr("stock + ?", item.Quantity))
|
|
} else {
|
|
tx.Model(&model.Product{}).Where("id = ?", item.ProductID).
|
|
Update("stock", gorm.Expr("stock + ?", item.Quantity))
|
|
}
|
|
}
|
|
|
|
// 退还积分
|
|
if order.PointsUsed > 0 {
|
|
var user model.User
|
|
tx.First(&user, userID)
|
|
tx.Model(&user).Update("points", gorm.Expr("points + ?", order.PointsUsed))
|
|
tx.Create(&model.PointsRecord{
|
|
UserID: userID,
|
|
Type: model.PointsTypeAdjust,
|
|
Points: order.PointsUsed,
|
|
Balance: user.Points + order.PointsUsed,
|
|
Source: model.PointsSourceRefund,
|
|
ReferenceID: uint(order.ID),
|
|
Remark: fmt.Sprintf("订单 %s 取消,退还积分", order.OrderNo),
|
|
})
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &types.CommonResp{
|
|
Code: 0,
|
|
Message: "订单已取消",
|
|
}, nil
|
|
}
|
|
|