feat(points): 增加双边积分与虚拟积分商城

This commit is contained in:
yml2213
2026-11-04 19:21:02 +08:00
parent c00d691301
commit d5abe67f60
42 changed files with 2593 additions and 316 deletions
+123
View File
@@ -0,0 +1,123 @@
package pointsmall
import (
"errors"
"time"
"hfb_sys/backend/internal/model"
)
var (
ErrDependencyUnavailable = errors.New("points mall dependency unavailable")
ErrInvalidInput = errors.New("invalid points mall input")
ErrProductUnavailable = errors.New("points mall product unavailable")
ErrInsufficientPoints = errors.New("insufficient points")
ErrRedeemLimitExceeded = errors.New("redeem limit exceeded")
ErrRedemptionNotPending = errors.New("redemption not pending")
)
type SummaryDTO struct {
AvailablePoints int64 `json:"available_points"`
LifetimePoints int64 `json:"lifetime_points"`
LevelCode string `json:"level_code"`
LevelName string `json:"level_name"`
PointsPerYuan int64 `json:"points_per_yuan"`
PointsMultiplierBps int `json:"points_multiplier_bps"`
}
type ProductDTO struct {
ID uint64 `json:"id"`
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Description string `json:"description"`
CoverURL string `json:"cover_url"`
RedemptionInstructions string `json:"redemption_instructions"`
PointsPrice int64 `json:"points_price"`
Stock int64 `json:"stock"`
RedeemedCount int64 `json:"redeemed_count"`
PerUserLimit int `json:"per_user_limit"`
Status string `json:"status"`
SortOrder int `json:"sort_order"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ProductRequest struct {
Title string `json:"title" binding:"required,max=128"`
Subtitle string `json:"subtitle" binding:"max=255"`
Description string `json:"description" binding:"required"`
CoverURL string `json:"cover_url"`
RedemptionInstructions string `json:"redemption_instructions" binding:"required"`
PointsPrice int64 `json:"points_price" binding:"required,min=1"`
Stock int64 `json:"stock" binding:"min=0"`
PerUserLimit int `json:"per_user_limit" binding:"required,min=1,max=100"`
Status string `json:"status" binding:"required,oneof=online offline"`
SortOrder int `json:"sort_order"`
}
type RedeemRequest struct {
Quantity int `json:"quantity" binding:"required,min=1,max=10"`
}
type CompleteRedemptionRequest struct {
Remark string `json:"remark" binding:"max=255"`
}
type RedemptionDTO struct {
ID uint64 `json:"id"`
RedemptionNo string `json:"redemption_no"`
UserID uint64 `json:"user_id"`
UserPhone string `json:"user_phone,omitempty"`
UserNickname string `json:"user_nickname,omitempty"`
ProductID uint64 `json:"product_id"`
ProductTitle string `json:"product_title"`
ProductCoverURL string `json:"product_cover_url"`
RedemptionInstructions string `json:"redemption_instructions"`
PointsPrice int64 `json:"points_price"`
Quantity int `json:"quantity"`
TotalPoints int64 `json:"total_points"`
Status string `json:"status"`
AdminRemark string `json:"admin_remark"`
CompletedBy *uint64 `json:"completed_by,omitempty"`
CompletedAt *time.Time `json:"completed_at"`
CreatedAt time.Time `json:"created_at"`
}
func toProductDTO(item model.PointsMallProduct) ProductDTO {
return ProductDTO{
ID: item.ID,
Title: item.Title,
Subtitle: item.Subtitle,
Description: item.Description,
CoverURL: item.CoverURL,
RedemptionInstructions: item.RedemptionInstructions,
PointsPrice: item.PointsPrice,
Stock: item.Stock,
RedeemedCount: item.RedeemedCount,
PerUserLimit: item.PerUserLimit,
Status: item.Status,
SortOrder: item.SortOrder,
CreatedAt: item.CreatedAt,
UpdatedAt: item.UpdatedAt,
}
}
func toRedemptionDTO(item model.PointsMallRedemption) RedemptionDTO {
return RedemptionDTO{
ID: item.ID,
RedemptionNo: item.RedemptionNo,
UserID: item.UserID,
ProductID: item.ProductID,
ProductTitle: item.ProductTitle,
ProductCoverURL: item.ProductCoverURL,
RedemptionInstructions: item.RedemptionInstructions,
PointsPrice: item.PointsPrice,
Quantity: item.Quantity,
TotalPoints: item.TotalPoints,
Status: item.Status,
AdminRemark: item.AdminRemark,
CompletedBy: item.CompletedBy,
CompletedAt: item.CompletedAt,
CreatedAt: item.CreatedAt,
}
}
@@ -0,0 +1,208 @@
package pointsmall
import (
"errors"
"net/http"
"strconv"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) Summary(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
item, err := h.service.Summary(c.Request.Context(), userID)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) Ledger(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
items, err := h.service.Ledger(c.Request.Context(), userID, parseLimit(c.Query("limit")))
if err != nil {
writeError(c, err)
return
}
response.OK(c, items)
}
func (h *Handler) Products(c *gin.Context) {
items, err := h.service.ListProducts(c.Request.Context(), false)
if err != nil {
writeError(c, err)
return
}
response.OK(c, items)
}
func (h *Handler) AdminProducts(c *gin.Context) {
items, err := h.service.ListProducts(c.Request.Context(), true)
if err != nil {
writeError(c, err)
return
}
response.OK(c, items)
}
func (h *Handler) CreateProduct(c *gin.Context) {
var req ProductRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "积分商品参数不正确")
return
}
item, err := h.service.CreateProduct(c.Request.Context(), req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) UpdateProduct(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
if id == 0 {
response.BadRequest(c, "商品 ID 不正确")
return
}
var req ProductRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "积分商品参数不正确")
return
}
item, err := h.service.UpdateProduct(c.Request.Context(), id, req)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) Redeem(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
productID, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var req RedeemRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "兑换数量不正确")
return
}
item, err := h.service.Redeem(c.Request.Context(), userID, productID, req.Quantity)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) MyRedemptions(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
response.Unauthorized(c, "缺少用户上下文")
return
}
items, err := h.service.ListRedemptions(c.Request.Context(), userID, false)
if err != nil {
writeError(c, err)
return
}
response.OK(c, items)
}
func (h *Handler) AdminRedemptions(c *gin.Context) {
items, err := h.service.ListRedemptions(c.Request.Context(), 0, true)
if err != nil {
writeError(c, err)
return
}
response.OK(c, items)
}
func (h *Handler) CompleteRedemption(c *gin.Context) {
adminID, ok := currentAdminID(c)
if !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var req CompleteRedemptionRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "处理备注不正确")
return
}
item, err := h.service.CompleteRedemption(c.Request.Context(), adminID, id, req.Remark)
if err != nil {
writeError(c, err)
return
}
response.OK(c, item)
}
func currentUserID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextUserID)
if !ok {
return 0, false
}
id, ok := value.(uint64)
return id, ok
}
func currentAdminID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextAdminID)
if !ok {
return 0, false
}
id, ok := value.(uint64)
return id, ok
}
func parseLimit(value string) int {
limit, err := strconv.Atoi(value)
if err != nil {
return 100
}
return limit
}
func writeError(c *gin.Context, err error) {
response.RecordError(c, err)
switch {
case errors.Is(err, ErrInvalidInput):
response.BadRequest(c, "积分商城参数不正确")
case errors.Is(err, ErrProductUnavailable):
response.Error(c, http.StatusConflict, "points_product_unavailable", "商品已下架或库存不足")
case errors.Is(err, ErrInsufficientPoints):
response.Error(c, http.StatusConflict, "insufficient_points", "可用积分不足")
case errors.Is(err, ErrRedeemLimitExceeded):
response.Error(c, http.StatusConflict, "points_redeem_limit", "已超过该商品限兑数量")
case errors.Is(err, ErrRedemptionNotPending):
response.Error(c, http.StatusConflict, "points_redemption_processed", "该兑换记录已处理")
case IsNotFound(err):
response.Error(c, http.StatusNotFound, "not_found", "积分商城数据不存在")
default:
response.Error(c, http.StatusInternalServerError, "internal_error", "积分商城服务暂时不可用")
}
}
@@ -0,0 +1,271 @@
package pointsmall
import (
"context"
"errors"
"fmt"
"strings"
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/rentergrowth"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) Summary(ctx context.Context, userID uint64) (*SummaryDTO, error) {
var user model.User
if err := r.db.WithContext(ctx).First(&user, userID).Error; err != nil {
return nil, err
}
cfg, err := rentergrowth.ConfigForTx(r.db.WithContext(ctx))
if err != nil {
return nil, err
}
level := rentergrowth.LevelForPoints(cfg, user.RenterGrowthPoints)
return &SummaryDTO{
AvailablePoints: user.PointsAvailable,
LifetimePoints: user.RenterGrowthPoints,
LevelCode: level.Code,
LevelName: level.Name,
PointsPerYuan: cfg.PointsPerYuan,
PointsMultiplierBps: level.PointsMultiplierBps,
}, nil
}
func (r *Repository) Ledger(ctx context.Context, userID uint64, limit int) ([]model.RenterGrowthLedger, error) {
if limit <= 0 || limit > 200 {
limit = 100
}
var rows []model.RenterGrowthLedger
err := r.db.WithContext(ctx).
Where("user_id = ?", userID).
Order("created_at DESC, id DESC").
Limit(limit).
Find(&rows).Error
return rows, err
}
func (r *Repository) ListProducts(ctx context.Context, includeOffline bool) ([]ProductDTO, error) {
var rows []model.PointsMallProduct
tx := r.db.WithContext(ctx).Order("sort_order DESC, id DESC")
if !includeOffline {
tx = tx.Where("status = ?", "online")
}
if err := tx.Find(&rows).Error; err != nil {
return nil, err
}
items := make([]ProductDTO, 0, len(rows))
for _, row := range rows {
items = append(items, toProductDTO(row))
}
return items, nil
}
func (r *Repository) CreateProduct(ctx context.Context, req ProductRequest) (*ProductDTO, error) {
item := productFromRequest(req)
if err := r.db.WithContext(ctx).Create(&item).Error; err != nil {
return nil, err
}
dto := toProductDTO(item)
return &dto, nil
}
func (r *Repository) UpdateProduct(ctx context.Context, id uint64, req ProductRequest) (*ProductDTO, error) {
var item model.PointsMallProduct
if err := r.db.WithContext(ctx).First(&item, id).Error; err != nil {
return nil, err
}
next := productFromRequest(req)
next.ID = item.ID
next.RedeemedCount = item.RedeemedCount
next.CreatedAt = item.CreatedAt
if err := r.db.WithContext(ctx).Model(&item).Updates(map[string]any{
"title": next.Title,
"subtitle": next.Subtitle,
"description": next.Description,
"cover_url": next.CoverURL,
"redemption_instructions": next.RedemptionInstructions,
"points_price": next.PointsPrice,
"stock": next.Stock,
"per_user_limit": next.PerUserLimit,
"status": next.Status,
"sort_order": next.SortOrder,
}).Error; err != nil {
return nil, err
}
return r.findProduct(ctx, id)
}
func (r *Repository) findProduct(ctx context.Context, id uint64) (*ProductDTO, error) {
var item model.PointsMallProduct
if err := r.db.WithContext(ctx).First(&item, id).Error; err != nil {
return nil, err
}
dto := toProductDTO(item)
return &dto, nil
}
func (r *Repository) Redeem(ctx context.Context, userID, productID uint64, quantity int) (*RedemptionDTO, error) {
if userID == 0 || productID == 0 || quantity <= 0 || quantity > 10 {
return nil, ErrInvalidInput
}
var result model.PointsMallRedemption
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var product model.PointsMallProduct
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&product, productID).Error; err != nil {
return err
}
if product.Status != "online" || product.Stock < int64(quantity) {
return ErrProductUnavailable
}
var redeemed int64
if err := tx.Model(&model.PointsMallRedemption{}).
Where("product_id = ? AND user_id = ? AND status <> ?", productID, userID, "cancelled").
Select("COALESCE(SUM(quantity), 0)").
Scan(&redeemed).Error; err != nil {
return err
}
if redeemed+int64(quantity) > int64(product.PerUserLimit) {
return ErrRedeemLimitExceeded
}
var user model.User
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
return err
}
totalPoints := product.PointsPrice * int64(quantity)
if totalPoints <= 0 || user.PointsAvailable < totalPoints {
return ErrInsufficientPoints
}
now := time.Now()
result = model.PointsMallRedemption{
RedemptionNo: fmt.Sprintf("PM%d%d", userID, now.UnixNano()),
UserID: userID,
ProductID: product.ID,
ProductTitle: product.Title,
ProductCoverURL: product.CoverURL,
RedemptionInstructions: product.RedemptionInstructions,
PointsPrice: product.PointsPrice,
Quantity: quantity,
TotalPoints: totalPoints,
Status: "pending",
CreatedAt: now,
UpdatedAt: now,
}
if err := tx.Create(&result).Error; err != nil {
return err
}
beforePoints := user.PointsAvailable
user.PointsAvailable -= totalPoints
if err := tx.Save(&user).Error; err != nil {
return err
}
if err := tx.Model(&product).Updates(map[string]any{
"stock": gorm.Expr("stock - ?", quantity),
"redeemed_count": gorm.Expr("redeemed_count + ?", quantity),
}).Error; err != nil {
return err
}
bizKey := fmt.Sprintf("mall:%d:redeem", result.ID)
ledger := model.RenterGrowthLedger{
UserID: userID,
Role: "mall",
RedemptionID: result.ID,
Points: -totalPoints,
BeforePoints: user.RenterGrowthPoints,
AfterPoints: user.RenterGrowthPoints,
AvailableBefore: beforePoints,
AvailableAfter: user.PointsAvailable,
BeforeLevel: user.RenterGrowthLevel,
AfterLevel: user.RenterGrowthLevel,
Source: "mall_redeem",
BizKey: &bizKey,
Remark: "积分商城兑换: " + product.Title,
CreatedAt: now,
}
return tx.Create(&ledger).Error
})
if err != nil {
return nil, err
}
dto := toRedemptionDTO(result)
return &dto, nil
}
func (r *Repository) ListRedemptions(ctx context.Context, userID uint64, admin bool) ([]RedemptionDTO, error) {
type row struct {
model.PointsMallRedemption
UserPhone string
UserNickname string
}
var rows []row
tx := r.db.WithContext(ctx).Table("points_mall_redemptions AS r").
Select("r.*, u.phone AS user_phone, u.nickname AS user_nickname").
Joins("LEFT JOIN users AS u ON u.id = r.user_id").
Order("r.created_at DESC, r.id DESC")
if !admin {
tx = tx.Where("r.user_id = ?", userID)
}
if err := tx.Scan(&rows).Error; err != nil {
return nil, err
}
items := make([]RedemptionDTO, 0, len(rows))
for _, item := range rows {
dto := toRedemptionDTO(item.PointsMallRedemption)
dto.UserPhone = item.UserPhone
dto.UserNickname = item.UserNickname
items = append(items, dto)
}
return items, nil
}
func (r *Repository) CompleteRedemption(ctx context.Context, adminID, id uint64, remark string) (*RedemptionDTO, error) {
var result model.PointsMallRedemption
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&result, id).Error; err != nil {
return err
}
if result.Status != "pending" {
return ErrRedemptionNotPending
}
now := time.Now()
result.Status = "completed"
result.AdminRemark = strings.TrimSpace(remark)
result.CompletedBy = &adminID
result.CompletedAt = &now
return tx.Save(&result).Error
})
if err != nil {
return nil, err
}
dto := toRedemptionDTO(result)
return &dto, nil
}
func productFromRequest(req ProductRequest) model.PointsMallProduct {
return model.PointsMallProduct{
Title: strings.TrimSpace(req.Title),
Subtitle: strings.TrimSpace(req.Subtitle),
Description: strings.TrimSpace(req.Description),
CoverURL: strings.TrimSpace(req.CoverURL),
RedemptionInstructions: strings.TrimSpace(req.RedemptionInstructions),
PointsPrice: req.PointsPrice,
Stock: req.Stock,
PerUserLimit: req.PerUserLimit,
Status: req.Status,
SortOrder: req.SortOrder,
}
}
func IsNotFound(err error) bool {
return errors.Is(err, gorm.ErrRecordNotFound)
}
@@ -0,0 +1,61 @@
package pointsmall
import (
"errors"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
)
func TestRedeemDeductsAvailablePointsAndStock(t *testing.T) {
db := database.NewTestDB()
user := model.User{Phone: "13900009601", PointsAvailable: 500}
if err := db.Create(&user).Error; err != nil {
t.Fatalf("create user failed: %v", err)
}
product := model.PointsMallProduct{
Title: "测试兑换码",
Description: "测试商品",
RedemptionInstructions: "联系客服领取",
PointsPrice: 100,
Stock: 2,
PerUserLimit: 2,
Status: "online",
}
if err := db.Create(&product).Error; err != nil {
t.Fatalf("create product failed: %v", err)
}
repo := NewRepository(db)
redemption, err := repo.Redeem(t.Context(), user.ID, product.ID, 2)
if err != nil {
t.Fatalf("redeem failed: %v", err)
}
if redemption.TotalPoints != 200 {
t.Fatalf("total points = %d, want 200", redemption.TotalPoints)
}
var savedUser model.User
if err := db.First(&savedUser, user.ID).Error; err != nil {
t.Fatalf("find user failed: %v", err)
}
if savedUser.PointsAvailable != 300 || savedUser.RenterGrowthPoints != 0 {
t.Fatalf("points after redeem = available %d lifetime %d", savedUser.PointsAvailable, savedUser.RenterGrowthPoints)
}
var savedProduct model.PointsMallProduct
if err := db.First(&savedProduct, product.ID).Error; err != nil {
t.Fatalf("find product failed: %v", err)
}
if savedProduct.Stock != 0 || savedProduct.RedeemedCount != 2 {
t.Fatalf("product stock/redeemed = %d/%d", savedProduct.Stock, savedProduct.RedeemedCount)
}
if _, err := repo.Redeem(t.Context(), user.ID, product.ID, 1); !errors.Is(err, ErrRedeemLimitExceeded) && !errors.Is(err, ErrProductUnavailable) {
t.Fatalf("repeat redeem error = %v, want limit or unavailable", err)
}
completed, err := repo.CompleteRedemption(t.Context(), 99, redemption.ID, "已发放")
if err != nil {
t.Fatalf("complete redemption failed: %v", err)
}
if completed.Status != "completed" {
t.Fatalf("redemption status = %s, want completed", completed.Status)
}
}
@@ -0,0 +1,47 @@
package pointsmall
import (
"context"
"hfb_sys/backend/internal/model"
)
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Summary(ctx context.Context, userID uint64) (*SummaryDTO, error) {
return s.repo.Summary(ctx, userID)
}
func (s *Service) Ledger(ctx context.Context, userID uint64, limit int) ([]model.RenterGrowthLedger, error) {
return s.repo.Ledger(ctx, userID, limit)
}
func (s *Service) ListProducts(ctx context.Context, includeOffline bool) ([]ProductDTO, error) {
return s.repo.ListProducts(ctx, includeOffline)
}
func (s *Service) CreateProduct(ctx context.Context, req ProductRequest) (*ProductDTO, error) {
return s.repo.CreateProduct(ctx, req)
}
func (s *Service) UpdateProduct(ctx context.Context, id uint64, req ProductRequest) (*ProductDTO, error) {
return s.repo.UpdateProduct(ctx, id, req)
}
func (s *Service) Redeem(ctx context.Context, userID, productID uint64, quantity int) (*RedemptionDTO, error) {
return s.repo.Redeem(ctx, userID, productID, quantity)
}
func (s *Service) ListRedemptions(ctx context.Context, userID uint64, admin bool) ([]RedemptionDTO, error) {
return s.repo.ListRedemptions(ctx, userID, admin)
}
func (s *Service) CompleteRedemption(ctx context.Context, adminID, id uint64, remark string) (*RedemptionDTO, error) {
return s.repo.CompleteRedemption(ctx, adminID, id, remark)
}