XinYeYouKu/app/services/OrderService.go

83 lines
2.3 KiB
Go

package services
import (
"qteam/app/constants/common"
"qteam/app/constants/errorcode"
"qteam/app/http/entities/front"
"qteam/app/models/ordermodel"
"qteam/app/models/productmodel"
"qteam/app/models/usersmodel"
"qteam/app/utils"
redis_util "qteam/app/utils/redis"
"qteam/config"
"strconv"
"time"
)
func CreateOrderService(userId int, productId int) (code int) {
var err error
{ // redis保证用户当前抽奖结束才能开始下次抽奖
key := utils.GetRealKey("lottery_code:" + strconv.Itoa(userId) + strconv.Itoa(productId))
ok, err := redis_util.AcquireLock(key, time.Second*10)
if ok {
defer redis_util.Del(key)
} else {
if err != nil {
utils.Log(nil, "CreateOrderService", err.Error())
}
code = errorcode.OrderLottery
return code
}
}
session := ordermodel.GetInstance().GetDb().NewSession()
defer func() {
if err != nil {
_ = session.Rollback()
return
}
_ = session.Close()
}()
var product productmodel.Product
has, err := productmodel.GetInstance().GetDb().Where("id =?", productId).Get(&product)
if err != nil {
return errorcode.SystemError
}
if !has {
return errorcode.OrderProductNotExist
}
var user usersmodel.Users
_, err = usersmodel.GetInstance().GetDb().Where("id =?", userId).Get(&user)
if err != nil {
return errorcode.SystemError
}
order := ordermodel.Order{
OrderNo: utils.GenerateOrderNumber(),
UserId: userId,
ProductId: productId,
ProductName: product.Name,
UserName: user.Name,
Mobile: user.Phone,
ActivityId: config.GetConf().ActivityId,
VoucherId: product.ThirdProductId,
State: common.STATUSABLED,
CreateTime: time.Now(),
}
if _, err := session.Insert(order); err != nil {
utils.Log(nil, "CreateOrderService", err.Error())
return errorcode.SystemError
}
if err = session.Begin(); err != nil {
return errorcode.SystemError
}
return errorcode.Success
}
func OrderQueryService(userId int, OrderRequest *front.OrderQueryRequest) (code int, data []ordermodel.Order, count int64) {
activityId := config.GetConf().ActivityId
repo := ordermodel.GetInstance().GetDb()
count, err := repo.Where("user_id = ? and activity_id = ?", userId, activityId).
Desc("id").Limit(OrderRequest.PageSize, (OrderRequest.Page-1)*OrderRequest.PageSize).FindAndCount(&data)
code = handErr(err)
return
}