117 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"fmt"
"gorm.io/gorm"
"hepa-calc-api/api/dao"
"hepa-calc-api/api/model"
"hepa-calc-api/extend/rabbitMq"
"time"
)
type CouponService struct {
}
// GrantUserCoupon 发放优惠卷
func (r *CouponService) GrantUserCoupon(tx *gorm.DB, userId, couponId int64, grantQuantity int) bool {
// 获取优惠卷数据
couponDao := dao.CouponDao{}
coupon, err := couponDao.GetCouponById(couponId)
if err != nil {
return false
}
// 判断优惠卷状态
if coupon.CouponStatus != 1 {
return true
}
// 判断优惠卷过期时间
if coupon.ValidType == 1 {
now := time.Now().Add(10 * 60 * time.Second)
validEndTime := time.Time(*coupon.ValidEndTime)
if validEndTime.Before(now) {
return false
}
}
// 判断优惠卷数量是否充足
if coupon.CouponCount <= coupon.CouponTakeCount {
return false
}
// 检测剩余数量
remainingQuantity := coupon.CouponCount - coupon.CouponTakeCount
if remainingQuantity <= grantQuantity {
return false
}
// 添加用户优惠卷表
userCoupon := &model.UserCoupon{
UserId: userId,
CouponId: couponId,
UserCouponStatus: 0,
IsWindows: 0,
CouponUseDate: nil,
}
if coupon.ValidType == 1 {
// 有效类型1:绝对时效xxx-xxx时间段有效 2:相对时效 n天内有效
userCoupon.ValidStartTime = coupon.ValidStartTime
userCoupon.ValidEndTime = coupon.ValidEndTime
} else {
validStartTime := model.LocalTime(time.Now())
userCoupon.ValidStartTime = &validStartTime
validEndTime := model.LocalTime(time.Now().Add(time.Duration(coupon.ValidDays) * 24 * time.Hour))
userCoupon.ValidEndTime = &validEndTime
}
userCouponDao := dao.UserCouponDao{}
userCoupon, err = userCouponDao.AddUserCoupon(tx, userCoupon)
if err != nil {
return false
}
// 增加优惠卷发放数量
err = couponDao.Inc(tx, couponId, "coupon_take_count", grantQuantity)
if err != nil {
return false
}
// 增加过期队列
if coupon.ValidType == 1 {
validEndTime := time.Time(*userCoupon.ValidEndTime)
// 计算当天的结束时间
now := time.Now()
year, month, day := now.Date()
location := now.Location()
endOfDay := time.Date(year, month, day, 23, 59, 59, 0, location)
if validEndTime.Before(endOfDay) {
delay := validEndTime.Sub(time.Now())
if delay < 5*time.Second {
delay = 5 * time.Second
}
// 添加处理优惠卷过期队列
data := make(map[string]interface{})
data["coupon_id"] = fmt.Sprintf("%d", coupon.CouponId)
p := rabbitMq.PublishS{
QueueName: "user.coupon.expired.delay.queue",
ExchangeName: "amqp.delay.direct",
RoutingKey: "UserCouponExpired",
Message: data,
Delay: delay,
}
err := p.PublishWithDelay()
if err != nil {
return false
}
}
}
return true
}