bindbox-game/internal/api/user/coupons_stats_app.go
邹方成 45815bfb7d chore: 清理无用文件与优化代码结构
refactor(utils): 修复密码哈希比较逻辑错误
feat(user): 新增按状态筛选优惠券接口
docs: 添加虚拟发货与任务中心相关文档
fix(wechat): 修正Code2Session上下文传递问题
test: 补充订单折扣与积分转换测试用例
build: 更新配置文件与构建脚本
style: 清理多余的空行与注释
2025-12-18 17:35:55 +08:00

62 lines
2.3 KiB
Go

package app
import (
"bindbox-game/internal/pkg/core"
)
type couponStatsResponse struct {
UnusedCount int64 `json:"unused_count"` // 可用优惠券数量
UsedCount int64 `json:"used_count"` // 已使用优惠券数量
ExpiredCount int64 `json:"expired_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)
// 统计各状态数量
unusedCount, _ := h.readDB.UserCoupons.WithContext(ctx.RequestContext()).ReadDB().
Where(h.readDB.UserCoupons.UserID.Eq(userID), h.readDB.UserCoupons.Status.Eq(1)).Count()
usedCount, _ := h.readDB.UserCoupons.WithContext(ctx.RequestContext()).ReadDB().
Where(h.readDB.UserCoupons.UserID.Eq(userID), h.readDB.UserCoupons.Status.Eq(2)).Count()
expiredCount, _ := h.readDB.UserCoupons.WithContext(ctx.RequestContext()).ReadDB().
Where(h.readDB.UserCoupons.UserID.Eq(userID), h.readDB.UserCoupons.Status.Eq(3)).Count()
// 统计可用优惠券总余额
var totalRemaining int64
_ = h.repo.GetDbR().Raw(
"SELECT COALESCE(SUM(balance_amount), 0) FROM user_coupons WHERE user_id = ? AND status = 1",
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.UnusedCount = unusedCount
rsp.UsedCount = usedCount
rsp.ExpiredCount = expiredCount
rsp.TotalRemaining = totalRemaining
rsp.TotalSaved = totalSaved
ctx.Payload(rsp)
}
}