bindbox-game/internal/api/app/coupon_transfer.go
2026-02-06 16:49:27 +08:00

82 lines
2.8 KiB
Go

package app
import (
"net/http"
"strconv"
"bindbox-game/internal/code"
"bindbox-game/internal/pkg/core"
"bindbox-game/internal/pkg/logger"
"bindbox-game/internal/repository/mysql"
usersvc "bindbox-game/internal/service/user"
)
type couponTransferHandler struct {
logger logger.CustomLogger
repo mysql.Repo
userSvc usersvc.Service
}
func NewCouponTransfer(l logger.CustomLogger, db mysql.Repo, userSvc usersvc.Service) *couponTransferHandler {
return &couponTransferHandler{logger: l, repo: db, userSvc: userSvc}
}
type TransferCouponRequest struct {
ReceiverID int64 `json:"receiver_id" binding:"required"`
}
// TransferCouponHandler 转赠优惠券
// @Summary 转赠优惠券给其他用户
// @Description 将自己持有的优惠券转赠给其他用户
// @Tags APP端.优惠券
// @Accept json
// @Produce json
// @Security LoginVerifyToken
// @Param user_id path int true "发送方用户ID"
// @Param user_coupon_id path int true "优惠券记录ID"
// @Param body body TransferCouponRequest true "接收方信息"
// @Success 200 {object} map[string]bool
// @Failure 400 {object} code.Failure
// @Router /api/app/users/{user_id}/coupons/{user_coupon_id}/transfer [post]
func (h *couponTransferHandler) TransferCouponHandler() core.HandlerFunc {
return func(c core.Context) {
userID, err := strconv.ParseInt(c.Param("user_id"), 10, 64)
if err != nil {
c.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "user_id 无效"))
return
}
userCouponID, err := strconv.ParseInt(c.Param("user_coupon_id"), 10, 64)
if err != nil {
c.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "user_coupon_id 无效"))
return
}
var req TransferCouponRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "请求参数错误"))
return
}
if err := h.userSvc.TransferCoupon(c.RequestContext(), userID, req.ReceiverID, userCouponID); err != nil {
switch err.Error() {
case "invalid_params":
c.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "参数无效"))
case "cannot_transfer_to_self":
c.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "不能转赠给自己"))
case "coupon_not_found":
c.AbortWithError(core.Error(http.StatusNotFound, code.ServerError, "优惠券不存在"))
case "coupon_not_available":
c.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "优惠券状态不可用"))
case "receiver_not_found":
c.AbortWithError(core.Error(http.StatusNotFound, code.ServerError, "接收用户不存在"))
default:
c.AbortWithError(core.Error(http.StatusInternalServerError, code.ServerError, err.Error()))
}
return
}
c.Payload(map[string]any{"success": true})
}
}