Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2ae9ad40de |
@@ -10,6 +10,12 @@ GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
|||||||
# PPanel Server 镜像标签(由 CI/CD 传入不可变 tag,如 git SHA)
|
# PPanel Server 镜像标签(由 CI/CD 传入不可变 tag,如 git SHA)
|
||||||
PPANEL_SERVER_TAG=CHANGE_ME_TO_GIT_SHA
|
PPANEL_SERVER_TAG=CHANGE_ME_TO_GIT_SHA
|
||||||
|
|
||||||
|
# 测试环境 MinIO / S3 兼容存储
|
||||||
|
# ppanel.yaml 中 S3.Endpoint 使用 http://127.0.0.1:9000,Bucket 与此处保持一致。
|
||||||
|
MINIO_ROOT_USER=CHANGE_ME_TO_S3_ACCESS_KEY
|
||||||
|
MINIO_ROOT_PASSWORD=CHANGE_ME_TO_S3_SECRET_KEY
|
||||||
|
MINIO_BUCKET=hifastvpn
|
||||||
|
|
||||||
# AWS 区域(香港)
|
# AWS 区域(香港)
|
||||||
AWS_REGION=ap-east-1
|
AWS_REGION=ap-east-1
|
||||||
|
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
syntax = "v1"
|
|
||||||
|
|
||||||
info (
|
|
||||||
title: "Promo API"
|
|
||||||
desc: "API for ppanel"
|
|
||||||
author: "Tension"
|
|
||||||
email: "tension@ppanel.com"
|
|
||||||
version: "0.0.1"
|
|
||||||
)
|
|
||||||
|
|
||||||
import "../types.api"
|
|
||||||
|
|
||||||
type (
|
|
||||||
PromoRule {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Params interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
StartTime int64 `json:"start_time"`
|
|
||||||
EndTime int64 `json:"end_time"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
CreatePromoRuleRequest {
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params interface{} `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
UpdatePromoRuleRequest {
|
|
||||||
Id int64 `json:"id" validate:"required"`
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params interface{} `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
DeletePromoRuleRequest {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoRuleDetailRequest {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoRuleListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
Type string `form:"type,omitempty" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
|
||||||
Enabled *bool `form:"enabled,omitempty"`
|
|
||||||
Search string `form:"search,omitempty"`
|
|
||||||
}
|
|
||||||
GetPromoRuleListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoRule `json:"list"`
|
|
||||||
}
|
|
||||||
PromoPriceInput {
|
|
||||||
SubscribeId int64 `json:"subscribe_id" validate:"required"`
|
|
||||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
PromoPrice {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
UnitPrice int64 `json:"unit_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
CreatePromoPriceRequest {
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required"`
|
|
||||||
Items []PromoPriceInput `json:"items" validate:"required,dive"`
|
|
||||||
}
|
|
||||||
GetPromoPriceListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoPriceListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoPrice `json:"list"`
|
|
||||||
}
|
|
||||||
DeletePromoPriceRequest {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
PromoUsage {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"user_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
GetPromoUsageListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"rule_id,omitempty"`
|
|
||||||
UserId int64 `form:"user_id,omitempty"`
|
|
||||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
|
||||||
OrderNo string `form:"order_no,omitempty"`
|
|
||||||
}
|
|
||||||
GetPromoUsageListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoUsage `json:"list"`
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
@server (
|
|
||||||
prefix: v1/admin/promo
|
|
||||||
group: admin/promo
|
|
||||||
middleware: AuthMiddleware
|
|
||||||
)
|
|
||||||
service ppanel {
|
|
||||||
@doc "Create promo rule"
|
|
||||||
@handler CreatePromoRule
|
|
||||||
post /rule (CreatePromoRuleRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Get promo rule list"
|
|
||||||
@handler GetPromoRuleList
|
|
||||||
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
|
|
||||||
|
|
||||||
@doc "Get promo rule detail"
|
|
||||||
@handler GetPromoRuleDetail
|
|
||||||
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Update promo rule"
|
|
||||||
@handler UpdatePromoRule
|
|
||||||
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Delete promo rule"
|
|
||||||
@handler DeletePromoRule
|
|
||||||
delete /rule/:id (DeletePromoRuleRequest)
|
|
||||||
|
|
||||||
@doc "Batch set promo price"
|
|
||||||
@handler CreatePromoPrice
|
|
||||||
post /price (CreatePromoPriceRequest)
|
|
||||||
|
|
||||||
@doc "Get promo price list"
|
|
||||||
@handler GetPromoPriceList
|
|
||||||
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
|
|
||||||
|
|
||||||
@doc "Delete promo price"
|
|
||||||
@handler DeletePromoPrice
|
|
||||||
delete /price/:id (DeletePromoPriceRequest)
|
|
||||||
|
|
||||||
@doc "Get promo usage list"
|
|
||||||
@handler GetPromoUsageList
|
|
||||||
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
|
|
||||||
}
|
|
||||||
+33
-14
@@ -76,6 +76,29 @@ type (
|
|||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
IsAdmin bool `json:"is_admin"`
|
IsAdmin bool `json:"is_admin"`
|
||||||
}
|
}
|
||||||
|
UserSubscribeDetail {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
UserId int64 `json:"user_id"`
|
||||||
|
User User `json:"user"`
|
||||||
|
OrderId int64 `json:"order_id"`
|
||||||
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
|
Subscribe Subscribe `json:"subscribe"`
|
||||||
|
NodeGroupId int64 `json:"node_group_id"`
|
||||||
|
GroupLocked bool `json:"group_locked"`
|
||||||
|
StartTime int64 `json:"start_time"`
|
||||||
|
ExpireTime int64 `json:"expire_time"`
|
||||||
|
ResetTime int64 `json:"reset_time"`
|
||||||
|
Traffic int64 `json:"traffic"`
|
||||||
|
Download int64 `json:"download"`
|
||||||
|
Upload int64 `json:"upload"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
Status uint8 `json:"status"`
|
||||||
|
EffectiveSpeed int64 `json:"effective_speed"`
|
||||||
|
IsThrottled bool `json:"is_throttled"`
|
||||||
|
ThrottleRule string `json:"throttle_rule,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
|
}
|
||||||
BatchDeleteUserRequest {
|
BatchDeleteUserRequest {
|
||||||
Ids []int64 `json:"ids" validate:"required"`
|
Ids []int64 `json:"ids" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -135,22 +158,18 @@ type (
|
|||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
}
|
}
|
||||||
CreateUserSubscribeRequest {
|
CreateUserSubscribeRequest {
|
||||||
UserId int64 `json:"user_id"`
|
UserId int64 `json:"user_id"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
SpeedLimit int64 `json:"speed_limit,optional"`
|
|
||||||
TrafficLimit string `json:"traffic_limit,optional"`
|
|
||||||
}
|
}
|
||||||
UpdateUserSubscribeRequest {
|
UpdateUserSubscribeRequest {
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Upload int64 `json:"upload"`
|
Upload int64 `json:"upload"`
|
||||||
Download int64 `json:"download"`
|
Download int64 `json:"download"`
|
||||||
SpeedLimit *int64 `json:"speed_limit,omitempty"`
|
|
||||||
TrafficLimit *string `json:"traffic_limit,omitempty"`
|
|
||||||
}
|
}
|
||||||
GetUserLoginLogsRequest {
|
GetUserLoginLogsRequest {
|
||||||
Page int `form:"page"`
|
Page int `form:"page"`
|
||||||
|
|||||||
@@ -26,6 +26,5 @@ import (
|
|||||||
"./admin/ads.api"
|
"./admin/ads.api"
|
||||||
"./admin/marketing.api"
|
"./admin/marketing.api"
|
||||||
"./admin/application.api"
|
"./admin/application.api"
|
||||||
"./admin/group.api"
|
|
||||||
"./admin/promo.api"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+7
-44
@@ -171,13 +171,13 @@ type (
|
|||||||
DeviceLimit int64 `json:"device_limit"`
|
DeviceLimit int64 `json:"device_limit"`
|
||||||
}
|
}
|
||||||
VerifyConfig {
|
VerifyConfig {
|
||||||
CaptchaType string `json:"captcha_type"` // local or turnstile
|
CaptchaType string `json:"captcha_type"` // local or turnstile
|
||||||
TurnstileSiteKey string `json:"turnstile_site_key"`
|
TurnstileSiteKey string `json:"turnstile_site_key"`
|
||||||
TurnstileSecret string `json:"turnstile_secret"`
|
TurnstileSecret string `json:"turnstile_secret"`
|
||||||
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
|
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
|
||||||
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
|
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
|
||||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
|
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
|
||||||
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
|
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
|
||||||
}
|
}
|
||||||
NodeConfig {
|
NodeConfig {
|
||||||
NodeSecret string `json:"node_secret"`
|
NodeSecret string `json:"node_secret"`
|
||||||
@@ -230,12 +230,6 @@ type (
|
|||||||
Discount float64 `json:"discount"`
|
Discount float64 `json:"discount"`
|
||||||
MapApple string `json:"map_apple"`
|
MapApple string `json:"map_apple"`
|
||||||
}
|
}
|
||||||
SubscribePromo {
|
|
||||||
RuleName string `json:"rule_name"`
|
|
||||||
RuleType string `json:"rule_type"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
|
||||||
}
|
|
||||||
TrafficLimit {
|
TrafficLimit {
|
||||||
StatType string `json:"stat_type"`
|
StatType string `json:"stat_type"`
|
||||||
StatValue int64 `json:"stat_value"`
|
StatValue int64 `json:"stat_value"`
|
||||||
@@ -250,7 +244,6 @@ 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"`
|
||||||
@@ -543,35 +536,6 @@ type (
|
|||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
}
|
}
|
||||||
UserSubscribeDetail {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"user_id"`
|
|
||||||
User User `json:"user"`
|
|
||||||
OrderId int64 `json:"order_id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
Subscribe Subscribe `json:"subscribe"`
|
|
||||||
NodeGroupId int64 `json:"node_group_id"`
|
|
||||||
NodeGroupName string `json:"node_group_name"`
|
|
||||||
GroupLocked bool `json:"group_locked"`
|
|
||||||
StartTime int64 `json:"start_time"`
|
|
||||||
ExpireTime int64 `json:"expire_time"`
|
|
||||||
ResetTime int64 `json:"reset_time"`
|
|
||||||
Traffic int64 `json:"traffic"`
|
|
||||||
Download int64 `json:"download"`
|
|
||||||
Upload int64 `json:"upload"`
|
|
||||||
SpeedLimit int64 `json:"speed_limit"`
|
|
||||||
TrafficLimit []TrafficLimit `json:"user_traffic_limit"`
|
|
||||||
PlanSpeedLimit int64 `json:"plan_speed_limit"`
|
|
||||||
Token string `json:"token"`
|
|
||||||
Status uint8 `json:"status"`
|
|
||||||
EffectiveSpeed int64 `json:"effective_speed"`
|
|
||||||
IsThrottled bool `json:"is_throttled"`
|
|
||||||
ThrottleRule string `json:"throttle_rule,omitempty"`
|
|
||||||
ThrottleStart int64 `json:"throttle_start,omitempty"`
|
|
||||||
ThrottleEnd int64 `json:"throttle_end,omitempty"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
UserAffiliate {
|
UserAffiliate {
|
||||||
Avatar string `json:"avatar"`
|
Avatar string `json:"avatar"`
|
||||||
Identifier string `json:"identifier"`
|
Identifier string `json:"identifier"`
|
||||||
@@ -715,7 +679,6 @@ type (
|
|||||||
Price int64 `json:"price"`
|
Price int64 `json:"price"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ services:
|
|||||||
depends_on:
|
depends_on:
|
||||||
tempo:
|
tempo:
|
||||||
condition: service_started
|
condition: service_started
|
||||||
|
minio:
|
||||||
|
condition: service_healthy
|
||||||
logging:
|
logging:
|
||||||
driver: "json-file"
|
driver: "json-file"
|
||||||
options:
|
options:
|
||||||
@@ -239,6 +241,63 @@ services:
|
|||||||
max-size: "10m"
|
max-size: "10m"
|
||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
|
# ----------------------------------------------------
|
||||||
|
# 10. MinIO (测试环境 S3 兼容对象存储)
|
||||||
|
# 仅绑定宿主机 127.0.0.1,供 host 网络的 ppanel-server 访问,不对公网开放。
|
||||||
|
# ----------------------------------------------------
|
||||||
|
minio:
|
||||||
|
image: minio/minio:RELEASE.2025-05-24T17-08-30Z-cpuv1
|
||||||
|
container_name: ppanel-minio
|
||||||
|
restart: always
|
||||||
|
command: server /data --console-address ":9001"
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: "${MINIO_ROOT_USER:?请在 .env 文件中设置 MINIO_ROOT_USER}"
|
||||||
|
MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:?请在 .env 文件中设置 MINIO_ROOT_PASSWORD}"
|
||||||
|
TZ: Asia/Shanghai
|
||||||
|
volumes:
|
||||||
|
- ./data/minio:/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:9000:9000"
|
||||||
|
- "127.0.0.1:9001:9001"
|
||||||
|
networks:
|
||||||
|
- ppanel_net
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 6
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
|
minio-init:
|
||||||
|
image: minio/mc:RELEASE.2025-07-21T05-28-08Z-cpuv1
|
||||||
|
container_name: ppanel-minio-init
|
||||||
|
restart: "no"
|
||||||
|
depends_on:
|
||||||
|
minio:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: "${MINIO_ROOT_USER:?请在 .env 文件中设置 MINIO_ROOT_USER}"
|
||||||
|
MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:?请在 .env 文件中设置 MINIO_ROOT_PASSWORD}"
|
||||||
|
MINIO_BUCKET: "${MINIO_BUCKET:?请在 .env 文件中设置 MINIO_BUCKET}"
|
||||||
|
entrypoint:
|
||||||
|
- /bin/sh
|
||||||
|
- -c
|
||||||
|
- |
|
||||||
|
set -e
|
||||||
|
mc alias set local http://minio:9000 "$${MINIO_ROOT_USER}" "$${MINIO_ROOT_PASSWORD}"
|
||||||
|
mc mb --ignore-existing "local/$${MINIO_BUCKET}"
|
||||||
|
networks:
|
||||||
|
- ppanel_net
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
loki_data:
|
loki_data:
|
||||||
grafana_data:
|
grafana_data:
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
-- Purpose: Rollback user-level speed limit overrides from user_subscribe
|
|
||||||
|
|
||||||
ALTER TABLE `user_subscribe`
|
|
||||||
DROP COLUMN IF EXISTS `traffic_limit`,
|
|
||||||
DROP COLUMN IF EXISTS `speed_limit`;
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
-- Purpose: Add user-level speed limit overrides to user_subscribe
|
|
||||||
|
|
||||||
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 = 0,
|
|
||||||
'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'''
|
|
||||||
);
|
|
||||||
|
|
||||||
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 = 'traffic_limit'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `user_subscribe` ADD COLUMN `traffic_limit` text DEFAULT NULL COMMENT ''User-level traffic limit rules override (JSON, NULL=use plan default)'' AFTER `speed_limit`',
|
|
||||||
'SELECT ''Column traffic_limit already exists in user_subscribe table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
SET @column_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_discount'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 1,
|
|
||||||
'ALTER TABLE `order` DROP COLUMN `promo_discount`',
|
|
||||||
'SELECT ''Column promo_discount does not exist in order 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 = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_rule_id'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 1,
|
|
||||||
'ALTER TABLE `order` DROP COLUMN `promo_rule_id`',
|
|
||||||
'SELECT ''Column promo_rule_id does not exist in order table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
DROP TABLE IF EXISTS `promo_usage`;
|
|
||||||
DROP TABLE IF EXISTS `subscribe_promo`;
|
|
||||||
DROP TABLE IF EXISTS `promo_rule`;
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
CREATE TABLE IF NOT EXISTS `promo_rule` (
|
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
||||||
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称',
|
|
||||||
`type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型:new_user / inactive_user / campaign',
|
|
||||||
`params` JSON NOT NULL COMMENT '类型专属参数',
|
|
||||||
`priority` INT NOT NULL DEFAULT 0 COMMENT '优先级,数值越大越优先匹配',
|
|
||||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
|
||||||
`start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间',
|
|
||||||
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间',
|
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
||||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
KEY `idx_enabled_priority` (`enabled`, `priority` DESC),
|
|
||||||
KEY `idx_deleted_at` (`deleted_at`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
|
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
||||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
|
|
||||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
|
|
||||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
|
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
|
|
||||||
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `promo_usage` (
|
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
||||||
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
|
|
||||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '使用的规则 ID',
|
|
||||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '购买的规格 ID',
|
|
||||||
`order_no` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '关联订单号',
|
|
||||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '使用时的促销单价(分)',
|
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
|
|
||||||
KEY `idx_order_no` (`order_no`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
|
|
||||||
|
|
||||||
SET @column_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_rule_id'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`',
|
|
||||||
'SELECT ''Column promo_rule_id already exists in order 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 = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_discount'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`',
|
|
||||||
'SELECT ''Column promo_discount already exists in order table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Batch set promo price
|
|
||||||
func CreatePromoPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.CreatePromoPriceRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewCreatePromoPriceLogic(c.Request.Context(), svcCtx)
|
|
||||||
err := l.CreatePromoPrice(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Create promo rule
|
|
||||||
func CreatePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.CreatePromoRuleRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewCreatePromoRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.CreatePromoRule(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
func DeletePromoPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.DeletePromoPriceRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Id = id
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewDeletePromoPriceLogic(c.Request.Context(), svcCtx)
|
|
||||||
err = l.DeletePromoPrice(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
func DeletePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.DeletePromoRuleRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Id = id
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewDeletePromoRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
err = l.DeletePromoRule(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
func GetPromoPriceListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoPriceListRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewGetPromoPriceListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoPriceList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
func GetPromoRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoRuleDetailRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Id = id
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewGetPromoRuleDetailLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoRuleDetail(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
func GetPromoRuleListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoRuleListRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewGetPromoRuleListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoRuleList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
func GetPromoUsageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoUsageListRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewGetPromoUsageListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoUsageList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
func UpdatePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.UpdatePromoRuleRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
req.Id = id
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewUpdatePromoRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.UpdatePromoRule(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,6 @@ import (
|
|||||||
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
||||||
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
||||||
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
||||||
adminPromo "github.com/perfect-panel/server/internal/handler/admin/promo"
|
|
||||||
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
||||||
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
||||||
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
||||||
@@ -375,38 +374,6 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
adminPromoGroupRouter := router.Group("/v1/admin/promo")
|
|
||||||
adminPromoGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
|
||||||
|
|
||||||
{
|
|
||||||
// Create promo rule
|
|
||||||
adminPromoGroupRouter.POST("/rule", adminPromo.CreatePromoRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
adminPromoGroupRouter.GET("/rule/list", adminPromo.GetPromoRuleListHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
adminPromoGroupRouter.GET("/rule/:id", adminPromo.GetPromoRuleDetailHandler(serverCtx))
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
adminPromoGroupRouter.PUT("/rule/:id", adminPromo.UpdatePromoRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
adminPromoGroupRouter.DELETE("/rule/:id", adminPromo.DeletePromoRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Batch set promo price
|
|
||||||
adminPromoGroupRouter.POST("/price", adminPromo.CreatePromoPriceHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
adminPromoGroupRouter.GET("/price/list", adminPromo.GetPromoPriceListHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
adminPromoGroupRouter.DELETE("/price/:id", adminPromo.DeletePromoPriceHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
adminPromoGroupRouter.GET("/usage/list", adminPromo.GetPromoUsageListHandler(serverCtx))
|
|
||||||
}
|
|
||||||
|
|
||||||
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
||||||
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||||
|
|
||||||
@@ -1011,16 +978,17 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
||||||
|
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
{
|
{
|
||||||
// Get subscribe list
|
// Get subscribe list
|
||||||
publicSubscribeGroupRouter.GET("/list", middleware.OptionalAuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/list", publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
||||||
|
|
||||||
// Get user subscribe node info
|
// Get user subscribe node info
|
||||||
publicSubscribeGroupRouter.GET("/node/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/node/list", publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
||||||
|
|
||||||
// Get subscribe group list
|
// Get subscribe group list
|
||||||
publicSubscribeGroupRouter.GET("/group/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/group/list", publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ func (l *DeleteSubscribeApplicationLogic) DeleteSubscribeApplication(req *types.
|
|||||||
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,128 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
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"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
enabledRulesCacheKey = "promo:rules:enabled"
|
|
||||||
subscribePromoKeyFmt = "promo:subscribe:%d"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ruleParams struct {
|
|
||||||
WindowHours int `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateRulePayload(ruleType string, params json.RawMessage, priority, startTime, endTime int64) error {
|
|
||||||
if priority < 0 {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "priority must be greater than or equal to 0")
|
|
||||||
}
|
|
||||||
if startTime >= endTime {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "start_time must be less than end_time")
|
|
||||||
}
|
|
||||||
|
|
||||||
var p ruleParams
|
|
||||||
if len(params) == 0 || !json.Valid(params) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params must be valid json")
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(params, &p); err != nil {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params must be valid json object")
|
|
||||||
}
|
|
||||||
|
|
||||||
switch ruleType {
|
|
||||||
case promoModel.RuleTypeNewUser:
|
|
||||||
if p.WindowHours <= 0 {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params.window_hours must be greater than 0")
|
|
||||||
}
|
|
||||||
case promoModel.RuleTypeInactiveUser:
|
|
||||||
if p.InactiveMonths <= 0 {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params.inactive_months must be greater than 0")
|
|
||||||
}
|
|
||||||
case promoModel.RuleTypeCampaign:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "type must be new_user, inactive_user or campaign")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func toRuleResponse(data *promoModel.Rule) types.PromoRule {
|
|
||||||
resp := types.PromoRule{
|
|
||||||
Id: data.Id,
|
|
||||||
Name: data.Name,
|
|
||||||
Type: data.Type,
|
|
||||||
Params: json.RawMessage(data.Params),
|
|
||||||
Priority: data.Priority,
|
|
||||||
Enabled: data.Enabled,
|
|
||||||
CreatedAt: data.CreatedAt.UnixMilli(),
|
|
||||||
UpdatedAt: data.UpdatedAt.UnixMilli(),
|
|
||||||
}
|
|
||||||
if data.StartTime != nil {
|
|
||||||
resp.StartTime = data.StartTime.UnixMilli()
|
|
||||||
}
|
|
||||||
if data.EndTime != nil {
|
|
||||||
resp.EndTime = data.EndTime.UnixMilli()
|
|
||||||
}
|
|
||||||
return resp
|
|
||||||
}
|
|
||||||
|
|
||||||
func toPriceResponse(data *promoModel.SubscribePromo, unitPrice int64) types.PromoPrice {
|
|
||||||
return types.PromoPrice{
|
|
||||||
Id: data.Id,
|
|
||||||
SubscribeId: data.SubscribeId,
|
|
||||||
PromoRuleId: data.PromoRuleId,
|
|
||||||
PromoPrice: data.PromoPrice,
|
|
||||||
UnitPrice: unitPrice,
|
|
||||||
CreatedAt: data.CreatedAt.UnixMilli(),
|
|
||||||
UpdatedAt: data.UpdatedAt.UnixMilli(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func toUsageResponse(data *promoModel.Usage) types.PromoUsage {
|
|
||||||
return types.PromoUsage{
|
|
||||||
Id: data.Id,
|
|
||||||
UserId: data.UserId,
|
|
||||||
PromoRuleId: data.PromoRuleId,
|
|
||||||
SubscribeId: data.SubscribeId,
|
|
||||||
OrderNo: data.OrderNo,
|
|
||||||
PromoPrice: data.PromoPrice,
|
|
||||||
CreatedAt: data.CreatedAt.UnixMilli(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ruleTimes(startTime, endTime int64) (*time.Time, *time.Time) {
|
|
||||||
start := time.UnixMilli(startTime)
|
|
||||||
end := time.UnixMilli(endTime)
|
|
||||||
return &start, &end
|
|
||||||
}
|
|
||||||
|
|
||||||
func clearRuleCache(ctx context.Context, svcCtx *svc.ServiceContext) {
|
|
||||||
if svcCtx != nil && svcCtx.Redis != nil {
|
|
||||||
_ = svcCtx.Redis.Del(ctx, enabledRulesCacheKey).Err()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func clearSubscribePromoCache(ctx context.Context, svcCtx *svc.ServiceContext, ids ...int64) {
|
|
||||||
if svcCtx == nil || svcCtx.Redis == nil || len(ids) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
keys := make([]string, 0, len(ids))
|
|
||||||
for _, id := range ids {
|
|
||||||
keys = append(keys, fmt.Sprintf(subscribePromoKeyFmt, id))
|
|
||||||
}
|
|
||||||
_ = svcCtx.Redis.Del(ctx, keys...).Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func wrapQueryError(msg string, err error) error {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "%s: %v", msg, err.Error())
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CreatePromoPriceLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Batch set promo price
|
|
||||||
func NewCreatePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoPriceLogic {
|
|
||||||
return &CreatePromoPriceLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *CreatePromoPriceLogic) CreatePromoPrice(req *types.CreatePromoPriceRequest) error {
|
|
||||||
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[CreatePromoPrice] Query Rule Error", logger.Field("error", err.Error()))
|
|
||||||
return wrapQueryError("get promo rule failed", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data := make([]*promoModel.SubscribePromo, 0, len(req.Items))
|
|
||||||
subscribeIds := make([]int64, 0, len(req.Items))
|
|
||||||
for _, item := range req.Items {
|
|
||||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
|
||||||
if err != nil {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "subscribe not found")
|
|
||||||
}
|
|
||||||
if item.PromoPrice >= sub.UnitPrice {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo_price must be less than unit_price")
|
|
||||||
}
|
|
||||||
data = append(data, &promoModel.SubscribePromo{
|
|
||||||
SubscribeId: item.SubscribeId,
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
PromoPrice: item.PromoPrice,
|
|
||||||
})
|
|
||||||
subscribeIds = append(subscribeIds, item.SubscribeId)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := l.svcCtx.PromoModel.UpsertSubscribePromos(l.ctx, data); err != nil {
|
|
||||||
l.Errorw("[CreatePromoPrice] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "set promo price failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearSubscribePromoCache(l.ctx, l.svcCtx, subscribeIds...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CreatePromoRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create promo rule
|
|
||||||
func NewCreatePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoRuleLogic {
|
|
||||||
return &CreatePromoRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *CreatePromoRuleLogic) CreatePromoRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
|
|
||||||
if err := validateRulePayload(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
start, end := ruleTimes(req.StartTime, req.EndTime)
|
|
||||||
data := &promoModel.Rule{
|
|
||||||
Name: req.Name,
|
|
||||||
Type: req.Type,
|
|
||||||
Params: string(req.Params),
|
|
||||||
Priority: req.Priority,
|
|
||||||
Enabled: *req.Enabled,
|
|
||||||
StartTime: start,
|
|
||||||
EndTime: end,
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, data); err != nil {
|
|
||||||
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearRuleCache(l.ctx, l.svcCtx)
|
|
||||||
resp := toRuleResponse(data)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DeletePromoPriceLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
func NewDeletePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePromoPriceLogic {
|
|
||||||
return &DeletePromoPriceLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *DeletePromoPriceLogic) DeletePromoPrice(req *types.DeletePromoPriceRequest) error {
|
|
||||||
data, err := l.svcCtx.PromoModel.FindSubscribePromo(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo price not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[DeletePromoPrice] Database Query Error", logger.Field("error", err.Error()))
|
|
||||||
return wrapQueryError("get promo price failed", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = l.svcCtx.PromoModel.DeleteSubscribePromo(l.ctx, req.Id); err != nil {
|
|
||||||
l.Errorw("[DeletePromoPrice] Database Delete Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearSubscribePromoCache(l.ctx, l.svcCtx, data.SubscribeId)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DeletePromoRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
func NewDeletePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePromoRuleLogic {
|
|
||||||
return &DeletePromoRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *DeletePromoRuleLogic) DeletePromoRule(req *types.DeletePromoRuleRequest) error {
|
|
||||||
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[DeletePromoRule] Database Delete Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearRuleCache(l.ctx, l.svcCtx)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoPriceListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
func NewGetPromoPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoPriceListLogic {
|
|
||||||
return &GetPromoPriceListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoPriceListLogic) GetPromoPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QuerySubscribePromoList(l.ctx, promoModel.SubscribePromoFilter{
|
|
||||||
Page: int(req.Page),
|
|
||||||
Size: int(req.Size),
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo price list failed", err)
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoPriceListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoPrice, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
var unitPrice int64
|
|
||||||
sub, subErr := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
|
||||||
if subErr == nil {
|
|
||||||
unitPrice = sub.UnitPrice
|
|
||||||
}
|
|
||||||
resp.List = append(resp.List, toPriceResponse(item, unitPrice))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoRuleDetailLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
func NewGetPromoRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoRuleDetailLogic {
|
|
||||||
return &GetPromoRuleDetailLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoRuleDetailLogic) GetPromoRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
|
|
||||||
data, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo rule detail failed", err)
|
|
||||||
}
|
|
||||||
resp := toRuleResponse(data)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoRuleListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
func NewGetPromoRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoRuleListLogic {
|
|
||||||
return &GetPromoRuleListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoRuleListLogic) GetPromoRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, promoModel.RuleFilter{
|
|
||||||
Page: int(req.Page),
|
|
||||||
Size: int(req.Size),
|
|
||||||
Type: req.Type,
|
|
||||||
Enabled: req.Enabled,
|
|
||||||
Search: req.Search,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo rule list failed", err)
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoRuleListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoRule, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, toRuleResponse(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoUsageListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
func NewGetPromoUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoUsageListLogic {
|
|
||||||
return &GetPromoUsageListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoUsageListLogic) GetPromoUsageList(req *types.GetPromoUsageListRequest) (*types.GetPromoUsageListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QueryUsageList(l.ctx, promoModel.UsageFilter{
|
|
||||||
Page: int(req.Page),
|
|
||||||
Size: int(req.Size),
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
UserId: req.UserId,
|
|
||||||
SubscribeId: req.SubscribeId,
|
|
||||||
OrderNo: req.OrderNo,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo usage list failed", err)
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoUsageListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoUsage, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, toUsageResponse(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
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/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UpdatePromoRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
func NewUpdatePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePromoRuleLogic {
|
|
||||||
return &UpdatePromoRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *UpdatePromoRuleLogic) UpdatePromoRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
|
|
||||||
if err := validateRulePayload(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[UpdatePromoRule] Database Query Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo rule failed", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
start, end := ruleTimes(req.StartTime, req.EndTime)
|
|
||||||
data.Name = req.Name
|
|
||||||
data.Type = req.Type
|
|
||||||
data.Params = string(req.Params)
|
|
||||||
data.Priority = req.Priority
|
|
||||||
data.Enabled = *req.Enabled
|
|
||||||
data.StartTime = start
|
|
||||||
data.EndTime = end
|
|
||||||
|
|
||||||
if err = l.svcCtx.PromoModel.UpdateRule(l.ctx, data); err != nil {
|
|
||||||
l.Errorw("[UpdatePromoRule] Database Update Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearRuleCache(l.ctx, l.svcCtx)
|
|
||||||
resp := toRuleResponse(data)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithNodeLogic) ResetSortWithNode(req *types.ResetSortRequest)
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithServerLogic) ResetSortWithServer(req *types.ResetSortReque
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,170 +0,0 @@
|
|||||||
package common
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type PromoResult struct {
|
|
||||||
Eligible bool
|
|
||||||
RuleID int64
|
|
||||||
RuleName string
|
|
||||||
RuleType string
|
|
||||||
PromoPrice int64
|
|
||||||
ExpiresAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoRuleParams struct {
|
|
||||||
WindowHours int `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64) (*PromoResult, error) {
|
|
||||||
result := &PromoResult{}
|
|
||||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
if len(rules) == 0 {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var currentUser user.User
|
|
||||||
now := time.Now()
|
|
||||||
for _, rule := range rules {
|
|
||||||
if rule == nil || !isPromoRuleInTimeWindow(rule, now) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if rule.PromoPrice <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
params := promoRuleParams{}
|
|
||||||
if rule.Params != "" {
|
|
||||||
if err = json.Unmarshal([]byte(rule.Params), ¶ms); err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, ¤tUser, now)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !eligible {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return &PromoResult{
|
|
||||||
Eligible: true,
|
|
||||||
RuleID: rule.Id,
|
|
||||||
RuleName: rule.Name,
|
|
||||||
RuleType: rule.Type,
|
|
||||||
PromoPrice: rule.PromoPrice,
|
|
||||||
ExpiresAt: expiresAt,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPromoRuleInTimeWindow(rule *promo.RuleWithPrice, now time.Time) bool {
|
|
||||||
if rule.StartTime != nil && !rule.StartTime.IsZero() && now.Before(*rule.StartTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if rule.EndTime != nil && !rule.EndTime.IsZero() && now.After(*rule.EndTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluatePromoRule(
|
|
||||||
ctx context.Context,
|
|
||||||
db *gorm.DB,
|
|
||||||
rule *promo.RuleWithPrice,
|
|
||||||
params promoRuleParams,
|
|
||||||
userID int64,
|
|
||||||
currentUser *user.User,
|
|
||||||
now time.Time,
|
|
||||||
) (bool, time.Time, error) {
|
|
||||||
switch rule.Type {
|
|
||||||
case promo.RuleTypeNewUser:
|
|
||||||
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
|
|
||||||
case promo.RuleTypeInactiveUser:
|
|
||||||
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
|
|
||||||
case promo.RuleTypeCampaign:
|
|
||||||
return true, promoRuleExpiresAt(rule), nil
|
|
||||||
default:
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluateNewUserPromo(
|
|
||||||
ctx context.Context,
|
|
||||||
db *gorm.DB,
|
|
||||||
params promoRuleParams,
|
|
||||||
userID int64,
|
|
||||||
currentUser *user.User,
|
|
||||||
now time.Time,
|
|
||||||
) (bool, time.Time, error) {
|
|
||||||
if params.WindowHours <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if currentUser.Id == 0 {
|
|
||||||
if err := db.WithContext(ctx).Model(&user.User{}).Where("id = ?", userID).First(currentUser).Error; err != nil {
|
|
||||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expiresAt := currentUser.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
|
||||||
return now.Before(expiresAt), expiresAt, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluateInactiveUserPromo(
|
|
||||||
ctx context.Context,
|
|
||||||
db *gorm.DB,
|
|
||||||
params promoRuleParams,
|
|
||||||
userID int64,
|
|
||||||
ruleExpiresAt time.Time,
|
|
||||||
now time.Time,
|
|
||||||
) (bool, time.Time, error) {
|
|
||||||
if params.InactiveMonths <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var lastSub user.Subscribe
|
|
||||||
err := db.WithContext(ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ?", userID).
|
|
||||||
Order("expire_time DESC").
|
|
||||||
Limit(1).
|
|
||||||
Take(&lastSub).Error
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return true, ruleExpiresAt, nil
|
|
||||||
}
|
|
||||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
|
||||||
return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
|
|
||||||
if rule != nil && rule.EndTime != nil {
|
|
||||||
return *rule.EndTime
|
|
||||||
}
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,7 @@ package order
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"math"
|
||||||
|
|
||||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
@@ -114,28 +115,14 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
||||||
}
|
}
|
||||||
|
|
||||||
priceResult, err := calculatePurchasePrice(
|
var discount float64 = 1
|
||||||
l.ctx,
|
if len(newUserDiscount.Discounts) > 0 {
|
||||||
l.svcCtx,
|
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||||
u.Id,
|
|
||||||
targetSubscribeID,
|
|
||||||
sub.UnitPrice,
|
|
||||||
req.Quantity,
|
|
||||||
newUserDiscount.Discounts,
|
|
||||||
newUserDiscount.EligibleForDiscount,
|
|
||||||
!isSingleModeRenewal,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[PreCreateOrder] Promo price calculation error",
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
logger.Field("user_id", u.Id),
|
|
||||||
logger.Field("subscribe_id", targetSubscribeID),
|
|
||||||
)
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
price := priceResult.OriginalPrice
|
price := sub.UnitPrice * req.Quantity
|
||||||
amount := priceResult.PayableBase
|
|
||||||
discountAmount := priceResult.DiscountAmount
|
amount := int64(math.Round(float64(price) * discount))
|
||||||
|
discountAmount := price - amount
|
||||||
var couponAmount int64
|
var couponAmount int64
|
||||||
if req.Coupon != "" {
|
if req.Coupon != "" {
|
||||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||||
@@ -198,7 +185,6 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
Price: price,
|
Price: price,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
Discount: discountAmount,
|
Discount: discountAmount,
|
||||||
PromoDiscount: priceResult.PromoDiscount,
|
|
||||||
GiftAmount: deductionAmount,
|
GiftAmount: deductionAmount,
|
||||||
Coupon: req.Coupon,
|
Coupon: req.Coupon,
|
||||||
CouponDiscount: couponAmount,
|
CouponDiscount: couponAmount,
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"math"
|
|
||||||
|
|
||||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
)
|
|
||||||
|
|
||||||
type orderPriceResult struct {
|
|
||||||
OriginalPrice int64
|
|
||||||
PayableBase int64
|
|
||||||
DiscountAmount int64
|
|
||||||
PromoRuleId int64
|
|
||||||
PromoDiscount int64
|
|
||||||
PromoPrice int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func calculatePurchasePrice(
|
|
||||||
ctx context.Context,
|
|
||||||
svcCtx *svc.ServiceContext,
|
|
||||||
userID int64,
|
|
||||||
subscribeID int64,
|
|
||||||
unitPrice int64,
|
|
||||||
quantity int64,
|
|
||||||
discounts []types.SubscribeDiscount,
|
|
||||||
eligibleForDiscount bool,
|
|
||||||
allowPromo bool,
|
|
||||||
) (*orderPriceResult, error) {
|
|
||||||
originalPrice := unitPrice * quantity
|
|
||||||
result := &orderPriceResult{
|
|
||||||
OriginalPrice: originalPrice,
|
|
||||||
PayableBase: originalPrice,
|
|
||||||
}
|
|
||||||
|
|
||||||
if allowPromo {
|
|
||||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < unitPrice {
|
|
||||||
result.PayableBase = promoResult.PromoPrice * quantity
|
|
||||||
result.PromoRuleId = promoResult.RuleID
|
|
||||||
result.PromoDiscount = originalPrice - result.PayableBase
|
|
||||||
result.PromoPrice = promoResult.PromoPrice
|
|
||||||
if result.PromoDiscount < 0 {
|
|
||||||
result.PromoDiscount = 0
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
discount := float64(1)
|
|
||||||
if len(discounts) > 0 {
|
|
||||||
discount = getDiscount(discounts, quantity, eligibleForDiscount)
|
|
||||||
}
|
|
||||||
result.PayableBase = int64(math.Round(float64(originalPrice) * discount))
|
|
||||||
result.DiscountAmount = originalPrice - result.PayableBase
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type fakePromoModel struct {
|
|
||||||
rules []*promo.RuleWithPrice
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryEligibleRules(context.Context, int64) ([]*promo.RuleWithPrice, error) {
|
|
||||||
return m.rules, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) DeleteRule(context.Context, int64) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryRuleList(context.Context, promo.RuleFilter) (int64, []*promo.Rule, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) UpsertSubscribePromos(context.Context, []*promo.SubscribePromo) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) FindSubscribePromo(context.Context, int64) (*promo.SubscribePromo, error) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) DeleteSubscribePromo(context.Context, int64) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QuerySubscribePromoList(context.Context, promo.SubscribePromoFilter) (int64, []*promo.SubscribePromo, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 9,
|
|
||||||
Name: "campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 600,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
|
||||||
context.Background(),
|
|
||||||
svcCtx,
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
1000,
|
|
||||||
3,
|
|
||||||
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.OriginalPrice != 3000 {
|
|
||||||
t.Fatalf("OriginalPrice = %d, want 3000", result.OriginalPrice)
|
|
||||||
}
|
|
||||||
if result.PayableBase != 1800 {
|
|
||||||
t.Fatalf("PayableBase = %d, want 1800", result.PayableBase)
|
|
||||||
}
|
|
||||||
if result.DiscountAmount != 0 {
|
|
||||||
t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount)
|
|
||||||
}
|
|
||||||
if result.PromoRuleId != 9 {
|
|
||||||
t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId)
|
|
||||||
}
|
|
||||||
if result.PromoDiscount != 1200 {
|
|
||||||
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 10,
|
|
||||||
Name: "invalid campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 1000,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
|
||||||
context.Background(),
|
|
||||||
svcCtx,
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
1000,
|
|
||||||
3,
|
|
||||||
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.PayableBase != 1500 {
|
|
||||||
t.Fatalf("PayableBase = %d, want 1500", result.PayableBase)
|
|
||||||
}
|
|
||||||
if result.DiscountAmount != 1500 {
|
|
||||||
t.Fatalf("DiscountAmount = %d, want 1500", result.DiscountAmount)
|
|
||||||
}
|
|
||||||
if result.PromoRuleId != 0 || result.PromoDiscount != 0 {
|
|
||||||
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,7 @@ package order
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"math"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -203,28 +204,14 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
priceResult, err := calculatePurchasePrice(
|
var discount float64 = 1
|
||||||
l.ctx,
|
if len(newUserDiscount.Discounts) > 0 {
|
||||||
l.svcCtx,
|
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||||
u.Id,
|
|
||||||
targetSubscribeID,
|
|
||||||
sub.UnitPrice,
|
|
||||||
req.Quantity,
|
|
||||||
newUserDiscount.Discounts,
|
|
||||||
newUserDiscount.EligibleForDiscount,
|
|
||||||
orderType == 1,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[Purchase] Promo price calculation error",
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
logger.Field("user_id", u.Id),
|
|
||||||
logger.Field("subscribe_id", targetSubscribeID),
|
|
||||||
)
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
price := priceResult.OriginalPrice
|
price := sub.UnitPrice * req.Quantity
|
||||||
amount := priceResult.PayableBase
|
// discount amount
|
||||||
discountAmount := priceResult.DiscountAmount
|
amount := int64(math.Round(float64(price) * discount))
|
||||||
|
discountAmount := price - amount
|
||||||
|
|
||||||
// Validate amount to prevent overflow
|
// Validate amount to prevent overflow
|
||||||
if amount > MaxOrderAmount {
|
if amount > MaxOrderAmount {
|
||||||
@@ -319,8 +306,6 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
Price: price,
|
Price: price,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
Discount: discountAmount,
|
Discount: discountAmount,
|
||||||
PromoRuleId: priceResult.PromoRuleId,
|
|
||||||
PromoDiscount: priceResult.PromoDiscount,
|
|
||||||
GiftAmount: deductionAmount,
|
GiftAmount: deductionAmount,
|
||||||
Coupon: req.Coupon,
|
Coupon: req.Coupon,
|
||||||
CouponDiscount: coupon,
|
CouponDiscount: coupon,
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
package subscribe
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
stderrors "errors"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-sql-driver/mysql"
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/constant"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
promoRuleTypeNewUser = "new_user"
|
|
||||||
promoRuleTypeInactiveUser = "inactive_user"
|
|
||||||
promoRuleTypeCampaign = "campaign"
|
|
||||||
)
|
|
||||||
|
|
||||||
type subscribePromoCandidate struct {
|
|
||||||
SubscribeId int64 `gorm:"column:subscribe_id"`
|
|
||||||
RuleName string `gorm:"column:rule_name"`
|
|
||||||
RuleType string `gorm:"column:rule_type"`
|
|
||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
|
||||||
Params string `gorm:"column:params"`
|
|
||||||
StartTime *time.Time `gorm:"column:start_time"`
|
|
||||||
EndTime *time.Time `gorm:"column:end_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoRuleParams struct {
|
|
||||||
WindowHours int64 `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]*types.SubscribePromo, error) {
|
|
||||||
result := make(map[int64]*types.SubscribePromo)
|
|
||||||
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
userInfo, _ := ctx.Value(constant.CtxKeyUser).(*user.User)
|
|
||||||
candidates, err := querySubscribePromoCandidates(ctx, svcCtx, subscribeIDs, userInfo != nil)
|
|
||||||
if err != nil {
|
|
||||||
if isMissingPromoTableError(err) {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
|
||||||
now := time.Now()
|
|
||||||
for _, candidate := range candidates {
|
|
||||||
if _, exists := result[candidate.SubscribeId]; exists {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !candidate.isActive(now) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ok, expiresAt, err := evaluator.match(candidate, now)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
result[candidate.SubscribeId] = &types.SubscribePromo{
|
|
||||||
RuleName: candidate.RuleName,
|
|
||||||
RuleType: candidate.RuleType,
|
|
||||||
PromoPrice: candidate.PromoPrice,
|
|
||||||
ExpiresAt: unixSeconds(expiresAt),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
|
|
||||||
var candidates []subscribePromoCandidate
|
|
||||||
query := svcCtx.DB.WithContext(ctx).
|
|
||||||
Table("subscribe_promo AS sp").
|
|
||||||
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").
|
|
||||||
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
|
|
||||||
if !loggedIn {
|
|
||||||
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
|
|
||||||
}
|
|
||||||
err := query.
|
|
||||||
Order("sp.subscribe_id ASC").
|
|
||||||
Order("pr.priority DESC").
|
|
||||||
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 {
|
|
||||||
if c.PromoPrice <= 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if c.StartTime != nil && now.Before(*c.StartTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if c.EndTime != nil && now.After(*c.EndTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoEligibilityEvaluator struct {
|
|
||||||
ctx context.Context
|
|
||||||
db *gorm.DB
|
|
||||||
userInfo *user.User
|
|
||||||
lastExpire *time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) match(candidate subscribePromoCandidate, now time.Time) (bool, time.Time, error) {
|
|
||||||
switch candidate.RuleType {
|
|
||||||
case promoRuleTypeCampaign:
|
|
||||||
return true, candidate.expiresAt(), nil
|
|
||||||
case promoRuleTypeNewUser:
|
|
||||||
if e.userInfo == nil {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
params, err := candidate.params()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if params.WindowHours <= 0 || e.userInfo.CreatedAt.IsZero() {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
expiresAt := e.userInfo.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
|
||||||
return now.Before(expiresAt), expiresAt, nil
|
|
||||||
case promoRuleTypeInactiveUser:
|
|
||||||
if e.userInfo == nil {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
params, err := candidate.params()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if params.InactiveMonths <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
lastExpire, err := e.lastSubscribeExpireAt()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if lastExpire.Equal(time.UnixMilli(0)) || lastExpire.After(now) {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
if lastExpire.IsZero() {
|
|
||||||
return true, candidate.expiresAt(), nil
|
|
||||||
}
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
|
||||||
return !lastExpire.After(threshold), candidate.expiresAt(), nil
|
|
||||||
default:
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
|
||||||
if e.lastExpire != nil {
|
|
||||||
return *e.lastExpire, nil
|
|
||||||
}
|
|
||||||
var item user.Subscribe
|
|
||||||
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).
|
|
||||||
Take(&item).Error
|
|
||||||
if err != nil {
|
|
||||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
zero := time.Time{}
|
|
||||||
e.lastExpire = &zero
|
|
||||||
return zero, nil
|
|
||||||
}
|
|
||||||
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
|
|
||||||
}
|
|
||||||
e.lastExpire = &item.ExpireTime
|
|
||||||
return item.ExpireTime, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) expiresAt() time.Time {
|
|
||||||
if c.EndTime == nil {
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
return *c.EndTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
|
|
||||||
if c.Params == "" {
|
|
||||||
return promoRuleParams{}, nil
|
|
||||||
}
|
|
||||||
var params promoRuleParams
|
|
||||||
if err := json.Unmarshal([]byte(c.Params), ¶ms); err != nil {
|
|
||||||
return promoRuleParams{}, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "parse promo rule params failed")
|
|
||||||
}
|
|
||||||
return params, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func unixSeconds(t time.Time) int64 {
|
|
||||||
if t.IsZero() {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return t.Unix()
|
|
||||||
}
|
|
||||||
|
|
||||||
func isMissingPromoTableError(err error) bool {
|
|
||||||
var mysqlErr *mysql.MySQLError
|
|
||||||
if stderrors.As(err, &mysqlErr) {
|
|
||||||
return mysqlErr.Number == 1146
|
|
||||||
}
|
|
||||||
return strings.Contains(err.Error(), "Error 1146")
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package subscribe
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
campaignEnd := now.Add(2 * time.Hour)
|
|
||||||
|
|
||||||
campaign := subscribePromoCandidate{
|
|
||||||
RuleName: "限时活动",
|
|
||||||
RuleType: promoRuleTypeCampaign,
|
|
||||||
PromoPrice: 99,
|
|
||||||
EndTime: &campaignEnd,
|
|
||||||
}
|
|
||||||
ok, expiresAt, err := (&promoEligibilityEvaluator{}).match(campaign, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("campaign match error: %v", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("campaign promo should match without login")
|
|
||||||
}
|
|
||||||
if got, want := unixSeconds(expiresAt), campaignEnd.Unix(); got != want {
|
|
||||||
t.Fatalf("campaign expires_at = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
newUser := subscribePromoCandidate{
|
|
||||||
RuleName: "新客7天优惠",
|
|
||||||
RuleType: promoRuleTypeNewUser,
|
|
||||||
PromoPrice: 279,
|
|
||||||
Params: `{"window_hours":168}`,
|
|
||||||
}
|
|
||||||
ok, _, err = (&promoEligibilityEvaluator{}).match(newUser, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("anonymous new_user match error: %v", err)
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
t.Fatal("new_user promo should not match without login")
|
|
||||||
}
|
|
||||||
|
|
||||||
userInfo := &user.User{Id: 1, CreatedAt: now.Add(-24 * time.Hour)}
|
|
||||||
ok, expiresAt, err = (&promoEligibilityEvaluator{userInfo: userInfo}).match(newUser, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("logged-in new_user match error: %v", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("new_user promo should match inside window")
|
|
||||||
}
|
|
||||||
if got, want := unixSeconds(expiresAt), userInfo.CreatedAt.Add(168*time.Hour).Unix(); got != want {
|
|
||||||
t.Fatalf("new_user expires_at = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
start := now.Add(-time.Hour)
|
|
||||||
end := now.Add(time.Hour)
|
|
||||||
|
|
||||||
if !(subscribePromoCandidate{PromoPrice: 1, StartTime: &start, EndTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate inside active window should be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 0, StartTime: &start, EndTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate with zero promo price should not be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 1, StartTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate before start time should not be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 1, EndTime: &start}).isActive(now) {
|
|
||||||
t.Fatal("candidate after end time should not be active")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -47,11 +47,9 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
Total: total,
|
Total: total,
|
||||||
}
|
}
|
||||||
list := make([]types.Subscribe, len(data))
|
list := make([]types.Subscribe, len(data))
|
||||||
subscribeIDs := make([]int64, 0, len(data))
|
|
||||||
for i, item := range data {
|
for i, item := range data {
|
||||||
var sub types.Subscribe
|
var sub types.Subscribe
|
||||||
tool.DeepCopy(&sub, item)
|
tool.DeepCopy(&sub, item)
|
||||||
subscribeIDs = append(subscribeIDs, sub.Id)
|
|
||||||
if item.Discount != "" {
|
if item.Discount != "" {
|
||||||
var discount []types.SubscribeDiscount
|
var discount []types.SubscribeDiscount
|
||||||
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
||||||
@@ -71,15 +69,6 @@ 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
|
||||||
|
|||||||
@@ -39,14 +39,14 @@ func (l *DeviceWsConnectLogic) DeviceWsConnect(c *gin.Context) error {
|
|||||||
value, _ = c.GetQuery("identifier")
|
value, _ = c.GetQuery("identifier")
|
||||||
if value == nil || value.(string) == "" {
|
if value == nil || value.(string) == "" {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect identifier is empty")
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect identifier is empty")
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.InvalidParams), "identifier is empty")
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "identifier is empty")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
identifier := value.(string)
|
identifier := value.(string)
|
||||||
_, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, identifier)
|
_, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, identifier)
|
||||||
if err != nil && !sysErr.Is(err, gorm.ErrRecordNotFound) {
|
if err != nil && !sysErr.Is(err, gorm.ErrRecordNotFound) {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect FindOneDeviceByIdentifier err: %v", err)
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect FindOneDeviceByIdentifier err: %v", err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
value = l.ctx.Value(constant.CtxKeyUser)
|
value = l.ctx.Value(constant.CtxKeyUser)
|
||||||
@@ -67,7 +67,7 @@ func (l *DeviceWsConnectLogic) DeviceWsConnect(c *gin.Context) error {
|
|||||||
err := l.svcCtx.UserModel.InsertDevice(l.ctx, &device)
|
err := l.svcCtx.UserModel.InsertDevice(l.ctx, &device)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect InsertDevice err: %v", err)
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect InsertDevice err: %v", err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//默认在线设备1
|
//默认在线设备1
|
||||||
|
|||||||
@@ -22,92 +22,77 @@ import (
|
|||||||
|
|
||||||
func AuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
func AuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
if !authenticateRequest(c, svc, c.GetHeader("Authorization"), true) {
|
ctx := c.Request.Context()
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func OptionalAuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
jwtConfig := svc.Config.JwtAuth
|
||||||
return func(c *gin.Context) {
|
// get token from header
|
||||||
token := c.GetHeader("Authorization")
|
token := c.GetHeader("Authorization")
|
||||||
if token == "" {
|
if token == "" {
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !authenticateRequest(c, svc, token, false) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func authenticateRequest(c *gin.Context, svc *svc.ServiceContext, token string, requireToken bool) bool {
|
|
||||||
ctx := c.Request.Context()
|
|
||||||
|
|
||||||
if token == "" {
|
|
||||||
if requireToken {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Token Empty")
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Token Empty")
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenEmpty), "Token Empty"))
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenEmpty), "Token Empty"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// parse token
|
||||||
|
claims, err := jwt.ParseJwtToken(token, jwtConfig.AccessSecret)
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] ParseJwtToken", logger.Field("error", err.Error()), logger.Field("token", token))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenExpire), "Token Invalid"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return !requireToken
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := jwt.ParseJwtToken(token, svc.Config.JwtAuth.AccessSecret)
|
loginType := parseLoginType(claims)
|
||||||
if err != nil {
|
if claims["identifier"] != nil {
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] ParseJwtToken", logger.Field("error", err.Error()), logger.Field("token", token))
|
ctx = context.WithValue(ctx, constant.CtxKeyIdentifier, claims["identifier"].(string))
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenExpire), "Token Invalid"))
|
}
|
||||||
c.Abort()
|
// get user id from token
|
||||||
return false
|
userId := int64(claims["UserId"].(float64))
|
||||||
}
|
// get session id from token
|
||||||
|
sessionId := claims["SessionId"].(string)
|
||||||
|
// get session id from redis
|
||||||
|
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||||
|
value, err := svc.Redis.Get(c, sessionIdCacheKey).Result()
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Redis Get", logger.Field("error", err.Error()), logger.Field("sessionId", sessionId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
loginType := parseLoginType(claims)
|
//verify user id
|
||||||
if claims["identifier"] != nil {
|
if value != fmt.Sprintf("%v", userId) {
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeyIdentifier, claims["identifier"].(string))
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Invalid Access", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
||||||
}
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
userId := int64(claims["UserId"].(float64))
|
c.Abort()
|
||||||
sessionId := claims["SessionId"].(string)
|
return
|
||||||
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
}
|
||||||
value, err := svc.Redis.Get(c, sessionIdCacheKey).Result()
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Redis Get", logger.Field("error", err.Error()), logger.Field("sessionId", sessionId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if value != fmt.Sprintf("%v", userId) {
|
// sliding session: refresh TTL on every active request
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Invalid Access", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
svc.Redis.Expire(c, sessionIdCacheKey, time.Duration(svc.Config.JwtAuth.AccessExpire)*time.Second)
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
userInfo, err := svc.UserModel.FindOne(c, userId)
|
||||||
return false
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] UserModel FindOne", logger.Field("error", err.Error()), logger.Field("userId", userId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// admin verify
|
||||||
|
paths := strings.Split(c.Request.URL.Path, "/")
|
||||||
|
if tool.StringSliceContains(paths, "admin") && !*userInfo.IsAdmin {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Not Admin User", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxLoginType, loginType)
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxKeyUser, userInfo)
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxKeySessionID, sessionId)
|
||||||
|
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
svc.Redis.Expire(c, sessionIdCacheKey, time.Duration(svc.Config.JwtAuth.AccessExpire)*time.Second)
|
|
||||||
|
|
||||||
userInfo, err := svc.UserModel.FindOne(c, userId)
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] UserModel FindOne", logger.Field("error", err.Error()), logger.Field("userId", userId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
paths := strings.Split(c.Request.URL.Path, "/")
|
|
||||||
if tool.StringSliceContains(paths, "admin") && !*userInfo.IsAdmin {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Not Admin User", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxLoginType, loginType)
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeyUser, userInfo)
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeySessionID, sessionId)
|
|
||||||
|
|
||||||
c.Request = c.Request.WithContext(ctx)
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseLoginType(claims map[string]interface{}) string {
|
func parseLoginType(claims map[string]interface{}) string {
|
||||||
|
|||||||
@@ -22,8 +22,6 @@ type Details struct {
|
|||||||
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
||||||
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
||||||
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
|
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID"`
|
|
||||||
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
|
||||||
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
||||||
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
|
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
|
||||||
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Id"`
|
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Id"`
|
||||||
|
|||||||
@@ -3,34 +3,32 @@ package order
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type Order struct {
|
type Order struct {
|
||||||
Id int64 `gorm:"primaryKey"`
|
Id int64 `gorm:"primaryKey"`
|
||||||
ParentId int64 `gorm:"type:bigint;default:null;comment:Parent Order Id"`
|
ParentId int64 `gorm:"type:bigint;default:null;comment:Parent Order Id"`
|
||||||
UserId int64 `gorm:"type:bigint;not null;default:0;comment:User Id"`
|
UserId int64 `gorm:"type:bigint;not null;default:0;comment:User Id"`
|
||||||
SubscriptionUserId int64 `gorm:"type:bigint;not null;default:0;comment:Target user ID for subscription (0=same as UserId)"`
|
SubscriptionUserId int64 `gorm:"type:bigint;not null;default:0;comment:Target user ID for subscription (0=same as UserId)"`
|
||||||
OrderNo string `gorm:"type:varchar(255);not null;default:'';unique;comment:Order No"`
|
OrderNo string `gorm:"type:varchar(255);not null;default:'';unique;comment:Order No"`
|
||||||
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Type: 1: Subscribe, 2: Renewal, 3: ResetTraffic, 4: Recharge"`
|
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Type: 1: Subscribe, 2: Renewal, 3: ResetTraffic, 4: Recharge"`
|
||||||
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
|
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
|
||||||
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
||||||
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
||||||
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
|
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
|
||||||
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
|
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID"`
|
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
||||||
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
|
||||||
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
Commission int64 `gorm:"type:int;not null;default:0;comment:Order Commission"`
|
||||||
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
|
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Method Id"`
|
||||||
Commission int64 `gorm:"type:int;not null;default:0;comment:Order Commission"`
|
Method string `gorm:"type:varchar(255);not null;default:'';comment:Payment Method"`
|
||||||
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Method Id"`
|
FeeAmount int64 `gorm:"type:int;not null;default:0;comment:Fee Amount"`
|
||||||
Method string `gorm:"type:varchar(255);not null;default:'';comment:Payment Method"`
|
TradeNo string `gorm:"type:varchar(255);default:null;comment:Trade No"`
|
||||||
FeeAmount int64 `gorm:"type:int;not null;default:0;comment:Fee Amount"`
|
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"`
|
||||||
TradeNo string `gorm:"type:varchar(255);default:null;comment:Trade No"`
|
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
|
||||||
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"`
|
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
|
||||||
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
|
AppAccountToken string `gorm:"type:varchar(36);default:null;comment:Apple IAP App Account Token (UUID)"`
|
||||||
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
|
ActivationContext string `gorm:"type:text;default:null;comment:Activation context JSON (guest/redemption info for DB fallback)"`
|
||||||
AppAccountToken string `gorm:"type:varchar(36);default:null;comment:Apple IAP App Account Token (UUID)"`
|
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
|
||||||
ActivationContext string `gorm:"type:text;default:null;comment:Activation context JSON (guest/redemption info for DB fallback)"`
|
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||||
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
|
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrdersTotal struct {
|
type OrdersTotal struct {
|
||||||
|
|||||||
@@ -1,218 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
|
||||||
|
|
||||||
type RuleWithPrice struct {
|
|
||||||
Rule
|
|
||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type RuleFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
Type string
|
|
||||||
Enabled *bool
|
|
||||||
Search string
|
|
||||||
}
|
|
||||||
|
|
||||||
type SubscribePromoFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
PromoRuleId int64
|
|
||||||
}
|
|
||||||
|
|
||||||
type UsageFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
PromoRuleId int64
|
|
||||||
UserId int64
|
|
||||||
SubscribeId int64
|
|
||||||
OrderNo string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Model interface {
|
|
||||||
QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error)
|
|
||||||
InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error
|
|
||||||
InsertRule(ctx context.Context, data *Rule) error
|
|
||||||
FindRule(ctx context.Context, id int64) (*Rule, error)
|
|
||||||
UpdateRule(ctx context.Context, data *Rule) error
|
|
||||||
DeleteRule(ctx context.Context, id int64) error
|
|
||||||
QueryRuleList(ctx context.Context, filter RuleFilter) (int64, []*Rule, error)
|
|
||||||
UpsertSubscribePromos(ctx context.Context, data []*SubscribePromo) error
|
|
||||||
FindSubscribePromo(ctx context.Context, id int64) (*SubscribePromo, error)
|
|
||||||
DeleteSubscribePromo(ctx context.Context, id int64) error
|
|
||||||
QuerySubscribePromoList(ctx context.Context, filter SubscribePromoFilter) (int64, []*SubscribePromo, error)
|
|
||||||
QueryUsageList(ctx context.Context, filter UsageFilter) (int64, []*Usage, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type defaultPromoModel struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewModel(db *gorm.DB, _ *redis.Client) Model {
|
|
||||||
return &defaultPromoModel{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizePage(page, size int) (int, int) {
|
|
||||||
if page <= 0 {
|
|
||||||
page = 1
|
|
||||||
}
|
|
||||||
if size <= 0 {
|
|
||||||
size = 10
|
|
||||||
}
|
|
||||||
if size > 100 {
|
|
||||||
size = 100
|
|
||||||
}
|
|
||||||
return page, size
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) {
|
|
||||||
var list []*RuleWithPrice
|
|
||||||
err := m.db.WithContext(ctx).
|
|
||||||
Table("promo_rule AS pr").
|
|
||||||
Select("pr.*, sp.promo_price").
|
|
||||||
Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id").
|
|
||||||
Where("sp.subscribe_id = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, true).
|
|
||||||
Where("pr.deleted_at IS NULL").
|
|
||||||
Order("pr.priority DESC").
|
|
||||||
Order("pr.id ASC").
|
|
||||||
Find(&list).Error
|
|
||||||
return list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error {
|
|
||||||
db := m.db.WithContext(ctx)
|
|
||||||
if len(tx) > 0 {
|
|
||||||
db = tx[0].WithContext(ctx)
|
|
||||||
}
|
|
||||||
return db.Model(&Usage{}).Create(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertRule(ctx context.Context, data *Rule) error {
|
|
||||||
return m.db.WithContext(ctx).Create(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) FindRule(ctx context.Context, id int64) (*Rule, error) {
|
|
||||||
var data Rule
|
|
||||||
err := m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", id).First(&data).Error
|
|
||||||
return &data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
|
|
||||||
return m.db.WithContext(ctx).Save(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
|
|
||||||
result := m.db.WithContext(ctx).Delete(&Rule{}, id)
|
|
||||||
if result.Error != nil {
|
|
||||||
return result.Error
|
|
||||||
}
|
|
||||||
if result.RowsAffected == 0 {
|
|
||||||
return gorm.ErrRecordNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryRuleList(ctx context.Context, filter RuleFilter) (int64, []*Rule, error) {
|
|
||||||
page, size := normalizePage(filter.Page, filter.Size)
|
|
||||||
var total int64
|
|
||||||
var list []*Rule
|
|
||||||
|
|
||||||
query := m.db.WithContext(ctx).Model(&Rule{})
|
|
||||||
if filter.Type != "" {
|
|
||||||
query = query.Where("type = ?", filter.Type)
|
|
||||||
}
|
|
||||||
if filter.Enabled != nil {
|
|
||||||
query = query.Where("enabled = ?", *filter.Enabled)
|
|
||||||
}
|
|
||||||
if filter.Search != "" {
|
|
||||||
search := "%" + filter.Search + "%"
|
|
||||||
query = query.Where("name LIKE ?", search)
|
|
||||||
}
|
|
||||||
if err := query.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := query.Order("priority DESC").Order("id DESC").
|
|
||||||
Limit(size).Offset((page - 1) * size).
|
|
||||||
Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) UpsertSubscribePromos(ctx context.Context, data []*SubscribePromo) error {
|
|
||||||
if len(data) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return m.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
||||||
Columns: []clause.Column{{Name: "subscribe_id"}, {Name: "promo_rule_id"}},
|
|
||||||
DoUpdates: clause.AssignmentColumns([]string{"promo_price", "updated_at"}),
|
|
||||||
}).Create(&data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) FindSubscribePromo(ctx context.Context, id int64) (*SubscribePromo, error) {
|
|
||||||
var data SubscribePromo
|
|
||||||
err := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("id = ?", id).First(&data).Error
|
|
||||||
return &data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) DeleteSubscribePromo(ctx context.Context, id int64) error {
|
|
||||||
result := m.db.WithContext(ctx).Delete(&SubscribePromo{}, id)
|
|
||||||
if result.Error != nil {
|
|
||||||
return result.Error
|
|
||||||
}
|
|
||||||
if result.RowsAffected == 0 {
|
|
||||||
return gorm.ErrRecordNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QuerySubscribePromoList(ctx context.Context, filter SubscribePromoFilter) (int64, []*SubscribePromo, error) {
|
|
||||||
page, size := normalizePage(filter.Page, filter.Size)
|
|
||||||
var total int64
|
|
||||||
var list []*SubscribePromo
|
|
||||||
|
|
||||||
query := m.db.WithContext(ctx).Model(&SubscribePromo{})
|
|
||||||
if filter.PromoRuleId > 0 {
|
|
||||||
query = query.Where("promo_rule_id = ?", filter.PromoRuleId)
|
|
||||||
}
|
|
||||||
if err := query.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryUsageList(ctx context.Context, filter UsageFilter) (int64, []*Usage, error) {
|
|
||||||
page, size := normalizePage(filter.Page, filter.Size)
|
|
||||||
var total int64
|
|
||||||
var list []*Usage
|
|
||||||
|
|
||||||
query := m.db.WithContext(ctx).Model(&Usage{})
|
|
||||||
if filter.PromoRuleId > 0 {
|
|
||||||
query = query.Where("promo_rule_id = ?", filter.PromoRuleId)
|
|
||||||
}
|
|
||||||
if filter.UserId > 0 {
|
|
||||||
query = query.Where("user_id = ?", filter.UserId)
|
|
||||||
}
|
|
||||||
if filter.SubscribeId > 0 {
|
|
||||||
query = query.Where("subscribe_id = ?", filter.SubscribeId)
|
|
||||||
}
|
|
||||||
if filter.OrderNo != "" {
|
|
||||||
query = query.Where("order_no LIKE ?", "%"+filter.OrderNo+"%")
|
|
||||||
}
|
|
||||||
if err := query.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsNotFound(err error) bool {
|
|
||||||
return errors.Is(err, gorm.ErrRecordNotFound)
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
RuleTypeNewUser = "new_user"
|
|
||||||
RuleTypeInactiveUser = "inactive_user"
|
|
||||||
RuleTypeCampaign = "campaign"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Rule struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
Name string `gorm:"type:varchar(100);not null;default:'';comment:Rule Name"`
|
|
||||||
Type string `gorm:"type:varchar(32);not null;default:'';comment:Rule Type"`
|
|
||||||
Params string `gorm:"type:json;not null;comment:Rule Params"`
|
|
||||||
Priority int64 `gorm:"type:int;not null;default:0;comment:Priority"`
|
|
||||||
Enabled bool `gorm:"type:tinyint(1);not null;default:1;comment:Enabled"`
|
|
||||||
StartTime *time.Time `gorm:"default:null;comment:Start Time"`
|
|
||||||
EndTime *time.Time `gorm:"default:null;comment:End Time"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
DeletedAt gorm.DeletedAt `gorm:"index;comment:Delete Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Rule) TableName() string {
|
|
||||||
return "promo_rule"
|
|
||||||
}
|
|
||||||
|
|
||||||
type SubscribePromo struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe 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"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (SubscribePromo) TableName() string {
|
|
||||||
return "subscribe_promo"
|
|
||||||
}
|
|
||||||
|
|
||||||
type Usage struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
UserId int64 `gorm:"type:bigint unsigned;not null;comment:User ID"`
|
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
|
||||||
OrderNo string `gorm:"type:varchar(255);not null;default:'';comment:Order No"`
|
|
||||||
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Usage) TableName() string {
|
|
||||||
return "promo_usage"
|
|
||||||
}
|
|
||||||
@@ -101,8 +101,6 @@ type Subscribe struct {
|
|||||||
Traffic int64 `gorm:"default:0;comment:Traffic"`
|
Traffic int64 `gorm:"default:0;comment:Traffic"`
|
||||||
Download int64 `gorm:"default:0;comment:Download Traffic"`
|
Download int64 `gorm:"default:0;comment:Download Traffic"`
|
||||||
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
|
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
|
||||||
SpeedLimit int64 `gorm:"default:0;comment:User-level speed limit override (Mbps, 0=use plan default)"`
|
|
||||||
TrafficLimit string `gorm:"type:text;default:null;comment:User-level traffic limit rules override (JSON)"`
|
|
||||||
ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"`
|
ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"`
|
||||||
ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"`
|
ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"`
|
||||||
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
|
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import (
|
|||||||
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
"github.com/perfect-panel/server/internal/model/payment"
|
"github.com/perfect-panel/server/internal/model/payment"
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
"github.com/perfect-panel/server/internal/model/system"
|
"github.com/perfect-panel/server/internal/model/system"
|
||||||
"github.com/perfect-panel/server/internal/model/ticket"
|
"github.com/perfect-panel/server/internal/model/ticket"
|
||||||
@@ -46,7 +45,7 @@ type ServiceContext struct {
|
|||||||
ExchangeRate float64
|
ExchangeRate float64
|
||||||
GeoIP *IPLocation
|
GeoIP *IPLocation
|
||||||
SignatureValidator *signature.Validator
|
SignatureValidator *signature.Validator
|
||||||
S3Store *storage.S3Store
|
S3Store *storage.S3Store
|
||||||
|
|
||||||
//NodeCache *cache.NodeCacheClient
|
//NodeCache *cache.NodeCacheClient
|
||||||
AuthModel auth.Model
|
AuthModel auth.Model
|
||||||
@@ -64,7 +63,6 @@ type ServiceContext struct {
|
|||||||
RedemptionCodeModel redemption.RedemptionCodeModel
|
RedemptionCodeModel redemption.RedemptionCodeModel
|
||||||
RedemptionRecordModel redemption.RedemptionRecordModel
|
RedemptionRecordModel redemption.RedemptionRecordModel
|
||||||
PaymentModel payment.Model
|
PaymentModel payment.Model
|
||||||
PromoModel promo.Model
|
|
||||||
DocumentModel document.Model
|
DocumentModel document.Model
|
||||||
SubscribeModel subscribe.Model
|
SubscribeModel subscribe.Model
|
||||||
TrafficLogModel traffic.Model
|
TrafficLogModel traffic.Model
|
||||||
@@ -140,7 +138,6 @@ func NewServiceContext(c config.Config) *ServiceContext {
|
|||||||
RedemptionCodeModel: redemption.NewRedemptionCodeModel(db, rds),
|
RedemptionCodeModel: redemption.NewRedemptionCodeModel(db, rds),
|
||||||
RedemptionRecordModel: redemption.NewRedemptionRecordModel(db, rds),
|
RedemptionRecordModel: redemption.NewRedemptionRecordModel(db, rds),
|
||||||
PaymentModel: payment.NewModel(db, rds),
|
PaymentModel: payment.NewModel(db, rds),
|
||||||
PromoModel: promo.NewModel(db, rds),
|
|
||||||
DocumentModel: document.NewModel(db, rds),
|
DocumentModel: document.NewModel(db, rds),
|
||||||
SubscribeModel: subscribe.NewModel(db, rds),
|
SubscribeModel: subscribe.NewModel(db, rds),
|
||||||
TrafficLogModel: traffic.NewModel(db),
|
TrafficLogModel: traffic.NewModel(db),
|
||||||
|
|||||||
+34
-168
@@ -436,21 +436,6 @@ type CreatePaymentMethodRequest struct {
|
|||||||
Enable *bool `json:"enable" validate:"required"`
|
Enable *bool `json:"enable" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreatePromoRuleRequest struct {
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params json.RawMessage `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreatePromoPriceRequest struct {
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required"`
|
|
||||||
Items []PromoPriceInput `json:"items" validate:"required,dive"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreateQuotaTaskRequest struct {
|
type CreateQuotaTaskRequest struct {
|
||||||
Subscribers []int64 `json:"subscribers"`
|
Subscribers []int64 `json:"subscribers"`
|
||||||
IsActive *bool `json:"is_active"`
|
IsActive *bool `json:"is_active"`
|
||||||
@@ -556,12 +541,10 @@ type CreateUserRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserSubscribeRequest struct {
|
type CreateUserSubscribeRequest struct {
|
||||||
UserId int64 `json:"user_id"`
|
UserId int64 `json:"user_id"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
SpeedLimit int64 `json:"speed_limit,optional"`
|
|
||||||
TrafficLimit string `json:"traffic_limit,optional"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserTicketFollowRequest struct {
|
type CreateUserTicketFollowRequest struct {
|
||||||
@@ -634,14 +617,6 @@ type DeletePaymentMethodRequest struct {
|
|||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DeletePromoPriceRequest struct {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeletePromoRuleRequest struct {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeleteRedemptionCodeRequest struct {
|
type DeleteRedemptionCodeRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -1350,48 +1325,6 @@ type GetPaymentMethodListResponse struct {
|
|||||||
List []PaymentMethodDetail `json:"list"`
|
List []PaymentMethodDetail `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetPromoPriceListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoPriceListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoPrice `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleDetailRequest struct {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
Type string `form:"type,omitempty" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
|
||||||
Enabled *bool `form:"enabled,omitempty"`
|
|
||||||
Search string `form:"search,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoRule `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoUsageListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"rule_id,omitempty"`
|
|
||||||
UserId int64 `form:"user_id,omitempty"`
|
|
||||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
|
||||||
OrderNo string `form:"order_no,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoUsageListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoUsage `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPreSendEmailCountRequest struct {
|
type GetPreSendEmailCountRequest struct {
|
||||||
Scope int8 `json:"scope"`
|
Scope int8 `json:"scope"`
|
||||||
RegisterStartTime int64 `json:"register_start_time,omitempty"`
|
RegisterStartTime int64 `json:"register_start_time,omitempty"`
|
||||||
@@ -1933,8 +1866,6 @@ type Order struct {
|
|||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
Commission int64 `json:"commission,omitempty"`
|
Commission int64 `json:"commission,omitempty"`
|
||||||
@@ -1958,8 +1889,6 @@ type OrderDetail struct {
|
|||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
Commission int64 `json:"commission,omitempty"`
|
Commission int64 `json:"commission,omitempty"`
|
||||||
@@ -2081,7 +2010,6 @@ type PreOrderResponse struct {
|
|||||||
Price int64 `json:"price"`
|
Price int64 `json:"price"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
@@ -2104,44 +2032,6 @@ type PrePurchaseOrderResponse struct {
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PromoPrice struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
UnitPrice int64 `json:"unit_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoPriceInput struct {
|
|
||||||
SubscribeId int64 `json:"subscribe_id" validate:"required"`
|
|
||||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoRule struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Params json.RawMessage `json:"params"`
|
|
||||||
Priority int64 `json:"priority"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
StartTime int64 `json:"start_time"`
|
|
||||||
EndTime int64 `json:"end_time"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoUsage struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"user_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PreRenewalOrderResponse struct {
|
type PreRenewalOrderResponse struct {
|
||||||
OrderNo string `json:"orderNo"`
|
OrderNo string `json:"orderNo"`
|
||||||
}
|
}
|
||||||
@@ -2888,13 +2778,6 @@ type StripePayment struct {
|
|||||||
PublishableKey string `json:"publishable_key"`
|
PublishableKey string `json:"publishable_key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscribePromo struct {
|
|
||||||
RuleName string `json:"rule_name"`
|
|
||||||
RuleType string `json:"rule_type"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Subscribe struct {
|
type Subscribe struct {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -2903,7 +2786,6 @@ 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"`
|
||||||
@@ -3310,17 +3192,6 @@ type UpdatePaymentMethodRequest struct {
|
|||||||
Enable *bool `json:"enable" validate:"required"`
|
Enable *bool `json:"enable" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdatePromoRuleRequest struct {
|
|
||||||
Id int64 `json:"id" validate:"required"`
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params json.RawMessage `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateRedemptionCodeRequest struct {
|
type UpdateRedemptionCodeRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
TotalCount int64 `json:"total_count,omitempty"`
|
TotalCount int64 `json:"total_count,omitempty"`
|
||||||
@@ -3446,14 +3317,12 @@ type UpdateUserSubscribeNoteRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserSubscribeRequest struct {
|
type UpdateUserSubscribeRequest struct {
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Upload int64 `json:"upload"`
|
Upload int64 `json:"upload"`
|
||||||
Download int64 `json:"download"`
|
Download int64 `json:"download"`
|
||||||
SpeedLimit *int64 `json:"speed_limit,omitempty"`
|
|
||||||
TrafficLimit *string `json:"traffic_limit,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserTicketStatusRequest struct {
|
type UpdateUserTicketStatusRequest struct {
|
||||||
@@ -3605,33 +3474,30 @@ type UserSubscribe struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type UserSubscribeDetail struct {
|
type UserSubscribeDetail struct {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
UserId int64 `json:"user_id"`
|
UserId int64 `json:"user_id"`
|
||||||
User User `json:"user"`
|
User User `json:"user"`
|
||||||
OrderId int64 `json:"order_id"`
|
OrderId int64 `json:"order_id"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Subscribe Subscribe `json:"subscribe"`
|
Subscribe Subscribe `json:"subscribe"`
|
||||||
NodeGroupId int64 `json:"node_group_id"`
|
NodeGroupId int64 `json:"node_group_id"`
|
||||||
NodeGroupName string `json:"node_group_name"`
|
NodeGroupName string `json:"node_group_name"`
|
||||||
GroupLocked bool `json:"group_locked"`
|
GroupLocked bool `json:"group_locked"`
|
||||||
StartTime int64 `json:"start_time"`
|
StartTime int64 `json:"start_time"`
|
||||||
ExpireTime int64 `json:"expire_time"`
|
ExpireTime int64 `json:"expire_time"`
|
||||||
ResetTime int64 `json:"reset_time"`
|
ResetTime int64 `json:"reset_time"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
Download int64 `json:"download"`
|
Download int64 `json:"download"`
|
||||||
Upload int64 `json:"upload"`
|
Upload int64 `json:"upload"`
|
||||||
SpeedLimit int64 `json:"speed_limit"`
|
Token string `json:"token"`
|
||||||
TrafficLimit []TrafficLimit `json:"user_traffic_limit"`
|
Status uint8 `json:"status"`
|
||||||
PlanSpeedLimit int64 `json:"plan_speed_limit"`
|
EffectiveSpeed int64 `json:"effective_speed"`
|
||||||
Token string `json:"token"`
|
IsThrottled bool `json:"is_throttled"`
|
||||||
Status uint8 `json:"status"`
|
ThrottleRule string `json:"throttle_rule,omitempty"`
|
||||||
EffectiveSpeed int64 `json:"effective_speed"`
|
ThrottleStart int64 `json:"throttle_start,omitempty"`
|
||||||
IsThrottled bool `json:"is_throttled"`
|
ThrottleEnd int64 `json:"throttle_end,omitempty"`
|
||||||
ThrottleRule string `json:"throttle_rule,omitempty"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
ThrottleStart int64 `json:"throttle_start,omitempty"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
ThrottleEnd int64 `json:"throttle_end,omitempty"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserSubscribeInfo struct {
|
type UserSubscribeInfo struct {
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# HiFast 上传链路运维 Runbook
|
||||||
|
|
||||||
|
## 适用范围
|
||||||
|
|
||||||
|
本文档用于测试环境 `https://tapi.hifast.biz/v1/public/file/upload` 上传链路自检和 MinIO sidecar 运维。测试环境的对象存储应自包含在 compose 栈内,不依赖外部 `107.173.50.22:5017`。
|
||||||
|
|
||||||
|
## 当前测试环境配置
|
||||||
|
|
||||||
|
- Compose 文件:`/root/bindbox/docker-compose.cloud.yml`
|
||||||
|
- 应用配置:`/root/bindbox/configs/ppanel.yaml`
|
||||||
|
- MinIO 数据目录:`/root/bindbox/data/minio`
|
||||||
|
- MinIO API:`http://127.0.0.1:9000`
|
||||||
|
- MinIO Console:`http://127.0.0.1:9001`,仅绑定本机,需 SSH 隧道访问
|
||||||
|
- Bucket:与 `ppanel.yaml` 的 `S3.Bucket` 保持一致,当前为 `hifastvpn`
|
||||||
|
|
||||||
|
`ppanel-server` 使用 host 网络,所以 `S3.Endpoint` 必须写宿主机 loopback:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
S3:
|
||||||
|
Enable: true
|
||||||
|
Endpoint: "http://127.0.0.1:9000"
|
||||||
|
Bucket: "hifastvpn"
|
||||||
|
UsePathStyle: true
|
||||||
|
```
|
||||||
|
|
||||||
|
## 启停与状态检查
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/bindbox
|
||||||
|
docker compose -f docker-compose.cloud.yml up -d minio minio-init
|
||||||
|
docker restart ppanel-server
|
||||||
|
|
||||||
|
docker compose -f docker-compose.cloud.yml ps minio minio-init ppanel-server
|
||||||
|
curl -fsS http://127.0.0.1:9000/minio/health/live
|
||||||
|
curl -fsS https://tapi.hifast.biz/v1/common/heartbeat
|
||||||
|
```
|
||||||
|
|
||||||
|
`minio-init` 是一次性 bucket 初始化容器,正常状态是 `exited` 且退出码为 `0`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker inspect ppanel-minio-init --format 'status={{.State.Status}} exit={{.State.ExitCode}}'
|
||||||
|
docker logs --tail 50 ppanel-minio-init
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bucket 重建
|
||||||
|
|
||||||
|
如 bucket 被误删或新环境首次初始化失败:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/bindbox
|
||||||
|
docker compose -f docker-compose.cloud.yml up -d minio
|
||||||
|
docker compose -f docker-compose.cloud.yml run --rm minio-init
|
||||||
|
```
|
||||||
|
|
||||||
|
确认 bucket:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker logs --tail 50 ppanel-minio-init
|
||||||
|
find /root/bindbox/data/minio -maxdepth 3 -type d | sort | head
|
||||||
|
```
|
||||||
|
|
||||||
|
## 上传链路自检
|
||||||
|
|
||||||
|
基础健康检查:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -i https://tapi.hifast.biz/v1/common/heartbeat
|
||||||
|
```
|
||||||
|
|
||||||
|
完整上传需要有效用户 JWT。复测标准:
|
||||||
|
|
||||||
|
- `POST /v1/public/file/upload` 返回 HTTP 200
|
||||||
|
- 响应业务 `code=200`
|
||||||
|
- `data.url` 指向 `S3.PublicBaseURL + object_key`
|
||||||
|
- MinIO 数据目录可看到对应对象
|
||||||
|
- `ppanel-server` 日志没有 `put object failed` 或 `context canceled`
|
||||||
|
|
||||||
|
排查命令:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker logs --since 10m ppanel-server | grep -Ei 'file/upload|put object|context canceled|s3'
|
||||||
|
find /root/bindbox/data/minio/hifastvpn -type f | sort | tail
|
||||||
|
```
|
||||||
|
|
||||||
|
## 备份
|
||||||
|
|
||||||
|
变更前必须备份:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/bindbox
|
||||||
|
ts=$(date +%Y%m%d%H%M%S)
|
||||||
|
cp docker-compose.cloud.yml docker-compose.cloud.yml.bak.hif-101.$ts
|
||||||
|
cp .env .env.bak.hif-101.$ts
|
||||||
|
cp configs/ppanel.yaml configs/ppanel.yaml.bak.$ts
|
||||||
|
```
|
||||||
|
|
||||||
|
MinIO 数据备份:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/bindbox
|
||||||
|
tar -czf minio-data.$(date +%Y%m%d%H%M%S).tar.gz data/minio
|
||||||
|
```
|
||||||
|
|
||||||
|
## 回滚
|
||||||
|
|
||||||
|
恢复外部 S3 配置或回到变更前状态:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/bindbox
|
||||||
|
cp configs/ppanel.yaml.bak.YYYYMMDDHHMMSS configs/ppanel.yaml
|
||||||
|
cp docker-compose.cloud.yml.bak.hif-101.YYYYMMDDHHMMSS docker-compose.cloud.yml
|
||||||
|
cp .env.bak.hif-101.YYYYMMDDHHMMSS .env
|
||||||
|
docker compose -f docker-compose.cloud.yml stop minio
|
||||||
|
docker restart ppanel-server
|
||||||
|
```
|
||||||
|
|
||||||
|
保留 `/root/bindbox/data/minio` 便于复盘,不要在回滚时删除数据目录。
|
||||||
|
|
||||||
|
## 旧 Endpoint 清理
|
||||||
|
|
||||||
|
测试栈活动配置不得继续引用旧外部 endpoint:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /root/bindbox
|
||||||
|
grep -R '107\.173\.50\.22:5017' -n docker-compose.cloud.yml configs/ppanel.yaml .env || true
|
||||||
|
```
|
||||||
+1
-1
@@ -31,7 +31,6 @@ import (
|
|||||||
"apis/admin/marketing.api"
|
"apis/admin/marketing.api"
|
||||||
"apis/admin/application.api"
|
"apis/admin/application.api"
|
||||||
"apis/admin/group.api"
|
"apis/admin/group.api"
|
||||||
"apis/admin/promo.api"
|
|
||||||
"apis/public/user.api"
|
"apis/public/user.api"
|
||||||
"apis/public/subscribe.api"
|
"apis/public/subscribe.api"
|
||||||
"apis/public/redemption.api"
|
"apis/public/redemption.api"
|
||||||
@@ -45,3 +44,4 @@ import (
|
|||||||
"apis/public/portal.api"
|
"apis/public/portal.api"
|
||||||
"apis/public/iap.api"
|
"apis/public/iap.api"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/hibiken/asynq"
|
"github.com/hibiken/asynq"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/model/redemption"
|
"github.com/perfect-panel/server/internal/model/redemption"
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
@@ -149,7 +148,6 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
l.recordPromoUsage(ctx, orderInfo)
|
|
||||||
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",
|
||||||
@@ -159,44 +157,6 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) {
|
|
||||||
if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
promoPrice := int64(0)
|
|
||||||
if orderInfo.Price > orderInfo.PromoDiscount {
|
|
||||||
promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity
|
|
||||||
}
|
|
||||||
if promoPrice <= 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
||||||
var count int64
|
|
||||||
if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil {
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
if count > 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return l.svc.PromoModel.InsertUsage(ctx, &promo.Usage{
|
|
||||||
UserId: orderInfo.UserId,
|
|
||||||
PromoRuleId: orderInfo.PromoRuleId,
|
|
||||||
SubscribeId: orderInfo.SubscribeId,
|
|
||||||
OrderNo: orderInfo.OrderNo,
|
|
||||||
PromoPrice: promoPrice,
|
|
||||||
}, 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
|
||||||
func (l *ActivateOrderLogic) parsePayload(ctx context.Context, payload []byte) (*queueTypes.ForthwithActivateOrderPayload, error) {
|
func (l *ActivateOrderLogic) parsePayload(ctx context.Context, payload []byte) (*queueTypes.ForthwithActivateOrderPayload, error) {
|
||||||
var p queueTypes.ForthwithActivateOrderPayload
|
var p queueTypes.ForthwithActivateOrderPayload
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
//go:build ignore
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
// Package scripts keeps standalone maintenance tools out of normal package
|
|
||||||
// builds. Run individual tools with go run scripts/<tool>.go.
|
|
||||||
package scripts
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
//go:build ignore
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
Reference in New Issue
Block a user