bindbox-game/internal/api/user/coupons_stats_app.go

65 lines
2.1 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 app
import (
"bindbox-game/internal/pkg/core"
)
type couponStatsResponse struct {
ValidCount int64 `json:"valid_count"` // 有效优惠券数量
InvalidCount int64 `json:"invalid_count"` // 已失效优惠券数量
TotalRemaining int64 `json:"total_remaining"` // 可用优惠券总余额(分)
TotalSaved int64 `json:"total_saved"` // 累计节省金额(分)
}
// GetUserCouponStats 获取用户优惠券统计
// @Summary 获取用户优惠券统计
// @Description 获取用户优惠券各状态数量和累计金额
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Param user_id path integer true "用户ID"
// @Security LoginVerifyToken
// @Success 200 {object} couponStatsResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/users/{user_id}/coupons/stats [get]
func (h *handler) GetUserCouponStats() core.HandlerFunc {
return func(ctx core.Context) {
rsp := new(couponStatsResponse)
userID := int64(ctx.SessionUserInfo().Id)
uc := h.readDB.UserCoupons
// 有效status=1 且 balance>0
validCount, _ := uc.WithContext(ctx.RequestContext()).ReadDB().
Where(uc.UserID.Eq(userID), uc.Status.Eq(1), uc.BalanceAmount.Gt(0)).Count()
// 已失效:(status=1 且 balance=0) 或 status=2 或 status=3
var invalidCount int64
_ = h.repo.GetDbR().Raw(
"SELECT COUNT(*) FROM user_coupons WHERE user_id = ? AND ((status = 1 AND balance_amount = 0) OR status IN (2, 3))",
userID,
).Scan(&invalidCount).Error
// 可用优惠券总余额
var totalRemaining int64
_ = h.repo.GetDbR().Raw(
"SELECT COALESCE(SUM(balance_amount), 0) FROM user_coupons WHERE user_id = ? AND status = 1 AND balance_amount > 0",
userID,
).Scan(&totalRemaining).Error
// 累计节省金额
var totalSaved int64
_ = h.repo.GetDbR().Raw(
"SELECT COALESCE(SUM(ABS(change_amount)), 0) FROM user_coupon_ledger WHERE user_id = ? AND change_amount < 0",
userID,
).Scan(&totalSaved).Error
rsp.ValidCount = validCount
rsp.InvalidCount = invalidCount
rsp.TotalRemaining = totalRemaining
rsp.TotalSaved = totalSaved
ctx.Payload(rsp)
}
}