You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.8 KiB
Go

8 months ago
package service
import (
e "errors"
"gold-shop/errors"
"gold-shop/global"
"gold-shop/model"
"gold-shop/request"
"gold-shop/utils"
"gorm.io/gorm"
)
var OrderService = orderService{}
type orderService struct {
}
func (orderService) Order(orderRequest request.OrderRequest, user *model.User) (*model.Order, error) {
product := &model.Product{}
8 months ago
err := global.DB.Where("id", orderRequest.ProductID).First(product).Error
8 months ago
if e.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.NewBusinessError("商品不存在")
}
totalAmount := float64(orderRequest.Num) * product.Price
if user.Balance < totalAmount {
return nil, errors.NewBusinessError("账号余额不足")
}
orderNo := utils.GenerateNo("order")
tx := global.DB.Begin()
order := model.Order{}
order.OrderNo = orderNo
order.Amount = totalAmount
order.UserID = user.ID
err = global.DB.Save(&order).Error
if err != nil {
tx.Rollback()
return nil, errors.NewBusinessError("保存数据失败")
}
orderProduct := model.OrderProduct{}
orderProduct.ProductID = orderRequest.ProductID
orderProduct.OrderNo = orderNo
orderProduct.Price = product.Price
orderProduct.Amount = totalAmount
orderProduct.Num = orderRequest.Num
err = global.DB.Save(&orderProduct).Error
if err != nil {
tx.Rollback()
return nil, errors.NewBusinessError("保存数据失败")
}
global.DB.Model(user).Update("balance", gorm.Expr("balance - ?", totalAmount))
tx.Commit()
return &order, nil
}
7 months ago
func (orderService) GetOrders(userID, page, pageSize int) ([]model.Order, int64) {
orders := make([]model.Order, pageSize)
offset := (page - 1) * pageSize
var total int64
global.DB.Where("user_id", userID).Preload("OrderProducts").Offset(offset).Limit(pageSize).Find(&orders)
global.DB.Model(&model.Order{}).Where("user_id", userID).Count(&total)
return orders, total
}