Compare commits

...

13 Commits

Author SHA1 Message Date
shanshanzhong147 b6d0c89aa1 修复(#105): 消除 goctl 重新生成漂移
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 23:51:25 -07:00
shanshanzhong147 27986044a1 修复(#105): 补齐 goctl API 聚合入口
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 23:28:16 -07:00
shanshanzhong147 197fed7d12 新功能(#102): 新增邀请记录接口并删除旧邀请销售接口
Build docker and publish / build (20.15.1) (push) Failing after 10m56s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m50s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 22:50:16 -07:00
shanshanzhong147 f452f80100 配置(#98): 扩展文件上传 Content-Type 白名单支持图片
Build docker and publish / build (20.15.1) (push) Failing after 9m55s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m7s
- 在 etc/ppanel.yaml 与 internal/config/config.go 的 S3.AllowedContentTypes 新增 image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp
- 保留原 zip/gzip/text/json/octet-stream
- validateInitRequest 在拒绝时携带 content_type is not allowed 业务消息
- 新增 internal/logic/public/file/common_test.go,覆盖允许/拒绝及无 Content-Type 嗅探
- doc/tapi-file-upload-zh.md 同步允许类型列表与错误码说明

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 19:50:51 -07:00
shanshanzhong147 1022160ff8 新功能(#89): 增强邀请列表接口 + 新增全局邀请管理接口
Build docker and publish / build (20.15.1) (push) Failing after 9m30s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m48s
P01: GET /v1/admin/user/invite/list 增加 search/enable/user_id_search
筛选参数,响应新增 order_count/has_purchased/inviter_commission/
inviter_gift_days/invitee_gift_days 权益字段。

P02: 新增 GET /v1/admin/invite/list 全局邀请管理接口,支持按
邀请人/被邀请人筛选和搜索,返回邀请关系及权益聚合数据。

共用 QueryBenefits 批量查询防 N+1,分页上限 100。

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 10:32:28 -07:00
shanshanzhong147 82eff47f38 新功能(#69): 用户级限速覆盖 — 数据层 + 核心逻辑 + 管理接口
Build docker and publish / build (20.15.1) (push) Failing after 8m52s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m51s
- 新增 migration 02153: user_subscribe 表添加 speed_limit、traffic_limit 列(幂等)
- model 层 Subscribe/SubscribeDetails 新增用户级限速字段(*string 类型支持 nil 回退)
- server 用户列表和管理员详情接口支持用户级限速覆盖优先级计算
- 更新管理员订阅更新接口支持写入/清除用户级限速

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 08:07:16 -07:00
shanshanzhong147 d351b50066 修复(#71): 管理员订阅限速接口拒绝负数限速和非法 traffic_limit
Build docker and publish / build (20.15.1) (push) Failing after 8m50s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m56s
- SpeedLimit 加 validate:"gte=0" 校验
- TrafficLimit 加 JSON 格式校验
- 新增单测覆盖负数限速和非法 JSON 场景

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 07:13:05 -07:00
shanshanzhong147 4366a9be8b 修复(#79): 促销管理后台API + 审查问题修复
Build docker and publish / build (20.15.1) (push) Failing after 9m10s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m18s
- 实现促销管理接口:规则CRUD、优惠价配置、使用记录查询
- 修复 UpsertPrices 新增记录时提前 return 的问题
- DeleteRule/DeletePrice 不存在记录返回 code=404
- SetPromoPriceRequest.items 空数组校验
- 分页参数限制 page>0、1<=size<=200
- 下单侧促销价格按数量档总价口径计算(含 #87 修复)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 06:32:42 -07:00
shanshanzhong147 b5e50d1ee5 修复(#75): 按数量精确匹配套餐列表促销
Build docker and publish / build (20.15.1) (push) Failing after 9m2s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m58s
- loadSubscribePromoMap 返回 map[subscribeID]map[quantity]*SubscribePromo 二级映射
- 候选查询按 subscribe_id、quantity、priority DESC 排序,一次取出所有 quantity 档位
- 下单路径 QueryEligibleRules 将 quantity 条件移至 JOIN,精确匹配
- 永久订阅(expire_time=0)用 CASE WHEN 排序兜底,不再误判为回归促销
- 新增 promoEligibility、model、subscribe promo 单元测试

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 06:22:49 -07:00
shanshanzhong147 02b41e7a2c 修复(#85): 促销系统 quantity 设计修正补丁(跨任务统一修复)
Build docker and publish / build (20.15.1) (push) Failing after 8m50s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m19s
- subscribe_promo 表加 quantity 字段,BIGINT NOT NULL DEFAULT 1
- EvaluatePromo 加 quantity 参数,按 subscribeID + quantity 精确匹配
- Promo 从 Subscribe 顶层移到 SubscribeDiscount
- 查询加 quantity,返回 map[subscribeID][quantity] 二级映射
- recordPromoUsage 错误向上传播,不再静默吞掉
- preCreate 和 purchase 的 allowPromo 判定统一为 orderType==1
- 迁移脚本增加幂等处理(guarded DROP/ADD/MODIFY)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 05:57:21 -07:00
shanshanzhong147 d12c340743 新功能(#77): 套餐列表 API 返回规格级促销信息
Build docker and publish / build (20.15.1) (push) Failing after 8m23s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m54s
将 promo 字段从 Subscribe 顶层移至 SubscribeDiscount(discount[] 项内),
促销查询按 subscribe_id + quantity 维度写入,每个规格独立命中最高优先级规则。

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 02:19:58 -07:00
shanshanzhong147 c90edac630 修复(#73): 修正促销迁移表结构 — subscribe_promo 加 quantity + 索引优化
Build docker and publish / build (20.15.1) (push) Failing after 8m28s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m59s
- subscribe_promo 新增 quantity 列,唯一键改为 (subscribe_id, quantity, promo_rule_id)
- promo_rule 索引合并为 idx_enabled_priority_deleted (enabled, deleted_at, priority DESC)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 01:10:31 -07:00
shanshanzhong147 b9192db042 feat: 文件上传接口直接返回完整 URL + 提现 content 改为非必填
Build docker and publish / build (20.15.1) (push) Failing after 8m29s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m3s
- FileUploadResponse / FileUploadCompleteResponse 精简为只返回 url
- S3Store.BuildObjectURL 拼接完整访问地址
- 提现 method=0 时 content 不再参与必填校验
- 新增用户端 API 接口文档
2026-05-27 00:57:21 -07:00
112 changed files with 6613 additions and 1769 deletions
+48
View File
@@ -0,0 +1,48 @@
syntax = "v1"
info (
title: "invite admin API"
desc: "API for ppanel"
author: "Tension"
email: "tension@ppanel.com"
version: "0.0.1"
)
type (
GetInviteManageListRequest {
Page int `form:"page"`
Size int `form:"size"`
Search string `form:"search"`
InviterId int64 `form:"inviter_id"`
InviteeId int64 `form:"invitee_id"`
}
InviteManageRecord {
InviterId int64 `json:"inviter_id"`
InviterIdentifier string `json:"inviter_identifier"`
InviteeId int64 `json:"invitee_id"`
InviteeIdentifier string `json:"invitee_identifier"`
InviteeAvatar string `json:"invitee_avatar"`
InviteeEnable bool `json:"invitee_enable"`
InvitedAt int64 `json:"invited_at"`
OrderCount int64 `json:"order_count"`
HasPurchased bool `json:"has_purchased"`
InviterCommission int64 `json:"inviter_commission"`
InviterGiftDays int64 `json:"inviter_gift_days"`
InviteeGiftDays int64 `json:"invitee_gift_days"`
}
GetInviteManageListResponse {
Total int64 `json:"total"`
List []InviteManageRecord `json:"list"`
}
)
@server (
prefix: v1/admin/invite
group: admin/invite
middleware: AuthMiddleware
)
service ppanel {
@doc "Get invite manage list"
@handler GetInviteManageList
get /list (GetInviteManageListRequest) returns (GetInviteManageListResponse)
}
+121
View File
@@ -0,0 +1,121 @@
syntax = "v1"
info (
title: "promo admin API"
desc: "API for ppanel"
author: "Tension"
email: "tension@ppanel.com"
version: "0.0.1"
)
import "../types.api"
type (
CreatePromoRuleRequest {
Name string `json:"name" validate:"required,max=100"`
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority" validate:"gte=0"`
Enabled *bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
}
UpdatePromoRuleRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
Name string `json:"name" validate:"required,max=100"`
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority" validate:"gte=0"`
Enabled *bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
}
GetPromoRuleDetailRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
}
DeletePromoRuleRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
}
GetPromoRuleListRequest {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
Enabled *bool `form:"enabled"`
Search string `form:"search,omitempty"`
}
GetPromoRuleListResponse {
Total int64 `json:"total"`
List []PromoRule `json:"list"`
}
SetPromoPriceRequest {
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"`
}
GetPromoPriceListRequest {
PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"`
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
}
GetPromoPriceListResponse {
Total int64 `json:"total"`
List []PromoPrice `json:"list"`
}
DeletePromoPriceRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
}
GetPromoUsageListRequest {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
RuleId 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 CreateRule
post /rule (CreatePromoRuleRequest) returns (PromoRule)
@doc "Get promo rule list"
@handler GetRuleList
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
@doc "Get promo rule detail"
@handler GetRuleDetail
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
@doc "Update promo rule"
@handler UpdateRule
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
@doc "Delete promo rule"
@handler DeleteRule
delete /rule/:id (DeletePromoRuleRequest)
@doc "Set promo prices"
@handler SetPrice
post /price (SetPromoPriceRequest)
@doc "Get promo price list"
@handler GetPriceList
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
@doc "Delete promo price"
@handler DeletePrice
delete /price/:id (DeletePromoPriceRequest)
@doc "Get promo usage list"
@handler GetUsageList
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
}
+2 -1
View File
@@ -46,6 +46,7 @@ type (
SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"`
NewUserOnly *bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -74,6 +75,7 @@ type (
SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"`
NewUserOnly *bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -175,4 +177,3 @@ service ppanel {
@handler ResetAllSubscribeToken
post /reset_all_token returns (ResetAllSubscribeTokenResponse)
}
+45 -1
View File
@@ -23,10 +23,12 @@ type (
SubscribeId *int64 `form:"subscribe_id,omitempty"`
UserSubscribeId *int64 `form:"user_subscribe_id,omitempty"`
ShortCode string `form:"short_code,omitempty"`
DeviceId *int64 `form:"device_id,omitempty"`
FamilyJoined *bool `form:"family_joined,omitempty"`
FamilyStatus string `form:"family_status,omitempty"`
FamilyOwnerUserId *int64 `form:"family_owner_user_id,omitempty"`
FamilyId *int64 `form:"family_id,omitempty"`
SortOrder string `form:"sort_order,omitempty"`
}
// GetUserListResponse
GetUserListResponse {
@@ -134,6 +136,40 @@ type (
List []UserDevice `json:"list"`
Total int64 `json:"total"`
}
GetAdminUserInviteStatsRequest {
UserId int64 `form:"user_id" validate:"required"`
}
GetAdminUserInviteStatsResponse {
InviteCount int64 `json:"invite_count"`
TotalCommission int64 `json:"total_commission"`
CurrentCommission int64 `json:"current_commission"`
ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase bool `json:"only_first_purchase"`
}
GetAdminUserInviteListRequest {
Page int `form:"page"`
Size int `form:"size"`
UserId int64 `form:"user_id" validate:"required"`
Search string `form:"search,omitempty"`
Enable *bool `form:"enable,omitempty"`
UserIdSearch int64 `form:"user_id_search,omitempty"`
}
AdminInvitedUser {
Id int64 `json:"id"`
Avatar string `json:"avatar"`
Identifier string `json:"identifier"`
Enable bool `json:"enable"`
CreatedAt int64 `json:"created_at"`
OrderCount int64 `json:"order_count"`
HasPurchased bool `json:"has_purchased"`
InviterCommission int64 `json:"inviter_commission"`
InviterGiftDays int64 `json:"inviter_gift_days"`
InviteeGiftDays int64 `json:"invitee_gift_days"`
}
GetAdminUserInviteListResponse {
Total int64 `json:"total"`
List []AdminInvitedUser `json:"list"`
}
CreateUserSubscribeRequest {
UserId int64 `json:"user_id"`
ExpiredAt int64 `json:"expired_at"`
@@ -149,7 +185,7 @@ type (
ExpiredAt int64 `json:"expired_at"`
Upload int64 `json:"upload"`
Download int64 `json:"download"`
SpeedLimit *int64 `json:"speed_limit,omitempty"`
SpeedLimit *int64 `json:"speed_limit,omitempty" validate:"omitempty,gte=0"`
TrafficLimit *string `json:"traffic_limit,omitempty"`
}
GetUserLoginLogsRequest {
@@ -318,6 +354,14 @@ service ppanel {
@handler GetUserSubscribeTrafficLogs
get /subscribe/traffic_logs (GetUserSubscribeTrafficLogsRequest) returns (GetUserSubscribeTrafficLogsResponse)
@doc "Get admin user invite stats"
@handler GetAdminUserInviteStats
get /invite/stats (GetAdminUserInviteStatsRequest) returns (GetAdminUserInviteStatsResponse)
@doc "Get admin user invite list"
@handler GetAdminUserInviteList
get /invite/list (GetAdminUserInviteListRequest) returns (GetAdminUserInviteListResponse)
@doc "Get user subcribe devices"
@handler GetUserSubscribeDevices
get /subscribe/device (GetUserSubscribeDevicesRequest) returns (GetUserSubscribeDevicesResponse)
+2 -3
View File
@@ -111,7 +111,7 @@ type (
@server (
prefix: v1/server
group: server
group: node/server
middleware: ServerMiddleware
)
service ppanel {
@@ -138,11 +138,10 @@ service ppanel {
@server (
prefix: v2/server
group: server
group: node/server
)
service ppanel {
@doc "Get Server Protocol Config"
@handler QueryServerProtocolConfig
get /:server_id (QueryServerConfigRequest) returns (QueryServerConfigResponse)
}
+48
View File
@@ -0,0 +1,48 @@
syntax = "v1"
info (
title: "ppanel API"
desc: "API for ppanel"
author: "Tension"
email: "tension@ppanel.com"
version: "0.0.1"
)
import (
"common.api"
"node/node.api"
"auth/auth.api"
"admin/system.api"
"admin/user.api"
"admin/auth.api"
"admin/server.api"
"admin/subscribe.api"
"admin/payment.api"
"admin/coupon.api"
"admin/redemption.api"
"admin/order.api"
"admin/ticket.api"
"admin/announcement.api"
"admin/document.api"
"admin/tool.api"
"admin/console.api"
"admin/log.api"
"admin/ads.api"
"admin/marketing.api"
"admin/application.api"
"admin/promo.api"
"admin/invite.api"
"admin/group.api"
"public/user.api"
"public/subscribe.api"
"public/redemption.api"
"public/recovery.api"
"public/order.api"
"public/announcement.api"
"public/ticket.api"
"public/payment.api"
"public/document.api"
"public/file.api"
"public/portal.api"
"public/iap.api"
)
+2 -13
View File
@@ -16,13 +16,7 @@ type (
}
FileUploadResponse {
FileId string `json:"file_id"`
FileName string `json:"file_name"`
ObjectKey string `json:"object_key"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
Etag string `json:"etag"`
Status string `json:"status"`
Url string `json:"url"`
}
FileUploadInitRequest {
@@ -47,12 +41,7 @@ type (
}
FileUploadCompleteResponse {
FileId string `json:"file_id"`
ObjectKey string `json:"object_key"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
Etag string `json:"etag"`
Status string `json:"status"`
Url string `json:"url"`
}
)
+13 -13
View File
@@ -201,21 +201,22 @@ type (
GrowthRate string `json:"growth_rate"`
PaidGrowthRate string `json:"paid_growth_rate"`
}
GetInviteSalesRequest {
GetInviteRecordsRequest {
Page int `form:"page"`
Size int `form:"size"`
StartTime int64 `form:"start_time"`
EndTime int64 `form:"end_time"`
}
InvitedUserSale {
Amount float64 `json:"amount"`
UpdatedAt int64 `json:"updated_at"`
UserHash string `json:"user_hash"`
ProductName string `json:"product_name"`
InviteRecord {
Role string `json:"role"`
PeerHash string `json:"peer_hash"`
GiftDays int64 `json:"gift_days"`
OrderNo string `json:"order_no"`
CreatedAt int64 `json:"created_at"`
}
GetInviteSalesResponse {
Total int64 `json:"total"`
List []InvitedUserSale `json:"list"`
GetInviteRecordsResponse {
Total int64 `json:"total"`
List []InviteRecord `json:"list"`
}
GetSubscribeStatusRequest {
Email string `form:"email" json:"email" validate:"omitempty,email"`
@@ -397,9 +398,9 @@ service ppanel {
@handler GetAgentRealtime
get /agent_realtime (GetAgentRealtimeRequest) returns (GetAgentRealtimeResponse)
@doc "Get Invite Sales"
@handler GetInviteSales
get /invite_sales (GetInviteSalesRequest) returns (GetInviteSalesResponse)
@doc "Get Invite Records"
@handler GetInviteRecords
get /invite_records (GetInviteRecordsRequest) returns (GetInviteRecordsResponse)
@doc "Get Subscribe Status"
@handler GetSubscribeStatus
@@ -424,4 +425,3 @@ service ppanel {
@handler DeviceWsConnect
get /device_ws_connect
}
+62 -15
View File
@@ -160,15 +160,17 @@ type (
OnlyRealDevice bool `json:"only_real_device"`
}
RegisterConfig {
StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"`
TrialSubscribe int64 `json:"trial_subscribe"`
TrialTime int64 `json:"trial_time"`
TrialTimeUnit string `json:"trial_time_unit"`
EnableIpRegisterLimit bool `json:"enable_ip_register_limit"`
IpRegisterLimit int64 `json:"ip_register_limit"`
IpRegisterLimitDuration int64 `json:"ip_register_limit_duration"`
DeviceLimit int64 `json:"device_limit"`
StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"`
EnableTrialEmailWhitelist bool `json:"enable_trial_email_whitelist"`
TrialSubscribe int64 `json:"trial_subscribe"`
TrialTime int64 `json:"trial_time"`
TrialTimeUnit string `json:"trial_time_unit"`
TrialEmailDomainWhitelist string `json:"trial_email_domain_whitelist"`
EnableIpRegisterLimit bool `json:"enable_ip_register_limit"`
IpRegisterLimit int64 `json:"ip_register_limit"`
IpRegisterLimitDuration int64 `json:"ip_register_limit_duration"`
DeviceLimit int64 `json:"device_limit"`
}
VerifyConfig {
CaptchaType string `json:"captcha_type"` // local or turnstile
@@ -226,9 +228,46 @@ type (
CurrencySymbol string `json:"currency_symbol"`
}
SubscribeDiscount {
Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"`
MapApple string `json:"map_apple"`
Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"`
NewUserOnly bool `json:"new_user_only"`
MapApple string `json:"map_apple"`
Promo *SubscribePromo `json:"promo"`
}
PromoPrice {
Id int64 `json:"id"`
SubscribeId int64 `json:"subscribe_id"`
PromoRuleId int64 `json:"promo_rule_id"`
Quantity int64 `json:"quantity"`
PromoPrice int64 `json:"promo_price"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
PromoPriceItem {
SubscribeId int64 `json:"subscribe_id" validate:"required,gt=0"`
Quantity int64 `json:"quantity" validate:"required,gt=0,lte=1000"`
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
}
PromoRule {
Id int64 `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Params map[string]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"`
}
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"`
}
SubscribePromo {
RuleName string `json:"rule_name"`
@@ -250,7 +289,6 @@ type (
UnitPrice int64 `json:"unit_price"`
UnitTime string `json:"unit_time"`
Discount []SubscribeDiscount `json:"discount"`
Promo *SubscribePromo `json:"promo"`
NodeCount int64 `json:"node_count"`
Replacement int64 `json:"replacement"`
Inventory int64 `json:"inventory"`
@@ -258,6 +296,7 @@ type (
SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"`
NewUserOnly bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -427,6 +466,8 @@ type (
Amount int64 `json:"amount"`
GiftAmount int64 `json:"gift_amount"`
Discount int64 `json:"discount"`
PromoRuleId int64 `json:"promo_rule_id"`
PromoDiscount int64 `json:"promo_discount"`
Coupon string `json:"coupon"`
CouponDiscount int64 `json:"coupon_discount"`
Commission int64 `json:"commission,omitempty"`
@@ -449,6 +490,8 @@ type (
Amount int64 `json:"amount"`
GiftAmount int64 `json:"gift_amount"`
Discount int64 `json:"discount"`
PromoRuleId int64 `json:"promo_rule_id"`
PromoDiscount int64 `json:"promo_discount"`
Coupon string `json:"coupon"`
CouponDiscount int64 `json:"coupon_discount"`
Commission int64 `json:"commission,omitempty"`
@@ -522,10 +565,13 @@ type (
}
UserSubscribe {
Id int64 `json:"id"`
IdStr string `json:"id_str"`
UserId int64 `json:"user_id"`
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"`
StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"`
FinishedAt int64 `json:"finished_at"`
@@ -871,8 +917,9 @@ type (
Sandbox *bool `json:"sandbox,omitempty"`
}
AttachAppleTransactionResponse {
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
ExistingOrderNo string `json:"existing_order_no,omitempty"`
}
RestoreAppleTransactionsRequest {
Transactions []string `json:"transactions" validate:"required"`
+3
View File
@@ -4316,6 +4316,9 @@
"discount": {
"type": "number",
"format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
}
},
"title": "SubscribeDiscount",
+560
View File
@@ -0,0 +1,560 @@
# 提现 & 文件上传 & 日志上报 — 用户端 API 接口文档
> 基于 ppanel-server 源码整理,所有时间戳均为**秒级 Unix**。
---
## 目录
- [一、提现接口](#一提现接口)
- [1.1 申请提现](#11-申请提现)
- [1.2 取消提现](#12-取消提现)
- [1.3 查询提现记录](#13-查询提现记录)
- [二、枚举值与状态流转](#二枚举值与状态流转)
- [三、文件上传接口](#三文件上传接口)
- [3.1 直传文件(小文件)](#31-直传文件小文件)
- [3.2 初始化上传(大文件 — 预签名)](#32-初始化上传大文件--预签名)
- [3.3 确认上传完成](#33-确认上传完成)
- [四、日志查询接口 (Admin)](#四日志查询接口-admin)
- [4.1 错误日志列表](#41-错误日志列表)
- [4.2 错误日志详情](#42-错误日志详情)
- [4.3 日志消息原始详情](#43-日志消息原始详情)
---
## 一、提现接口
> 认证方式: JWT(用户登录态)
>
> 路由前缀: `/v1/public/user`
### 1.1 申请提现
提交佣金提现申请,创建一条待审核的提现记录。
```
POST /v1/public/user/commission_withdraw
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `amount` | int64 | 是 | — | 提现金额(分) |
| `method` | uint8 | 是 | `oneof=0 1 2 3` | 收款方式(见枚举表) |
| `content` | string | 否 | — | 提现备注 |
| `account` | string | 条件必填 | — | 收款账号 |
| `qr_code_url` | string | 条件必填 | — | 收款码图片 URL |
**各收款方式的必填字段**
| method | 收款方式 | 必填字段 |
|--------|---------|---------|
| `1` 支付宝 | `qr_code_url` | 收款码图片 |
| `2` 微信 | `qr_code_url` | 收款码图片 |
| `3` 银行卡 | `account` | 收款账号 |
| `0` 其他 | `account` 必填 |
**Request 示例**
```json
{
"amount": 5000,
"content": "提现到支付宝",
"method": 1,
"account": "user@example.com",
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png"
}
```
**Response**: [`WithdrawalLog`](#withdrawallog-对象)
---
### 1.2 取消提现
用户取消自己的待审核提现申请,佣金退回账户。
```
POST /v1/public/user/withdrawal_cancel
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `withdrawal_id` | int64 | 是 | `required,gt=0` | 提现记录 ID |
**Request 示例**
```json
{
"withdrawal_id": 123
}
```
**Response**: [`WithdrawalLog`](#withdrawallog-对象)(状态已变为 `3=已取消`
---
### 1.3 查询提现记录
分页查询当前用户的提现记录(自动按 JWT 中的 userId 过滤)。
```
GET /v1/public/user/withdrawal_log
```
**Query 参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `page` | int | 否 | 页码,默认 1 |
| `size` | int | 否 | 每页条数,默认 10 |
**Request 示例**
```
GET /v1/public/user/withdrawal_log?page=1&size=10
```
**Response**
```json
{
"list": [WithdrawalLog, ...],
"total": 25
}
```
---
## 二、枚举值与状态流转
### 提现状态 (`status`)
| 值 | 说明 |
|----|------|
| 0 | 待审核 |
| 1 | 已通过 |
| 2 | 已拒绝 |
| 3 | 已取消 |
### 收款方式 (`method`)
| 值 | 说明 |
|----|------|
| 0 | 其他 |
| 1 | 支付宝 |
| 2 | 微信 |
| 3 | 银行卡 |
### 状态流转
```
┌── 管理员通过 ──▶ 已通过 (1)
待审核 (0) ──────┼── 管理员拒绝 ──▶ 已拒绝 (2)
└── 用户取消 ───▶ 已取消 (3)
```
### WithdrawalLog 对象
所有提现接口共用的响应结构:
```json
{
"id": 1,
"user_id": 100,
"amount": 5000,
"content": "提现备注",
"status": 0,
"reason": "",
"method": 1,
"account": "user@example.com",
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png",
"created_at": 1716700000,
"updated_at": 1716700000
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | int64 | 提现记录 ID |
| `user_id` | int64 | 用户 ID |
| `amount` | int64 | 提现金额(分) |
| `content` | string | 提现备注 |
| `status` | uint8 | 状态(见枚举表) |
| `reason` | string | 拒绝原因(仅 status=2 时有值,其余 omitempty |
| `method` | uint8 | 收款方式(见枚举表) |
| `account` | string | 收款账号 |
| `qr_code_url` | string | 收款码图片 URL |
| `created_at` | int64 | 创建时间(秒级 Unix |
| `updated_at` | int64 | 更新时间(秒级 Unix |
---
## 三、文件上传接口
> 认证方式: JWT + DeviceMiddleware(用户登录态 + 设备认证)
>
> 路由前缀: `/v1/public/file`
>
> 存储后端: S3 兼容(RustFS
提供两种上传方式:
| 方式 | 适用场景 | 流程 |
|------|---------|------|
| **直传** | 小文件(收款码等) | 1 次请求,`multipart/form-data` 直接上传 |
| **预签名** | 大文件 / 客户端直传 S3 | init → 客户端 PUT 到预签名 URL → complete 确认 |
---
### 3.1 直传文件(小文件)
通过 `multipart/form-data` 直接上传文件到服务端,服务端转存至 S3。
```
POST /v1/public/file/upload
Content-Type: multipart/form-data
```
**Form 参数**
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `biz_type` | string | 是 | 业务类型(如 `withdrawal_qrcode``avatar` 等) |
| `file` | file | 是 | 上传的文件(multipart |
**cURL 示例**
```bash
curl -X POST /v1/public/file/upload \
-H "Authorization: Bearer <token>" \
-F "biz_type=withdrawal_qrcode" \
-F "file=@/path/to/alipay_qr.png"
```
**Response**
```json
{
"file_id": "a1b2c3d4e5f678901234",
"file_name": "alipay_qr.png",
"object_key": "app-upload/2026/05/27/100/alipay_qr.png__a1b2c3d4e5f678901234",
"size": 52480,
"content_type": "image/png",
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
"status": "completed"
}
```
**FileUploadResponse 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `file_id` | string | 文件唯一 ID24 字符 hex |
| `file_name` | string | 原始文件名 |
| `object_key` | string | S3 对象路径 |
| `size` | int64 | 文件大小(字节) |
| `content_type` | string | MIME 类型 |
| `etag` | string | S3 ETag |
| `status` | string | 状态,直传成功即 `completed` |
---
### 3.2 初始化上传(大文件 — 预签名)
获取 S3 预签名 URL,客户端直接 PUT 到 S3,避免文件经过服务端。
```
POST /v1/public/file/upload/init
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `biz_type` | string | 是 | `required` | 业务类型 |
| `file_name` | string | 是 | `required` | 文件名 |
| `content_type` | string | 是 | `required` | MIME 类型(如 `image/png` |
| `size` | int64 | 是 | `required` | 文件大小(字节) |
| `sha256` | string | 否 | — | 文件 SHA256(可选校验) |
**Request 示例**
```json
{
"biz_type": "withdrawal_qrcode",
"file_name": "wechat_qr.png",
"content_type": "image/png",
"size": 102400,
"sha256": "e3b0c44298fc1c149afbf4c8996fb924..."
}
```
**Response**
```json
{
"file_id": "b2c3d4e5f6789012345a",
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
"upload_url": "https://s3.example.com/bucket/app-upload/...?X-Amz-Signature=...",
"method": "PUT",
"headers": {
"Content-Type": "image/png"
},
"expired_at": 1716700300
}
```
**FileUploadInitResponse 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `file_id` | string | 文件唯一 ID |
| `object_key` | string | S3 对象路径 |
| `upload_url` | string | 预签名上传 URL |
| `method` | string | HTTP 方法(`PUT` |
| `headers` | map | 上传时需携带的请求头 |
| `expired_at` | int64 | 预签名过期时间(秒级 Unix,默认 300 秒) |
**客户端上传流程**
```
1. 调用 /upload/init 获取 upload_url
2. 用返回的 method + headers 直接上传文件到 upload_url
3. 上传成功后调用 /upload/complete 确认
```
---
### 3.3 确认上传完成
客户端通过预签名 URL 上传完成后,调用此接口确认文件状态。
```
POST /v1/public/file/upload/complete
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `file_id` | string | 是 | `required` | init 返回的 file_id |
**Request 示例**
```json
{
"file_id": "b2c3d4e5f6789012345a"
}
```
**Response**
```json
{
"file_id": "b2c3d4e5f6789012345a",
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
"size": 102400,
"content_type": "image/png",
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
"status": "completed"
}
```
**FileUploadCompleteResponse 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `file_id` | string | 文件唯一 ID |
| `object_key` | string | S3 对象路径 |
| `size` | int64 | 实际文件大小(S3 HeadObject 获取) |
| `content_type` | string | MIME 类型 |
| `etag` | string | S3 ETag |
| `status` | string | `completed` |
**校验规则**
- 文件大小不能超过配置的 `S3.MaxUploadSize`
- Content-Type 必须在配置的 `S3.AllowedContentTypes` 白名单内(若配置了)
- complete 时会校验 S3 上的实际文件大小是否与 init 声明的一致
- 只能确认自己发起的上传(userId 校验)
---
## 四、日志查询接口 (Admin)
> 认证方式: AuthMiddleware(管理员权限)
>
> 路由前缀: `/v1/admin/log`
>
> 数据来源: `log_message` 表(客户端上报的错误/崩溃日志)
---
### 4.1 错误日志列表
分页查询客户端上报的错误日志,支持多维度筛选。
```
GET /v1/admin/log/error_message/list
```
**Query 参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `page` | int | 是 | 页码 |
| `size` | int | 是 | 每页条数 |
| `platform` | string | 否 | 平台筛选(ios / android / windows / mac / harmony |
| `level` | uint8 | 否 | 日志级别 |
| `user_id` | int64 | 否 | 用户 ID |
| `device_id` | string | 否 | 设备 ID |
| `error_code` | string | 否 | 错误码 |
| `keyword` | string | 否 | 关键字搜索(匹配 message) |
| `start` | int64 | 否 | 开始时间(秒级 Unix) |
| `end` | int64 | 否 | 结束时间(秒级 Unix) |
**Request 示例**
```
GET /v1/admin/log/error_message/list?page=1&size=20&platform=ios&start=1716600000&end=1716700000
```
**Response**
```json
{
"total": 50,
"list": [
{
"id": 1,
"platform": "ios",
"app_version": "2.1.0",
"os_name": "iOS",
"os_version": "17.5",
"device_id": "A1B2C3D4",
"user_id": 100,
"session_id": "sess_xxx",
"level": 3,
"error_code": "VPN_CONNECT_FAIL",
"message": "Failed to establish VPN tunnel",
"created_at": 1716700000
}
]
}
```
**ErrorLogMessage 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | int64 | 日志 ID |
| `platform` | string | 平台 |
| `app_version` | string | 客户端版本 |
| `os_name` | string | 操作系统名称 |
| `os_version` | string | 操作系统版本 |
| `device_id` | string | 设备 ID |
| `user_id` | int64 | 用户 ID |
| `session_id` | string | 会话 ID |
| `level` | uint8 | 日志级别 |
| `error_code` | string | 错误码 |
| `message` | string | 错误消息 |
| `created_at` | int64 | 创建时间(秒级 Unix |
---
### 4.2 错误日志详情
获取单条错误日志的完整详情(列表字段 + 堆栈/IP/UA 等扩展信息)。
```
GET /v1/admin/log/error_message/detail
```
**Response**
```json
{
"id": 1,
"platform": "ios",
"app_version": "2.1.0",
"os_name": "iOS",
"os_version": "17.5",
"device_id": "A1B2C3D4",
"user_id": 100,
"session_id": "sess_xxx",
"level": 3,
"error_code": "VPN_CONNECT_FAIL",
"message": "Failed to establish VPN tunnel",
"stack": "at VPNManager.connect() line 42\nat ...",
"client_ip": "1.2.3.4",
"user_agent": "PPanel/2.1.0 iOS/17.5",
"locale": "zh-CN",
"occurred_at": 1716700000,
"created_at": 1716700000
}
```
**相比列表额外返回的字段**
| 字段 | 类型 | 说明 |
|------|------|------|
| `stack` | string | 堆栈信息 |
| `client_ip` | string | 客户端 IP |
| `user_agent` | string | User-Agent |
| `locale` | string | 客户端语言/地区 |
| `occurred_at` | int64 | 错误发生时间(秒级 Unix) |
---
### 4.3 日志消息原始详情
获取单条 `log_message` 的完整原始数据(含 context、digest 等全量字段)。
```
GET /v1/admin/log/message/detail
```
**Query 参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `id` | int64 | 是 | 日志消息 ID |
**Response**
```json
{
"id": 1,
"platform": "ios",
"app_version": "2.1.0",
"os_name": "iOS",
"os_version": "17.5",
"device_id": "A1B2C3D4",
"user_id": 100,
"session_id": "sess_xxx",
"level": 3,
"error_code": "VPN_CONNECT_FAIL",
"message": "Failed to establish VPN tunnel",
"stack": "at VPNManager.connect() line 42\nat ...",
"context": { "server_id": 5, "protocol": "vmess" },
"client_ip": "1.2.3.4",
"user_agent": "PPanel/2.1.0 iOS/17.5",
"locale": "zh-CN",
"digest": "sha256_abc123...",
"occurred_at": 1716700000,
"created_at": 1716700000
}
```
**相比详情额外返回的字段**
| 字段 | 类型 | 说明 |
|------|------|------|
| `context` | any | 附加上下文(原始 JSON |
| `digest` | string | 内容摘要(用于去重) |
+6
View File
@@ -128,6 +128,10 @@ curl -X PUT 'https://bucket.s3.ap-east-1.amazonaws.com/...' \
说明:
- `Content-Type` 需和 `init` 返回的 `headers.Content-Type` 一致
- 允许的 `Content-Type` 由服务端 `S3.AllowedContentTypes` 配置控制,默认包含:
- 压缩包:`application/zip``application/x-zip-compressed``application/gzip``application/x-gzip`
- 通用文件:`application/octet-stream``text/plain``application/json`
- 图片:`image/jpeg``image/jpg``image/png``image/webp``image/gif``image/heic``image/heif``image/bmp`
- `upload_url` 有过期时间,通常 300 秒
- 成功时 S3 常见返回 `200``204`
@@ -164,11 +168,13 @@ curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/complete' \
- 如果请求带了 `X-App-Id`,就按现有逻辑验签
- 如果没有 `X-App-Id`,仍按旧逻辑放行
- 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256`
- 允许的 `Content-Type` 与预签名三段式一致;multipart 文件字段未显式携带 `Content-Type` 时,服务端会基于文件内容嗅探常见类型。
## 常见错误码
- `200`: 成功
- `400`: 参数错误
- `400 content_type is not allowed`: 文件 `Content-Type` 不在 `S3.AllowedContentTypes` 白名单内
- `40008`: 缺少签名头
- `40009`: 签名已过期
- `40010`: 签名无效
+1 -1
View File
@@ -74,7 +74,7 @@ S3:
UsePathStyle: false
PresignExpireSeconds: 300
MaxUploadSize: 104857600
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"
device:
enable: true # 开启设备加密通信
+4
View File
@@ -2,6 +2,8 @@ module github.com/perfect-panel/server
go 1.24
replace github.com/zeromicro/go-zero => ./internal/gozero
require (
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f
github.com/alibabacloud-go/darabonba-openapi v0.1.18
@@ -33,6 +35,7 @@ require (
github.com/spf13/cobra v1.8.1
github.com/stripe/stripe-go/v81 v81.1.0
github.com/twilio/twilio-go v1.23.11
github.com/zeromicro/go-zero v0.0.0
go.opentelemetry.io/otel v1.29.0
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.24.0
@@ -53,6 +56,7 @@ require (
)
require (
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Masterminds/sprig/v3 v3.3.0
github.com/aws/aws-sdk-go-v2 v1.41.7
github.com/aws/aws-sdk-go-v2/config v1.32.17
+3
View File
@@ -8,6 +8,8 @@ filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f h1:RDkg3pyE1qGbBpRWmvSN9RNZC5nUrOaEPiEpEb8y2f0=
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f/go.mod h1:zA7AF9RTfpluCfz0omI4t5KCMaWHUMicsZoMccnaT44=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
@@ -264,6 +266,7 @@ github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@@ -1,4 +1,10 @@
ALTER TABLE `withdrawals`
ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '收款方式 0:其他 1:支付宝 2:微信 3:银行卡' AFTER `content`,
ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '收款账号' AFTER `method`,
ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '收款码图片URL' AFTER `account`;
SELECT COUNT(*) INTO @col_exists FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'withdrawals' AND COLUMN_NAME = 'method';
SET @ddl = IF(@col_exists = 0,
'ALTER TABLE `withdrawals` ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 AFTER `content`, ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '''' AFTER `method`, ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '''' AFTER `account`',
'SELECT 1');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -1,5 +1,35 @@
-- Purpose: Rollback user-level speed limit overrides from user_subscribe
SET @traffic_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'traffic_limit'
);
ALTER TABLE `user_subscribe`
DROP COLUMN IF EXISTS `traffic_limit`,
DROP COLUMN IF EXISTS `speed_limit`;
SET @traffic_limit_sql = IF(
@traffic_limit_exists = 1,
'ALTER TABLE `user_subscribe` DROP COLUMN `traffic_limit`',
'SELECT 1'
);
PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
EXECUTE traffic_limit_stmt;
DEALLOCATE PREPARE traffic_limit_stmt;
SET @speed_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'speed_limit'
);
SET @speed_limit_sql = IF(
@speed_limit_exists = 1,
'ALTER TABLE `user_subscribe` DROP COLUMN `speed_limit`',
'SELECT 1'
);
PREPARE speed_limit_stmt FROM @speed_limit_sql;
EXECUTE speed_limit_stmt;
DEALLOCATE PREPARE speed_limit_stmt;
@@ -1,6 +1,4 @@
-- Purpose: Add user-level speed limit overrides to user_subscribe
SET @column_exists = (
SET @speed_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
@@ -8,17 +6,17 @@ SET @column_exists = (
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'''
SET @speed_limit_sql = IF(
@speed_limit_exists = 0,
'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` BIGINT NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps), 0 uses plan-level'' AFTER `upload`',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
PREPARE speed_limit_stmt FROM @speed_limit_sql;
EXECUTE speed_limit_stmt;
DEALLOCATE PREPARE speed_limit_stmt;
SET @column_exists = (
SET @traffic_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
@@ -26,12 +24,12 @@ SET @column_exists = (
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'''
SET @traffic_limit_sql = IF(
@traffic_limit_exists = 0,
'ALTER TABLE `user_subscribe` ADD COLUMN `traffic_limit` TEXT DEFAULT NULL COMMENT ''User-level traffic limit override (JSON), NULL uses plan-level'' AFTER `speed_limit`',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
EXECUTE traffic_limit_stmt;
DEALLOCATE PREPARE traffic_limit_stmt;
@@ -11,22 +11,158 @@ CREATE TABLE IF NOT EXISTS `promo_rule` (
`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`)
KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_enabled_priority'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `promo_rule` DROP INDEX `idx_enabled_priority`',
'SELECT ''Index idx_enabled_priority does not exist on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_deleted_at'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `promo_rule` DROP INDEX `idx_deleted_at`',
'SELECT ''Index idx_deleted_at does not exist on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_enabled_priority_deleted'
);
SET @sql = IF(
@index_exists = 0,
'ALTER TABLE `promo_rule` ADD KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)',
'SELECT ''Index idx_enabled_priority_deleted already exists on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
`quantity` BIGINT NOT NULL DEFAULT 1 COMMENT '购买数量',
`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`),
UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
KEY `idx_promo_rule_id` (`promo_rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND COLUMN_NAME = 'quantity'
);
SET @sql = IF(
@column_exists = 0,
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
'SELECT ''Column quantity already exists in subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
'SELECT ''Column quantity does not exist in subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_rule'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
'SELECT ''Index uk_subscribe_rule does not exist on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_qty_rule'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
'SELECT ''Index uk_subscribe_qty_rule does not exist on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_quantity_rule'
);
SET @sql = IF(
@index_exists = 0,
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
'SELECT ''Index uk_subscribe_quantity_rule already exists on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE TABLE IF NOT EXISTS `promo_usage` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
+1 -1
View File
@@ -58,7 +58,7 @@ type S3Config struct {
UsePathStyle bool `yaml:"UsePathStyle" default:"false"`
PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"`
MaxUploadSize int64 `yaml:"MaxUploadSize" default:"104857600"`
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"`
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"`
}
type RedisConfig struct {
+35
View File
@@ -0,0 +1,35 @@
package logx
import (
"context"
"log"
)
type Logger interface {
Error(...any)
Errorf(string, ...any)
Info(...any)
Infof(string, ...any)
}
type logger struct{}
func WithContext(context.Context) Logger {
return logger{}
}
func (logger) Error(v ...any) {
log.Print(v...)
}
func (logger) Errorf(format string, v ...any) {
log.Printf(format, v...)
}
func (logger) Info(v ...any) {
log.Print(v...)
}
func (logger) Infof(format string, v ...any) {
log.Printf(format, v...)
}
+5
View File
@@ -0,0 +1,5 @@
module github.com/zeromicro/go-zero
go 1.24
require github.com/gin-gonic/gin v1.10.0
+27
View File
@@ -0,0 +1,27 @@
package httpx
import (
"context"
"encoding/json"
"net/http"
)
func Parse(r *http.Request, v any) error {
if r.Body == nil {
return nil
}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(v); err != nil {
return err
}
return nil
}
func ErrorCtx(_ context.Context, w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
func OkJsonCtx(_ context.Context, w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(v)
}
+72
View File
@@ -0,0 +1,72 @@
package rest
import "github.com/gin-gonic/gin"
type Middleware = gin.HandlerFunc
type Route struct {
Method string
Path string
Handler gin.HandlerFunc
Middlewares []Middleware
}
type RouteOption func(*routeOptions)
type routeOptions struct {
prefix string
}
type Server struct {
router *gin.Engine
optionalAuth Middleware
}
type ServerOption func(*Server)
func NewServer(router *gin.Engine, opts ...ServerOption) *Server {
server := &Server{router: router}
for _, opt := range opts {
opt(server)
}
return server
}
func WithOptionalAuth(middleware Middleware) ServerOption {
return func(server *Server) {
server.optionalAuth = middleware
}
}
func WithMiddlewares(middlewares []Middleware, routes ...Route) []Route {
for i := range routes {
routes[i].Middlewares = append(routes[i].Middlewares, middlewares...)
}
return routes
}
func WithPrefix(prefix string) RouteOption {
return func(opts *routeOptions) {
opts.prefix = prefix
}
}
func WithJwt(_ string) RouteOption {
return func(_ *routeOptions) {}
}
func (server *Server) AddRoutes(routes []Route, opts ...RouteOption) {
options := routeOptions{}
for _, opt := range opts {
opt(&options)
}
for _, route := range routes {
handlers := append([]gin.HandlerFunc{}, route.Middlewares...)
if server.optionalAuth != nil && options.prefix == "/v1/public/subscribe" && route.Path == "/list" && len(handlers) > 0 {
handlers[0] = server.optionalAuth
}
handlers = append(handlers, route.Handler)
server.router.Handle(route.Method, options.prefix+route.Path, handlers...)
}
}
@@ -0,0 +1,25 @@
package invite
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/invite"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Get invite manage list
func GetInviteManageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetInviteManageListRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := invite.NewGetInviteManageListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetInviteManageList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
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"
)
func CreateRuleHandler(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.NewCreateRuleLogic(c.Request.Context(), svcCtx)
resp, err := l.CreateRule(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
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"
)
func DeletePriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.DeletePromoPriceRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewDeletePriceLogic(c.Request.Context(), svcCtx)
err := l.DeletePrice(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,26 @@
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"
)
func DeleteRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.DeletePromoRuleRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewDeleteRuleLogic(c.Request.Context(), svcCtx)
err := l.DeleteRule(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,23 @@
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"
)
func GetPriceListHandler(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.NewGetPriceListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetPriceList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
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"
)
func GetRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetPromoRuleDetailRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewGetRuleDetailLogic(c.Request.Context(), svcCtx)
resp, err := l.GetRuleDetail(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
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"
)
func GetRuleListHandler(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.NewGetRuleListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetRuleList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
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"
)
func GetUsageListHandler(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.NewGetUsageListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetUsageList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
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"
)
func SetPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.SetPromoPriceRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewSetPriceLogic(c.Request.Context(), svcCtx)
err := l.SetPrice(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,27 @@
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"
)
func UpdateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.UpdatePromoRuleRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewUpdateRuleLogic(c.Request.Context(), svcCtx)
resp, err := l.UpdateRule(&req)
result.HttpResult(c, resp, err)
}
}
@@ -1,6 +1,9 @@
package user
import (
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/user"
"github.com/perfect-panel/server/internal/svc"
@@ -18,9 +21,25 @@ func UpdateUserSubscribeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context)
result.ParamErrorResult(c, validateErr)
return
}
if err := validateUpdateUserSubscribeTrafficLimit(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := user.NewUpdateUserSubscribeLogic(c.Request.Context(), svcCtx)
err := l.UpdateUserSubscribe(&req)
result.HttpResult(c, nil, err)
}
}
func validateUpdateUserSubscribeTrafficLimit(req *types.UpdateUserSubscribeRequest) error {
if req.TrafficLimit == nil || *req.TrafficLimit == "" {
return nil
}
var rules []types.TrafficLimit
if err := json.Unmarshal([]byte(*req.TrafficLimit), &rules); err != nil {
return errors.New("traffic_limit must be a valid JSON array")
}
return nil
}
@@ -0,0 +1,59 @@
package user
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/xerr"
)
func TestUpdateUserSubscribeHandlerRejectsInvalidLimits(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
body string
}{
{
name: "negative speed limit",
body: `{"user_subscribe_id":1,"subscribe_id":1,"traffic":0,"expired_at":4102444800000,"upload":0,"download":0,"speed_limit":-1}`,
},
{
name: "invalid traffic limit json",
body: `{"user_subscribe_id":1,"subscribe_id":1,"traffic":0,"expired_at":4102444800000,"upload":0,"download":0,"traffic_limit":"not-json"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router := gin.New()
router.PUT("/v1/admin/user/subscribe", UpdateUserSubscribeHandler(&svc.ServiceContext{}))
req := httptest.NewRequest(http.MethodPut, "/v1/admin/user/subscribe", bytes.NewBufferString(tt.body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected HTTP 200, got %d", rec.Code)
}
var resp struct {
Code uint32 `json:"code"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if resp.Code != xerr.InvalidParams {
t.Fatalf("expected code %d, got %d (%s)", xerr.InvalidParams, resp.Code, resp.Msg)
}
})
}
}
@@ -0,0 +1,11 @@
package common
import (
"github.com/gin-gonic/gin"
authHandler "github.com/perfect-panel/server/internal/handler/auth"
"github.com/perfect-panel/server/internal/svc"
)
func CheckCodeLegacyHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return authHandler.CheckCodeLegacyV1Handler(svcCtx)
}
@@ -0,0 +1,11 @@
package common
import (
"github.com/gin-gonic/gin"
authHandler "github.com/perfect-panel/server/internal/handler/auth"
"github.com/perfect-panel/server/internal/svc"
)
func CheckCodeLegacyV2Handler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return authHandler.CheckCodeLegacyV2Handler(svcCtx)
}
@@ -0,0 +1 @@
package common
@@ -0,0 +1 @@
package common
@@ -0,0 +1,11 @@
package server
import (
"github.com/gin-gonic/gin"
serverhandler "github.com/perfect-panel/server/internal/handler/server"
"github.com/perfect-panel/server/internal/svc"
)
func GetServerConfigHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return serverhandler.GetServerConfigHandler(svcCtx)
}
@@ -0,0 +1,11 @@
package server
import (
"github.com/gin-gonic/gin"
serverhandler "github.com/perfect-panel/server/internal/handler/server"
"github.com/perfect-panel/server/internal/svc"
)
func GetServerUserListHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return serverhandler.GetServerUserListHandler(svcCtx)
}
@@ -0,0 +1,11 @@
package server
import (
"github.com/gin-gonic/gin"
serverhandler "github.com/perfect-panel/server/internal/handler/server"
"github.com/perfect-panel/server/internal/svc"
)
func PushOnlineUsersHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return serverhandler.PushOnlineUsersHandler(svcCtx)
}
@@ -0,0 +1,11 @@
package server
import (
"github.com/gin-gonic/gin"
serverhandler "github.com/perfect-panel/server/internal/handler/server"
"github.com/perfect-panel/server/internal/svc"
)
func QueryServerProtocolConfigHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return serverhandler.QueryServerProtocolConfigHandler(svcCtx)
}
@@ -0,0 +1,11 @@
package server
import (
"github.com/gin-gonic/gin"
serverhandler "github.com/perfect-panel/server/internal/handler/server"
"github.com/perfect-panel/server/internal/svc"
)
func ServerPushStatusHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return serverhandler.ServerPushStatusHandler(svcCtx)
}
@@ -0,0 +1,11 @@
package server
import (
"github.com/gin-gonic/gin"
serverhandler "github.com/perfect-panel/server/internal/handler/server"
"github.com/perfect-panel/server/internal/svc"
)
func ServerPushUserTrafficHandler(svcCtx *svc.ServiceContext) gin.HandlerFunc {
return serverhandler.ServerPushUserTrafficHandler(svcCtx)
}
@@ -0,0 +1 @@
package apple
@@ -0,0 +1 @@
package apple
@@ -0,0 +1 @@
package apple
@@ -0,0 +1 @@
package apple
@@ -8,10 +8,10 @@ import (
"github.com/perfect-panel/server/pkg/result"
)
// Get invite sales data
func GetInviteSalesHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
// Get invite gift records
func GetInviteRecordsHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetInviteSalesRequest
var req types.GetInviteRecordsRequest
if err := c.ShouldBind(&req); err != nil {
result.ParamErrorResult(c, err)
return
@@ -23,8 +23,8 @@ func GetInviteSalesHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return
}
l := user.NewGetInviteSalesLogic(c.Request.Context(), svcCtx)
resp, err := l.GetInviteSales(&req)
l := user.NewGetInviteRecordsLogic(c.Request.Context(), svcCtx)
resp, err := l.GetInviteRecords(&req)
result.HttpResult(c, resp, err)
}
}
+2331 -1165
View File
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
package invite
import (
"context"
modellog "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type Benefits struct {
OrderCount int64
HasPurchased bool
InviterCommission int64
InviterGiftDays int64
InviteeGiftDays int64
}
type InviteRelation struct {
InviteeId int64
InviterId int64
}
type paidOrderRow struct {
UserId int64 `gorm:"column:user_id"`
OrderNo string `gorm:"column:order_no"`
}
type systemLogRow struct {
ObjectID int64 `gorm:"column:object_id"`
Content string `gorm:"column:content"`
}
func NormalizePage(page, size int) (int, int) {
if page < 1 {
page = 1
}
if size < 1 {
size = 10
}
if size > 100 {
size = 100
}
return page, size
}
func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation) (map[int64]Benefits, error) {
result := make(map[int64]Benefits, len(relations))
if len(relations) == 0 {
return result, nil
}
inviteeIds := make([]int64, 0, len(relations))
inviteeToInviter := make(map[int64]int64, len(relations))
for _, relation := range relations {
inviteeIds = append(inviteeIds, relation.InviteeId)
inviteeToInviter[relation.InviteeId] = relation.InviterId
result[relation.InviteeId] = Benefits{}
}
var orderCounts []struct {
UserId int64 `gorm:"column:user_id"`
Cnt int64 `gorm:"column:cnt"`
}
if err := db.WithContext(ctx).
Table("`order`").
Select("user_id, COUNT(*) as cnt").
Where("user_id IN ? AND status IN ?", inviteeIds, []int{2, 5}).
Group("user_id").
Scan(&orderCounts).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invitee paid orders failed: %v", err)
}
for _, row := range orderCounts {
benefit := result[row.UserId]
benefit.OrderCount = row.Cnt
benefit.HasPurchased = row.Cnt > 0
result[row.UserId] = benefit
}
var paidOrders []paidOrderRow
if err := db.WithContext(ctx).
Table("`order`").
Select("user_id, order_no").
Where("user_id IN ? AND status IN ?", inviteeIds, []int{2, 5}).
Scan(&paidOrders).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invitee paid orders failed: %v", err)
}
if len(paidOrders) == 0 {
return result, nil
}
orderNos := make([]string, 0, len(paidOrders))
orderToInvitee := make(map[string]int64, len(paidOrders))
inviterIds := make([]int64, 0, len(relations))
inviteeAndInviterSet := make(map[int64]struct{}, len(relations)*2)
for _, order := range paidOrders {
orderNos = append(orderNos, order.OrderNo)
orderToInvitee[order.OrderNo] = order.UserId
}
for _, relation := range relations {
inviterIds = append(inviterIds, relation.InviterId)
inviteeAndInviterSet[relation.InviteeId] = struct{}{}
inviteeAndInviterSet[relation.InviterId] = struct{}{}
}
inviteeAndInviterIds := make([]int64, 0, len(inviteeAndInviterSet))
for userId := range inviteeAndInviterSet {
inviteeAndInviterIds = append(inviteeAndInviterIds, userId)
}
if err := fillCommissionBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderNos, inviterIds); err != nil {
return nil, err
}
if err := fillGiftBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderNos, inviteeAndInviterIds); err != nil {
return nil, err
}
return result, nil
}
func fillCommissionBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderNos []string, inviterIds []int64) error {
var rows []systemLogRow
if err := db.WithContext(ctx).
Table("system_logs").
Select("object_id, content").
Where("type = ? AND object_id IN ? AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.order_no')) IN ? AND JSON_EXTRACT(content, '$.type') IN ?", modellog.TypeCommission.Uint8(), inviterIds, orderNos, []int{int(modellog.CommissionTypePurchase), int(modellog.CommissionTypeRenewal)}).
Scan(&rows).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite commission logs failed: %v", err)
}
for _, row := range rows {
content := modellog.Commission{}
if err := content.Unmarshal([]byte(row.Content)); err != nil {
continue
}
inviteeId, ok := orderToInvitee[content.OrderNo]
if !ok || inviteeToInviter[inviteeId] != row.ObjectID {
continue
}
benefit := benefits[inviteeId]
benefit.InviterCommission += content.Amount
benefits[inviteeId] = benefit
}
return nil
}
func fillGiftBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderNos []string, userIds []int64) error {
var rows []systemLogRow
if err := db.WithContext(ctx).
Table("system_logs").
Select("object_id, content").
Where("type = ? AND object_id IN ? AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.order_no')) IN ?", modellog.TypeGift.Uint8(), userIds, orderNos).
Scan(&rows).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite gift logs failed: %v", err)
}
for _, row := range rows {
content := modellog.Gift{}
if err := content.Unmarshal([]byte(row.Content)); err != nil {
continue
}
if content.Type != modellog.GiftTypeIncrease {
continue
}
inviteeId, ok := orderToInvitee[content.OrderNo]
if !ok {
continue
}
benefit := benefits[inviteeId]
switch row.ObjectID {
case inviteeToInviter[inviteeId]:
benefit.InviterGiftDays += content.Amount
case inviteeId:
benefit.InviteeGiftDays += content.Amount
default:
continue
}
benefits[inviteeId] = benefit
}
return nil
}
func QueryIdentifiers(ctx context.Context, db *gorm.DB, userIds []int64) (map[int64]string, error) {
identifiers := make(map[int64]string, len(userIds))
if len(userIds) == 0 {
return identifiers, nil
}
type identifierRow struct {
UserId int64 `gorm:"column:user_id"`
Identifier string `gorm:"column:identifier"`
}
var rows []identifierRow
if err := db.WithContext(ctx).
Table("user_auth_methods uam").
Select("uam.user_id, uam.auth_identifier as identifier").
Joins("JOIN (SELECT user_id, MIN(id) AS id FROM user_auth_methods WHERE user_id IN ? GROUP BY user_id) first_uam ON first_uam.id = uam.id", userIds).
Scan(&rows).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user identifiers failed: %v", err)
}
for _, row := range rows {
identifiers[row.UserId] = row.Identifier
}
return identifiers, nil
}
@@ -0,0 +1,117 @@
package invite
import (
"context"
"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"
"gorm.io/gorm"
)
type GetInviteManageListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetInviteManageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetInviteManageListLogic {
return &GetInviteManageListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetInviteManageListLogic) GetInviteManageList(req *types.GetInviteManageListRequest) (resp *types.GetInviteManageListResponse, err error) {
req.Page, req.Size = NormalizePage(req.Page, req.Size)
type inviteRow struct {
InviteeId int64 `gorm:"column:invitee_id"`
InviteeAvatar string `gorm:"column:invitee_avatar"`
InviteeEnable bool `gorm:"column:invitee_enable"`
InvitedAt int64 `gorm:"column:invited_at"`
InviterId int64 `gorm:"column:inviter_id"`
}
baseQuery := applyInviteManageFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user invitee").
Where("invitee.referer_id > 0 AND invitee.deleted_at IS NULL"), req)
var total int64
if err = baseQuery.Count(&total).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invite manage records failed: %v", err)
}
var rows []inviteRow
if err = applyInviteManageFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user invitee").
Select("invitee.id as invitee_id, invitee.avatar as invitee_avatar, invitee.enable as invitee_enable, UNIX_TIMESTAMP(invitee.created_at) as invited_at, invitee.referer_id as inviter_id").
Where("invitee.referer_id > 0 AND invitee.deleted_at IS NULL"), req).
Order("invitee.created_at DESC").
Limit(req.Size).
Offset((req.Page - 1) * req.Size).
Scan(&rows).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite manage records failed: %v", err)
}
relations := make([]InviteRelation, 0, len(rows))
userIds := make([]int64, 0, len(rows)*2)
for _, row := range rows {
relations = append(relations, InviteRelation{InviteeId: row.InviteeId, InviterId: row.InviterId})
userIds = append(userIds, row.InviteeId, row.InviterId)
}
benefits, err := QueryBenefits(l.ctx, l.svcCtx.DB, relations)
if err != nil {
return nil, err
}
identifiers, err := QueryIdentifiers(l.ctx, l.svcCtx.DB, userIds)
if err != nil {
return nil, err
}
list := make([]types.InviteManageRecord, 0, len(rows))
for _, row := range rows {
benefit := benefits[row.InviteeId]
list = append(list, types.InviteManageRecord{
InviterId: row.InviterId,
InviterIdentifier: identifiers[row.InviterId],
InviteeId: row.InviteeId,
InviteeIdentifier: identifiers[row.InviteeId],
InviteeAvatar: row.InviteeAvatar,
InviteeEnable: row.InviteeEnable,
InvitedAt: row.InvitedAt,
OrderCount: benefit.OrderCount,
HasPurchased: benefit.HasPurchased,
InviterCommission: benefit.InviterCommission,
InviterGiftDays: benefit.InviterGiftDays,
InviteeGiftDays: benefit.InviteeGiftDays,
})
}
return &types.GetInviteManageListResponse{
Total: total,
List: list,
}, nil
}
func applyInviteManageFilters(db *gorm.DB, req *types.GetInviteManageListRequest) *gorm.DB {
if req.InviterId > 0 {
db = db.Where("invitee.referer_id = ?", req.InviterId)
}
if req.InviteeId > 0 {
db = db.Where("invitee.id = ?", req.InviteeId)
}
if req.Search != "" {
search := "%" + req.Search + "%"
db = db.Where(
"(EXISTS (SELECT 1 FROM user_auth_methods inviter_auth WHERE inviter_auth.user_id = invitee.referer_id AND inviter_auth.auth_identifier LIKE ?) OR EXISTS (SELECT 1 FROM user_auth_methods invitee_auth WHERE invitee_auth.user_id = invitee.id AND invitee_auth.auth_identifier LIKE ?))",
search,
search,
)
}
return db
}
@@ -0,0 +1,58 @@
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 CreateRuleLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRuleLogic {
return &CreateRuleLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CreateRuleLogic) CreateRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
return nil, err
}
params, err := paramsToString(req.Params)
if err != nil {
return nil, err
}
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
rule := &promomodel.Rule{
Name: req.Name,
Type: req.Type,
Params: params,
Priority: req.Priority,
Enabled: enabled,
StartTime: unixPtrToTimePtr(req.StartTime),
EndTime: unixPtrToTimePtr(req.EndTime),
}
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, rule); err != nil {
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
l.Errorw("[CreatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
}
resp := convertRule(rule)
return &resp, nil
}
@@ -0,0 +1,47 @@
package promo
import (
"context"
stderrors "errors"
"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"
"gorm.io/gorm"
)
type DeletePriceLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeletePriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePriceLogic {
return &DeletePriceLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error {
price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id)
if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
l.Errorw("[DeletePromoPrice] Price Not Found", logger.Field("id", req.Id))
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo price not found"), "promo price not found: %d", req.Id)
}
l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error())
}
if err := l.svcCtx.PromoModel.DeletePrice(l.ctx, req.Id); err != nil {
l.Errorw("[DeletePromoPrice] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, subscribePromoCacheKey(price.SubscribeId)).Err(); err != nil {
l.Errorw("[DeletePromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
}
return nil
}
@@ -0,0 +1,46 @@
package promo
import (
"context"
stderrors "errors"
"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"
"gorm.io/gorm"
)
type DeleteRuleLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRuleLogic {
return &DeleteRuleLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error {
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id); err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
l.Errorw("[DeletePromoRule] Rule Not Found", logger.Field("id", req.Id))
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo rule not found"), "promo rule not found: %d", req.Id)
}
l.Errorw("[DeletePromoRule] Find Rule Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
l.Errorw("[DeletePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
}
return nil
}
@@ -0,0 +1,93 @@
package promo
import (
"context"
"testing"
promomodel "github.com/perfect-panel/server/internal/model/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/xerr"
pkgerrors "github.com/pkg/errors"
"gorm.io/gorm"
)
type fakePromoModel struct{}
func (fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promomodel.RuleWithPrice, error) {
return nil, nil
}
func (fakePromoModel) InsertUsage(context.Context, *promomodel.Usage, ...*gorm.DB) error {
return nil
}
func (fakePromoModel) InsertRule(context.Context, *promomodel.Rule) error {
return nil
}
func (fakePromoModel) FindRule(context.Context, int64) (*promomodel.Rule, error) {
return nil, gorm.ErrRecordNotFound
}
func (fakePromoModel) UpdateRule(context.Context, *promomodel.Rule) error {
return nil
}
func (fakePromoModel) DeleteRule(context.Context, int64) error {
return nil
}
func (fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promomodel.Rule, error) {
return 0, nil, nil
}
func (fakePromoModel) UpsertPrices(context.Context, int64, []*promomodel.SubscribePromo) error {
return nil
}
func (fakePromoModel) FindPrice(context.Context, int64) (*promomodel.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (fakePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promomodel.SubscribePromo, error) {
return 0, nil, nil
}
func (fakePromoModel) QueryUsageList(context.Context, promomodel.UsageFilter) (int64, []*promomodel.Usage, error) {
return 0, nil, nil
}
func (fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func TestDeleteRuleNotFoundReturns404(t *testing.T) {
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
err := NewDeleteRuleLogic(context.Background(), svcCtx).DeleteRule(&types.DeletePromoRuleRequest{Id: 1})
assertCodeError(t, err, 404)
}
func TestDeletePriceNotFoundReturns404(t *testing.T) {
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
err := NewDeletePriceLogic(context.Background(), svcCtx).DeletePrice(&types.DeletePromoPriceRequest{Id: 1})
assertCodeError(t, err, 404)
}
func assertCodeError(t *testing.T, err error, want uint32) {
t.Helper()
if err == nil {
t.Fatal("expected error")
}
codeErr, ok := pkgerrors.Cause(err).(*xerr.CodeError)
if !ok {
t.Fatalf("expected CodeError, got %T", pkgerrors.Cause(err))
}
if got := codeErr.GetErrCode(); got != want {
t.Fatalf("unexpected error code: got %d want %d", got, want)
}
}
@@ -0,0 +1,41 @@
package promo
import (
"context"
"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 GetPriceListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPriceListLogic {
return &GetPriceListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetPriceListLogic) GetPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
total, list, err := l.svcCtx.PromoModel.QueryPriceList(l.ctx, req.PromoRuleId, int(req.Page), int(req.Size))
if err != nil {
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo price list error: %v", err.Error())
}
resp := &types.GetPromoPriceListResponse{
Total: total,
List: make([]types.PromoPrice, 0, len(list)),
}
for _, item := range list {
resp.List = append(resp.List, convertPrice(item))
}
return resp, nil
}
@@ -0,0 +1,35 @@
package promo
import (
"context"
"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 GetRuleDetailLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleDetailLogic {
return &GetRuleDetailLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetRuleDetailLogic) GetRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
if err != nil {
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule detail error: %v", err.Error())
}
resp := convertRule(rule)
return &resp, nil
}
@@ -0,0 +1,41 @@
package promo
import (
"context"
"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 GetRuleListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleListLogic {
return &GetRuleListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetRuleListLogic) GetRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, int(req.Page), int(req.Size), req.Type, req.Enabled, req.Search)
if err != nil {
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule list error: %v", err.Error())
}
resp := &types.GetPromoRuleListResponse{
Total: total,
List: make([]types.PromoRule, 0, len(list)),
}
for _, item := range list {
resp.List = append(resp.List, convertRule(item))
}
return resp, nil
}
@@ -0,0 +1,49 @@
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 GetUsageListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUsageListLogic {
return &GetUsageListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetUsageListLogic) GetUsageList(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),
RuleId: req.RuleId,
UserId: req.UserId,
SubscribeId: req.SubscribeId,
OrderNo: req.OrderNo,
})
if err != nil {
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo usage list error: %v", err.Error())
}
resp := &types.GetPromoUsageListResponse{
Total: total,
List: make([]types.PromoUsage, 0, len(list)),
}
for _, item := range list {
resp.List = append(resp.List, convertUsage(item))
}
return resp, nil
}
@@ -0,0 +1,81 @@
package promo
import (
"context"
promomodel "github.com/perfect-panel/server/internal/model/promo"
subscribeModel "github.com/perfect-panel/server/internal/model/subscribe"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type SetPriceLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSetPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetPriceLogic {
return &SetPriceLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SetPriceLogic) SetPrice(req *types.SetPromoPriceRequest) error {
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
l.Errorw("[SetPromoPrice] Find Rule Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
subscribeIds := make([]int64, 0, len(req.Items))
seenSubscribeIds := make(map[int64]struct{}, len(req.Items))
for _, item := range req.Items {
if _, ok := seenSubscribeIds[item.SubscribeId]; ok {
continue
}
seenSubscribeIds[item.SubscribeId] = struct{}{}
subscribeIds = append(subscribeIds, item.SubscribeId)
}
var subscribes []*subscribeModel.Subscribe
if err := l.svcCtx.DB.WithContext(l.ctx).Model(&subscribeModel.Subscribe{}).Where("id IN ?", subscribeIds).Find(&subscribes).Error; err != nil {
l.Errorw("[SetPromoPrice] Find Subscribe Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
}
subscribeById := make(map[int64]*subscribeModel.Subscribe, len(subscribes))
for _, sub := range subscribes {
subscribeById[sub.Id] = sub
}
items := make([]*promomodel.SubscribePromo, 0, len(req.Items))
cacheKeys := make([]string, 0, len(req.Items))
for _, item := range req.Items {
sub, ok := subscribeById[item.SubscribeId]
if !ok {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "subscribe plan not found")
}
originPrice := sub.UnitPrice * item.Quantity
if item.PromoPrice >= originPrice {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "promo_price must be less than unit_price * quantity")
}
items = append(items, &promomodel.SubscribePromo{
SubscribeId: item.SubscribeId,
PromoRuleId: req.PromoRuleId,
Quantity: item.Quantity,
PromoPrice: item.PromoPrice,
})
cacheKeys = append(cacheKeys, subscribePromoCacheKey(item.SubscribeId))
}
if err := l.svcCtx.PromoModel.UpsertPrices(l.ctx, req.PromoRuleId, items); err != nil {
l.Errorw("[SetPromoPrice] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "set promo price error: %v", err.Error())
}
if len(cacheKeys) > 0 {
if err := l.svcCtx.Redis.Del(l.ctx, cacheKeys...).Err(); err != nil {
l.Errorw("[SetPromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
}
}
return nil
}
+162
View File
@@ -0,0 +1,162 @@
package promo
import (
"encoding/json"
"fmt"
"math"
"time"
promomodel "github.com/perfect-panel/server/internal/model/promo"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
const (
ruleCacheKey = "promo:rules:enabled"
subscribeCachePref = "promo:subscribe:"
)
func validateRuleInput(ruleType string, params map[string]interface{}, priority int64, startTime, endTime *int64) error {
if priority < 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "priority must be greater than or equal to 0")
}
if startTime != nil && endTime != nil && *startTime >= *endTime {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "start_time must be less than end_time")
}
switch ruleType {
case "new_user":
windowHours, ok := numberParam(params, "window_hours")
if !ok || windowHours <= 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.window_hours must be greater than 0")
}
case "inactive_user":
inactiveMonths, ok := numberParam(params, "inactive_months")
if !ok || inactiveMonths <= 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.inactive_months must be greater than 0")
}
case "campaign":
if params == nil {
return nil
}
default:
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "unsupported promo rule type")
}
return nil
}
func numberParam(params map[string]interface{}, key string) (int64, bool) {
if params == nil {
return 0, false
}
value, ok := params[key]
if !ok {
return 0, false
}
switch v := value.(type) {
case float64:
if math.Trunc(v) != v {
return 0, false
}
return int64(v), true
case int64:
return v, true
case int:
return int64(v), true
case json.Number:
n, err := v.Int64()
return n, err == nil
default:
return 0, false
}
}
func paramsToString(params map[string]interface{}) (string, error) {
if params == nil {
params = map[string]interface{}{}
}
b, err := json.Marshal(params)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid params")
}
return string(b), nil
}
func parseParams(data string) map[string]interface{} {
if data == "" {
return map[string]interface{}{}
}
var params map[string]interface{}
if err := json.Unmarshal([]byte(data), &params); err != nil {
return map[string]interface{}{}
}
return params
}
func unixPtrToTimePtr(ts *int64) *time.Time {
if ts == nil || *ts == 0 {
return nil
}
t := time.Unix(*ts, 0)
return &t
}
func timePtrToUnixPtr(t *time.Time) *int64 {
if t == nil {
return nil
}
ts := t.Unix()
return &ts
}
func convertRule(item *promomodel.Rule) types.PromoRule {
if item == nil {
return types.PromoRule{}
}
return types.PromoRule{
Id: item.Id,
Name: item.Name,
Type: item.Type,
Params: parseParams(item.Params),
Priority: item.Priority,
Enabled: item.Enabled,
StartTime: timePtrToUnixPtr(item.StartTime),
EndTime: timePtrToUnixPtr(item.EndTime),
CreatedAt: item.CreatedAt.Unix(),
UpdatedAt: item.UpdatedAt.Unix(),
}
}
func convertPrice(item *promomodel.SubscribePromo) types.PromoPrice {
if item == nil {
return types.PromoPrice{}
}
return types.PromoPrice{
Id: item.Id,
SubscribeId: item.SubscribeId,
PromoRuleId: item.PromoRuleId,
Quantity: item.Quantity,
PromoPrice: item.PromoPrice,
CreatedAt: item.CreatedAt.Unix(),
UpdatedAt: item.UpdatedAt.Unix(),
}
}
func convertUsage(item *promomodel.Usage) types.PromoUsage {
if item == nil {
return types.PromoUsage{}
}
return types.PromoUsage{
Id: item.Id,
UserId: item.UserId,
PromoRuleId: item.PromoRuleId,
SubscribeId: item.SubscribeId,
OrderNo: item.OrderNo,
PromoPrice: item.PromoPrice,
CreatedAt: item.CreatedAt.Unix(),
}
}
func subscribePromoCacheKey(subscribeId int64) string {
return fmt.Sprintf("%s%d", subscribeCachePref, subscribeId)
}
@@ -0,0 +1,60 @@
package promo
import (
"context"
"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 UpdateRuleLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRuleLogic {
return &UpdateRuleLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateRuleLogic) UpdateRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
return nil, err
}
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
if err != nil {
l.Errorw("[UpdatePromoRule] Find Rule Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
params, err := paramsToString(req.Params)
if err != nil {
return nil, err
}
enabled := rule.Enabled
if req.Enabled != nil {
enabled = *req.Enabled
}
rule.Name = req.Name
rule.Type = req.Type
rule.Params = params
rule.Priority = req.Priority
rule.Enabled = enabled
rule.StartTime = unixPtrToTimePtr(req.StartTime)
rule.EndTime = unixPtrToTimePtr(req.EndTime)
if err := l.svcCtx.PromoModel.UpdateRule(l.ctx, rule); err != nil {
l.Errorw("[UpdatePromoRule] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
l.Errorw("[UpdatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
}
resp := convertRule(rule)
return &resp, nil
}
@@ -3,11 +3,13 @@ package user
import (
"context"
adminInvite "github.com/perfect-panel/server/internal/logic/admin/invite"
"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"
"gorm.io/gorm"
)
type GetAdminUserInviteListLogic struct {
@@ -25,15 +27,7 @@ func NewGetAdminUserInviteListLogic(ctx context.Context, svcCtx *svc.ServiceCont
}
func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdminUserInviteListRequest) (resp *types.GetAdminUserInviteListResponse, err error) {
if req.Page < 1 {
req.Page = 1
}
if req.Size < 1 {
req.Size = 10
}
if req.Size > 100 {
req.Size = 100
}
req.Page, req.Size = adminInvite.NormalizePage(req.Page, req.Size)
type InvitedUser struct {
Id int64 `gorm:"column:id"`
@@ -44,19 +38,19 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
}
var total int64
baseQuery := l.svcCtx.DB.WithContext(l.ctx).
baseQuery := applyAdminUserInviteFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user u").
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId)
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId), req)
if err = baseQuery.Count(&total).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invited users failed: %v", err)
}
var rows []InvitedUser
err = l.svcCtx.DB.WithContext(l.ctx).
err = applyAdminUserInviteFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user u").
Select("u.id, u.avatar, u.enable, UNIX_TIMESTAMP(u.created_at) as created_at, COALESCE((SELECT uam.auth_identifier FROM user_auth_methods uam WHERE uam.user_id = u.id ORDER BY uam.id ASC LIMIT 1), '') as identifier").
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId).
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId), req).
Order("u.created_at DESC").
Limit(req.Size).
Offset((req.Page - 1) * req.Size).
@@ -65,14 +59,29 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invited users failed: %v", err)
}
relations := make([]adminInvite.InviteRelation, 0, len(rows))
for _, r := range rows {
relations = append(relations, adminInvite.InviteRelation{InviteeId: r.Id, InviterId: req.UserId})
}
benefits, err := adminInvite.QueryBenefits(l.ctx, l.svcCtx.DB, relations)
if err != nil {
return nil, err
}
list := make([]types.AdminInvitedUser, 0, len(rows))
for _, r := range rows {
benefit := benefits[r.Id]
list = append(list, types.AdminInvitedUser{
Id: r.Id,
Avatar: r.Avatar,
Identifier: r.Identifier,
Enable: r.Enable,
CreatedAt: r.CreatedAt,
Id: r.Id,
Avatar: r.Avatar,
Identifier: r.Identifier,
Enable: r.Enable,
CreatedAt: r.CreatedAt,
OrderCount: benefit.OrderCount,
HasPurchased: benefit.HasPurchased,
InviterCommission: benefit.InviterCommission,
InviterGiftDays: benefit.InviterGiftDays,
InviteeGiftDays: benefit.InviteeGiftDays,
})
}
@@ -81,3 +90,16 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
List: list,
}, nil
}
func applyAdminUserInviteFilters(db *gorm.DB, req *types.GetAdminUserInviteListRequest) *gorm.DB {
if req.Search != "" {
db = db.Where("EXISTS (SELECT 1 FROM user_auth_methods uam WHERE uam.user_id = u.id AND uam.auth_identifier LIKE ?)", "%"+req.Search+"%")
}
if req.Enable != nil {
db = db.Where("u.enable = ?", *req.Enable)
}
if req.UserIdSearch > 0 {
db = db.Where("u.id = ?", req.UserIdSearch)
}
return db
}
@@ -2,6 +2,7 @@ package user
import (
"context"
"encoding/json"
"github.com/perfect-panel/server/internal/model/group"
"github.com/perfect-panel/server/internal/svc"
@@ -36,6 +37,13 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
}
var subscribeDetails types.UserSubscribeDetail
tool.DeepCopy(&subscribeDetails, sub)
subscribeDetails.SpeedLimit = sub.SpeedLimit
if sub.TrafficLimit != nil && *sub.TrafficLimit != "" {
_ = json.Unmarshal([]byte(*sub.TrafficLimit), &subscribeDetails.TrafficLimit)
}
if sub.Subscribe != nil {
subscribeDetails.PlanSpeedLimit = sub.Subscribe.SpeedLimit
}
// 填充分组名
if sub.NodeGroupId > 0 {
@@ -47,7 +55,17 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
// Calculate speed limit status
if sub.Subscribe != nil && sub.Status == 1 {
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, sub.Subscribe.SpeedLimit, sub.Subscribe.TrafficLimit)
baseSpeed := sub.Subscribe.SpeedLimit
if sub.SpeedLimit > 0 {
baseSpeed = sub.SpeedLimit
}
trafficLimit := sub.Subscribe.TrafficLimit
if sub.TrafficLimit != nil && *sub.TrafficLimit != "" {
trafficLimit = *sub.TrafficLimit
}
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, baseSpeed, trafficLimit)
subscribeDetails.EffectiveSpeed = result.EffectiveSpeed
subscribeDetails.IsThrottled = result.IsThrottled
subscribeDetails.ThrottleRule = result.ThrottleRule
@@ -39,22 +39,32 @@ func (l *UpdateUserSubscribeLogic) UpdateUserSubscribe(req *types.UpdateUserSubs
} else {
userSub.Status = 1
}
speedLimit := userSub.SpeedLimit
if req.SpeedLimit != nil {
speedLimit = *req.SpeedLimit
}
trafficLimit := userSub.TrafficLimit
if req.TrafficLimit != nil {
trafficLimit = req.TrafficLimit
}
err = l.svcCtx.UserModel.UpdateSubscribe(l.ctx, &user.Subscribe{
Id: userSub.Id,
UserId: userSub.UserId,
OrderId: userSub.OrderId,
SubscribeId: req.SubscribeId,
StartTime: userSub.StartTime,
ExpireTime: time.UnixMilli(req.ExpiredAt),
Traffic: req.Traffic,
Download: req.Download,
Upload: req.Upload,
Token: userSub.Token,
UUID: userSub.UUID,
Status: userSub.Status,
NodeGroupId: userSub.NodeGroupId,
GroupLocked: userSub.GroupLocked,
Id: userSub.Id,
UserId: userSub.UserId,
OrderId: userSub.OrderId,
SubscribeId: req.SubscribeId,
StartTime: userSub.StartTime,
ExpireTime: time.UnixMilli(req.ExpiredAt),
Traffic: req.Traffic,
Download: req.Download,
Upload: req.Upload,
SpeedLimit: speedLimit,
TrafficLimit: trafficLimit,
Token: userSub.Token,
UUID: userSub.UUID,
Status: userSub.Status,
NodeGroupId: userSub.NodeGroupId,
GroupLocked: userSub.GroupLocked,
})
if err != nil {
@@ -0,0 +1 @@
package common
@@ -0,0 +1 @@
package common
+19 -5
View File
@@ -11,6 +11,7 @@ import (
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type PromoResult struct {
@@ -27,13 +28,13 @@ type promoRuleParams struct {
InactiveMonths int `json:"inactive_months"`
}
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64) (*PromoResult, error) {
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
result := &PromoResult{}
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 {
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 || quantity <= 0 {
return result, nil
}
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID)
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID, quantity)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
}
@@ -148,7 +149,12 @@ func evaluateInactiveUserPromo(
err := db.WithContext(ctx).
Model(&user.Subscribe{}).
Where("user_id = ?", userID).
Order("expire_time DESC").
Order(clause.OrderBy{
Expression: clause.Expr{
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
Vars: []interface{}{time.UnixMilli(0)},
},
}).
Limit(1).
Take(&lastSub).Error
if err != nil {
@@ -158,8 +164,16 @@ func evaluateInactiveUserPromo(
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
}
return evaluateInactiveUserExpire(lastSub.ExpireTime, params, now), ruleExpiresAt, nil
}
func evaluateInactiveUserExpire(lastExpire time.Time, params promoRuleParams, now time.Time) bool {
if lastExpire.Equal(time.UnixMilli(0)) {
return false
}
threshold := now.AddDate(0, -params.InactiveMonths, 0)
return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil
return lastExpire.Before(threshold) || lastExpire.Equal(threshold)
}
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
@@ -0,0 +1,46 @@
package common
import (
"testing"
"time"
)
func TestEvaluateInactiveUserExpire(t *testing.T) {
now := time.Date(2026, 5, 27, 8, 0, 0, 0, time.UTC)
params := promoRuleParams{InactiveMonths: 3}
tests := []struct {
name string
lastExpire time.Time
want bool
}{
{
name: "permanent subscription is not inactive",
lastExpire: time.UnixMilli(0),
want: false,
},
{
name: "active subscription is not inactive",
lastExpire: now.Add(time.Hour),
want: false,
},
{
name: "expire at threshold is inactive",
lastExpire: now.AddDate(0, -3, 0),
want: true,
},
{
name: "expire before threshold is inactive",
lastExpire: now.AddDate(0, -3, -1),
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := evaluateInactiveUserExpire(tt.lastExpire, params, now); got != tt.want {
t.Fatalf("evaluateInactiveUserExpire() = %v, want %v", got, tt.want)
}
})
}
}
@@ -0,0 +1 @@
package common
@@ -0,0 +1 @@
package common
@@ -0,0 +1 @@
package server
@@ -0,0 +1 @@
package server
@@ -0,0 +1 @@
package server
@@ -0,0 +1 @@
package server
@@ -0,0 +1 @@
package server
@@ -0,0 +1 @@
package server
+1 -1
View File
@@ -80,7 +80,7 @@ func validateInitRequest(svcCtx *svc.ServiceContext, bizType, fileName, contentT
allowed := allowedContentTypeSet(svcCtx.Config.S3.AllowedContentTypes)
if len(allowed) > 0 {
if _, ok := allowed[strings.ToLower(strings.TrimSpace(contentType))]; !ok {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "content_type is not allowed")
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "content_type is not allowed"), "content_type is not allowed")
}
}
return nil
+91
View File
@@ -0,0 +1,91 @@
package file
import (
"mime/multipart"
"strings"
"testing"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/storage"
)
const testAllowedContentTypes = "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"
type testMultipartFile struct {
*strings.Reader
}
func (testMultipartFile) Close() error {
return nil
}
func TestValidateInitRequestAllowedContentTypes(t *testing.T) {
svcCtx := &svc.ServiceContext{
Config: config.Config{
S3: config.S3Config{
Enable: true,
MaxUploadSize: 1024,
AllowedContentTypes: testAllowedContentTypes,
},
},
S3Store: &storage.S3Store{},
}
tests := []struct {
name string
contentType string
wantErr bool
}{
{name: "allow jpeg", contentType: "image/jpeg"},
{name: "allow png", contentType: "image/png"},
{name: "allow webp", contentType: "image/webp"},
{name: "reject unknown", contentType: "application/x-sh", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateInitRequest(svcCtx, "app-package", "demo.bin", tt.contentType, 10)
if tt.wantErr {
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "content_type is not allowed") {
t.Fatalf("expected content type error, got %v", err)
}
return
}
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
})
}
}
func TestSniffContentTypeDetectsCommonImages(t *testing.T) {
tests := []struct {
name string
data string
want string
}{
{name: "jpeg", data: "\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01", want: "image/jpeg"},
{name: "png", data: "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR", want: "image/png"},
{name: "webp", data: "RIFF\x1a\x00\x00\x00WEBPVP8 \x0e\x00\x00\x00", want: "image/webp"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
file := testMultipartFile{Reader: strings.NewReader(tt.data)}
got, err := sniffContentType(&multipart.FileHeader{}, file)
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
if got != tt.want {
t.Fatalf("expected %q, got %q", tt.want, got)
}
if pos, err := file.Seek(0, 1); err != nil || pos != 0 {
t.Fatalf("expected reader reset to start, pos=%d err=%v", pos, err)
}
})
}
}
@@ -61,11 +61,6 @@ func (l *FileUploadCompleteLogic) FileUploadComplete(req *types.FileUploadComple
}
return &types.FileUploadCompleteResponse{
FileId: meta.FileID,
ObjectKey: meta.ObjectKey,
Size: head.ContentLength,
ContentType: head.ContentType,
Etag: head.ETag,
Status: meta.Status,
Url: l.svcCtx.S3Store.BuildObjectURL(meta.ObjectKey),
}, nil
}
@@ -52,20 +52,13 @@ func (l *FileUploadLogic) FileUpload(req *types.FileUploadRequest, fileHeader *m
fileID := buildFileID(u.Id, req.BizType, fileHeader.Filename)
objectKey := buildObjectKey(l.svcCtx.Config.S3.Prefix, u.Id, req.BizType, fileID, fileHeader.Filename, now)
putResult, err := l.svcCtx.S3Store.PutObject(l.ctx, objectKey, file, fileHeader.Size, contentType)
if err != nil {
if _, err := l.svcCtx.S3Store.PutObject(l.ctx, objectKey, file, fileHeader.Size, contentType); err != nil {
l.Errorw("put object failed", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("file_id", fileID))
return nil, err
}
return &types.FileUploadResponse{
FileId: fileID,
FileName: fileHeader.Filename,
ObjectKey: objectKey,
Size: fileHeader.Size,
ContentType: contentType,
Etag: putResult.ETag,
Status: fileUploadCompleteStatus,
Url: l.svcCtx.S3Store.BuildObjectURL(objectKey),
}, nil
}
@@ -0,0 +1 @@
package apple
@@ -0,0 +1 @@
package apple
@@ -0,0 +1 @@
package apple
@@ -0,0 +1 @@
package apple
@@ -47,13 +47,18 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1")
req.Quantity = 1
}
entitlement, entErr := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, u.Id)
if entErr != nil {
return nil, entErr
}
targetSubscribeID := req.SubscribeId
orderType := uint8(1)
isSingleModeRenewal := false
decision, routeErr := commonLogic.ResolvePurchaseRoute(
l.ctx,
l.svcCtx.Config.Subscribe.SingleModel,
u.Id,
entitlement.EffectiveUserID,
req.SubscribeId,
l.svcCtx.UserModel.FindSingleModeAnchorSubscribe,
)
@@ -68,15 +73,44 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
targetSubscribeID = decision.ResolvedSubscribeID
isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal
if isSingleModeRenewal && decision.Anchor != nil {
orderType = 2
l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview",
logger.Field("mode", "single"),
logger.Field("route", "purchase_to_renewal"),
logger.Field("anchor_user_subscribe_id", decision.Anchor.Id),
logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
)
}
}
// Keep promo eligibility preview aligned with Purchase: an existing paid subscription
// routes the request to renewal semantics, where first-purchase promos are disabled.
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
var existSub user.Subscribe
if e := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Subscribe{}).
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%')", entitlement.EffectiveUserID).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC").
First(&existSub).Error; e == nil && existSub.Id > 0 && existSub.Token != "" {
orderType = 2
l.Infow("[PreCreateOrder] purchase preview routed to renewal because an existing subscription was found",
logger.Field("route_mode", "global_single_subscription"),
logger.Field("route", "purchase_to_existing_subscription"),
logger.Field("existing_subscribe_id", existSub.Id),
logger.Field("existing_status", existSub.Status),
logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
logger.Field("resolved_subscribe_id", targetSubscribeID),
)
} else if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) {
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", e.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find existing subscription error: %v", e.Error())
}
}
// find subscribe plan
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID)
if err != nil {
@@ -86,7 +120,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
// check subscribe plan quota limit for new purchase flow only
if !isSingleModeRenewal && sub.Quota > 0 {
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id)
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, entitlement.EffectiveUserID)
if err != nil {
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
@@ -102,7 +136,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
}
}
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount)
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount)
if err != nil {
l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility",
logger.Field("error", err.Error()),
@@ -117,13 +151,13 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
priceResult, err := calculatePurchasePrice(
l.ctx,
l.svcCtx,
u.Id,
entitlement.EffectiveUserID,
targetSubscribeID,
sub.UnitPrice,
req.Quantity,
newUserDiscount.Discounts,
newUserDiscount.EligibleForDiscount,
!isSingleModeRenewal,
orderType == 1,
)
if err != nil {
l.Errorw("[PreCreateOrder] Promo price calculation error",
+3 -3
View File
@@ -36,12 +36,12 @@ func calculatePurchasePrice(
}
if allowPromo {
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID)
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity)
if err != nil {
return nil, err
}
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < unitPrice {
result.PayableBase = promoResult.PromoPrice * quantity
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < originalPrice {
result.PayableBase = promoResult.PromoPrice
result.PromoRuleId = promoResult.RuleID
result.PromoDiscount = originalPrice - result.PayableBase
result.PromoPrice = promoResult.PromoPrice
+147 -37
View File
@@ -11,31 +11,85 @@ import (
)
type fakePromoModel struct {
rules []*promo.RuleWithPrice
rules []*promo.RuleWithPrice
lastSubscribeID int64
lastQuantity int64
requireQuantity int64
quantityMismatch []*promo.RuleWithPrice
}
func (m fakePromoModel) QueryEligibleRules(context.Context, int64) ([]*promo.RuleWithPrice, error) {
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
m.lastSubscribeID = subscribeID
m.lastQuantity = quantity
if m.requireQuantity > 0 && quantity != m.requireQuantity {
return m.quantityMismatch, nil
}
return m.rules, nil
}
func (m fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
return 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,
func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
return nil
}
func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
return nil, gorm.ErrRecordNotFound
}
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, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
return 0, nil, nil
}
func (m *fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
return nil
}
func (m *fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (m *fakePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (m *fakePromoModel) QueryPriceList(context.Context, int64, int, int) (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 (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 9,
Name: "campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
}},
PromoPrice: 279,
},
}}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: model,
}
result, err := calculatePurchasePrice(
@@ -43,9 +97,9 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
svcCtx,
1,
2,
1000,
3,
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
100,
7,
[]types.SubscribeDiscount{{Quantity: 7, Discount: 50}},
true,
true,
)
@@ -53,11 +107,11 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
t.Fatalf("calculatePurchasePrice returned error: %v", err)
}
if result.OriginalPrice != 3000 {
t.Fatalf("OriginalPrice = %d, want 3000", result.OriginalPrice)
if result.OriginalPrice != 700 {
t.Fatalf("OriginalPrice = %d, want 700", result.OriginalPrice)
}
if result.PayableBase != 1800 {
t.Fatalf("PayableBase = %d, want 1800", result.PayableBase)
if result.PayableBase != 279 {
t.Fatalf("PayableBase = %d, want 279", result.PayableBase)
}
if result.DiscountAmount != 0 {
t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount)
@@ -65,25 +119,32 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
if result.PromoRuleId != 9 {
t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId)
}
if result.PromoDiscount != 1200 {
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
if result.PromoDiscount != 421 {
t.Fatalf("PromoDiscount = %d, want 421", result.PromoDiscount)
}
if result.PromoPrice != 279 {
t.Fatalf("PromoPrice = %d, want 279", result.PromoPrice)
}
if model.lastQuantity != 7 {
t.Fatalf("promo query quantity = %d, want 7", model.lastQuantity)
}
}
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
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,
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 10,
Name: "invalid campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
}},
PromoPrice: 3000,
},
}}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: model,
}
result, err := calculatePurchasePrice(
@@ -111,3 +172,52 @@ func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
}
}
func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
promoModel := &fakePromoModel{
requireQuantity: 6,
rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 11,
Name: "quantity campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
PromoPrice: 3000,
},
},
}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: promoModel,
}
result, err := calculatePurchasePrice(
context.Background(),
svcCtx,
1,
2,
1000,
6,
[]types.SubscribeDiscount{{Quantity: 6, Discount: 80}},
true,
true,
)
if err != nil {
t.Fatalf("calculatePurchasePrice returned error: %v", err)
}
if promoModel.lastSubscribeID != 2 {
t.Fatalf("lastSubscribeID = %d, want 2", promoModel.lastSubscribeID)
}
if promoModel.lastQuantity != 6 {
t.Fatalf("lastQuantity = %d, want 6", promoModel.lastQuantity)
}
if result.PayableBase != 3000 {
t.Fatalf("PayableBase = %d, want 3000", result.PayableBase)
}
if result.PromoRuleId != 11 {
t.Fatalf("PromoRuleId = %d, want 11", result.PromoRuleId)
}
}
+42 -21
View File
@@ -15,6 +15,7 @@ import (
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const (
@@ -25,6 +26,7 @@ const (
type subscribePromoCandidate struct {
SubscribeId int64 `gorm:"column:subscribe_id"`
Quantity int64 `gorm:"column:quantity"`
RuleName string `gorm:"column:rule_name"`
RuleType string `gorm:"column:rule_type"`
PromoPrice int64 `gorm:"column:promo_price"`
@@ -38,8 +40,8 @@ type promoRuleParams struct {
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)
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
result := make(map[int64]map[int64]*types.SubscribePromo)
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
return result, nil
}
@@ -56,7 +58,13 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
now := time.Now()
for _, candidate := range candidates {
if _, exists := result[candidate.SubscribeId]; exists {
if candidate.Quantity <= 0 {
continue
}
if result[candidate.SubscribeId] == nil {
result[candidate.SubscribeId] = make(map[int64]*types.SubscribePromo)
}
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
continue
}
if !candidate.isActive(now) {
@@ -69,7 +77,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
if !ok {
continue
}
result[candidate.SubscribeId] = &types.SubscribePromo{
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
RuleName: candidate.RuleName,
RuleType: candidate.RuleType,
PromoPrice: candidate.PromoPrice,
@@ -82,18 +90,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
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").
err := subscribePromoCandidatesQuery(ctx, svcCtx.DB, subscribeIDs, loggedIn).
Scan(&candidates).Error
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
@@ -101,6 +98,22 @@ func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceConte
return candidates, nil
}
func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeIDs []int64, loggedIn bool) *gorm.DB {
query := db.WithContext(ctx).
Table("subscribe_promo AS sp").
Select("sp.subscribe_id, sp.quantity, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
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)
}
return query.
Order("sp.subscribe_id ASC").
Order("sp.quantity ASC").
Order("pr.priority DESC").
Order("pr.id ASC")
}
func (c subscribePromoCandidate) isActive(now time.Time) bool {
if c.PromoPrice <= 0 {
return false
@@ -171,11 +184,7 @@ func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
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").
err := e.lastSubscribeExpireQuery().
Limit(1).
Take(&item).Error
if err != nil {
@@ -190,6 +199,18 @@ func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
return item.ExpireTime, nil
}
func (e *promoEligibilityEvaluator) lastSubscribeExpireQuery() *gorm.DB {
return e.db.WithContext(e.ctx).
Model(&user.Subscribe{}).
Where("user_id = ?", e.userInfo.Id).
Order(clause.OrderBy{
Expression: clause.Expr{
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
Vars: []interface{}{time.UnixMilli(0)},
},
})
}
func (c subscribePromoCandidate) expiresAt() time.Time {
if c.EndTime == nil {
return time.Time{}
@@ -1,10 +1,15 @@
package subscribe
import (
"context"
"strings"
"testing"
"time"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/types"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
@@ -73,3 +78,83 @@ func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
t.Fatal("candidate after end time should not be active")
}
}
func TestLastSubscribeExpireAtPrioritizesPermanentSubscription(t *testing.T) {
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
SkipInitializeWithVersion: true,
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
if err != nil {
t.Fatalf("open dry-run db: %v", err)
}
evaluator := &promoEligibilityEvaluator{
db: db,
userInfo: &user.User{Id: 7},
}
var item user.Subscribe
tx := evaluator.lastSubscribeExpireQuery().Limit(1).Take(&item)
sql := tx.Statement.SQL.String()
if !strings.Contains(sql, "CASE WHEN expire_time = ? THEN 0 ELSE 1 END") {
t.Fatalf("SQL missing permanent subscription priority order: %s", sql)
}
if strings.Contains(sql, "expire_time !=") {
t.Fatalf("SQL should not filter out permanent subscriptions: %s", sql)
}
if len(tx.Statement.Vars) < 2 {
t.Fatalf("SQL vars length = %d, want at least 2; vars=%v", len(tx.Statement.Vars), tx.Statement.Vars)
}
if got, want := tx.Statement.Vars[1], time.UnixMilli(0); got != want {
t.Fatalf("permanent subscription order var = %v, want %v; vars=%v", got, want, tx.Statement.Vars)
}
}
func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
SkipInitializeWithVersion: true,
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
if err != nil {
t.Fatalf("open dry-run db: %v", err)
}
var candidates []subscribePromoCandidate
tx := subscribePromoCandidatesQuery(context.Background(), db, []int64{11, 12}, true).Scan(&candidates)
stmt := tx.Statement
sql := stmt.SQL.String()
if !strings.Contains(sql, "sp.subscribe_id, sp.quantity, sp.promo_price") {
t.Fatalf("SQL missing quantity select: %s", sql)
}
if !strings.Contains(sql, "ORDER BY sp.subscribe_id ASC,sp.quantity ASC,pr.priority DESC,pr.id ASC") {
t.Fatalf("SQL missing quantity order: %s", sql)
}
}
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
{Quantity: 1},
{Quantity: 12},
}}
promos := map[int64]*types.SubscribePromo{
3: {RuleName: "季度优惠", PromoPrice: 2900},
12: {RuleName: "年度优惠", PromoPrice: 9900},
}
applySubscribeDiscountPromos(&subscribe, promos)
if subscribe.Discount[0].Promo != nil {
t.Fatalf("quantity 1 promo should be nil, got %+v", subscribe.Discount[0].Promo)
}
if subscribe.Discount[1].Promo == nil {
t.Fatal("quantity 12 promo should match")
}
if got, want := subscribe.Discount[1].Promo.RuleName, "年度优惠"; got != want {
t.Fatalf("promo rule name = %q, want %q", got, want)
}
subscribe = types.Subscribe{Discount: []types.SubscribeDiscount{{Quantity: 6}}}
applySubscribeDiscountPromos(&subscribe, promos)
if subscribe.Discount[0].Promo != nil {
t.Fatalf("promo should be nil when quantity does not match, got %+v", subscribe.Discount[0].Promo)
}
}
@@ -56,11 +56,19 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
var discount []types.SubscribeDiscount
_ = json.Unmarshal([]byte(item.Discount), &discount)
sub.Discount = discount
list[i] = sub
}
list[i] = sub
}
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
if err != nil {
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
return nil, err
}
for i := range list {
applySubscribeDiscountPromos(&list[i], promos[list[i].Id])
}
// 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个
hasAppId, _ := l.ctx.Value(constant.CtxKeyHasAppId).(bool)
if !hasAppId {
@@ -71,16 +79,13 @@ 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.Total = int64(len(list))
return
}
func applySubscribeDiscountPromos(subscribe *types.Subscribe, promoByQuantity map[int64]*types.SubscribePromo) {
for i := range subscribe.Discount {
subscribe.Discount[i].Promo = promoByQuantity[subscribe.Discount[i].Quantity]
}
}
@@ -46,8 +46,8 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for bank transfer")
}
default: // WithdrawalMethodOther
if req.Account == "" && req.Content == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account or content is required for other methods")
if req.Account == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for other methods")
}
}
@@ -0,0 +1,198 @@
package user
import (
"context"
"encoding/json"
logmodel "github.com/perfect-panel/server/internal/model/log"
ordermodel "github.com/perfect-panel/server/internal/model/order"
"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/hash"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
const (
inviteRecordRoleInviter = "inviter"
inviteRecordRoleInvitee = "invitee"
)
type GetInviteRecordsLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
type inviteRecordLog struct {
Id int64 `gorm:"column:id"`
ObjectId int64 `gorm:"column:object_id"`
Content string `gorm:"column:content"`
CreatedAt int64 `gorm:"column:created_at"`
}
type inviteGiftContent struct {
OrderNo string `json:"order_no"`
Amount int64 `json:"amount"`
}
type parsedInviteRecordLog struct {
log inviteRecordLog
content inviteGiftContent
}
type inviteOrderUser struct {
OrderNo string `gorm:"column:order_no"`
UserId int64 `gorm:"column:user_id"`
}
// Get invite gift records
func NewGetInviteRecordsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetInviteRecordsLogic {
return &GetInviteRecordsLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequest) (resp *types.GetInviteRecordsResponse, err error) {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
l.Errorw("[GetInviteRecords] user not found in context")
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
normalizeInviteRecordsPagination(req)
query := l.svcCtx.DB.WithContext(l.ctx).
Table("system_logs").
Where("type = ? AND object_id = ?", logmodel.TypeGift.Uint8(), u.Id).
Where("JSON_VALID(content) = 1").
Where("JSON_UNQUOTE(JSON_EXTRACT(content, '$.remark')) = ?", "邀请赠送")
if req.StartTime > 0 {
query = query.Where("created_at >= FROM_UNIXTIME(?)", req.StartTime)
}
if req.EndTime > 0 {
query = query.Where("created_at <= FROM_UNIXTIME(?)", req.EndTime)
}
var total int64
if err = query.Count(&total).Error; err != nil {
l.Errorw("[GetInviteRecords] count logs failed",
logger.Field("error", err.Error()),
logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count logs failed: %v", err.Error())
}
var logs []inviteRecordLog
if err = query.
Select("id, object_id, content, CAST(UNIX_TIMESTAMP(created_at) * 1000 AS SIGNED) AS created_at").
Order("created_at DESC, id DESC").
Limit(req.Size).
Offset((req.Page - 1) * req.Size).
Scan(&logs).Error; err != nil {
l.Errorw("[GetInviteRecords] query logs failed",
logger.Field("error", err.Error()),
logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query logs failed: %v", err.Error())
}
parsedLogs, orderNos := l.parseInviteRecordContents(logs)
if len(logs) == 0 || len(parsedLogs) == 0 {
return &types.GetInviteRecordsResponse{Total: total, List: []types.InviteRecord{}}, nil
}
orders, err := l.queryInviteRecordOrders(orderNos)
if err != nil {
l.Errorw("[GetInviteRecords] query orders failed",
logger.Field("error", err.Error()),
logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query orders failed: %v", err.Error())
}
list := make([]types.InviteRecord, 0, len(parsedLogs))
for _, parsed := range parsedLogs {
content := parsed.content
logItem := parsed.log
record := types.InviteRecord{
Role: inviteRecordRoleInviter,
GiftDays: content.Amount,
OrderNo: content.OrderNo,
CreatedAt: logItem.CreatedAt,
}
if orderInfo, ok := orders[content.OrderNo]; ok {
peerId := orderInfo.UserId
if orderInfo.UserId == u.Id {
record.Role = inviteRecordRoleInvitee
peerId = u.RefererId
}
if peerId > 0 {
record.PeerHash = hash.InvitePeerHash(peerId)
}
}
list = append(list, record)
}
return &types.GetInviteRecordsResponse{
Total: total,
List: list,
}, nil
}
func normalizeInviteRecordsPagination(req *types.GetInviteRecordsRequest) {
if req.Page < 1 {
req.Page = 1
}
if req.Size < 1 {
req.Size = 10
}
if req.Size > 100 {
req.Size = 100
}
}
func (l *GetInviteRecordsLogic) parseInviteRecordContents(logs []inviteRecordLog) ([]parsedInviteRecordLog, []string) {
parsedLogs := make([]parsedInviteRecordLog, 0, len(logs))
orderNos := make([]string, 0, len(logs))
for _, logItem := range logs {
var content inviteGiftContent
if err := json.Unmarshal([]byte(logItem.Content), &content); err != nil {
l.Infow("[GetInviteRecords] parse content failed",
logger.Field("error", err.Error()),
logger.Field("log_id", logItem.Id))
continue
}
parsedLogs = append(parsedLogs, parsedInviteRecordLog{log: logItem, content: content})
if content.OrderNo != "" {
orderNos = append(orderNos, content.OrderNo)
}
}
return parsedLogs, orderNos
}
func (l *GetInviteRecordsLogic) queryInviteRecordOrders(orderNos []string) (map[string]inviteOrderUser, error) {
orders := make(map[string]inviteOrderUser, len(orderNos))
if len(orderNos) == 0 {
return orders, nil
}
var orderData []inviteOrderUser
err := l.svcCtx.DB.WithContext(l.ctx).
Model(&ordermodel.Order{}).
Select("order_no, user_id").
Where("order_no IN ?", orderNos).
Scan(&orderData).Error
if err != nil {
return nil, err
}
for _, item := range orderData {
orders[item.OrderNo] = item
}
return orders, nil
}
@@ -0,0 +1,157 @@
package user
import (
"context"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
modeluser "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/hash"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestGetInviteRecordsInviter(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
mock.ExpectQuery("count(*)").
WithArgs(34, int64(100), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(100), "邀请赠送", 10).
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(1, 100, `{"order_no":"order-1","amount":7,"remark":"邀请赠送"}`, 1779934580000))
mock.ExpectQuery("SELECT order_no, user_id FROM `order`").
WithArgs("order-1").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id"}).AddRow("order-1", 200))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(100, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
assertInviteRecordResponse(t, resp, types.InviteRecord{
Role: inviteRecordRoleInviter,
PeerHash: hash.InvitePeerHash(200),
GiftDays: 7,
OrderNo: "order-1",
CreatedAt: 1779934580000,
})
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsInvitee(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
mock.ExpectQuery("count(*)").
WithArgs(34, int64(200), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(200), "邀请赠送", 10).
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(2, 200, `{"order_no":"order-2","amount":7,"remark":"邀请赠送"}`, 1779934590000))
mock.ExpectQuery("SELECT order_no, user_id FROM `order`").
WithArgs("order-2").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id"}).AddRow("order-2", 200))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(200, 100), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
assertInviteRecordResponse(t, resp, types.InviteRecord{
Role: inviteRecordRoleInvitee,
PeerHash: hash.InvitePeerHash(100),
GiftDays: 7,
OrderNo: "order-2",
CreatedAt: 1779934590000,
})
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsMissingOrderReturnsDirtyRecord(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
mock.ExpectQuery("count(*)").
WithArgs(34, int64(100), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(100), "邀请赠送", 10).
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(3, 100, `{"order_no":"missing-order","amount":7,"remark":"邀请赠送"}`, 1779934600000))
mock.ExpectQuery("SELECT order_no, user_id FROM `order`").
WithArgs("missing-order").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id"}))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(100, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
assertInviteRecordResponse(t, resp, types.InviteRecord{
Role: inviteRecordRoleInviter,
GiftDays: 7,
OrderNo: "missing-order",
CreatedAt: 1779934600000,
})
assertInviteRecordsExpectations(t, mock)
}
func newInviteRecordsTestSvc(t *testing.T) (*svc.ServiceContext, sqlmock.Sqlmock, func()) {
t.Helper()
sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherFunc(func(expectedSQL, actualSQL string) error {
if strings.Contains(actualSQL, expectedSQL) {
return nil
}
return fmt.Errorf("actual sql %q does not contain %q", actualSQL, expectedSQL)
})))
if err != nil {
t.Fatalf("create sqlmock: %v", err)
}
db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{})
if err != nil {
_ = sqlDB.Close()
t.Fatalf("open gorm db: %v", err)
}
return &svc.ServiceContext{DB: db}, mock, func() {
_ = sqlDB.Close()
}
}
func inviteRecordsContext(userId, refererId int64) context.Context {
return context.WithValue(context.Background(), constant.CtxKeyUser, &modeluser.User{
Id: userId,
RefererId: refererId,
})
}
func assertInviteRecordResponse(t *testing.T, resp *types.GetInviteRecordsResponse, want types.InviteRecord) {
t.Helper()
if resp == nil {
t.Fatal("response is nil")
}
if resp.Total != 1 {
t.Fatalf("Total = %d, want 1", resp.Total)
}
if len(resp.List) != 1 {
t.Fatalf("len(List) = %d, want 1", len(resp.List))
}
if got := resp.List[0]; got != want {
t.Fatalf("record = %+v, want %+v", got, want)
}
}
func assertInviteRecordsExpectations(t *testing.T, mock sqlmock.Sqlmock) {
t.Helper()
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
@@ -1,145 +0,0 @@
package user
import (
"context"
"fmt"
"hash/fnv"
"strconv"
"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/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetInviteSalesLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetInviteSalesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetInviteSalesLogic {
return &GetInviteSalesLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetInviteSalesLogic) GetInviteSales(req *types.GetInviteSalesRequest) (resp *types.GetInviteSalesResponse, err error) {
// 1. Get current user
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
l.Errorw("[GetInviteSales] user not found in context")
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
userId := u.Id
// 2. Count total sales
var totalSales int64
db := l.svcCtx.DB.WithContext(l.ctx).
Table("`order` o").
Joins("JOIN user u ON o.user_id = u.id").
Where("u.referer_id = ? AND o.status IN ?", userId, []int{2, 5})
if req.StartTime > 0 {
db = db.Where("o.updated_at >= FROM_UNIXTIME(?)", req.StartTime)
}
if req.EndTime > 0 {
db = db.Where("o.updated_at <= FROM_UNIXTIME(?)", req.EndTime)
}
err = db.Count(&totalSales).Error
if err != nil {
l.Errorw("[GetInviteSales] count sales failed",
logger.Field("error", err.Error()),
logger.Field("user_id", userId))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
"count sales failed: %v", err.Error())
}
// 3. Pagination
if req.Page < 1 {
req.Page = 1
}
if req.Size < 1 {
req.Size = 10
}
if req.Size > 100 {
req.Size = 100
}
offset := (req.Page - 1) * req.Size
// 4. Get sales data
type OrderWithUser struct {
Amount int64 `gorm:"column:amount"`
UpdatedAt int64 `gorm:"column:updated_at"`
UserId int64 `gorm:"column:user_id"`
ProductName string `gorm:"column:product_name"`
Quantity int64 `gorm:"column:quantity"`
}
var orderData []OrderWithUser
query := l.svcCtx.DB.WithContext(l.ctx).
Table("`order` o").
Select("o.amount, CAST(UNIX_TIMESTAMP(o.updated_at) * 1000 AS SIGNED) as updated_at, u.id as user_id, s.name as product_name, o.quantity").
Joins("JOIN user u ON o.user_id = u.id").
Joins("LEFT JOIN subscribe s ON o.subscribe_id = s.id").
Where("u.referer_id = ? AND o.status IN ?", userId, []int{2, 5}) // status 2: Active, 5: Finished
if req.StartTime > 0 {
query = query.Where("o.updated_at >= FROM_UNIXTIME(?)", req.StartTime)
}
if req.EndTime > 0 {
query = query.Where("o.updated_at <= FROM_UNIXTIME(?)", req.EndTime)
}
err = query.Order("o.updated_at DESC").
Limit(req.Size).
Offset(offset).
Scan(&orderData).Error
if err != nil {
l.Errorw("[GetInviteSales] query sales failed",
logger.Field("error", err.Error()),
logger.Field("user_id", userId))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
"query sales failed: %v", err.Error())
}
// 5. Get sales list
const HashSalt = "ppanel_invite_sales_v1" // Fixed Key
var list []types.InvitedUserSale
for _, order := range orderData {
// Calculate unique numeric hash (FNV-64a)
h := fnv.New64a()
h.Write([]byte(HashSalt))
h.Write([]byte(strconv.FormatInt(order.UserId, 10)))
// Truncate to 10 digits using modulo 10^10
hashVal := h.Sum64() % 10000000000
userHashStr := fmt.Sprintf("%010d", hashVal)
// Format product name: prefer subscribe name, fallback to quantity-based label
productName := order.ProductName
if productName == "" {
productName = fmt.Sprintf("%d天VPN服务", order.Quantity)
if order.Quantity <= 0 {
productName = "VPN服务"
}
}
list = append(list, types.InvitedUserSale{
Amount: float64(order.Amount) / 100.0, // Convert cents to dollars
UpdatedAt: order.UpdatedAt,
UserHash: userHashStr,
ProductName: productName,
})
}
return &types.GetInviteSalesResponse{
Total: totalSales,
List: list,
}, nil
}
@@ -307,14 +307,24 @@ func (l *GetServerUserListLogic) canUseExpiredNodeGroup(userSub *user.Subscribe,
// calculateEffectiveSpeedLimit 计算用户的实际限速值(考虑按量限速规则)
func (l *GetServerUserListLogic) calculateEffectiveSpeedLimit(sub *subscribe.Subscribe, userSub *user.Subscribe) int64 {
baseSpeed := sub.SpeedLimit
if userSub.SpeedLimit > 0 {
baseSpeed = userSub.SpeedLimit
}
trafficLimit := sub.TrafficLimit
if userSub.TrafficLimit != nil && *userSub.TrafficLimit != "" {
trafficLimit = *userSub.TrafficLimit
}
result := speedlimit.CalculateWithCache(
l.ctx.Request.Context(),
l.svcCtx.Redis,
l.svcCtx.DB,
userSub.UserId,
userSub.Id,
sub.SpeedLimit,
sub.TrafficLimit,
baseSpeed,
trafficLimit,
30*time.Second,
)
return result.EffectiveSpeed
+170 -3
View File
@@ -2,6 +2,7 @@ package promo
import (
"context"
"errors"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
@@ -13,8 +14,28 @@ type RuleWithPrice struct {
}
type Model interface {
QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error)
QueryEligibleRules(ctx context.Context, subscribeId int64, quantity 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, page, size int, ruleType string, enabled *bool, search string) (int64, []*Rule, error)
UpsertPrices(ctx context.Context, ruleId int64, items []*SubscribePromo) error
FindPrice(ctx context.Context, id int64) (*SubscribePromo, error)
DeletePrice(ctx context.Context, id int64) error
QueryPriceList(ctx context.Context, ruleId int64, page, size int) (int64, []*SubscribePromo, error)
QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error)
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
type UsageFilter struct {
Page int
Size int
RuleId int64
UserId int64
SubscribeId int64
OrderNo string
}
type defaultPromoModel struct {
@@ -25,13 +46,13 @@ func NewModel(db *gorm.DB, _ *redis.Client) Model {
return &defaultPromoModel{db: db}
}
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) {
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64, quantity 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("sp.subscribe_id = ? AND sp.quantity = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, quantity, true).
Where("pr.deleted_at IS NULL").
Order("pr.priority DESC").
Order("pr.id ASC").
@@ -46,3 +67,149 @@ func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...
}
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 resp Rule
if err := m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", id).First(&resp).Error; err != nil {
return nil, err
}
return &resp, nil
}
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
return m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", data.Id).Updates(map[string]interface{}{
"name": data.Name,
"type": data.Type,
"params": data.Params,
"priority": data.Priority,
"enabled": data.Enabled,
"start_time": data.StartTime,
"end_time": data.EndTime,
}).Error
}
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
return m.db.WithContext(ctx).Delete(&Rule{}, id).Error
}
func (m *defaultPromoModel) QueryRuleList(ctx context.Context, page, size int, ruleType string, enabled *bool, search string) (int64, []*Rule, error) {
if page <= 0 {
page = 1
}
if size <= 0 {
size = 10
}
var total int64
var list []*Rule
db := m.db.WithContext(ctx).Model(&Rule{})
if ruleType != "" {
db = db.Where("type = ?", ruleType)
}
if enabled != nil {
db = db.Where("enabled = ?", *enabled)
}
if search != "" {
db = db.Where("name LIKE ?", "%"+search+"%")
}
if err := db.Count(&total).Error; err != nil {
return 0, nil, err
}
err := db.Order("priority DESC").Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
return total, list, err
}
func (m *defaultPromoModel) UpsertPrices(ctx context.Context, ruleId int64, items []*SubscribePromo) error {
return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for _, item := range items {
if item == nil {
continue
}
item.PromoRuleId = ruleId
var existing SubscribePromo
err := tx.Model(&SubscribePromo{}).
Where("subscribe_id = ? AND quantity = ? AND promo_rule_id = ?", item.SubscribeId, item.Quantity, ruleId).
First(&existing).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
if errors.Is(err, gorm.ErrRecordNotFound) {
if err := tx.Create(item).Error; err != nil {
return err
}
continue
}
existing.Quantity = item.Quantity
existing.PromoPrice = item.PromoPrice
if err := tx.Save(&existing).Error; err != nil {
return err
}
}
return nil
})
}
func (m *defaultPromoModel) FindPrice(ctx context.Context, id int64) (*SubscribePromo, error) {
var resp SubscribePromo
if err := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("id = ?", id).First(&resp).Error; err != nil {
return nil, err
}
return &resp, nil
}
func (m *defaultPromoModel) DeletePrice(ctx context.Context, id int64) error {
return m.db.WithContext(ctx).Delete(&SubscribePromo{}, id).Error
}
func (m *defaultPromoModel) QueryPriceList(ctx context.Context, ruleId int64, page, size int) (int64, []*SubscribePromo, error) {
if page <= 0 {
page = 1
}
if size <= 0 {
size = 10
}
var total int64
var list []*SubscribePromo
db := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("promo_rule_id = ?", ruleId)
if err := db.Count(&total).Error; err != nil {
return 0, nil, err
}
err := db.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
return total, list, err
}
func (m *defaultPromoModel) QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error) {
if params.Page <= 0 {
params.Page = 1
}
if params.Size <= 0 {
params.Size = 10
}
var total int64
var list []*Usage
db := m.db.WithContext(ctx).Model(&Usage{})
if params.RuleId > 0 {
db = db.Where("promo_rule_id = ?", params.RuleId)
}
if params.UserId > 0 {
db = db.Where("user_id = ?", params.UserId)
}
if params.SubscribeId > 0 {
db = db.Where("subscribe_id = ?", params.SubscribeId)
}
if params.OrderNo != "" {
db = db.Where("order_no = ?", params.OrderNo)
}
if err := db.Count(&total).Error; err != nil {
return 0, nil, err
}
err := db.Order("id DESC").Limit(params.Size).Offset((params.Page - 1) * params.Size).Find(&list).Error
return total, list, err
}
func (m *defaultPromoModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.db.WithContext(ctx).Transaction(fn)
}

Some files were not shown because too many files have changed in this diff Show More