Compare commits

..

2 Commits

Author SHA1 Message Date
shanshanzhong147 5d2460c310 修复(#79): 合并internal并适配数量配价
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 01:14:32 -07:00
shanshanzhong147 e27b2320b4 新功能(#79): 实现促销管理接口并支持数量配价
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 00:54:32 -07:00
25 changed files with 135 additions and 780 deletions
+7 -7
View File
@@ -37,8 +37,8 @@ type (
Id int64 `uri:"id" validate:"required,gt=0"` Id int64 `uri:"id" validate:"required,gt=0"`
} }
GetPromoRuleListRequest { GetPromoRuleListRequest {
Page int64 `form:"page" validate:"required,gt=0"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"` Size int64 `form:"size" validate:"required"`
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"` Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
Enabled *bool `form:"enabled"` Enabled *bool `form:"enabled"`
Search string `form:"search,omitempty"` Search string `form:"search,omitempty"`
@@ -49,12 +49,12 @@ type (
} }
SetPromoPriceRequest { SetPromoPriceRequest {
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"` PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"` Items []PromoPriceItem `json:"items" validate:"required,dive"`
} }
GetPromoPriceListRequest { GetPromoPriceListRequest {
PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"` PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"`
Page int64 `form:"page" validate:"required,gt=0"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"` Size int64 `form:"size" validate:"required"`
} }
GetPromoPriceListResponse { GetPromoPriceListResponse {
Total int64 `json:"total"` Total int64 `json:"total"`
@@ -64,8 +64,8 @@ type (
Id int64 `uri:"id" validate:"required,gt=0"` Id int64 `uri:"id" validate:"required,gt=0"`
} }
GetPromoUsageListRequest { GetPromoUsageListRequest {
Page int64 `form:"page" validate:"required,gt=0"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"` Size int64 `form:"size" validate:"required"`
RuleId int64 `form:"rule_id,omitempty"` RuleId int64 `form:"rule_id,omitempty"`
UserId int64 `form:"user_id,omitempty"` UserId int64 `form:"user_id,omitempty"`
SubscribeId int64 `form:"subscribe_id,omitempty"` SubscribeId int64 `form:"subscribe_id,omitempty"`
+1 -1
View File
@@ -229,7 +229,6 @@ type (
Quantity int64 `json:"quantity"` Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"` Discount float64 `json:"discount"`
MapApple string `json:"map_apple"` MapApple string `json:"map_apple"`
Promo *SubscribePromo `json:"promo"`
} }
PromoPrice { PromoPrice {
Id int64 `json:"id"` Id int64 `json:"id"`
@@ -286,6 +285,7 @@ type (
UnitPrice int64 `json:"unit_price"` UnitPrice int64 `json:"unit_price"`
UnitTime string `json:"unit_time"` UnitTime string `json:"unit_time"`
Discount []SubscribeDiscount `json:"discount"` Discount []SubscribeDiscount `json:"discount"`
Promo *SubscribePromo `json:"promo"`
NodeCount int64 `json:"node_count"` NodeCount int64 `json:"node_count"`
Replacement int64 `json:"replacement"` Replacement int64 `json:"replacement"`
Inventory int64 `json:"inventory"` Inventory int64 `json:"inventory"`
-3
View File
@@ -4316,9 +4316,6 @@
"discount": { "discount": {
"type": "number", "type": "number",
"format": "double" "format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
} }
}, },
"title": "SubscribeDiscount", "title": "SubscribeDiscount",
@@ -1,37 +1,5 @@
-- Purpose: Rollback user-level speed limit overrides from user_subscribe -- Purpose: Rollback user-level speed limit overrides from user_subscribe
SET @column_exists = ( ALTER TABLE `user_subscribe`
SELECT COUNT(*) DROP COLUMN IF EXISTS `traffic_limit`,
FROM INFORMATION_SCHEMA.COLUMNS DROP COLUMN IF EXISTS `speed_limit`;
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'traffic_limit'
);
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `user_subscribe` DROP COLUMN `traffic_limit`',
'SELECT ''Column traffic_limit does not exist in user_subscribe table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'speed_limit'
);
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `user_subscribe` DROP COLUMN `speed_limit`',
'SELECT ''Column speed_limit does not exist in user_subscribe table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -10,7 +10,7 @@ SET @column_exists = (
SET @sql = IF( SET @sql = IF(
@column_exists = 0, @column_exists = 0,
'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` BIGINT NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps, 0=use plan default)'' AFTER `upload`', 'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` int NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps, 0=use plan default)'' AFTER `upload`',
'SELECT ''Column speed_limit already exists in user_subscribe table''' 'SELECT ''Column speed_limit already exists in user_subscribe table'''
); );
@@ -11,63 +11,10 @@ CREATE TABLE IF NOT EXISTS `promo_rule` (
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间', `deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC) KEY `idx_enabled_priority` (`enabled`, `priority` DESC),
KEY `idx_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_enabled_priority'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `promo_rule` DROP INDEX `idx_enabled_priority`',
'SELECT ''Index idx_enabled_priority does not exist on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_deleted_at'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `promo_rule` DROP INDEX `idx_deleted_at`',
'SELECT ''Index idx_deleted_at does not exist on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_enabled_priority_deleted'
);
SET @sql = IF(
@index_exists = 0,
'ALTER TABLE `promo_rule` ADD KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)',
'SELECT ''Index idx_enabled_priority_deleted already exists on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE TABLE IF NOT EXISTS `subscribe_promo` ( CREATE TABLE IF NOT EXISTS `subscribe_promo` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID', `subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
@@ -77,92 +24,10 @@ CREATE TABLE IF NOT EXISTS `subscribe_promo` (
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`), UNIQUE KEY `uk_subscribe_qty_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
KEY `idx_promo_rule_id` (`promo_rule_id`) KEY `idx_promo_rule_id` (`promo_rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND COLUMN_NAME = 'quantity'
);
SET @sql = IF(
@column_exists = 0,
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
'SELECT ''Column quantity already exists in subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
'SELECT ''Column quantity does not exist in subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_rule'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
'SELECT ''Index uk_subscribe_rule does not exist on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_qty_rule'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
'SELECT ''Index uk_subscribe_qty_rule does not exist on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_quantity_rule'
);
SET @sql = IF(
@index_exists = 0,
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
'SELECT ''Index uk_subscribe_quantity_rule already exists on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE TABLE IF NOT EXISTS `promo_usage` ( CREATE TABLE IF NOT EXISTS `promo_usage` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID', `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
@@ -2,14 +2,12 @@ package promo
import ( import (
"context" "context"
stderrors "errors"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm"
) )
type DeletePriceLogic struct { type DeletePriceLogic struct {
@@ -29,10 +27,6 @@ func NewDeletePriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delet
func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error { func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error {
price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id) price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id)
if err != nil { if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
l.Errorw("[DeletePromoPrice] Price Not Found", logger.Field("id", req.Id))
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo price not found"), "promo price not found: %d", req.Id)
}
l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error())) l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error()) return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error())
} }
@@ -2,14 +2,12 @@ package promo
import ( import (
"context" "context"
stderrors "errors"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm"
) )
type DeleteRuleLogic struct { type DeleteRuleLogic struct {
@@ -27,14 +25,6 @@ func NewDeleteRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delete
} }
func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error { func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error {
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id); err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
l.Errorw("[DeletePromoRule] Rule Not Found", logger.Field("id", req.Id))
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo rule not found"), "promo rule not found: %d", req.Id)
}
l.Errorw("[DeletePromoRule] Find Rule Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil { if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error())) l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error()) return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error())
@@ -1,93 +0,0 @@
package promo
import (
"context"
"testing"
promomodel "github.com/perfect-panel/server/internal/model/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/xerr"
pkgerrors "github.com/pkg/errors"
"gorm.io/gorm"
)
type fakePromoModel struct{}
func (fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promomodel.RuleWithPrice, error) {
return nil, nil
}
func (fakePromoModel) InsertUsage(context.Context, *promomodel.Usage, ...*gorm.DB) error {
return nil
}
func (fakePromoModel) InsertRule(context.Context, *promomodel.Rule) error {
return nil
}
func (fakePromoModel) FindRule(context.Context, int64) (*promomodel.Rule, error) {
return nil, gorm.ErrRecordNotFound
}
func (fakePromoModel) UpdateRule(context.Context, *promomodel.Rule) error {
return nil
}
func (fakePromoModel) DeleteRule(context.Context, int64) error {
return nil
}
func (fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promomodel.Rule, error) {
return 0, nil, nil
}
func (fakePromoModel) UpsertPrices(context.Context, int64, []*promomodel.SubscribePromo) error {
return nil
}
func (fakePromoModel) FindPrice(context.Context, int64) (*promomodel.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (fakePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promomodel.SubscribePromo, error) {
return 0, nil, nil
}
func (fakePromoModel) QueryUsageList(context.Context, promomodel.UsageFilter) (int64, []*promomodel.Usage, error) {
return 0, nil, nil
}
func (fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func TestDeleteRuleNotFoundReturns404(t *testing.T) {
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
err := NewDeleteRuleLogic(context.Background(), svcCtx).DeleteRule(&types.DeletePromoRuleRequest{Id: 1})
assertCodeError(t, err, 404)
}
func TestDeletePriceNotFoundReturns404(t *testing.T) {
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
err := NewDeletePriceLogic(context.Background(), svcCtx).DeletePrice(&types.DeletePromoPriceRequest{Id: 1})
assertCodeError(t, err, 404)
}
func assertCodeError(t *testing.T, err error, want uint32) {
t.Helper()
if err == nil {
t.Fatal("expected error")
}
codeErr, ok := pkgerrors.Cause(err).(*xerr.CodeError)
if !ok {
t.Fatalf("expected CodeError, got %T", pkgerrors.Cause(err))
}
if got := codeErr.GetErrCode(); got != want {
t.Fatalf("unexpected error code: got %d want %d", got, want)
}
}
+7 -21
View File
@@ -4,12 +4,12 @@ import (
"context" "context"
promomodel "github.com/perfect-panel/server/internal/model/promo" promomodel "github.com/perfect-panel/server/internal/model/promo"
subscribeModel "github.com/perfect-panel/server/internal/model/subscribe"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm"
) )
type SetPriceLogic struct { type SetPriceLogic struct {
@@ -31,31 +31,17 @@ func (l *SetPriceLogic) SetPrice(req *types.SetPromoPriceRequest) error {
l.Errorw("[SetPromoPrice] Find Rule Error", logger.Field("error", err.Error())) l.Errorw("[SetPromoPrice] Find Rule Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error()) return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
} }
subscribeIds := make([]int64, 0, len(req.Items))
seenSubscribeIds := make(map[int64]struct{}, len(req.Items))
for _, item := range req.Items {
if _, ok := seenSubscribeIds[item.SubscribeId]; ok {
continue
}
seenSubscribeIds[item.SubscribeId] = struct{}{}
subscribeIds = append(subscribeIds, item.SubscribeId)
}
var subscribes []*subscribeModel.Subscribe
if err := l.svcCtx.DB.WithContext(l.ctx).Model(&subscribeModel.Subscribe{}).Where("id IN ?", subscribeIds).Find(&subscribes).Error; err != nil {
l.Errorw("[SetPromoPrice] Find Subscribe Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
}
subscribeById := make(map[int64]*subscribeModel.Subscribe, len(subscribes))
for _, sub := range subscribes {
subscribeById[sub.Id] = sub
}
items := make([]*promomodel.SubscribePromo, 0, len(req.Items)) items := make([]*promomodel.SubscribePromo, 0, len(req.Items))
cacheKeys := make([]string, 0, len(req.Items)) cacheKeys := make([]string, 0, len(req.Items))
for _, item := range req.Items { for _, item := range req.Items {
sub, ok := subscribeById[item.SubscribeId] sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
if !ok { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "subscribe plan not found") return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "subscribe plan not found")
} }
l.Errorw("[SetPromoPrice] Find Subscribe Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
}
originPrice := sub.UnitPrice * item.Quantity originPrice := sub.UnitPrice * item.Quantity
if item.PromoPrice >= originPrice { if item.PromoPrice >= originPrice {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "promo_price must be less than unit_price * quantity") return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "promo_price must be less than unit_price * quantity")
+2 -16
View File
@@ -11,7 +11,6 @@ import (
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause"
) )
type PromoResult struct { type PromoResult struct {
@@ -149,12 +148,7 @@ func evaluateInactiveUserPromo(
err := db.WithContext(ctx). err := db.WithContext(ctx).
Model(&user.Subscribe{}). Model(&user.Subscribe{}).
Where("user_id = ?", userID). Where("user_id = ?", userID).
Order(clause.OrderBy{ Order("expire_time DESC").
Expression: clause.Expr{
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
Vars: []interface{}{time.UnixMilli(0)},
},
}).
Limit(1). Limit(1).
Take(&lastSub).Error Take(&lastSub).Error
if err != nil { if err != nil {
@@ -164,16 +158,8 @@ func evaluateInactiveUserPromo(
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed") return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
} }
return evaluateInactiveUserExpire(lastSub.ExpireTime, params, now), ruleExpiresAt, nil
}
func evaluateInactiveUserExpire(lastExpire time.Time, params promoRuleParams, now time.Time) bool {
if lastExpire.Equal(time.UnixMilli(0)) {
return false
}
threshold := now.AddDate(0, -params.InactiveMonths, 0) threshold := now.AddDate(0, -params.InactiveMonths, 0)
return lastExpire.Before(threshold) || lastExpire.Equal(threshold) return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil
} }
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time { func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
@@ -1,46 +0,0 @@
package common
import (
"testing"
"time"
)
func TestEvaluateInactiveUserExpire(t *testing.T) {
now := time.Date(2026, 5, 27, 8, 0, 0, 0, time.UTC)
params := promoRuleParams{InactiveMonths: 3}
tests := []struct {
name string
lastExpire time.Time
want bool
}{
{
name: "permanent subscription is not inactive",
lastExpire: time.UnixMilli(0),
want: false,
},
{
name: "active subscription is not inactive",
lastExpire: now.Add(time.Hour),
want: false,
},
{
name: "expire at threshold is inactive",
lastExpire: now.AddDate(0, -3, 0),
want: true,
},
{
name: "expire before threshold is inactive",
lastExpire: now.AddDate(0, -3, -1),
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := evaluateInactiveUserExpire(tt.lastExpire, params, now); got != tt.want {
t.Fatalf("evaluateInactiveUserExpire() = %v, want %v", got, tt.want)
}
})
}
}
@@ -47,18 +47,13 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1") l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1")
req.Quantity = 1 req.Quantity = 1
} }
entitlement, entErr := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, u.Id)
if entErr != nil {
return nil, entErr
}
targetSubscribeID := req.SubscribeId targetSubscribeID := req.SubscribeId
orderType := uint8(1)
isSingleModeRenewal := false isSingleModeRenewal := false
decision, routeErr := commonLogic.ResolvePurchaseRoute( decision, routeErr := commonLogic.ResolvePurchaseRoute(
l.ctx, l.ctx,
l.svcCtx.Config.Subscribe.SingleModel, l.svcCtx.Config.Subscribe.SingleModel,
entitlement.EffectiveUserID, u.Id,
req.SubscribeId, req.SubscribeId,
l.svcCtx.UserModel.FindSingleModeAnchorSubscribe, l.svcCtx.UserModel.FindSingleModeAnchorSubscribe,
) )
@@ -73,44 +68,15 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
targetSubscribeID = decision.ResolvedSubscribeID targetSubscribeID = decision.ResolvedSubscribeID
isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal
if isSingleModeRenewal && decision.Anchor != nil { if isSingleModeRenewal && decision.Anchor != nil {
orderType = 2
l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview", l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview",
logger.Field("mode", "single"), logger.Field("mode", "single"),
logger.Field("route", "purchase_to_renewal"), logger.Field("route", "purchase_to_renewal"),
logger.Field("anchor_user_subscribe_id", decision.Anchor.Id), logger.Field("anchor_user_subscribe_id", decision.Anchor.Id),
logger.Field("user_id", u.Id), logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
) )
} }
} }
// Keep promo eligibility preview aligned with Purchase: an existing paid subscription
// routes the request to renewal semantics, where first-purchase promos are disabled.
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
var existSub user.Subscribe
if e := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Subscribe{}).
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%')", entitlement.EffectiveUserID).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC").
First(&existSub).Error; e == nil && existSub.Id > 0 && existSub.Token != "" {
orderType = 2
l.Infow("[PreCreateOrder] purchase preview routed to renewal because an existing subscription was found",
logger.Field("route_mode", "global_single_subscription"),
logger.Field("route", "purchase_to_existing_subscription"),
logger.Field("existing_subscribe_id", existSub.Id),
logger.Field("existing_status", existSub.Status),
logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
logger.Field("resolved_subscribe_id", targetSubscribeID),
)
} else if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) {
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", e.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find existing subscription error: %v", e.Error())
}
}
// find subscribe plan // find subscribe plan
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID) sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID)
if err != nil { if err != nil {
@@ -120,7 +86,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
// check subscribe plan quota limit for new purchase flow only // check subscribe plan quota limit for new purchase flow only
if !isSingleModeRenewal && sub.Quota > 0 { if !isSingleModeRenewal && sub.Quota > 0 {
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, entitlement.EffectiveUserID) userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id)
if err != nil { if err != nil {
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id)) l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error()) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
@@ -136,7 +102,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
} }
} }
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount) newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount)
if err != nil { if err != nil {
l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility", l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility",
logger.Field("error", err.Error()), logger.Field("error", err.Error()),
@@ -151,13 +117,13 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
priceResult, err := calculatePurchasePrice( priceResult, err := calculatePurchasePrice(
l.ctx, l.ctx,
l.svcCtx, l.svcCtx,
entitlement.EffectiveUserID, u.Id,
targetSubscribeID, targetSubscribeID,
sub.UnitPrice, sub.UnitPrice,
req.Quantity, req.Quantity,
newUserDiscount.Discounts, newUserDiscount.Discounts,
newUserDiscount.EligibleForDiscount, newUserDiscount.EligibleForDiscount,
orderType == 1, !isSingleModeRenewal,
) )
if err != nil { if err != nil {
l.Errorw("[PreCreateOrder] Promo price calculation error", l.Errorw("[PreCreateOrder] Promo price calculation error",
+2 -2
View File
@@ -40,8 +40,8 @@ func calculatePurchasePrice(
if err != nil { if err != nil {
return nil, err return nil, err
} }
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < originalPrice { if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < unitPrice {
result.PayableBase = promoResult.PromoPrice result.PayableBase = promoResult.PromoPrice * quantity
result.PromoRuleId = promoResult.RuleID result.PromoRuleId = promoResult.RuleID
result.PromoDiscount = originalPrice - result.PayableBase result.PromoDiscount = originalPrice - result.PayableBase
result.PromoPrice = promoResult.PromoPrice result.PromoPrice = promoResult.PromoPrice
@@ -12,71 +12,64 @@ import (
type fakePromoModel struct { type fakePromoModel struct {
rules []*promo.RuleWithPrice rules []*promo.RuleWithPrice
lastSubscribeID int64
lastQuantity int64
requireQuantity int64
quantityMismatch []*promo.RuleWithPrice
} }
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) { func (m fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promo.RuleWithPrice, error) {
m.lastSubscribeID = subscribeID
m.lastQuantity = quantity
if m.requireQuantity > 0 && quantity != m.requireQuantity {
return m.quantityMismatch, nil
}
return m.rules, nil return m.rules, nil
} }
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error { func (m fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
return nil return nil
} }
func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error { func (m fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
return nil return nil
} }
func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) { func (m fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
return nil, gorm.ErrRecordNotFound return nil, gorm.ErrRecordNotFound
} }
func (m *fakePromoModel) UpdateRule(context.Context, *promo.Rule) error { func (m fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
return nil return nil
} }
func (m *fakePromoModel) DeleteRule(context.Context, int64) error { func (m fakePromoModel) DeleteRule(context.Context, int64) error {
return nil return nil
} }
func (m *fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) { func (m fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
return 0, nil, nil return 0, nil, nil
} }
func (m *fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error { func (m fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
return nil return nil
} }
func (m *fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) { func (m fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound return nil, gorm.ErrRecordNotFound
} }
func (m *fakePromoModel) DeletePrice(context.Context, int64) error { func (m fakePromoModel) DeletePrice(context.Context, int64) error {
return nil return nil
} }
func (m *fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promo.SubscribePromo, error) { func (m fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promo.SubscribePromo, error) {
return 0, nil, nil return 0, nil, nil
} }
func (m *fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) { func (m fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
return 0, nil, nil return 0, nil, nil
} }
func (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error { func (m fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil return nil
} }
func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) { func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{ svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
{ {
Rule: promo.Rule{ Rule: promo.Rule{
Id: 9, Id: 9,
@@ -84,12 +77,9 @@ func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
Type: promo.RuleTypeCampaign, Type: promo.RuleTypeCampaign,
Enabled: true, Enabled: true,
}, },
PromoPrice: 279, PromoPrice: 600,
}, },
}} }},
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: model,
} }
result, err := calculatePurchasePrice( result, err := calculatePurchasePrice(
@@ -97,9 +87,9 @@ func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
svcCtx, svcCtx,
1, 1,
2, 2,
100, 1000,
7, 3,
[]types.SubscribeDiscount{{Quantity: 7, Discount: 50}}, []types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
true, true,
true, true,
) )
@@ -107,11 +97,11 @@ func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
t.Fatalf("calculatePurchasePrice returned error: %v", err) t.Fatalf("calculatePurchasePrice returned error: %v", err)
} }
if result.OriginalPrice != 700 { if result.OriginalPrice != 3000 {
t.Fatalf("OriginalPrice = %d, want 700", result.OriginalPrice) t.Fatalf("OriginalPrice = %d, want 3000", result.OriginalPrice)
} }
if result.PayableBase != 279 { if result.PayableBase != 1800 {
t.Fatalf("PayableBase = %d, want 279", result.PayableBase) t.Fatalf("PayableBase = %d, want 1800", result.PayableBase)
} }
if result.DiscountAmount != 0 { if result.DiscountAmount != 0 {
t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount) t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount)
@@ -119,19 +109,15 @@ func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
if result.PromoRuleId != 9 { if result.PromoRuleId != 9 {
t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId) t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId)
} }
if result.PromoDiscount != 421 { if result.PromoDiscount != 1200 {
t.Fatalf("PromoDiscount = %d, want 421", result.PromoDiscount) t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
}
if result.PromoPrice != 279 {
t.Fatalf("PromoPrice = %d, want 279", result.PromoPrice)
}
if model.lastQuantity != 7 {
t.Fatalf("promo query quantity = %d, want 7", model.lastQuantity)
} }
} }
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) { func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{ svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
{ {
Rule: promo.Rule{ Rule: promo.Rule{
Id: 10, Id: 10,
@@ -139,12 +125,9 @@ func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
Type: promo.RuleTypeCampaign, Type: promo.RuleTypeCampaign,
Enabled: true, Enabled: true,
}, },
PromoPrice: 3000, PromoPrice: 1000,
}, },
}} }},
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: model,
} }
result, err := calculatePurchasePrice( result, err := calculatePurchasePrice(
@@ -172,52 +155,3 @@ func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount) t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
} }
} }
func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
promoModel := &fakePromoModel{
requireQuantity: 6,
rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 11,
Name: "quantity campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
PromoPrice: 3000,
},
},
}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: promoModel,
}
result, err := calculatePurchasePrice(
context.Background(),
svcCtx,
1,
2,
1000,
6,
[]types.SubscribeDiscount{{Quantity: 6, Discount: 80}},
true,
true,
)
if err != nil {
t.Fatalf("calculatePurchasePrice returned error: %v", err)
}
if promoModel.lastSubscribeID != 2 {
t.Fatalf("lastSubscribeID = %d, want 2", promoModel.lastSubscribeID)
}
if promoModel.lastQuantity != 6 {
t.Fatalf("lastQuantity = %d, want 6", promoModel.lastQuantity)
}
if result.PayableBase != 3000 {
t.Fatalf("PayableBase = %d, want 3000", result.PayableBase)
}
if result.PromoRuleId != 11 {
t.Fatalf("PromoRuleId = %d, want 11", result.PromoRuleId)
}
}
+18 -39
View File
@@ -15,7 +15,6 @@ import (
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause"
) )
const ( const (
@@ -26,7 +25,6 @@ const (
type subscribePromoCandidate struct { type subscribePromoCandidate struct {
SubscribeId int64 `gorm:"column:subscribe_id"` SubscribeId int64 `gorm:"column:subscribe_id"`
Quantity int64 `gorm:"column:quantity"`
RuleName string `gorm:"column:rule_name"` RuleName string `gorm:"column:rule_name"`
RuleType string `gorm:"column:rule_type"` RuleType string `gorm:"column:rule_type"`
PromoPrice int64 `gorm:"column:promo_price"` PromoPrice int64 `gorm:"column:promo_price"`
@@ -40,8 +38,8 @@ type promoRuleParams struct {
InactiveMonths int `json:"inactive_months"` InactiveMonths int `json:"inactive_months"`
} }
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) { func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]*types.SubscribePromo, error) {
result := make(map[int64]map[int64]*types.SubscribePromo) result := make(map[int64]*types.SubscribePromo)
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil { if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
return result, nil return result, nil
} }
@@ -58,13 +56,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo} evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
now := time.Now() now := time.Now()
for _, candidate := range candidates { for _, candidate := range candidates {
if candidate.Quantity <= 0 { if _, exists := result[candidate.SubscribeId]; exists {
continue
}
if result[candidate.SubscribeId] == nil {
result[candidate.SubscribeId] = make(map[int64]*types.SubscribePromo)
}
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
continue continue
} }
if !candidate.isActive(now) { if !candidate.isActive(now) {
@@ -77,7 +69,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
if !ok { if !ok {
continue continue
} }
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{ result[candidate.SubscribeId] = &types.SubscribePromo{
RuleName: candidate.RuleName, RuleName: candidate.RuleName,
RuleType: candidate.RuleType, RuleType: candidate.RuleType,
PromoPrice: candidate.PromoPrice, PromoPrice: candidate.PromoPrice,
@@ -90,28 +82,23 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) { func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
var candidates []subscribePromoCandidate var candidates []subscribePromoCandidate
err := subscribePromoCandidatesQuery(ctx, svcCtx.DB, subscribeIDs, loggedIn). query := svcCtx.DB.WithContext(ctx).
Scan(&candidates).Error
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
}
return candidates, nil
}
func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeIDs []int64, loggedIn bool) *gorm.DB {
query := db.WithContext(ctx).
Table("subscribe_promo AS sp"). Table("subscribe_promo AS sp").
Select("sp.subscribe_id, sp.quantity, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time"). Select("sp.subscribe_id, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL"). Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true) Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
if !loggedIn { if !loggedIn {
query = query.Where("pr.type = ?", promoRuleTypeCampaign) query = query.Where("pr.type = ?", promoRuleTypeCampaign)
} }
return query. err := query.
Order("sp.subscribe_id ASC"). Order("sp.subscribe_id ASC").
Order("sp.quantity ASC").
Order("pr.priority DESC"). Order("pr.priority DESC").
Order("pr.id ASC") Order("pr.id ASC").
Scan(&candidates).Error
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
}
return candidates, nil
} }
func (c subscribePromoCandidate) isActive(now time.Time) bool { func (c subscribePromoCandidate) isActive(now time.Time) bool {
@@ -184,7 +171,11 @@ func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
return *e.lastExpire, nil return *e.lastExpire, nil
} }
var item user.Subscribe var item user.Subscribe
err := e.lastSubscribeExpireQuery(). err := e.db.WithContext(e.ctx).
Model(&user.Subscribe{}).
Where("user_id = ?", e.userInfo.Id).
Where("expire_time != ?", time.UnixMilli(0)).
Order("expire_time DESC").
Limit(1). Limit(1).
Take(&item).Error Take(&item).Error
if err != nil { if err != nil {
@@ -199,18 +190,6 @@ func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
return item.ExpireTime, nil return item.ExpireTime, nil
} }
func (e *promoEligibilityEvaluator) lastSubscribeExpireQuery() *gorm.DB {
return e.db.WithContext(e.ctx).
Model(&user.Subscribe{}).
Where("user_id = ?", e.userInfo.Id).
Order(clause.OrderBy{
Expression: clause.Expr{
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
Vars: []interface{}{time.UnixMilli(0)},
},
})
}
func (c subscribePromoCandidate) expiresAt() time.Time { func (c subscribePromoCandidate) expiresAt() time.Time {
if c.EndTime == nil { if c.EndTime == nil {
return time.Time{} return time.Time{}
@@ -1,15 +1,10 @@
package subscribe package subscribe
import ( import (
"context"
"strings"
"testing" "testing"
"time" "time"
"github.com/perfect-panel/server/internal/model/user" "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/types"
"gorm.io/driver/mysql"
"gorm.io/gorm"
) )
func TestPromoEligibilityEvaluatorMatch(t *testing.T) { func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
@@ -78,83 +73,3 @@ func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
t.Fatal("candidate after end time should not be active") t.Fatal("candidate after end time should not be active")
} }
} }
func TestLastSubscribeExpireAtPrioritizesPermanentSubscription(t *testing.T) {
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
SkipInitializeWithVersion: true,
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
if err != nil {
t.Fatalf("open dry-run db: %v", err)
}
evaluator := &promoEligibilityEvaluator{
db: db,
userInfo: &user.User{Id: 7},
}
var item user.Subscribe
tx := evaluator.lastSubscribeExpireQuery().Limit(1).Take(&item)
sql := tx.Statement.SQL.String()
if !strings.Contains(sql, "CASE WHEN expire_time = ? THEN 0 ELSE 1 END") {
t.Fatalf("SQL missing permanent subscription priority order: %s", sql)
}
if strings.Contains(sql, "expire_time !=") {
t.Fatalf("SQL should not filter out permanent subscriptions: %s", sql)
}
if len(tx.Statement.Vars) < 2 {
t.Fatalf("SQL vars length = %d, want at least 2; vars=%v", len(tx.Statement.Vars), tx.Statement.Vars)
}
if got, want := tx.Statement.Vars[1], time.UnixMilli(0); got != want {
t.Fatalf("permanent subscription order var = %v, want %v; vars=%v", got, want, tx.Statement.Vars)
}
}
func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
SkipInitializeWithVersion: true,
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
if err != nil {
t.Fatalf("open dry-run db: %v", err)
}
var candidates []subscribePromoCandidate
tx := subscribePromoCandidatesQuery(context.Background(), db, []int64{11, 12}, true).Scan(&candidates)
stmt := tx.Statement
sql := stmt.SQL.String()
if !strings.Contains(sql, "sp.subscribe_id, sp.quantity, sp.promo_price") {
t.Fatalf("SQL missing quantity select: %s", sql)
}
if !strings.Contains(sql, "ORDER BY sp.subscribe_id ASC,sp.quantity ASC,pr.priority DESC,pr.id ASC") {
t.Fatalf("SQL missing quantity order: %s", sql)
}
}
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
{Quantity: 1},
{Quantity: 12},
}}
promos := map[int64]*types.SubscribePromo{
3: {RuleName: "季度优惠", PromoPrice: 2900},
12: {RuleName: "年度优惠", PromoPrice: 9900},
}
applySubscribeDiscountPromos(&subscribe, promos)
if subscribe.Discount[0].Promo != nil {
t.Fatalf("quantity 1 promo should be nil, got %+v", subscribe.Discount[0].Promo)
}
if subscribe.Discount[1].Promo == nil {
t.Fatal("quantity 12 promo should match")
}
if got, want := subscribe.Discount[1].Promo.RuleName, "年度优惠"; got != want {
t.Fatalf("promo rule name = %q, want %q", got, want)
}
subscribe = types.Subscribe{Discount: []types.SubscribeDiscount{{Quantity: 6}}}
applySubscribeDiscountPromos(&subscribe, promos)
if subscribe.Discount[0].Promo != nil {
t.Fatalf("promo should be nil when quantity does not match, got %+v", subscribe.Discount[0].Promo)
}
}
@@ -56,17 +56,9 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
var discount []types.SubscribeDiscount var discount []types.SubscribeDiscount
_ = json.Unmarshal([]byte(item.Discount), &discount) _ = json.Unmarshal([]byte(item.Discount), &discount)
sub.Discount = discount sub.Discount = discount
}
list[i] = sub list[i] = sub
} }
list[i] = sub
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
if err != nil {
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
return nil, err
}
for i := range list {
applySubscribeDiscountPromos(&list[i], promos[list[i].Id])
} }
// 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个 // 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个
@@ -79,13 +71,16 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
} }
} }
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
if err != nil {
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
return nil, err
}
for i := range list {
list[i].Promo = promos[list[i].Id]
}
resp.List = list resp.List = list
resp.Total = int64(len(list)) resp.Total = int64(len(list))
return return
} }
func applySubscribeDiscountPromos(subscribe *types.Subscribe, promoByQuantity map[int64]*types.SubscribePromo) {
for i := range subscribe.Discount {
subscribe.Discount[i].Promo = promoByQuantity[subscribe.Discount[i].Quantity]
}
}
+2 -13
View File
@@ -81,15 +81,7 @@ func (m *defaultPromoModel) FindRule(ctx context.Context, id int64) (*Rule, erro
} }
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error { func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
return m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", data.Id).Updates(map[string]interface{}{ return m.db.WithContext(ctx).Save(data).Error
"name": data.Name,
"type": data.Type,
"params": data.Params,
"priority": data.Priority,
"enabled": data.Enabled,
"start_time": data.StartTime,
"end_time": data.EndTime,
}).Error
} }
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error { func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
@@ -137,10 +129,7 @@ func (m *defaultPromoModel) UpsertPrices(ctx context.Context, ruleId int64, item
return err return err
} }
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
if err := tx.Create(item).Error; err != nil { return tx.Create(item).Error
return err
}
continue
} }
existing.Quantity = item.Quantity existing.Quantity = item.Quantity
existing.PromoPrice = item.PromoPrice existing.PromoPrice = item.PromoPrice
+1 -1
View File
@@ -33,7 +33,7 @@ func (Rule) TableName() string {
type SubscribePromo struct { type SubscribePromo struct {
Id int64 `gorm:"primaryKey"` Id int64 `gorm:"primaryKey"`
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"` SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
Quantity int64 `gorm:"type:int;not null;default:0;comment:购买数量"` Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"` PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"` PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"` CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
-58
View File
@@ -1,58 +0,0 @@
package types
import (
"testing"
"github.com/go-playground/validator/v10"
)
func TestPromoPriceItemsMustNotBeEmpty(t *testing.T) {
validate := validator.New()
req := SetPromoPriceRequest{
PromoRuleId: 1,
Items: []PromoPriceItem{},
}
if err := validate.Struct(req); err == nil {
t.Fatal("expected empty promo price items to fail validation")
}
}
func TestPromoListPageSizeLimit(t *testing.T) {
validate := validator.New()
tests := []struct {
name string
req any
}{
{
name: "rule list",
req: GetPromoRuleListRequest{
Page: 1,
Size: 201,
},
},
{
name: "price list",
req: GetPromoPriceListRequest{
PromoRuleId: 1,
Page: 1,
Size: 201,
},
},
{
name: "usage list",
req: GetPromoUsageListRequest{
Page: 1,
Size: 201,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := validate.Struct(tt.req); err == nil {
t.Fatal("expected page size greater than 200 to fail validation")
}
})
}
}
+8 -8
View File
@@ -1147,8 +1147,8 @@ type GetCouponListResponse struct {
type GetPromoPriceListRequest struct { type GetPromoPriceListRequest struct {
PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"` PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"`
Page int64 `form:"page" validate:"required,gt=0"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"` Size int64 `form:"size" validate:"required"`
} }
type GetPromoPriceListResponse struct { type GetPromoPriceListResponse struct {
@@ -1161,8 +1161,8 @@ type GetPromoRuleDetailRequest struct {
} }
type GetPromoRuleListRequest struct { type GetPromoRuleListRequest struct {
Page int64 `form:"page" validate:"required,gt=0"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"` Size int64 `form:"size" validate:"required"`
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"` Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
Enabled *bool `form:"enabled"` Enabled *bool `form:"enabled"`
Search string `form:"search,omitempty"` Search string `form:"search,omitempty"`
@@ -1174,8 +1174,8 @@ type GetPromoRuleListResponse struct {
} }
type GetPromoUsageListRequest struct { type GetPromoUsageListRequest struct {
Page int64 `form:"page" validate:"required,gt=0"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"` Size int64 `form:"size" validate:"required"`
RuleId int64 `form:"rule_id,omitempty"` RuleId int64 `form:"rule_id,omitempty"`
UserId int64 `form:"user_id,omitempty"` UserId int64 `form:"user_id,omitempty"`
SubscribeId int64 `form:"subscribe_id,omitempty"` SubscribeId int64 `form:"subscribe_id,omitempty"`
@@ -2880,6 +2880,7 @@ type Subscribe struct {
UnitPrice int64 `json:"unit_price"` UnitPrice int64 `json:"unit_price"`
UnitTime string `json:"unit_time"` UnitTime string `json:"unit_time"`
Discount []SubscribeDiscount `json:"discount"` Discount []SubscribeDiscount `json:"discount"`
Promo *SubscribePromo `json:"promo"`
NodeCount int64 `json:"node_count"` NodeCount int64 `json:"node_count"`
Replacement int64 `json:"replacement"` Replacement int64 `json:"replacement"`
Inventory int64 `json:"inventory"` Inventory int64 `json:"inventory"`
@@ -2944,7 +2945,6 @@ type SubscribeDiscount struct {
Discount float64 `json:"discount"` Discount float64 `json:"discount"`
NewUserOnly bool `json:"new_user_only"` NewUserOnly bool `json:"new_user_only"`
MapApple string `json:"map_apple"` MapApple string `json:"map_apple"`
Promo *SubscribePromo `json:"promo"`
} }
type SubscribeGroup struct { type SubscribeGroup struct {
@@ -3223,7 +3223,7 @@ type UpdateCouponRequest struct {
type SetPromoPriceRequest struct { type SetPromoPriceRequest struct {
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"` PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"` Items []PromoPriceItem `json:"items" validate:"required,dive"`
} }
type DeletePromoPriceRequest struct { type DeletePromoPriceRequest struct {
-3
View File
@@ -3680,9 +3680,6 @@
"discount": { "discount": {
"type": "number", "type": "number",
"format": "double" "format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
} }
}, },
"title": "SubscribeDiscount", "title": "SubscribeDiscount",
+12 -18
View File
@@ -149,20 +149,7 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
return err return err
} }
if err = l.recordPromoUsage(ctx, orderInfo); err != nil { l.recordPromoUsage(ctx, orderInfo)
if releaseErr := l.releaseClaim(ctx, orderInfo.OrderNo); releaseErr != nil {
logger.WithContext(ctx).Error("[ActivateOrderLogic] releaseClaim also failed, stuck recovery will handle",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("release_error", releaseErr.Error()),
)
}
logger.WithContext(ctx).Error("[ActivateOrderLogic] 促销使用记录写入失败,将重试",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
logger.Field("error", err.Error()),
)
return err
}
l.finalizeCouponAndOrder(ctx, orderInfo) l.finalizeCouponAndOrder(ctx, orderInfo)
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished", commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished",
@@ -172,9 +159,9 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
return nil return nil
} }
func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) error { func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) {
if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" { if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" {
return nil return
} }
promoPrice := int64(0) promoPrice := int64(0)
@@ -182,10 +169,10 @@ func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *or
promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity
} }
if promoPrice <= 0 { if promoPrice <= 0 {
return nil return
} }
return l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error { err := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var count int64 var count int64
if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil { if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil {
return e return e
@@ -201,6 +188,13 @@ func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *or
PromoPrice: promoPrice, PromoPrice: promoPrice,
}, tx) }, tx)
}) })
if err != nil {
logger.WithContext(ctx).Error("Insert promo usage failed",
logger.Field("error", err.Error()),
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
)
}
} }
// parsePayload unMarshals the task payload into a structured format // parsePayload unMarshals the task payload into a structured format
-3
View File
@@ -5900,9 +5900,6 @@
"discount": { "discount": {
"type": "number", "type": "number",
"format": "double" "format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
} }
}, },
"title": "SubscribeDiscount", "title": "SubscribeDiscount",