|
|
|
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{}
|
|
|
|
err := global.DB.Where("id", orderRequest.ProductID).First(product).Error
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|