Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 18df7e4d6b | |||
| 750b7be424 | |||
| aa11588c8f | |||
| c3050821d5 | |||
| 5b9f384f81 | |||
| 7236ca4cf2 | |||
| ae126296e3 | |||
| 1e99cfb83c | |||
| 0659a930f8 | |||
| c2d1b5a0d8 | |||
| 3644e9ce3f | |||
| e5d6539d79 | |||
| e17dc4a273 | |||
| b162022d39 | |||
| 075c1215ca | |||
| 8ba4471791 | |||
| 3e265bd837 | |||
| fefbd4f56a |
@@ -0,0 +1,50 @@
|
||||
syntax = "v1"
|
||||
|
||||
info (
|
||||
title: "Invite API"
|
||||
desc: "API for ppanel"
|
||||
author: "Tension"
|
||||
email: "tension@ppanel.com"
|
||||
version: "0.0.1"
|
||||
)
|
||||
|
||||
import "../types.api"
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -52,9 +52,10 @@ type (
|
||||
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"`
|
||||
RuleId int64 `form:"rule_id,omitempty"`
|
||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
||||
}
|
||||
GetPromoPriceListResponse {
|
||||
Total int64 `json:"total"`
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
@@ -229,6 +231,40 @@ type (
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
Reason string `json:"reason" validate:"required,max=500"`
|
||||
}
|
||||
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 {
|
||||
UserId int64 `form:"user_id" validate:"required"`
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
Search string `form:"search"`
|
||||
Enable *int `form:"enable"`
|
||||
UserIdSearch int64 `form:"user_id_search"`
|
||||
}
|
||||
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"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
@@ -381,4 +417,12 @@ service ppanel {
|
||||
@doc "Reject withdrawal"
|
||||
@handler RejectWithdrawal
|
||||
post /withdrawal/reject (RejectWithdrawalRequest)
|
||||
|
||||
@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)
|
||||
}
|
||||
|
||||
+2
-3
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -218,6 +218,22 @@ type (
|
||||
Total int64 `json:"total"`
|
||||
List []InviteRecord `json:"list"`
|
||||
}
|
||||
GetInviteSalesRequest {
|
||||
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"`
|
||||
}
|
||||
GetInviteSalesResponse {
|
||||
Total int64 `json:"total"`
|
||||
List []InvitedUserSale `json:"list"`
|
||||
}
|
||||
GetSubscribeStatusRequest {
|
||||
Email string `form:"email" json:"email" validate:"omitempty,email"`
|
||||
}
|
||||
@@ -402,6 +418,10 @@ service ppanel {
|
||||
@handler GetInviteRecords
|
||||
get /invite_records (GetInviteRecordsRequest) returns (GetInviteRecordsResponse)
|
||||
|
||||
@doc "Get Invite Sales"
|
||||
@handler GetInviteSales
|
||||
get /invite_sales (GetInviteSalesRequest) returns (GetInviteSalesResponse)
|
||||
|
||||
@doc "Get Subscribe Status"
|
||||
@handler GetSubscribeStatus
|
||||
post /subscribe_status (GetSubscribeStatusRequest) returns (GetSubscribeStatusResponse)
|
||||
|
||||
+23
-15
@@ -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,10 +228,11 @@ type (
|
||||
CurrencySymbol string `json:"currency_symbol"`
|
||||
}
|
||||
SubscribeDiscount {
|
||||
Quantity int64 `json:"quantity"`
|
||||
Discount float64 `json:"discount"`
|
||||
MapApple string `json:"map_apple"`
|
||||
Promo *SubscribePromo `json:"promo"`
|
||||
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"`
|
||||
@@ -293,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"`
|
||||
@@ -557,10 +561,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"`
|
||||
@@ -906,8 +913,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"`
|
||||
|
||||
@@ -0,0 +1,559 @@
|
||||
# App 邀请列表与商品套餐折扣需求梳理
|
||||
|
||||
本文基于当前 `ppanel-server` 代码现状,对以下两个需求做整理:
|
||||
|
||||
1. App 需要一个“邀请列表/邀请记录”接口。
|
||||
2. 商品套餐需要补充“折扣信息”,当存在折扣时,App 需要做样式展示,并支持用户继续下单购买。
|
||||
|
||||
目标是帮助产品、前端、后端快速统一口径,明确:
|
||||
|
||||
- 现在已有哪些接口可以复用
|
||||
- 哪些地方确实需要新增
|
||||
- “接口增加三个字段”更适合加在哪一层
|
||||
|
||||
---
|
||||
|
||||
## 1. 需求结论
|
||||
|
||||
### 1.1 邀请列表
|
||||
|
||||
当前公开侧已经有一部分邀请能力,但**没有一个完全匹配“App 邀请记录列表”语义的公开接口**。
|
||||
|
||||
现状:
|
||||
|
||||
- 已有 `GET /v1/public/user/affiliate/list`
|
||||
- 能返回“我邀请了哪些用户”
|
||||
- 但字段较少,只包含基础信息
|
||||
- 已有 `GET /v1/public/user/invite_sales`
|
||||
- 返回的是“被邀请用户的成交订单记录”
|
||||
- 不是“邀请用户记录列表”
|
||||
- 已有 `GET /v1/public/user/invite_stats`
|
||||
- 返回邀请统计
|
||||
- 不是列表
|
||||
|
||||
结论:
|
||||
|
||||
- 如果 App 只是要展示“我邀请了哪些人”,`/affiliate/list` 可以复用。
|
||||
- 如果 App 需要展示“邀请时间、是否购买、购买次数、带来的佣金/赠送天数”等完整邀请记录,则**建议新增一个公开接口**。
|
||||
|
||||
### 1.2 商品套餐折扣
|
||||
|
||||
当前公开侧套餐列表接口 `GET /v1/public/subscribe/list` **已经返回 `discount` 字段**,下单预览接口 `POST /v1/public/order/pre` 也已经支持折扣计算。
|
||||
|
||||
现状:
|
||||
|
||||
- 套餐列表已有折扣规则数组 `discount`
|
||||
- 预下单接口已有:
|
||||
- 原价 `price`
|
||||
- 实付 `amount`
|
||||
- 折扣金额 `discount`
|
||||
- 活动优惠 `promo_discount`
|
||||
- 优惠券减免 `coupon_discount`
|
||||
- 手续费 `fee_amount`
|
||||
|
||||
结论:
|
||||
|
||||
- 后端**不是完全没有折扣能力**,而是“已经有计算能力,但 App 展示层使用起来不够直接”。
|
||||
- 如果需求明确要求“接口增加三个字段”,**更推荐补在套餐列表返回的 `discount[]` 子项里**,而不是直接加在下单接口里。
|
||||
|
||||
---
|
||||
|
||||
## 2. 当前代码现状
|
||||
|
||||
## 2.1 邀请相关
|
||||
|
||||
### 2.1.1 已有公开接口
|
||||
|
||||
#### A. 邀请基础列表
|
||||
|
||||
接口:
|
||||
|
||||
- `GET /v1/public/user/affiliate/list`
|
||||
|
||||
请求:
|
||||
|
||||
- `page`
|
||||
- `size`
|
||||
|
||||
返回结构:
|
||||
|
||||
- `total`
|
||||
- `list[]`
|
||||
- `identifier`
|
||||
- `avatar`
|
||||
- `registered_at`
|
||||
- `enable`
|
||||
|
||||
特点:
|
||||
|
||||
- 能表达“我邀请了谁”
|
||||
- 不能表达“是否购买 / 购买次数 / 给我带来多少收益”
|
||||
|
||||
对应代码:
|
||||
|
||||
- `apis/public/user.api`
|
||||
- `internal/logic/public/user/queryUserAffiliateListLogic.go`
|
||||
|
||||
#### B. 邀请成交记录
|
||||
|
||||
接口:
|
||||
|
||||
- `GET /v1/public/user/invite_sales`
|
||||
|
||||
返回结构:
|
||||
|
||||
- `total`
|
||||
- `list[]`
|
||||
- `amount`
|
||||
- `updated_at`
|
||||
- `user_hash`
|
||||
- `product_name`
|
||||
|
||||
特点:
|
||||
|
||||
- 更像“邀请带来的订单流水”
|
||||
- 不是邀请用户列表
|
||||
|
||||
对应代码:
|
||||
|
||||
- `internal/logic/public/user/getInviteSalesLogic.go`
|
||||
|
||||
#### C. 邀请统计
|
||||
|
||||
接口:
|
||||
|
||||
- `GET /v1/public/user/invite_stats`
|
||||
|
||||
返回结构:
|
||||
|
||||
- `friendly_count`
|
||||
- `history_count`
|
||||
|
||||
特点:
|
||||
|
||||
- 只适合头部统计卡片
|
||||
- 不适合列表页
|
||||
|
||||
对应代码:
|
||||
|
||||
- `internal/logic/public/user/getUserInviteStatsLogic.go`
|
||||
|
||||
### 2.1.2 已有后台接口
|
||||
|
||||
后台已经有更完整的邀请记录能力,可以直接参考:
|
||||
|
||||
- `GetAdminUserInviteList`
|
||||
- `GetInviteManageList`
|
||||
|
||||
这些接口已经能返回:
|
||||
|
||||
- 邀请时间
|
||||
- 是否购买
|
||||
- 购买次数
|
||||
- 邀请人佣金
|
||||
- 邀请人赠送天数
|
||||
- 被邀请人赠送天数
|
||||
|
||||
对应代码:
|
||||
|
||||
- `internal/logic/admin/user/getAdminUserInviteListLogic.go`
|
||||
- `internal/logic/admin/invite/getInviteManageListLogic.go`
|
||||
|
||||
结论:
|
||||
|
||||
- 邀请记录的统计逻辑后端已经有现成实现思路。
|
||||
- 新增 App 公开接口时,建议复用这部分逻辑,不要从零再写一套。
|
||||
|
||||
---
|
||||
|
||||
## 2.2 套餐折扣相关
|
||||
|
||||
### 2.2.1 套餐列表接口已有折扣规则
|
||||
|
||||
接口:
|
||||
|
||||
- `GET /v1/public/subscribe/list`
|
||||
|
||||
当前返回的套餐结构 `Subscribe` 中已包含:
|
||||
|
||||
- `unit_price`
|
||||
- `discount []SubscribeDiscount`
|
||||
|
||||
其中 `SubscribeDiscount` 当前字段为:
|
||||
|
||||
- `quantity`
|
||||
- `discount`
|
||||
- `new_user_only`
|
||||
- `map_apple`
|
||||
- `promo`
|
||||
|
||||
对应代码:
|
||||
|
||||
- `apis/public/subscribe.api`
|
||||
- `internal/logic/public/subscribe/querySubscribeListLogic.go`
|
||||
- `internal/types/types.go`
|
||||
|
||||
说明:
|
||||
|
||||
- `discount` 是按购买数量 `quantity` 生效的阶梯折扣
|
||||
- 不是单个套餐固定只有一个折扣值
|
||||
|
||||
### 2.2.2 预下单接口已有价格计算结果
|
||||
|
||||
接口:
|
||||
|
||||
- `POST /v1/public/order/pre`
|
||||
|
||||
当前已返回:
|
||||
|
||||
- `price`:原价
|
||||
- `amount`:最终应付
|
||||
- `discount`:折扣减免金额
|
||||
- `promo_discount`:活动优惠金额
|
||||
- `gift_amount`:礼品余额抵扣
|
||||
- `coupon_discount`:优惠券减免
|
||||
- `fee_amount`:手续费
|
||||
|
||||
对应代码:
|
||||
|
||||
- `apis/public/order.api`
|
||||
- `internal/logic/public/order/preCreateOrderLogic.go`
|
||||
|
||||
说明:
|
||||
|
||||
- 只要 App 知道 `subscribe_id + quantity [+ coupon] [+ payment]`,就已经能拿到准确的下单金额
|
||||
- 所以“下单购买”这件事本身,后端主链路已经具备
|
||||
|
||||
---
|
||||
|
||||
## 3. 差距分析
|
||||
|
||||
## 3.1 邀请列表的真实缺口
|
||||
|
||||
如果产品要的是“邀请记录页”,通常至少会关心以下内容:
|
||||
|
||||
- 被邀请用户
|
||||
- 邀请时间
|
||||
- 是否已购买
|
||||
- 购买次数
|
||||
- 给邀请人带来的佣金
|
||||
- 双方赠送天数
|
||||
|
||||
而当前:
|
||||
|
||||
- `/affiliate/list` 只有基础用户列表
|
||||
- `/invite_sales` 是订单成交记录
|
||||
- `/invite_stats` 是统计值
|
||||
|
||||
所以当前公开侧缺一个“**邀请关系维度的邀请记录列表**”。
|
||||
|
||||
## 3.2 套餐折扣的真实缺口
|
||||
|
||||
后端目前的主要问题不是“不会算折扣”,而是:
|
||||
|
||||
- `discount[]` 更偏规则定义
|
||||
- App 如果只想直接展示“折后价 / 优惠金额 / 折扣标签”,还需要自己再算一层
|
||||
- 这会增加前端理解成本,也容易和后端口径不一致
|
||||
|
||||
所以当前更合理的改法是:
|
||||
|
||||
- 保留现有折扣规则
|
||||
- 再额外补充几个**面向展示的字段**
|
||||
|
||||
---
|
||||
|
||||
## 4. 推荐方案
|
||||
|
||||
## 4.1 邀请记录接口
|
||||
|
||||
### 方案建议
|
||||
|
||||
新增一个公开接口,例如:
|
||||
|
||||
- `GET /v1/public/user/invite_records`
|
||||
|
||||
说明:
|
||||
|
||||
- 从登录态中取当前用户 ID
|
||||
- 不从前端传 `user_id`
|
||||
- 只查“当前用户邀请的记录”
|
||||
|
||||
### 请求参数建议
|
||||
|
||||
```json
|
||||
{
|
||||
"page": 1,
|
||||
"size": 10
|
||||
}
|
||||
```
|
||||
|
||||
### 返回字段建议
|
||||
|
||||
```json
|
||||
{
|
||||
"total": 2,
|
||||
"list": [
|
||||
{
|
||||
"invitee_id": 1001,
|
||||
"invitee_identifier": "138****8888",
|
||||
"invitee_avatar": "https://...",
|
||||
"invitee_enable": true,
|
||||
"invited_at": 1716800000,
|
||||
"order_count": 3,
|
||||
"has_purchased": true,
|
||||
"inviter_commission": 1200,
|
||||
"inviter_gift_days": 30,
|
||||
"invitee_gift_days": 7
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 字段说明
|
||||
|
||||
- `invitee_id`:被邀请用户 ID
|
||||
- `invitee_identifier`:被邀请用户展示账号
|
||||
- `invitee_avatar`:头像
|
||||
- `invitee_enable`:是否启用
|
||||
- `invited_at`:邀请时间
|
||||
- `order_count`:该被邀请用户产生的有效订单数
|
||||
- `has_purchased`:是否已购买
|
||||
- `inviter_commission`:给邀请人带来的佣金,单位建议继续沿用分
|
||||
- `inviter_gift_days`:邀请人获赠天数
|
||||
- `invitee_gift_days`:被邀请人获赠天数
|
||||
|
||||
### 实现建议
|
||||
|
||||
优先复用现有后台逻辑思路:
|
||||
|
||||
- 参考 `internal/logic/admin/user/getAdminUserInviteListLogic.go`
|
||||
- 或参考 `internal/logic/admin/invite/getInviteManageListLogic.go`
|
||||
|
||||
公开接口与后台接口的主要差异只有两点:
|
||||
|
||||
- 公开接口不允许前端指定 `user_id`
|
||||
- 公开接口按当前登录用户本人维度返回
|
||||
|
||||
### 是否可以不新增接口
|
||||
|
||||
可以,但前提是 App 接受以下拆分:
|
||||
|
||||
- 列表页用 `/affiliate/list`
|
||||
- 顶部统计用 `/invite_stats`
|
||||
- 订单流水页用 `/invite_sales`
|
||||
|
||||
如果产品要的是一个完整“邀请记录页”,不建议这样拆三次请求,前端维护成本偏高。
|
||||
|
||||
---
|
||||
|
||||
## 4.2 套餐折扣字段建议
|
||||
|
||||
### 核心建议
|
||||
|
||||
“接口增加三个字段”建议**加在 `SubscribeDiscount` 子项里**,不要直接加在 `Subscribe` 顶层。
|
||||
|
||||
原因:
|
||||
|
||||
- 折扣是按 `quantity` 生效的
|
||||
- 一个套餐可能有多个折扣档位
|
||||
- 如果加在套餐顶层,很难表达“买 1 个月”和“买 12 个月”对应不同折扣
|
||||
|
||||
### 推荐新增字段
|
||||
|
||||
建议在 `SubscribeDiscount` 中增加以下三个展示字段:
|
||||
|
||||
- `discount_price`
|
||||
- `discount_amount`
|
||||
- `discount_desc`
|
||||
|
||||
推荐结构如下:
|
||||
|
||||
```json
|
||||
{
|
||||
"quantity": 12,
|
||||
"discount": 80,
|
||||
"new_user_only": false,
|
||||
"map_apple": "",
|
||||
"promo": null,
|
||||
"discount_price": 9600,
|
||||
"discount_amount": 2400,
|
||||
"discount_desc": "年付8折"
|
||||
}
|
||||
```
|
||||
|
||||
### 三个字段的含义
|
||||
|
||||
#### 1. `discount_price`
|
||||
|
||||
- 含义:该档位折后总价
|
||||
- 计算建议:`unit_price * quantity * discount / 100`
|
||||
- 单位:分
|
||||
|
||||
作用:
|
||||
|
||||
- App 可直接展示“折后价”
|
||||
- 下单时直接把该项的 `quantity` 带入 `/order/pre` 或 `/order/purchase`
|
||||
|
||||
#### 2. `discount_amount`
|
||||
|
||||
- 含义:该档位比原价便宜多少钱
|
||||
- 计算建议:`unit_price * quantity - discount_price`
|
||||
- 单位:分
|
||||
|
||||
作用:
|
||||
|
||||
- App 可直接展示“立省 xx”
|
||||
|
||||
#### 3. `discount_desc`
|
||||
|
||||
- 含义:折扣展示文案
|
||||
- 示例:
|
||||
- `年付8折`
|
||||
- `季付9折`
|
||||
- `新用户首单8折`
|
||||
|
||||
作用:
|
||||
|
||||
- App 可直接做角标、标签、促销文案展示
|
||||
|
||||
### 为什么不推荐这三个字段加在下单接口
|
||||
|
||||
因为下单接口本来就是“结果型接口”,它已经能返回:
|
||||
|
||||
- 原价
|
||||
- 折扣金额
|
||||
- 实付金额
|
||||
|
||||
如果只是为了 App 卡片展示,再去每个套餐都调一次 `/order/pre`,成本会比较高:
|
||||
|
||||
- 请求次数多
|
||||
- 页面首屏会更慢
|
||||
- 前端链路更复杂
|
||||
|
||||
更合适的做法是:
|
||||
|
||||
- 套餐列表接口负责“展示友好”
|
||||
- 预下单接口负责“结算准确”
|
||||
|
||||
---
|
||||
|
||||
## 5. 推荐改动清单
|
||||
|
||||
## 5.1 邀请列表
|
||||
|
||||
建议新增:
|
||||
|
||||
- 新接口:`GET /v1/public/user/invite_records`
|
||||
|
||||
建议新增类型:
|
||||
|
||||
- `GetUserInviteRecordsRequest`
|
||||
- `UserInviteRecord`
|
||||
- `GetUserInviteRecordsResponse`
|
||||
|
||||
建议实现位置:
|
||||
|
||||
- `apis/public/user.api`
|
||||
- `internal/types/types.go`
|
||||
- `internal/handler/public/user/`
|
||||
- `internal/logic/public/user/`
|
||||
|
||||
## 5.2 套餐折扣
|
||||
|
||||
建议调整:
|
||||
|
||||
- `SubscribeDiscount` 增加 3 个字段:
|
||||
- `discount_price`
|
||||
- `discount_amount`
|
||||
- `discount_desc`
|
||||
|
||||
建议实现位置:
|
||||
|
||||
- `apis/types.api`
|
||||
- `internal/types/types.go`
|
||||
- `internal/logic/public/subscribe/querySubscribeListLogic.go`
|
||||
|
||||
---
|
||||
|
||||
## 6. 前后端协作建议
|
||||
|
||||
## 6.1 App 侧调用建议
|
||||
|
||||
邀请页建议:
|
||||
|
||||
- 头部统计:`/v1/public/user/invite_stats`
|
||||
- 邀请记录列表:`/v1/public/user/invite_records`
|
||||
- 如果还要看成交流水:`/v1/public/user/invite_sales`
|
||||
|
||||
套餐页建议:
|
||||
|
||||
- 先调 `/v1/public/subscribe/list` 渲染套餐和折扣标签
|
||||
- 用户点某个折扣档位时,带 `subscribe_id + quantity` 调 `/v1/public/order/pre`
|
||||
- 用户确认后再调 `/v1/public/order/purchase`
|
||||
|
||||
## 6.2 单位口径建议
|
||||
|
||||
建议继续保持后端金额统一为“分”:
|
||||
|
||||
- `unit_price`
|
||||
- `discount_price`
|
||||
- `discount_amount`
|
||||
- `amount`
|
||||
- `coupon_discount`
|
||||
|
||||
这样可以避免前后端出现小数精度问题。
|
||||
|
||||
---
|
||||
|
||||
## 7. 最终建议
|
||||
|
||||
### 建议一
|
||||
|
||||
如果你们只是要“邀请用户名单”,可直接复用:
|
||||
|
||||
- `GET /v1/public/user/affiliate/list`
|
||||
|
||||
### 建议二
|
||||
|
||||
如果你们要的是完整“邀请记录”,建议新增:
|
||||
|
||||
- `GET /v1/public/user/invite_records`
|
||||
|
||||
这是本次需求里更合理的新增接口。
|
||||
|
||||
### 建议三
|
||||
|
||||
商品套餐“折扣信息”不建议重新设计一整套下单逻辑。
|
||||
|
||||
当前后端已经具备:
|
||||
|
||||
- 套餐折扣规则
|
||||
- 预下单价格计算
|
||||
- 正式下单购买
|
||||
|
||||
更推荐做法是:
|
||||
|
||||
- 在 `SubscribeDiscount` 里补 3 个展示字段:
|
||||
- `discount_price`
|
||||
- `discount_amount`
|
||||
- `discount_desc`
|
||||
|
||||
这样改动最小,也最贴近 App 展示场景。
|
||||
|
||||
---
|
||||
|
||||
## 8. 相关代码位置
|
||||
|
||||
- `internal/logic/public/user/queryUserAffiliateListLogic.go`
|
||||
- `internal/logic/public/user/getInviteSalesLogic.go`
|
||||
- `internal/logic/public/user/getUserInviteStatsLogic.go`
|
||||
- `internal/logic/admin/user/getAdminUserInviteListLogic.go`
|
||||
- `internal/logic/admin/invite/getInviteManageListLogic.go`
|
||||
- `internal/logic/public/subscribe/querySubscribeListLogic.go`
|
||||
- `internal/logic/public/order/preCreateOrderLogic.go`
|
||||
- `internal/logic/public/order/purchaseLogic.go`
|
||||
- `internal/types/types.go`
|
||||
- `apis/public/user.api`
|
||||
- `apis/public/subscribe.api`
|
||||
- `apis/public/order.api`
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
# App 端三个接口对接文档
|
||||
|
||||
> 适用:移动端 / 桌面端 App
|
||||
> 维护:基于当前 `internal/handler` + `internal/logic` 代码反向梳理
|
||||
> 时间:2026-05-27
|
||||
|
||||
涉及接口:
|
||||
|
||||
1. [文件上传](#1-文件上传) — `POST /v1/public/file/upload`
|
||||
2. [订阅列表(含促销 promo)](#2-订阅列表含促销-promo) — `GET /v1/public/subscribe/list`
|
||||
3. [邀请赠送记录](#3-邀请赠送记录) — `GET /v1/public/user/invite_records`
|
||||
|
||||
公共说明:
|
||||
|
||||
- BaseURL 示例:`https://tapi.hifast.biz`
|
||||
- 鉴权头:`Authorization: <JWT>`(注意:**不要**写 `Bearer ` 前缀,本项目 `AuthMiddleware` 直接取 token 值)
|
||||
- 业务码包在 `{ code, msg, data }` 信封中,`code = 200` 为成功
|
||||
- 默认 `Accept: application/json`,可选 `lang: zh_CN`
|
||||
- 经过 `AuthMiddleware` + `DeviceMiddleware` 的接口都需要登录态 + 设备绑定校验
|
||||
|
||||
---
|
||||
|
||||
## 1. 文件上传
|
||||
|
||||
### 1.1 Endpoint
|
||||
|
||||
```
|
||||
POST /v1/public/file/upload
|
||||
Content-Type: multipart/form-data
|
||||
```
|
||||
|
||||
- Handler: `internal/handler/public/file/fileUploadHandler.go`
|
||||
- Logic: `internal/logic/public/file/fileuploadlogic.go:33`
|
||||
- 路由: `internal/handler/routes.go:934`
|
||||
- 中间件: `AuthMiddleware` + `DeviceMiddleware`(必须登录)
|
||||
|
||||
### 1.2 请求
|
||||
|
||||
#### Form 参数
|
||||
|
||||
| 字段 | 位置 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `biz_type` | form | 是 | 业务分类标签,会作为对象 key 的一部分(如 `app-package`、`avatar`) |
|
||||
| `file` | form file | 是 | 待上传文件二进制 |
|
||||
|
||||
#### 文件约束(来自 `etc/ppanel.yaml` → `S3`,可调整)
|
||||
|
||||
| 项 | 默认值 |
|
||||
|---|---|
|
||||
| 单文件最大 | **104857600 字节(100 MiB)** |
|
||||
| 允许的 Content-Type | `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` |
|
||||
|
||||
> Content-Type 判定优先级:multipart 文件头里的 `Content-Type` → 文件嗅探(前 512 字节)→ 兜底 `application/octet-stream`。
|
||||
> **前端 form 上传时尽量带上 `Content-Type`**,否则被嗅探成 `application/octet-stream` 可能不在白名单里。
|
||||
|
||||
### 1.3 请求示例
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload' \
|
||||
-H 'Authorization: <JWT>' \
|
||||
-H 'Accept: application/json' \
|
||||
-F 'biz_type=app-package' \
|
||||
-F 'file=@"/Users/Apple/Documents/avatar.jpg";type=image/jpeg'
|
||||
```
|
||||
|
||||
### 1.4 响应
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `data.url` | string | 上传完成后的可访问 URL,规则:`{S3.PublicBaseURL or S3.Endpoint}/{bucket}/{prefix}/{YYYY}/{MM}/{DD}/{userId}/{safeFileName}__{fileId}` |
|
||||
|
||||
成功示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"data": {
|
||||
"url": "http://107.173.50.22:5016/hifastvpn/app-upload/2026/05/28/510/2026-05-27_20.03.55.jpg__226ad097c2ee4e3546e729c5"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 1.5 错误码
|
||||
|
||||
| 业务码 | 触发场景 |
|
||||
|---|---|
|
||||
| `InvalidAccess` | 未登录 / JWT 无效 |
|
||||
| `ParamError` | 缺少 `biz_type` 或 `file` |
|
||||
| `InvalidParams` | `biz_type` 为空、文件名为空、size <= 0、超过 `MaxUploadSize`、`Content-Type` 不在白名单 |
|
||||
| `ERROR` | S3 未启用(`S3.Enable=false`) / S3 写入失败 |
|
||||
|
||||
### 1.6 前端易踩坑
|
||||
|
||||
1. `file` 字段名必须是 `file`,写 `image` / `upload` 都不行。
|
||||
2. `biz_type` 走 form 字段(`form:"biz_type"`),不要塞 query 里。
|
||||
3. 上传成功只返回 `url`,不返回 `file_id` / 大小等元数据;如需附加元数据,请走分片协议 `POST /upload/init` + `POST /upload/complete`。
|
||||
4. 想上传 PDF / DOC 不会成功——白名单里没有,需要后端调 `S3.AllowedContentTypes`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 订阅列表(含促销 promo)
|
||||
|
||||
### 2.1 Endpoint
|
||||
|
||||
```
|
||||
GET /v1/public/subscribe/list
|
||||
```
|
||||
|
||||
- Handler: `internal/handler/public/subscribe/querySubscribeListHandler.go`
|
||||
- Logic: `internal/logic/public/subscribe/querySubscribeListLogic.go:32`
|
||||
- Promo 合并逻辑: `internal/logic/public/subscribe/promo.go`
|
||||
- 路由: `internal/handler/routes.go:1026`
|
||||
- 中间件: **`OptionalAuthMiddleware` + `DeviceMiddleware`**(**未登录也能请求**,但未登录时只能拿到 `rule_type = campaign` 的促销)
|
||||
|
||||
### 2.2 请求
|
||||
|
||||
#### Query 参数
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `language` | string | 否 | 语言筛选,传值后返回该语言版本;不传则按系统默认语言返回 |
|
||||
|
||||
#### 头部说明(影响返回内容)
|
||||
|
||||
| Header | 影响 |
|
||||
|---|---|
|
||||
| `Authorization` | 传则识别为登录态,能拿到 `new_user` / `inactive_user` 类型的个性化促销;不传只返回 `campaign` 类型 |
|
||||
| `X-App-Id` | **不传**会被识别为"老版本客户端",每个套餐的 `discount` 列表会被**截掉最后一个元素**。新版 App 必须带 `X-App-Id` |
|
||||
|
||||
### 2.3 请求示例
|
||||
|
||||
```bash
|
||||
curl -X GET 'https://tapi.hifast.biz/v1/public/subscribe/list?language=zh-CN' \
|
||||
-H 'Authorization: <JWT>' \
|
||||
-H 'X-App-Id: hifast-ios' \
|
||||
-H 'Accept: application/json'
|
||||
```
|
||||
|
||||
### 2.4 响应
|
||||
|
||||
#### 顶层
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `data.total` | int64 | 返回的套餐数量(= `len(list)`,不是数据库总数) |
|
||||
| `data.list` | Subscribe[] | 套餐列表 |
|
||||
|
||||
#### `Subscribe` 关键字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | int64 | 套餐 ID |
|
||||
| `name` | string | 套餐名 |
|
||||
| `language` | string | 当前返回的语言版本 |
|
||||
| `description` | string | 套餐描述(可能是富文本/Markdown) |
|
||||
| `unit_price` | int64 | 单时间单位**原价**,单位:**分** |
|
||||
| `unit_time` | string | 时间单位,枚举:`Day` / `Month` / `Year`(注意首字母大写) |
|
||||
| `discount` | SubscribeDiscount[] | 量级折扣 + 促销,按 `quantity` 升序 |
|
||||
| `node_count` | int64 | 节点数 |
|
||||
| `traffic` | int64 | 套餐总流量,单位:字节 |
|
||||
| `speed_limit` | int64 | 限速,单位见后端约定 |
|
||||
| `device_limit` | int64 | 同时在线设备数限制 |
|
||||
| `quota` | int64 | 总配额 |
|
||||
| `show` | bool | 是否在前端展示 |
|
||||
| `sell` | bool | 是否可售卖(本接口只返回 `sell=true`) |
|
||||
| `show_original_price` | bool | 是否展示划线原价 |
|
||||
| `reset_cycle` | int64 | 流量重置周期 |
|
||||
| `renewal_reset` | bool | 续费时是否重置流量 |
|
||||
| `created_at` / `updated_at` | int64 | 秒级 Unix 时间戳 |
|
||||
|
||||
#### `SubscribeDiscount` 字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `quantity` | int64 | 购买的时间单位数量(如 1 = 1 个月,3 = 3 个月) |
|
||||
| `discount` | float64 | 量级折扣比例,0 表示无折扣,0.05 表示再优惠 5% |
|
||||
| `map_apple` | string | 对应 Apple IAP 商品 ID |
|
||||
| `promo` | SubscribePromo \| null | **#77 新增的促销对象**,命中促销规则时下发,否则为 `null` |
|
||||
|
||||
#### `SubscribePromo` 字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `rule_name` | string | 促销规则名(运营在后台填写,可直接给用户展示,如"新人首单 8 折") |
|
||||
| `rule_type` | string | 规则类型枚举(见下表) |
|
||||
| `promo_price` | int64 | **促销价**,单位:**分**。优先级高于 `unit_price * discount`,前端命中促销时按此价显示 |
|
||||
| `expires_at` | int64 | 该促销对当前用户的失效时间(**秒级 Unix**),`0` 表示无明确截止 |
|
||||
|
||||
#### `rule_type` 枚举
|
||||
|
||||
| 值 | 含义 | 资格判定 |
|
||||
|---|---|---|
|
||||
| `campaign` | 全员/限时活动 | 仅看 `start_time` / `end_time` 是否在窗口内;**未登录也会下发** |
|
||||
| `new_user` | 新用户首单 | 登录用户,且 `now < user.created_at + params.window_hours`;`expires_at = user.created_at + window_hours` |
|
||||
| `inactive_user` | 老用户唤回 | 登录用户,且距离最近一个订阅过期已超过 `params.inactive_months` 个月;`expires_at = 规则 end_time` |
|
||||
|
||||
> 多条促销规则命中同一 `(subscribe_id, quantity)` 时,按 `priority DESC, id ASC` 取**首条**,不是合并。
|
||||
|
||||
### 2.5 响应示例
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"data": {
|
||||
"total": 1,
|
||||
"list": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "月付套餐",
|
||||
"language": "zh-CN",
|
||||
"description": "...",
|
||||
"unit_price": 1000,
|
||||
"unit_time": "Month",
|
||||
"show_original_price": true,
|
||||
"node_count": 30,
|
||||
"traffic": 107374182400,
|
||||
"device_limit": 3,
|
||||
"discount": [
|
||||
{
|
||||
"quantity": 1,
|
||||
"discount": 0,
|
||||
"map_apple": "ios.month1",
|
||||
"promo": {
|
||||
"rule_name": "新人首单 8 折",
|
||||
"rule_type": "new_user",
|
||||
"promo_price": 800,
|
||||
"expires_at": 1780500000
|
||||
}
|
||||
},
|
||||
{
|
||||
"quantity": 3,
|
||||
"discount": 0.05,
|
||||
"map_apple": "ios.month3",
|
||||
"promo": null
|
||||
}
|
||||
],
|
||||
"show": true,
|
||||
"sell": true,
|
||||
"created_at": 1764547200,
|
||||
"updated_at": 1779934580
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.6 价格计算建议(前端)
|
||||
|
||||
对每个 `discount` 元素:
|
||||
|
||||
```
|
||||
原价 = unit_price * quantity
|
||||
量级折后价 = round(原价 * (1 - discount))
|
||||
|
||||
if promo != null:
|
||||
实付 = promo.promo_price * quantity // 注意:promo_price 是「单价」,乘以 quantity
|
||||
划线价 = 原价 // 用于展示「省 XX」
|
||||
else:
|
||||
实付 = 量级折后价
|
||||
划线价 = 原价(show_original_price=true 时展示)
|
||||
```
|
||||
|
||||
> 注意:`promo_price` 设计为**单价**(与 `unit_price` 同级),不是总价。
|
||||
> 命中促销时建议同时显示 `rule_name`("新人首单 8 折")和倒计时(基于 `expires_at`)。
|
||||
|
||||
### 2.7 前端易踩坑
|
||||
|
||||
1. **必带 `X-App-Id`**——否则 `discount` 数组最后一个会被砍掉。
|
||||
2. **促销分登录态**:未登录时只能拿到 `campaign`;未拿到 `new_user`/`inactive_user` 时先检查是否传了 `Authorization`。
|
||||
3. **`unit_time` 是 PascalCase**:`Day` / `Month` / `Year`,别小写匹配。
|
||||
4. **金额单位都是分**(`unit_price`、`promo_price`),展示时除以 100。
|
||||
5. **`expires_at = 0`** 表示无截止,不要展示成 1970 年。
|
||||
6. `total` 是当前返回的条数,不是数据库总数(接口在 logic 里强制 `Size: 9999`,相当于不分页)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 邀请赠送记录
|
||||
|
||||
> 当前用户的"邀请赠送天数"流水。包含两类:
|
||||
> - 当前用户作为**邀请人**,被邀请的朋友下单触发的赠送;
|
||||
> - 当前用户作为**被邀请人**,自己下单触发的对应赠送(双向赠送)。
|
||||
>
|
||||
> 数据源:`system_logs` 表,`type = 33 (TypeGift)` 且 `content.remark = "邀请赠送"`。
|
||||
> 这里**只是赠送天数**,不包含邀请佣金(请走 affiliate 系列接口)。
|
||||
|
||||
### 3.1 Endpoint
|
||||
|
||||
```
|
||||
GET /v1/public/user/invite_records
|
||||
```
|
||||
|
||||
- Handler: `internal/handler/public/user/getInviteRecordsHandler.go`
|
||||
- Logic: `internal/logic/public/user/getInviteRecordsLogic.go:61`
|
||||
- 路由: `internal/handler/routes.go:1122`
|
||||
- 中间件: `AuthMiddleware` + `DeviceMiddleware`(必须登录)
|
||||
|
||||
### 3.2 请求
|
||||
|
||||
#### Query 参数
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `page` | int | 否 | `1` | 页码,<1 自动归一为 1 |
|
||||
| `size` | int | 否 | `10` | 每页条数,<1 归一为 10,**>100 截断为 100** |
|
||||
| `start_time` | int64 | 否 | `0` | 起始时间(**秒级 Unix**),`0` 表示不过滤下界 |
|
||||
| `end_time` | int64 | 否 | `0` | 截止时间(**秒级 Unix**),`0` 表示不过滤上界 |
|
||||
|
||||
> ⚠️ `start_time` / `end_time` 单位是**秒**(后端用 `FROM_UNIXTIME(?)`)。传毫秒会过滤掉所有记录。
|
||||
|
||||
#### 请求示例
|
||||
|
||||
```bash
|
||||
# 不带时间过滤
|
||||
curl -X GET 'https://tapi.hifast.biz/v1/public/user/invite_records?page=1&size=20' \
|
||||
-H 'Authorization: <JWT>' \
|
||||
-H 'Accept: application/json'
|
||||
|
||||
# 带时间过滤
|
||||
curl -X GET 'https://tapi.hifast.biz/v1/public/user/invite_records?page=1&size=20&start_time=1764547200&end_time=1780099200' \
|
||||
-H 'Authorization: <JWT>'
|
||||
```
|
||||
|
||||
> 旧 curl 模板里的 `--data-urlencode 'page=1'` 等对 GET 是 form body,不会被读取,请用 query string。
|
||||
|
||||
### 3.3 响应
|
||||
|
||||
#### 顶层
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `data.total` | int64 | 当前过滤条件下的**记录总数**(用于分页) |
|
||||
| `data.list` | InviteRecord[] | 当前页列表,可能为空数组 `[]` |
|
||||
|
||||
#### `InviteRecord` 字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `role` | string | 当前用户在该条记录中的角色:`inviter` 或 `invitee`(详见下表) |
|
||||
| `peer_hash` | string | 对端用户的脱敏哈希(10 位定长数字字符串),用于"匿名展示朋友"。订单已删 / 对端 id 缺失时为 `""` |
|
||||
| `gift_days` | int64 | 本次赠送天数(来源 `system_logs.content.amount`) |
|
||||
| `order_no` | string | 触发本次赠送的订单号 |
|
||||
| `created_at` | int64 | 赠送时间,**毫秒级 Unix**(SQL 端 `UNIX_TIMESTAMP(created_at) * 1000`) |
|
||||
|
||||
> ⚠️ **时间戳单位不一致**:请求里的 `start_time/end_time` 是**秒**,响应里的 `created_at` 是**毫秒**。前端请区分对待。
|
||||
> (与项目其它接口"统一秒级"约定不同,是该接口的当前实现。)
|
||||
|
||||
#### `role` 取值
|
||||
|
||||
| 值 | 含义 | `peer_hash` 来源 |
|
||||
|---|---|---|
|
||||
| `inviter` | 当前用户是**邀请人**,朋友下单触发的赠送 | 被邀请人(即订单的 `user_id`)的脱敏 hash |
|
||||
| `invitee` | 当前用户是**被邀请人**,自己下单触发的赠送 | 邀请人(`user.referer_id`)的脱敏 hash |
|
||||
|
||||
判定规则:默认 `inviter`;若 `order.user_id == 当前用户 id`,切换为 `invitee` 并改用 `referer_id` 计算 hash。
|
||||
|
||||
#### 排序与分页
|
||||
|
||||
- 排序:`created_at DESC, id DESC`(最近一条在最前)
|
||||
- 分页:`LIMIT size OFFSET (page-1)*size`
|
||||
- `total` **不**受 `LIMIT/OFFSET` 影响
|
||||
|
||||
### 3.4 响应示例
|
||||
|
||||
非空:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"data": {
|
||||
"total": 2,
|
||||
"list": [
|
||||
{
|
||||
"role": "inviter",
|
||||
"peer_hash": "0382716459",
|
||||
"gift_days": 30,
|
||||
"order_no": "20260527123456789",
|
||||
"created_at": 1779934580000
|
||||
},
|
||||
{
|
||||
"role": "invitee",
|
||||
"peer_hash": "1745920031",
|
||||
"gift_days": 30,
|
||||
"order_no": "20260520112233445",
|
||||
"created_at": 1779329780000
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
空:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"data": {
|
||||
"total": 0,
|
||||
"list": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.5 错误码
|
||||
|
||||
| 业务码 | 触发场景 |
|
||||
|---|---|
|
||||
| `InvalidAccess` | 未登录 / JWT 无效 |
|
||||
| `ParamError` | 参数绑定失败 |
|
||||
| `DatabaseQueryError` | DB 查询失败(count / 日志 / 订单任一) |
|
||||
|
||||
### 3.6 前端易踩坑
|
||||
|
||||
1. 传**毫秒**给 `start_time/end_time` → 永远拿到空集。请传**秒**。
|
||||
2. 拿到的 `created_at` 是**毫秒**,**不要再 `*1000`**,直接 `new Date(created_at)` 即可。
|
||||
3. 空列表是 `[]` 不是 `null`,可直接 `.map`。
|
||||
4. `peer_hash` 可能为 `""`,UI 兜底展示"未知朋友"。
|
||||
5. `size` 上限 100,传 1000 会被截断。
|
||||
6. 本接口**只含赠送天数**,不含邀请佣金(佣金 → affiliate 接口)。
|
||||
|
||||
---
|
||||
|
||||
## 附录:业务码常量速查
|
||||
|
||||
| 名称 | HTTP 含义 | 出现场景 |
|
||||
|---|---|---|
|
||||
| `200` | 成功 | `{"code":200,"msg":"success",...}` |
|
||||
| `InvalidAccess` | 未授权 | 未登录 / JWT 无效 / 设备未绑定 |
|
||||
| `ParamError` | 参数错误 | 请求绑定失败、缺必填项 |
|
||||
| `InvalidParams` | 参数校验不通过 | 业务规则校验失败(文件超限、Content-Type 不合法等) |
|
||||
| `DatabaseQueryError` | DB 错 | SQL 查询失败 |
|
||||
| `ERROR` | 通用错 | 第三方/中间件失败(S3 未启用、S3 写入失败等) |
|
||||
@@ -0,0 +1,796 @@
|
||||
# 促销优惠价系统设计文档
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
### 1.1 业务需求
|
||||
|
||||
为套餐规格提供可配置的优惠价格能力,支持多种促销场景:
|
||||
|
||||
- **新客优惠**:注册 N 天内的用户享受优惠价
|
||||
- **回归用户**:N 个月未活跃的用户享受优惠价
|
||||
- **活动促销**:指定时间段内所有用户享受优惠价
|
||||
- **未来可扩展**:首充优惠、邀请用户专属价、指定地区优惠等
|
||||
|
||||
### 1.2 设计原则
|
||||
|
||||
1. **纯新增,不改老代码**:现有的 `new_user_only` + `discount.NewUserOnly` + 24h 窗口逻辑全部保留不动
|
||||
2. **固定价格,非百分比**:运营直接设定优惠价(如 $5.99),不再需要反算折扣百分比
|
||||
3. **后台可配置**:规则类型、参数、时间窗口、优先级均可在管理后台配置
|
||||
4. **促销价不叠加批量折扣**:促销价命中时即为最终基础单价,跳过 `getDiscount()` 的百分比折扣
|
||||
|
||||
### 1.3 与现有体系的关系
|
||||
|
||||
```
|
||||
现有体系(保留不动):
|
||||
subscribe.NewUserOnly → 套餐级新客限制
|
||||
discount[].NewUserOnly → 折扣档位级新客限制
|
||||
newUserEligibility.go → 24h 窗口 + 家庭组判定
|
||||
newUserDiscountEligibility.go → 新客折扣资格组装
|
||||
getDiscount() → 百分比折扣选择
|
||||
order.IsNew → 订单首购标记(统计/佣金用)
|
||||
|
||||
新增体系(本次设计):
|
||||
promo_rule 表 → 可配置的促销规则
|
||||
subscribe_promo 表 → 规格×规则 的优惠价
|
||||
promo_usage 表 → 使用记录(运营分析用)
|
||||
EvaluatePromo() → 促销资格判定
|
||||
```
|
||||
|
||||
**互斥规则**:促销价命中时,跳过老的百分比折扣逻辑(`getDiscount()`)。
|
||||
两套体系不叠加 — 用户要么走促销价,要么走原价+百分比折扣,不会同时生效。
|
||||
|
||||
---
|
||||
|
||||
## 2. 数据模型
|
||||
|
||||
### 2.1 新增表:`promo_rule`(促销规则)
|
||||
|
||||
```sql
|
||||
CREATE TABLE `promo_rule` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称,如"新客7天优惠"',
|
||||
`type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型:new_user / inactive_user / campaign',
|
||||
`params` JSON NOT NULL COMMENT '类型专属参数',
|
||||
`priority` INT NOT NULL DEFAULT 0 COMMENT '优先级,数值越大越优先匹配',
|
||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
||||
`start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间,NULL=立即生效',
|
||||
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间,NULL=永不过期',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_enabled_priority` (`enabled`, `priority` DESC)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
||||
```
|
||||
|
||||
### 2.2 新增表:`subscribe_promo`(规格优惠价)
|
||||
|
||||
```sql
|
||||
CREATE TABLE `subscribe_promo` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
|
||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
|
||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
|
||||
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
||||
```
|
||||
|
||||
### 2.3 新增表:`promo_usage`(促销使用记录)
|
||||
|
||||
用于运营分析,不做强制去重约束。
|
||||
|
||||
```sql
|
||||
CREATE TABLE `promo_usage` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
|
||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '使用的规则 ID',
|
||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '购买的规格 ID',
|
||||
`order_no` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '关联订单号',
|
||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '使用时的促销单价(分)',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
|
||||
KEY `idx_order_no` (`order_no`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
|
||||
```
|
||||
|
||||
### 2.4 `order` 表新增字段
|
||||
|
||||
```sql
|
||||
ALTER TABLE `order`
|
||||
ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '促销规则ID, 0=未使用促销',
|
||||
ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT '促销优惠金额(分)';
|
||||
```
|
||||
|
||||
**字段说明**:
|
||||
|
||||
| 订单字段 | 含义 | 促销命中时 | 未命中时 |
|
||||
|---------|------|-----------|---------|
|
||||
| `Price` | 原始总价 = `UnitPrice × Quantity` | 不变,始终记录原价 | 不变 |
|
||||
| `promo_rule_id` | 使用的促销规则 | 规则 ID | 0 |
|
||||
| `promo_discount` | 促销优惠金额 | `(UnitPrice - PromoPrice) × Quantity` | 0 |
|
||||
| `Discount` | 百分比折扣金额 | **0**(不叠加) | 正常计算 |
|
||||
| `Amount` | 最终支付金额 | 基于促销价计算 | 基于原价+折扣计算 |
|
||||
|
||||
**订单自证**:任何一笔订单都能独立还原其价格构成,不需要回查促销规则表:
|
||||
```
|
||||
Amount = Price - promo_discount - Discount - CouponDiscount + FeeAmount - GiftAmount
|
||||
```
|
||||
|
||||
### 2.5 ER 关系
|
||||
|
||||
```
|
||||
subscribe (1) ──── (*) subscribe_promo (*) ──── (1) promo_rule
|
||||
│
|
||||
│
|
||||
user (1) ──────── (*) promo_usage (*) ─────────── (1) promo_rule
|
||||
│
|
||||
(*) order ← 新增 promo_rule_id, promo_discount
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 规则类型定义
|
||||
|
||||
### 3.1 `new_user` — 新客优惠
|
||||
|
||||
**含义**:用户注册后 N 小时内可享受优惠价
|
||||
|
||||
**params 结构**:
|
||||
|
||||
```json
|
||||
{
|
||||
"window_hours": 168
|
||||
}
|
||||
```
|
||||
|
||||
**判定逻辑**:
|
||||
|
||||
```
|
||||
eligible = (当前时间 - 用户注册时间) < window_hours
|
||||
expires_at = 用户注册时间 + window_hours
|
||||
```
|
||||
|
||||
**与老逻辑的区别**:
|
||||
|
||||
| | 老逻辑 | 新逻辑 |
|
||||
|--|--------|--------|
|
||||
| 窗口期 | 硬编码 24h | 配置化,后台可改 |
|
||||
| 判定基准 | 首台设备注册时间 + 家庭组 | 用户注册时间(`user.created_at`) |
|
||||
| 价格方式 | 百分比折扣 | 固定价格 |
|
||||
| 与折扣叠加 | 是(百分比折扣本身) | 否(替代原价,跳过折扣) |
|
||||
|
||||
### 3.2 `inactive_user` — 回归用户优惠
|
||||
|
||||
**含义**:最近 N 个月没有活跃订阅的用户可享受优惠价
|
||||
|
||||
**params 结构**:
|
||||
|
||||
```json
|
||||
{
|
||||
"inactive_months": 3
|
||||
}
|
||||
```
|
||||
|
||||
**判定逻辑**:
|
||||
|
||||
```
|
||||
last_active = 用户最后一个订阅的 expire_time
|
||||
eligible = last_active 为空(从未购买过)
|
||||
OR (当前时间 - last_active) >= inactive_months 个月
|
||||
expires_at = 规则的 end_time(如有),否则无过期
|
||||
```
|
||||
|
||||
**查询依据**:`user_subscribe` 表中该用户最近一条记录的 `expire_time`
|
||||
|
||||
**注意**:「从未购买过」的用户同时满足 `new_user` 和 `inactive_user`,靠 `priority` 排序选择高优先级的那条。
|
||||
|
||||
### 3.3 `campaign` — 活动促销
|
||||
|
||||
**含义**:在指定时间段内,所有用户均可享受优惠价
|
||||
|
||||
**params 结构**:
|
||||
|
||||
```json
|
||||
{}
|
||||
```
|
||||
|
||||
活动促销不需要额外参数,完全靠 `promo_rule.start_time` 和 `end_time` 控制。
|
||||
|
||||
**判定逻辑**:
|
||||
|
||||
```
|
||||
eligible = start_time <= 当前时间 <= end_time
|
||||
expires_at = end_time
|
||||
```
|
||||
|
||||
### 3.4 扩展预留
|
||||
|
||||
未来新增规则类型只需:
|
||||
1. 定义新的 `type` 字符串(如 `first_purchase`、`referral`、`region`)
|
||||
2. 定义对应的 `params` 结构
|
||||
3. 在判定逻辑中增加一个 `case` 分支
|
||||
|
||||
不需要改表结构,不需要改 API 格式。
|
||||
|
||||
---
|
||||
|
||||
## 4. 核心逻辑
|
||||
|
||||
### 4.1 促销资格判定
|
||||
|
||||
新增文件:`internal/logic/common/promoEligibility.go`
|
||||
|
||||
```go
|
||||
type PromoResult struct {
|
||||
Eligible bool
|
||||
RuleID int64
|
||||
RuleName string
|
||||
RuleType string
|
||||
PromoPrice int64 // 促销单价(分)
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64) (*PromoResult, error) {
|
||||
// 1. 查询该规格关联的所有已启用规则,按 priority DESC
|
||||
// 2. 遍历规则,按类型判定
|
||||
// 3. 首条命中即返回
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2 各类型判定函数
|
||||
|
||||
```go
|
||||
func evaluateNewUser(user *User, params RuleParams) (bool, time.Time) {
|
||||
windowHours := params.WindowHours
|
||||
if windowHours <= 0 {
|
||||
return false, time.Time{}
|
||||
}
|
||||
expiresAt := user.CreatedAt.Add(time.Duration(windowHours) * time.Hour)
|
||||
eligible := time.Now().Before(expiresAt)
|
||||
return eligible, expiresAt
|
||||
}
|
||||
|
||||
func evaluateInactiveUser(ctx context.Context, userID int64, rule PromoRule) (bool, time.Time) {
|
||||
inactiveMonths := rule.Params.InactiveMonths
|
||||
if inactiveMonths <= 0 {
|
||||
return false, time.Time{}
|
||||
}
|
||||
lastExpire := getLastSubscriptionExpireTime(ctx, userID)
|
||||
if lastExpire.IsZero() {
|
||||
return true, rule.GetExpiresAt()
|
||||
}
|
||||
threshold := time.Now().AddDate(0, -inactiveMonths, 0)
|
||||
eligible := lastExpire.Before(threshold)
|
||||
return eligible, rule.GetExpiresAt()
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 下单流程集成(不叠加方案)
|
||||
|
||||
在 `purchaseLogic.go` 中 `sub.UnitPrice * req.Quantity` 之前,插入促销价判定:
|
||||
|
||||
```go
|
||||
// === 新增:促销价判定 ===
|
||||
promoResult, promoErr := commonLogic.EvaluatePromo(l.ctx, l.svcCtx, u.Id, targetSubscribeID)
|
||||
if promoErr != nil {
|
||||
return nil, promoErr
|
||||
}
|
||||
|
||||
var promoDiscount int64
|
||||
var promoRuleID int64
|
||||
|
||||
if promoResult.Eligible {
|
||||
// 促销命中 → 用促销价,跳过百分比折扣
|
||||
price = promoResult.PromoPrice * req.Quantity
|
||||
promoDiscount = (sub.UnitPrice * req.Quantity) - price
|
||||
promoRuleID = promoResult.RuleID
|
||||
discount = 1 // 不叠加批量折扣
|
||||
discountAmount = 0
|
||||
} else {
|
||||
// 未命中 → 走原有逻辑(不动)
|
||||
price = sub.UnitPrice * req.Quantity
|
||||
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||
discountAmount = price - int64(math.Round(float64(price)*discount))
|
||||
}
|
||||
// === 新增结束 ===
|
||||
|
||||
// 后续 coupon / fee / gift 逻辑完全不动
|
||||
```
|
||||
|
||||
**订单创建时记录**:
|
||||
|
||||
```go
|
||||
orderInfo := &order.Order{
|
||||
// ... 原有字段不动 ...
|
||||
Price: sub.UnitPrice * req.Quantity, // 始终记录原价
|
||||
PromoRuleID: promoRuleID, // 新增
|
||||
PromoDiscount: promoDiscount, // 新增
|
||||
Discount: discountAmount, // 促销命中时为 0
|
||||
Amount: amount,
|
||||
}
|
||||
```
|
||||
|
||||
**激活时写 usage**(`activateOrderLogic.go` 追加):
|
||||
|
||||
```go
|
||||
if orderInfo.PromoRuleID > 0 {
|
||||
insertPromoUsage(ctx, orderInfo.UserId, orderInfo.PromoRuleID, orderInfo.SubscribeId, orderInfo.OrderNo, promoPrice)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4 价格计算完整流程
|
||||
|
||||
```
|
||||
┌───────────────────────────────────────────────────┐
|
||||
│ 1. 判定促销 │
|
||||
│ EvaluatePromo(userId, subscribeId) │
|
||||
├──────────────┬────────────────────────────────────┤
|
||||
│ 促销命中 │ 促销未命中 │
|
||||
├──────────────┼────────────────────────────────────┤
|
||||
│ basePrice │ basePrice │
|
||||
│ = promoPrice│ = unitPrice │
|
||||
│ │ │
|
||||
│ discount = 0 │ discount = getDiscount(...) │
|
||||
│ (跳过折扣) │ (百分比折扣正常生效) │
|
||||
├──────────────┴────────────────────────────────────┤
|
||||
│ 2. price = basePrice × quantity │
|
||||
│ amount = price - discountAmount │
|
||||
├───────────────────────────────────────────────────┤
|
||||
│ 3. 优惠券(原有逻辑,不动) │
|
||||
│ amount -= couponDiscount │
|
||||
├───────────────────────────────────────────────────┤
|
||||
│ 4. 手续费(原有逻辑,不动) │
|
||||
│ amount += feeAmount │
|
||||
├───────────────────────────────────────────────────┤
|
||||
│ 5. 余额抵扣(原有逻辑,不动) │
|
||||
│ amount -= giftAmount │
|
||||
└───────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 退款影响分析
|
||||
|
||||
### 5.1 结论:退款逻辑无需改动
|
||||
|
||||
当前退款流程(`refundOrderLogic.go`)基于**订单上已存储的字段**运作,不回查价格体系:
|
||||
|
||||
| 退款动作 | 数据来源 | 是否受促销影响 |
|
||||
|---------|---------|--------------|
|
||||
| 退款金额 | `order.Amount`(支付时已锁定) | 否 — Amount 已反映促销价 |
|
||||
| 佣金回退 | `system_log` 表中的 commission 记录 | 否 — 佣金是基于 Amount 计算的 |
|
||||
| 订阅终止 | `user_subscribe.status → 3` | 否 — 和价格无关 |
|
||||
| 审计日志 | `buildRefundAuditLog()` 读订单快照 | 否 — 记录的就是实际值 |
|
||||
|
||||
**原因**:订单创建时所有金额字段(Price、Amount、Discount、PromoDiscount、FeeAmount 等)都已写入 `order` 表。退款只读这些已存储的值,不会重新计算价格。
|
||||
|
||||
### 5.2 退款后的促销资格
|
||||
|
||||
退款后用户的订阅被终止(`expire_time = now - 1s`)。如果用户再次购买:
|
||||
|
||||
| 场景 | 促销资格 | 说明 |
|
||||
|------|---------|------|
|
||||
| 新客退款后重新购买 | 如仍在窗口期内 → 仍然可以享受促销价 | 正常行为,`promo_usage` 只是记录不做去重 |
|
||||
| 回归用户退款后重新购买 | 需重新判定 `inactive_months` | 退款后订阅 expire_time 被设为过去时间 |
|
||||
| 活动促销退款后重新购买 | 如活动仍在进行 → 可以继续购买 | 活动促销不限次数 |
|
||||
|
||||
这些都是合理的业务行为,不需要额外处理。
|
||||
|
||||
### 5.3 佣金影响
|
||||
|
||||
佣金计算公式(`activateOrderLogic.go:1104`):
|
||||
|
||||
```go
|
||||
amount := l.calculateCommission(orderInfo.Amount - orderInfo.FeeAmount, referralPercentage)
|
||||
```
|
||||
|
||||
- `Amount` 在促销命中时已反映促销价(更低的金额)
|
||||
- 所以佣金会相应减少 — **这是正确的行为**
|
||||
- 退款时佣金回退金额从 `system_log` 读取,回退的也是减少后的佣金
|
||||
|
||||
**无需任何改动**。
|
||||
|
||||
---
|
||||
|
||||
## 6. Apple IAP 影响分析
|
||||
|
||||
### 6.1 现状
|
||||
|
||||
- Apple IAP 价格在 App Store Connect 中配置,不支持后端动态定价
|
||||
- 当前通过 `discount[].MapApple` 字段映射 Apple Product ID
|
||||
- IAP 订单在 `appleIAPNotifyLogic.go` 中处理,走独立的价格逻辑
|
||||
|
||||
### 6.2 设计决策
|
||||
|
||||
**促销价不适用于 IAP 订单**。原因:
|
||||
- IAP 价格由 Apple 控制,后端无法干预
|
||||
- IAP 通知回调(`appleIAPNotifyLogic.go`)有独立的价格处理流程
|
||||
- IAP 审计订单设 `IsNew: false`,不走常规购买逻辑
|
||||
|
||||
**实现方式**:`EvaluatePromo()` 不需要特殊处理 — IAP 订单根本不经过 `purchaseLogic.go`,自然不会触发促销判定。
|
||||
|
||||
---
|
||||
|
||||
## 7. 各购买场景适配
|
||||
|
||||
### 7.1 需要集成促销的场景
|
||||
|
||||
| 文件 | 场景 | 集成方式 |
|
||||
|------|------|---------|
|
||||
| `purchaseLogic.go` | 新购 | 完整促销判定 + 不叠加逻辑 |
|
||||
| `preCreateOrderLogic.go` | 价格预览 | 同上(返回 promo_discount 字段) |
|
||||
|
||||
### 7.2 不需要改动的场景
|
||||
|
||||
| 文件 | 场景 | 原因 |
|
||||
|------|------|------|
|
||||
| `renewalLogic.go` | 续费 | 促销价仅限首购,续费走原价+折扣 |
|
||||
| `rechargeLogic.go` | 余额充值 | 充值不涉及套餐价格 |
|
||||
| `redeemCodeLogic.go` | 兑换码 | 兑换码有自己的固定逻辑 |
|
||||
| `recoverOrderLogic.go` | 历史导入 | 导入的是已完成订单 |
|
||||
| `appleIAPNotifyLogic.go` | IAP 续订 | Apple 控制价格 |
|
||||
| `portal/purchaseLogic.go` | 游客购买 | 游客无 user_id,无法判定促销资格 |
|
||||
| `refundOrderLogic.go` | 退款 | 读取订单已存储的金额,不重新计算 |
|
||||
| `activateOrderLogic.go` | 订单激活 | 只追加 promo_usage 写入,价格不重算 |
|
||||
|
||||
### 7.3 统计报表
|
||||
|
||||
现有统计 SQL(`order/model.go` 中 8 处)按 `is_new` 拆分收入,**不需要改动**。
|
||||
|
||||
未来如需促销维度报表,可通过 `order.promo_rule_id` 字段扩展:
|
||||
```sql
|
||||
SUM(CASE WHEN promo_rule_id > 0 THEN amount ELSE 0 END) AS promo_order_amount,
|
||||
SUM(CASE WHEN promo_rule_id = 0 THEN amount ELSE 0 END) AS normal_order_amount
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. API 设计
|
||||
|
||||
### 8.1 套餐列表 API(改造)
|
||||
|
||||
**接口**:`GET /v1/public/subscribe/list`
|
||||
|
||||
**响应变更**:在原有 `Subscribe` 结构体中追加 `promo` 字段。
|
||||
|
||||
```json
|
||||
{
|
||||
"list": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "基础套餐",
|
||||
"unit_price": 288,
|
||||
"discount": [...],
|
||||
"promo": {
|
||||
"rule_name": "新客7天优惠",
|
||||
"rule_type": "new_user",
|
||||
"promo_price": 279,
|
||||
"expires_at": 1748870400
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "标准套餐",
|
||||
"unit_price": 688,
|
||||
"promo": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**`promo` 字段说明**:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `rule_name` | string | 规则名称,前端展示用 |
|
||||
| `rule_type` | string | 规则类型,前端可据此展示不同样式 |
|
||||
| `promo_price` | int64 | 优惠单价(分),注意是单价不是总价 |
|
||||
| `expires_at` | int64 | 优惠过期时间戳(秒),0 = 无过期 |
|
||||
|
||||
- 用户未登录时:仅展示 `campaign` 类型促销(不需要用户信息)
|
||||
- 用户已登录:展示所有命中的促销
|
||||
- 未命中任何规则时,`promo` 为 `null`
|
||||
|
||||
### 8.2 预算订单 API(改造)
|
||||
|
||||
**接口**:`POST /v1/public/order/pre`
|
||||
|
||||
**响应追加字段**:
|
||||
|
||||
```json
|
||||
{
|
||||
"price": 688,
|
||||
"amount": 499,
|
||||
"discount": 0,
|
||||
"promo_discount": 189,
|
||||
"coupon_discount": 0,
|
||||
"fee_amount": 0,
|
||||
"gift_amount": 0
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 含义 |
|
||||
|------|------|
|
||||
| `price` | 原始总价 = `UnitPrice × Quantity` |
|
||||
| `promo_discount` | 促销优惠 = `(UnitPrice - PromoPrice) × Quantity` |
|
||||
| `discount` | 百分比折扣优惠(促销命中时为 0) |
|
||||
| `amount` | 最终支付金额 |
|
||||
|
||||
前端可展示:~~原价 ¥6.88~~ → 促销价 ¥4.99
|
||||
|
||||
### 8.3 管理后台 API(新增)
|
||||
|
||||
#### 8.3.1 促销规则 CRUD
|
||||
|
||||
```
|
||||
POST /v1/admin/promo/rule 创建规则
|
||||
GET /v1/admin/promo/rule/list 规则列表
|
||||
GET /v1/admin/promo/rule/:id 规则详情
|
||||
PUT /v1/admin/promo/rule/:id 更新规则
|
||||
DELETE /v1/admin/promo/rule/:id 删除规则(软删除)
|
||||
```
|
||||
|
||||
**创建/更新请求体**:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "新客7天优惠",
|
||||
"type": "new_user",
|
||||
"params": {
|
||||
"window_hours": 168
|
||||
},
|
||||
"priority": 10,
|
||||
"enabled": true,
|
||||
"start_time": null,
|
||||
"end_time": null
|
||||
}
|
||||
```
|
||||
|
||||
**校验规则**:
|
||||
- `type` 必须是已支持的类型
|
||||
- `params` 按 `type` 做结构校验(如 `new_user` 必须有 `window_hours > 0`)
|
||||
- `priority` >= 0
|
||||
- `start_time` < `end_time`(如果两者都提供)
|
||||
|
||||
#### 8.3.2 规格优惠价配置
|
||||
|
||||
```
|
||||
POST /v1/admin/promo/price 批量设置优惠价
|
||||
GET /v1/admin/promo/price/list 查询某规则下的所有优惠价
|
||||
DELETE /v1/admin/promo/price/:id 删除某条优惠价
|
||||
```
|
||||
|
||||
**批量设置请求体**:
|
||||
|
||||
```json
|
||||
{
|
||||
"promo_rule_id": 1,
|
||||
"items": [
|
||||
{"subscribe_id": 1, "promo_price": 279},
|
||||
{"subscribe_id": 2, "promo_price": 599}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**校验**:`promo_price` 必须 < 对应规格的 `unit_price`(防止配置错误)。
|
||||
|
||||
#### 8.3.3 使用记录查询
|
||||
|
||||
```
|
||||
GET /v1/admin/promo/usage/list?rule_id=1&page=1&size=20
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 缓存策略
|
||||
|
||||
### 9.1 规则缓存
|
||||
|
||||
```
|
||||
Key: promo:rules:enabled
|
||||
Value: JSON 数组(所有启用的规则,按 priority DESC)
|
||||
TTL: 300 秒(5 分钟)
|
||||
清除: 管理后台修改规则时主动删除
|
||||
```
|
||||
|
||||
### 9.2 规格优惠价缓存
|
||||
|
||||
```
|
||||
Key: promo:subscribe:{subscribe_id}
|
||||
Value: JSON 数组(该规格关联的所有 rule_id → promo_price)
|
||||
TTL: 300 秒
|
||||
清除: 管理后台修改优惠价时主动删除
|
||||
```
|
||||
|
||||
### 9.3 注意事项
|
||||
|
||||
- 缓存 TTL 300 秒意味着活动 `end_time` 到期后最多 5 分钟延迟,可接受
|
||||
- 管理后台操作后主动 DEL 缓存 key,确保配置变更及时生效
|
||||
- `EvaluatePromo()` 缓存未命中时回查 DB
|
||||
|
||||
---
|
||||
|
||||
## 10. 确定的决策项
|
||||
|
||||
| 编号 | 问题 | 结论 | 原因 |
|
||||
|------|------|------|------|
|
||||
| D-01 | 促销价与批量折扣叠加 | **不叠加** | 促销价即最终单价,跳过 `getDiscount()` |
|
||||
| D-02 | 未登录用户展示促销价 | 仅展示 `campaign` 类型 | `new_user`/`inactive_user` 需要用户信息 |
|
||||
| D-03 | 续费订单适用促销价 | **仅首购** | 促销价用于拉新/回归,续费走原价 |
|
||||
| D-04 | 回归用户判定方式 | 订阅过期时间 | `user_subscribe.expire_time`,数据最可靠 |
|
||||
| D-05 | 多规则命中 | 按 `priority` DESC 取第一条 | 运营可控 |
|
||||
| D-07 | Portal(游客)购买走促销 | **不走** | 游客无 user_id,无法判定资格 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 新增文件清单
|
||||
|
||||
| 层级 | 新增文件 | 说明 |
|
||||
|------|----------|------|
|
||||
| **Model** | `internal/model/promo_rule/promo_rule.go` | 促销规则模型 |
|
||||
| **Model** | `internal/model/subscribe_promo/subscribe_promo.go` | 规格优惠价模型 |
|
||||
| **Model** | `internal/model/promo_usage/promo_usage.go` | 使用记录模型 |
|
||||
| **Logic** | `internal/logic/common/promoEligibility.go` | 促销资格判定核心逻辑 |
|
||||
| **Logic** | `internal/logic/admin/promo/` 目录(CRUD) | 管理后台逻辑 |
|
||||
| **Handler** | `internal/handler/admin/promo/` 目录 | 管理后台 Handler |
|
||||
| **Types** | `internal/types/types.go` 追加 | 新增结构体 |
|
||||
| **Migration** | `initialize/migrate/database/02153_promo_rule.up.sql` | 建表 + order 加字段 |
|
||||
| **Migration** | `initialize/migrate/database/02153_promo_rule.down.sql` | 回滚 |
|
||||
|
||||
### 需改动的已有文件(仅追加)
|
||||
|
||||
| 文件 | 改动方式 |
|
||||
|------|----------|
|
||||
| `internal/logic/public/subscribe/querySubscribeListLogic.go` | 追加:查促销信息,填充 `promo` |
|
||||
| `internal/logic/public/order/purchaseLogic.go` | 追加:促销判定 + 不叠加分支 |
|
||||
| `internal/logic/public/order/preCreateOrderLogic.go` | 追加:预算时考虑促销价 |
|
||||
| `queue/logic/order/activateOrderLogic.go` | 追加:激活后写 `promo_usage` |
|
||||
| `internal/model/order/order.go` | 追加:`PromoRuleID`、`PromoDiscount` 字段 |
|
||||
| `internal/model/order/model.go` | 追加:`Details` 同步字段 |
|
||||
| `internal/types/types.go` | 追加:新增结构体、响应字段 |
|
||||
| `internal/svc/serviceContext.go` | 追加:注入新 Model |
|
||||
| 路由配置 | 追加:管理后台路由 |
|
||||
|
||||
---
|
||||
|
||||
## 12. 运营配置示例
|
||||
|
||||
### 场景 1:新客 7 天优惠
|
||||
|
||||
```
|
||||
promo_rule:
|
||||
name = "新客7天优惠"
|
||||
type = "new_user"
|
||||
params = {"window_hours": 168}
|
||||
priority = 10
|
||||
enabled = true
|
||||
start_time = NULL(永久生效)
|
||||
end_time = NULL
|
||||
|
||||
subscribe_promo:
|
||||
规格"7天" → promo_price = 279
|
||||
规格"30天" → promo_price = 599
|
||||
规格"90天" → promo_price = 1299
|
||||
规格"365天" → promo_price = 4499
|
||||
```
|
||||
|
||||
### 场景 2:回归用户优惠
|
||||
|
||||
```
|
||||
promo_rule:
|
||||
name = "回归用户专属价"
|
||||
type = "inactive_user"
|
||||
params = {"inactive_months": 3}
|
||||
priority = 5
|
||||
enabled = true
|
||||
|
||||
subscribe_promo:
|
||||
规格"30天" → promo_price = 499
|
||||
规格"90天" → promo_price = 999
|
||||
```
|
||||
|
||||
### 场景 3:双十一全站活动
|
||||
|
||||
```
|
||||
promo_rule:
|
||||
name = "双十一特惠"
|
||||
type = "campaign"
|
||||
params = {}
|
||||
priority = 20(优先级高于新客和回归)
|
||||
enabled = true
|
||||
start_time = "2026-11-01 00:00:00"
|
||||
end_time = "2026-11-12 00:00:00"
|
||||
|
||||
subscribe_promo:
|
||||
规格"90天" → promo_price = 999
|
||||
规格"365天" → promo_price = 3999
|
||||
```
|
||||
|
||||
**优先级效果**:双十一期间(priority=20),即使用户是新客(priority=10),也走双十一价格。双十一结束后,新客仍可享受新客优惠。
|
||||
|
||||
---
|
||||
|
||||
## 13. 迁移脚本
|
||||
|
||||
### 02153_promo_system.up.sql
|
||||
|
||||
```sql
|
||||
-- 促销规则表
|
||||
CREATE TABLE IF NOT EXISTS `promo_rule` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(100) NOT NULL DEFAULT '',
|
||||
`type` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`params` JSON NOT NULL,
|
||||
`priority` INT NOT NULL DEFAULT 0,
|
||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
`start_time` DATETIME DEFAULT NULL,
|
||||
`end_time` DATETIME DEFAULT NULL,
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` DATETIME DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_enabled_priority` (`enabled`, `priority` DESC)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
||||
|
||||
-- 规格促销价表
|
||||
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`subscribe_id` BIGINT UNSIGNED NOT NULL,
|
||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL,
|
||||
`promo_price` BIGINT NOT NULL DEFAULT 0,
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
|
||||
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
||||
|
||||
-- 促销使用记录表
|
||||
CREATE TABLE IF NOT EXISTS `promo_usage` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`user_id` BIGINT UNSIGNED NOT NULL,
|
||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL,
|
||||
`subscribe_id` BIGINT UNSIGNED NOT NULL,
|
||||
`order_no` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`promo_price` BIGINT NOT NULL DEFAULT 0,
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
|
||||
KEY `idx_order_no` (`order_no`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
|
||||
|
||||
-- order 表新增促销字段
|
||||
ALTER TABLE `order`
|
||||
ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '促销规则ID, 0=未使用促销',
|
||||
ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT '促销优惠金额(分)';
|
||||
```
|
||||
|
||||
### 02153_promo_system.down.sql
|
||||
|
||||
```sql
|
||||
ALTER TABLE `order`
|
||||
DROP COLUMN IF EXISTS `promo_discount`,
|
||||
DROP COLUMN IF EXISTS `promo_rule_id`;
|
||||
|
||||
DROP TABLE IF EXISTS `promo_usage`;
|
||||
DROP TABLE IF EXISTS `subscribe_promo`;
|
||||
DROP TABLE IF EXISTS `promo_rule`;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. 风险与注意事项
|
||||
|
||||
| 风险 | 应对 |
|
||||
|------|------|
|
||||
| 促销价 > 原价(配置错误) | 管理后台校验:`promo_price` 必须 < `unit_price` |
|
||||
| 规则删除后已有订单受影响 | 软删除(`deleted_at`),订单上已存储 `promo_rule_id` 和 `promo_discount`,不依赖规则表 |
|
||||
| 缓存与数据库不一致 | 管理后台修改时主动清缓存,判定逻辑以 DB 为准 |
|
||||
| 新促销和老 NewUserOnly 折扣共存 | **互斥**:促销命中时跳过 `getDiscount()` 的百分比折扣 |
|
||||
| 活动到期后 5 分钟内仍可下单 | 缓存 TTL=300s 的延迟,可接受;下单时可选择实时查 DB 校验 |
|
||||
| 退款后重新购买仍享促销 | 正常行为 — `promo_usage` 只做记录不做去重 |
|
||||
@@ -0,0 +1,153 @@
|
||||
# 用户端提现列表 API — 订阅字段现状调研
|
||||
|
||||
> 调研日期:2026-05-27
|
||||
> 调研范围:用户端「提现记录列表」接口当前返回字段,重点关注是否包含订阅相关信息
|
||||
|
||||
## 一、接口信息
|
||||
|
||||
| 项目 | 值 |
|
||||
|------|-----|
|
||||
| 方法 | `GET` |
|
||||
| 路径 | `/v1/public/user/withdrawal_log` |
|
||||
| 认证 | JWT Token(`AuthMiddleware` + `DeviceMiddleware`) |
|
||||
| 分组 | `apis/public/user.api` |
|
||||
|
||||
## 二、文件定位
|
||||
|
||||
| 层 | 路径 |
|
||||
|----|------|
|
||||
| API DSL | `apis/public/user.api:118` (`WithdrawalLog`) / `apis/public/user.api:368` (路由) |
|
||||
| Handler | `internal/handler/public/user/queryWithdrawalLogHandler.go` |
|
||||
| Logic | `internal/logic/public/user/queryWithdrawalLogLogic.go:30` |
|
||||
| 类型生成 | `internal/types/types.go`(`WithdrawalLog`、`QueryWithdrawalLogListRequest`、`QueryWithdrawalLogListResponse`) |
|
||||
| 数据模型 | `internal/model/user/user.go:167` (`Withdrawal`,表名 `withdrawals`) |
|
||||
|
||||
## 三、请求参数
|
||||
|
||||
```go
|
||||
QueryWithdrawalLogListRequest {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
}
|
||||
```
|
||||
|
||||
- 默认值:`page=1`、`size=10`(在 logic 内兜底)
|
||||
|
||||
## 四、响应结构
|
||||
|
||||
### 4.1 顶层响应
|
||||
|
||||
```go
|
||||
QueryWithdrawalLogListResponse {
|
||||
List []WithdrawalLog `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2 列表项 `WithdrawalLog`
|
||||
|
||||
```go
|
||||
WithdrawalLog {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
Amount int64 `json:"amount"` // 单位:分
|
||||
Content string `json:"content"` // 收款附加信息
|
||||
Status uint8 `json:"status"` // 0:Pending 1:Approved 2:Rejected 3:Cancelled
|
||||
Reason string `json:"reason,omitempty"` // 拒绝原因
|
||||
Method uint8 `json:"method"` // 0:其他 1:支付宝 2:微信 3:USDT
|
||||
Account string `json:"account"` // 收款账号
|
||||
QrCodeUrl string `json:"qr_code_url"` // 收款码图片 URL
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
```
|
||||
|
||||
## 五、底层数据模型 `Withdrawal`
|
||||
|
||||
```go
|
||||
type Withdrawal struct {
|
||||
Id int64
|
||||
UserId int64 // index:idx_user_id
|
||||
Amount int64
|
||||
Content string // type:text
|
||||
Status uint8 // 0:Pending 1:Approved 2:Rejected 3:Cancelled
|
||||
Reason string // varchar(500)
|
||||
Method uint8 // 0:其他 1:支付宝 2:微信 3:USDT
|
||||
Account string // varchar(255)
|
||||
QrCodeUrl string // varchar(500)
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
```
|
||||
|
||||
> 表名:`withdrawals`,与用户关联仅靠 `user_id` 外键,**无任何订阅 ID / 订阅快照字段**。
|
||||
|
||||
## 六、订阅字段现状(核心结论)
|
||||
|
||||
### 6.1 当前结论
|
||||
|
||||
| 维度 | 是否包含订阅信息 |
|
||||
|------|------------------|
|
||||
| API 响应(`WithdrawalLog`) | ❌ 无 |
|
||||
| 数据库表(`withdrawals`) | ❌ 无 |
|
||||
| Logic 查询逻辑 | ❌ 无 JOIN、无附加查询 `user_subscribe` |
|
||||
|
||||
提现记录与订阅之间**完全没有关联**。原因:佣金来源于多次订单累计,提现是从「佣金余额(`user.commission`)」整体扣减,不绑定到任何具体订阅。
|
||||
|
||||
### 6.2 Logic 当前实现要点
|
||||
|
||||
```go
|
||||
// internal/logic/public/user/queryWithdrawalLogLogic.go:46-72
|
||||
query := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.Withdrawal{}).
|
||||
Where("user_id = ?", u.Id)
|
||||
|
||||
// 仅按 user_id 过滤 + 分页 + 倒序,无任何 Preload / Join
|
||||
```
|
||||
|
||||
## 七、已发现的隐患(与本次需求关联)
|
||||
|
||||
### 7.1 时间戳违反项目约定 ⚠️
|
||||
|
||||
`queryWithdrawalLogLogic.go:70-71`:
|
||||
|
||||
```go
|
||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
||||
```
|
||||
|
||||
- 项目约定:**后端统一返回秒级 Unix 时间戳**(前端 `formatDate` 已按 `数字 × 1000` 处理)
|
||||
- 当前实现返回毫秒级,前端会解析为约公元 +55000 年的日期,**展示必然异常**
|
||||
- 修复方式:改为 `.Unix()`
|
||||
|
||||
> 该问题独立于「订阅字段」需求,但属于同一接口,建议同批修复。
|
||||
|
||||
## 八、可选扩展方向(待业务确认)
|
||||
|
||||
若产品希望在提现列表中展示订阅相关信息,可选方案如下:
|
||||
|
||||
| 方案 | 字段示意 | 实现成本 | 适用场景 |
|
||||
|------|----------|----------|----------|
|
||||
| A. 当前生效订阅摘要 | `current_subscribe: { id, name, expire_at }` | 中(每行额外查 `user_subscribe`) | 想让用户看到「我提的是哪个订阅产生的佣金对应的余额」 |
|
||||
| B. 用户全部订阅列表 | `subscribes: [{ id, name, expire_at }]` | 高(N+1 风险) | 极少场景,需评估必要性 |
|
||||
| C. 仅订阅 ID 数组 | `subscribe_ids: [int64]` | 低 | 仅前端跳详情用 |
|
||||
| D. 不加,保持现状 | — | 0 | 若业务上提现与订阅本就无关 |
|
||||
|
||||
> **推荐先与产品确认动机**:提现是佣金余额提现,与订阅本身没有直接业务关系,加字段前需明确「让用户看到订阅信息要解决什么问题」。
|
||||
|
||||
## 九、相关接口(一并列出,便于对照)
|
||||
|
||||
| 接口 | 方法 | 路径 | 说明 |
|
||||
|------|------|------|------|
|
||||
| 提交提现 | POST | `/v1/public/user/commission_withdraw` | 入参 `CommissionWithdrawRequest`,返回 `WithdrawalLog` |
|
||||
| 取消提现 | POST | `/v1/public/user/withdrawal_cancel` | 入参 `CancelWithdrawalRequest`,返回 `WithdrawalLog` |
|
||||
| 提现记录列表 | GET | `/v1/public/user/withdrawal_log` | 本文主角 |
|
||||
|
||||
> 三个接口共用 `WithdrawalLog` 类型,**任何字段变更需统一同步**,否则前端类型会错位。
|
||||
|
||||
## 十、后续动作建议
|
||||
|
||||
1. **产品确认**:是否真的需要在提现列表里返回订阅字段?目的是什么?
|
||||
2. **若需新增**:在 `apis/public/user.api` 修改 `WithdrawalLog`,运行 goctl 重新生成,再补 Logic 查询。
|
||||
3. **顺手修复**:将 `UnixMilli()` 改为 `Unix()`(独立小 PR 即可)。
|
||||
4. **如新增订阅字段**:注意三个接口(list / cancel / withdraw)的返回结构同步,避免前端类型联动断裂。
|
||||
@@ -0,0 +1,6 @@
|
||||
-- 02155 down
|
||||
--
|
||||
-- 本迁移只是把 02154 的偏差修正回它应有的目标定义,没有引入新的列/表。
|
||||
-- 回滚 02155 并不应该把列重新改坏成 varchar/INT NULL 的旧偏差,因此 down
|
||||
-- 为空操作。若需彻底删除 promo 系统,请回滚到 02154 的 down。
|
||||
SELECT '02155 has no destructive forward step; down is a no-op.';
|
||||
@@ -0,0 +1,241 @@
|
||||
-- 02155 Promo Schema Fix
|
||||
--
|
||||
-- 修复历史环境中 02154 未正确执行(或部分 GORM AutoMigrate 推断)导致的
|
||||
-- promo 系统列类型 / 索引偏差。完全幂等:可重复执行。
|
||||
--
|
||||
-- 覆盖偏差:
|
||||
-- 1) subscribe_promo.quantity 实际 int/NULL -> BIGINT NOT NULL DEFAULT 1
|
||||
-- 2) subscribe_promo 唯一索引 实际 (subscribe_id, promo_rule_id) -> (subscribe_id, quantity, promo_rule_id)
|
||||
-- 3) order.promo_rule_id 实际 int/NULL -> BIGINT UNSIGNED NOT NULL DEFAULT 0
|
||||
-- 4) order.promo_discount 实际 varchar(255)/NULL -> BIGINT NOT NULL DEFAULT 0
|
||||
--
|
||||
-- 设计原则:
|
||||
-- - 所有 ALTER 前先做 NULL/空串兜底,避免 NOT NULL 转换失败。
|
||||
-- - 类型已经正确的环境(02154 正常跑过)不会被改动,所有 IF 判断都基于
|
||||
-- INFORMATION_SCHEMA 当前真实状态。
|
||||
-- - 索引差异处理 4 个分支:仅当索引确实是错的旧形态时才替换,已经是新形态则不动。
|
||||
|
||||
|
||||
-- ============================================================================
|
||||
-- 1) subscribe_promo.quantity
|
||||
-- ============================================================================
|
||||
|
||||
-- 1.1 列不存在则补建(极端历史环境兜底)
|
||||
SET @col_exists = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND COLUMN_NAME = 'quantity'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_exists = 0,
|
||||
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
|
||||
'SELECT ''subscribe_promo.quantity exists, skip ADD'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- 1.2 NULL 兜底为 1(旧 AutoMigrate 推断列允许 NULL,必须先回填再 NOT NULL)
|
||||
UPDATE `subscribe_promo` SET `quantity` = 1 WHERE `quantity` IS NULL;
|
||||
|
||||
-- 1.3 类型 / 可空 / 默认值修正:只在与目标定义不一致时改
|
||||
SET @col_def_wrong = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND COLUMN_NAME = 'quantity'
|
||||
AND (
|
||||
LOWER(DATA_TYPE) <> 'bigint'
|
||||
OR IS_NULLABLE = 'YES'
|
||||
OR COLUMN_DEFAULT IS NULL
|
||||
OR COLUMN_DEFAULT <> '1'
|
||||
)
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_def_wrong = 1,
|
||||
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
|
||||
'SELECT ''subscribe_promo.quantity already matches target definition'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
|
||||
-- ============================================================================
|
||||
-- 2) subscribe_promo 唯一索引:旧形态 -> (subscribe_id, quantity, promo_rule_id)
|
||||
-- ============================================================================
|
||||
|
||||
-- 2.1 删除已知的所有旧形态唯一索引(如果存在)
|
||||
SET @idx_exists = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND INDEX_NAME = 'idx_subscribe_rule'
|
||||
);
|
||||
SET @sql = IF(
|
||||
@idx_exists = 1,
|
||||
'ALTER TABLE `subscribe_promo` DROP INDEX `idx_subscribe_rule`',
|
||||
'SELECT ''subscribe_promo.idx_subscribe_rule absent'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @idx_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(
|
||||
@idx_exists = 1,
|
||||
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
|
||||
'SELECT ''subscribe_promo.uk_subscribe_rule absent'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @idx_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(
|
||||
@idx_exists = 1,
|
||||
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
|
||||
'SELECT ''subscribe_promo.uk_subscribe_qty_rule absent'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- 2.2 新建目标唯一索引(缺失时才建)
|
||||
SET @idx_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(
|
||||
@idx_exists = 0,
|
||||
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
|
||||
'SELECT ''subscribe_promo.uk_subscribe_quantity_rule exists'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
|
||||
-- ============================================================================
|
||||
-- 3) order.promo_rule_id -> BIGINT UNSIGNED NOT NULL DEFAULT 0
|
||||
-- ============================================================================
|
||||
|
||||
SET @col_exists = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_rule_id'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_exists = 0,
|
||||
'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`',
|
||||
'SELECT ''order.promo_rule_id exists, skip ADD'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
UPDATE `order` SET `promo_rule_id` = 0 WHERE `promo_rule_id` IS NULL;
|
||||
|
||||
SET @col_def_wrong = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_rule_id'
|
||||
AND (
|
||||
LOWER(DATA_TYPE) <> 'bigint'
|
||||
OR INSTR(LOWER(COLUMN_TYPE), 'unsigned') = 0
|
||||
OR IS_NULLABLE = 'YES'
|
||||
OR COLUMN_DEFAULT IS NULL
|
||||
OR COLUMN_DEFAULT <> '0'
|
||||
)
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_def_wrong = 1,
|
||||
'ALTER TABLE `order` MODIFY COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销''',
|
||||
'SELECT ''order.promo_rule_id already matches target definition'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
|
||||
-- ============================================================================
|
||||
-- 4) order.promo_discount -> BIGINT NOT NULL DEFAULT 0
|
||||
-- 历史 AutoMigrate 推断为 varchar(255)/NULL,金额字段错存为字符串。
|
||||
-- 必须先把空串/NULL 兜底为 '0',再 MODIFY,否则 MySQL 转 BIGINT 会写 0
|
||||
-- (这里我们仍兜底显式化,避免触发 strict mode 报错)。
|
||||
-- ============================================================================
|
||||
|
||||
SET @col_exists = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_discount'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_exists = 0,
|
||||
'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`',
|
||||
'SELECT ''order.promo_discount exists, skip ADD'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- 当且仅当当前是字符串型时做兜底(避免对已经是 BIGINT 的环境跑无谓 UPDATE)
|
||||
SET @col_is_string = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_discount'
|
||||
AND LOWER(DATA_TYPE) IN ('varchar', 'char', 'text')
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_is_string = 1,
|
||||
'UPDATE `order` SET `promo_discount` = ''0'' WHERE `promo_discount` IS NULL OR `promo_discount` = ''''',
|
||||
'SELECT ''order.promo_discount not string type, skip backfill'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @col_def_wrong = (
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_discount'
|
||||
AND (
|
||||
LOWER(DATA_TYPE) <> 'bigint'
|
||||
OR IS_NULLABLE = 'YES'
|
||||
OR COLUMN_DEFAULT IS NULL
|
||||
OR COLUMN_DEFAULT <> '0'
|
||||
)
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@col_def_wrong = 1,
|
||||
'ALTER TABLE `order` MODIFY COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)''',
|
||||
'SELECT ''order.promo_discount already matches target definition'''
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -1,24 +1,24 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func ReportLogMessageHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.ReportLogMessageRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
l := common.NewReportLogMessageLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.ReportLogMessage(&req, c)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
var req types.ReportLogMessageRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
l := common.NewReportLogMessageLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.ReportLogMessage(&req, c)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/public/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Get invite sales data
|
||||
func GetInviteSalesHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetInviteSalesRequest
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewGetInviteSalesLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetInviteSales(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -1121,6 +1121,10 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// Get Invite Records
|
||||
publicUserGroupRouter.GET("/invite_records", publicUser.GetInviteRecordsHandler(serverCtx))
|
||||
|
||||
// Get Invite Sales
|
||||
publicUserGroupRouter.GET("/invite_sales", publicUser.GetInviteSalesHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx)) // alias: backward-compat
|
||||
|
||||
// Get User Invite Stats
|
||||
publicUserGroupRouter.GET("/invite_stats", publicUser.GetUserInviteStatsHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/stats", publicUser.GetUserInviteStatsHandler(serverCtx)) // alias: backward-compat
|
||||
|
||||
@@ -23,8 +23,9 @@ type InviteRelation struct {
|
||||
}
|
||||
|
||||
type paidOrderRow struct {
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
OrderNo string `gorm:"column:order_no"`
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
SubscriptionUserId int64 `gorm:"column:subscription_user_id"`
|
||||
OrderNo string `gorm:"column:order_no"`
|
||||
}
|
||||
|
||||
type systemLogRow struct {
|
||||
@@ -81,7 +82,7 @@ func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation)
|
||||
var paidOrders []paidOrderRow
|
||||
if err := db.WithContext(ctx).
|
||||
Table("`order`").
|
||||
Select("user_id, order_no").
|
||||
Select("user_id, subscription_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)
|
||||
@@ -92,11 +93,16 @@ func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation)
|
||||
|
||||
orderNos := make([]string, 0, len(paidOrders))
|
||||
orderToInvitee := make(map[string]int64, len(paidOrders))
|
||||
orderToSubscriptionUser := 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
|
||||
if order.SubscriptionUserId > 0 && order.SubscriptionUserId != order.UserId {
|
||||
orderToSubscriptionUser[order.OrderNo] = order.SubscriptionUserId
|
||||
inviteeAndInviterSet[order.SubscriptionUserId] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, relation := range relations {
|
||||
inviterIds = append(inviterIds, relation.InviterId)
|
||||
@@ -111,7 +117,7 @@ func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation)
|
||||
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 {
|
||||
if err := fillGiftBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderToSubscriptionUser, orderNos, inviteeAndInviterIds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -143,7 +149,7 @@ func fillCommissionBenefits(ctx context.Context, db *gorm.DB, benefits map[int64
|
||||
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 {
|
||||
func fillGiftBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderToSubscriptionUser map[string]int64, orderNos []string, userIds []int64) error {
|
||||
var rows []systemLogRow
|
||||
if err := db.WithContext(ctx).
|
||||
Table("system_logs").
|
||||
@@ -170,6 +176,8 @@ func fillGiftBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benef
|
||||
benefit.InviterGiftDays += content.Amount
|
||||
case inviteeId:
|
||||
benefit.InviteeGiftDays += content.Amount
|
||||
case orderToSubscriptionUser[content.OrderNo]:
|
||||
benefit.InviteeGiftDays += content.Amount
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package invite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestQueryBenefitsCountsFamilyOwnerGiftAsInviteeGift(t *testing.T) {
|
||||
db, mock, cleanup := newBenefitsTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("COUNT(*) as cnt").
|
||||
WithArgs(int64(200), 2, 5).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "cnt"}).AddRow(200, 1))
|
||||
mock.ExpectQuery("SELECT user_id, subscription_user_id, order_no FROM `order`").
|
||||
WithArgs(int64(200), 2, 5).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "subscription_user_id", "order_no"}).AddRow(200, 900, "family-order"))
|
||||
mock.ExpectQuery("object_id IN").
|
||||
WithArgs(33, int64(100), "family-order", 331, 332).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}))
|
||||
mock.ExpectQuery("object_id IN").
|
||||
WithArgs(34, int64(900), int64(200), int64(100), "family-order").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}).
|
||||
AddRow(900, `{"type":341,"order_no":"family-order","amount":7,"balance":7,"remark":"邀请赠送"}`))
|
||||
|
||||
benefits, err := QueryBenefits(context.Background(), db, []InviteRelation{{InviteeId: 200, InviterId: 100}})
|
||||
if err != nil {
|
||||
t.Fatalf("QueryBenefits returned error: %v", err)
|
||||
}
|
||||
|
||||
benefit := benefits[200]
|
||||
if benefit.InviteeGiftDays != 7 {
|
||||
t.Fatalf("InviteeGiftDays = %d, want 7", benefit.InviteeGiftDays)
|
||||
}
|
||||
if benefit.InviterGiftDays != 0 {
|
||||
t.Fatalf("InviterGiftDays = %d, want 0", benefit.InviterGiftDays)
|
||||
}
|
||||
assertBenefitsExpectations(t, mock)
|
||||
}
|
||||
|
||||
func TestQueryBenefitsKeepsDirectInviteeGift(t *testing.T) {
|
||||
db, mock, cleanup := newBenefitsTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("COUNT(*) as cnt").
|
||||
WithArgs(int64(200), 2, 5).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "cnt"}).AddRow(200, 1))
|
||||
mock.ExpectQuery("SELECT user_id, subscription_user_id, order_no FROM `order`").
|
||||
WithArgs(int64(200), 2, 5).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "subscription_user_id", "order_no"}).AddRow(200, 0, "direct-order"))
|
||||
mock.ExpectQuery("object_id IN").
|
||||
WithArgs(33, int64(100), "direct-order", 331, 332).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}))
|
||||
mock.ExpectQuery("object_id IN").
|
||||
WithArgs(34, int64(200), int64(100), "direct-order").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}).
|
||||
AddRow(200, `{"type":341,"order_no":"direct-order","amount":5,"balance":5,"remark":"邀请赠送"}`))
|
||||
|
||||
benefits, err := QueryBenefits(context.Background(), db, []InviteRelation{{InviteeId: 200, InviterId: 100}})
|
||||
if err != nil {
|
||||
t.Fatalf("QueryBenefits returned error: %v", err)
|
||||
}
|
||||
|
||||
if got := benefits[200].InviteeGiftDays; got != 5 {
|
||||
t.Fatalf("InviteeGiftDays = %d, want 5", got)
|
||||
}
|
||||
assertBenefitsExpectations(t, mock)
|
||||
}
|
||||
|
||||
func newBenefitsTestDB(t *testing.T) (*gorm.DB, 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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func assertBenefitsExpectations(t *testing.T, mock sqlmock.Sqlmock) {
|
||||
t.Helper()
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func (l *GetInviteManageListLogic) GetInviteManageList(req *types.GetInviteManag
|
||||
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").
|
||||
Select("invitee.id as invitee_id, invitee.avatar as invitee_avatar, invitee.enable as invitee_enable, CAST(UNIX_TIMESTAMP(invitee.created_at) AS SIGNED) 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).
|
||||
|
||||
@@ -67,6 +67,17 @@ func (l *RefundOrderLogic) RefundOrder(req *types.RefundOrderRequest) error {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderStatusError), "order %d status %d is not refundable", orderInfo.Id, orderInfo.Status)
|
||||
}
|
||||
|
||||
// 幂等校验:若该 order_no 已存在 333 退款日志,拒绝再次退款。
|
||||
// HIF-131 案例:订单状态被外部入口(stuckOrderRecovery 把 6 视为卡住的 claim)回退到 5,
|
||||
// 让 lockCommissionSource 误抓到原始 331/332 amount 再次扣减佣金。
|
||||
refunded, err := l.hasRefundLog(tx, orderInfo.OrderNo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if refunded {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderAlreadyRefunded), "order %d already has refund commission log", orderInfo.Id)
|
||||
}
|
||||
|
||||
userSub, err := l.lockRefundTargetSubscription(tx, &orderInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -256,6 +267,13 @@ func (l *RefundOrderLogic) lockCommissionSource(tx *gorm.DB, orderNo string, ord
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
// hasRefundLog 检查指定 order_no 是否已有 333 (CommissionTypeRefund) 退款佣金日志。
|
||||
// 仅扫 type=33 + 内容含 order_no 的命中项,再用 JSON 二次确认 content.type==333,
|
||||
// 防止 content.order_no 子串误判。
|
||||
func (l *RefundOrderLogic) hasRefundLog(tx *gorm.DB, orderNo string) (bool, error) {
|
||||
return log.HasRefundCommissionLog(tx, orderNo)
|
||||
}
|
||||
|
||||
func (l *RefundOrderLogic) buildRefundAuditLog(
|
||||
operator *modeluser.User,
|
||||
orderInfo *modelorder.Order,
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
modelorder "github.com/perfect-panel/server/internal/model/order"
|
||||
modeluser "github.com/perfect-panel/server/internal/model/user"
|
||||
"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"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestOrderStatusName(t *testing.T) {
|
||||
@@ -83,3 +95,155 @@ func TestBuildRefundAuditLog(t *testing.T) {
|
||||
t.Fatalf("unexpected commission transition: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefundOrder_RejectsWhenRefundLogExists 验证 HIF-131 / HIF-132 修复:
|
||||
// 当 system_logs 已存在该订单的 333 退款佣金日志时,再次调用 RefundOrder 必须:
|
||||
// 1. 返回 OrderAlreadyRefunded 错误码;
|
||||
// 2. 不再查询 / 锁定 commission 来源(lockCommissionSource 不应触发);
|
||||
// 3. 不写入新的 333 日志、不更新 user.commission、不更新 order.status。
|
||||
//
|
||||
// 通过 sqlmock 严格定义期望 SQL:只允许出现 BEGIN / SELECT order FOR UPDATE /
|
||||
// SELECT system_logs(命中 333)/ ROLLBACK,不允许出现 commission 锁/更新/插入。
|
||||
func TestRefundOrder_RejectsWhenRefundLogExists(t *testing.T) {
|
||||
const (
|
||||
orderID = int64(53647)
|
||||
orderNo = "202605301925431836075753253"
|
||||
operatorUID = int64(519)
|
||||
)
|
||||
|
||||
db, mock, cleanup := newRefundOrderTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery("FROM `order`").
|
||||
WithArgs(orderID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "order_no", "status", "type", "commission", "user_id"}).
|
||||
AddRow(orderID, orderNo, uint8(5), uint8(2), int64(2250), int64(72028)))
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
|
||||
AddRow(1, fmt.Sprintf(`{"type":333,"order_no":"%s","amount":-2250,"timestamp":0}`, orderNo)))
|
||||
mock.ExpectRollback()
|
||||
|
||||
logic := newTestRefundOrderLogic(t, db, operatorUID)
|
||||
err := logic.RefundOrder(&types.RefundOrderRequest{Id: orderID, Reason: "duplicate"})
|
||||
if err == nil {
|
||||
t.Fatalf("RefundOrder expected error, got nil")
|
||||
}
|
||||
if !isErrCode(err, xerr.OrderAlreadyRefunded) {
|
||||
t.Fatalf("RefundOrder error code = %v, want OrderAlreadyRefunded; raw=%v", errCodeOf(err), err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefundOrder_RejectsWhenStatusAlreadyRefunded 覆盖既有 status==6 拒绝路径,
|
||||
// 确保新增的 333 日志校验不会破坏原有「订单已被标记为退款」短路逻辑。
|
||||
func TestRefundOrder_RejectsWhenStatusAlreadyRefunded(t *testing.T) {
|
||||
const (
|
||||
orderID = int64(1001)
|
||||
orderNo = "ORD-STATUS-6"
|
||||
operatorUID = int64(519)
|
||||
)
|
||||
|
||||
db, mock, cleanup := newRefundOrderTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery("FROM `order`").
|
||||
WithArgs(orderID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "order_no", "status"}).
|
||||
AddRow(orderID, orderNo, uint8(orderStatusRefunded)))
|
||||
mock.ExpectRollback()
|
||||
|
||||
logic := newTestRefundOrderLogic(t, db, operatorUID)
|
||||
err := logic.RefundOrder(&types.RefundOrderRequest{Id: orderID})
|
||||
if !isErrCode(err, xerr.OrderAlreadyRefunded) {
|
||||
t.Fatalf("RefundOrder error code = %v, want OrderAlreadyRefunded; raw=%v", errCodeOf(err), err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefundOrder_RejectsWhenStatusNotRefundable 覆盖非 2/5 状态短路。
|
||||
func TestRefundOrder_RejectsWhenStatusNotRefundable(t *testing.T) {
|
||||
const (
|
||||
orderID = int64(1002)
|
||||
orderNo = "ORD-STATUS-1"
|
||||
operatorUID = int64(519)
|
||||
)
|
||||
|
||||
db, mock, cleanup := newRefundOrderTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery("FROM `order`").
|
||||
WithArgs(orderID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "order_no", "status"}).
|
||||
AddRow(orderID, orderNo, uint8(1)))
|
||||
mock.ExpectRollback()
|
||||
|
||||
logic := newTestRefundOrderLogic(t, db, operatorUID)
|
||||
err := logic.RefundOrder(&types.RefundOrderRequest{Id: orderID})
|
||||
if !isErrCode(err, xerr.OrderStatusError) {
|
||||
t.Fatalf("RefundOrder error code = %v, want OrderStatusError; raw=%v", errCodeOf(err), err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newRefundOrderTestDB(t *testing.T) (*gorm.DB, 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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func newTestRefundOrderLogic(t *testing.T, db *gorm.DB, operatorID int64) *RefundOrderLogic {
|
||||
t.Helper()
|
||||
ctx := context.WithValue(context.Background(), constant.CtxKeyUser, &modeluser.User{Id: operatorID})
|
||||
return &RefundOrderLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: &svc.ServiceContext{DB: db},
|
||||
}
|
||||
}
|
||||
|
||||
// errCodeOf / isErrCode 用于绕开 wrapped error 检查内层 xerr 错误码。
|
||||
func errCodeOf(err error) uint32 {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
type coder interface {
|
||||
GetErrCode() uint32
|
||||
}
|
||||
cause := errors.Cause(err)
|
||||
if c, ok := cause.(coder); ok {
|
||||
return c.GetErrCode()
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func isErrCode(err error, code uint32) bool {
|
||||
return errCodeOf(err) == code
|
||||
}
|
||||
|
||||
@@ -12,7 +12,11 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type fakePromoModel struct{}
|
||||
type fakePromoModel struct {
|
||||
insertRule func(context.Context, *promomodel.Rule) error
|
||||
findRule func(context.Context, int64) (*promomodel.Rule, error)
|
||||
updateRule func(context.Context, *promomodel.Rule) error
|
||||
}
|
||||
|
||||
func (fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promomodel.RuleWithPrice, error) {
|
||||
return nil, nil
|
||||
@@ -22,15 +26,24 @@ func (fakePromoModel) InsertUsage(context.Context, *promomodel.Usage, ...*gorm.D
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) InsertRule(context.Context, *promomodel.Rule) error {
|
||||
func (m fakePromoModel) InsertRule(ctx context.Context, rule *promomodel.Rule) error {
|
||||
if m.insertRule != nil {
|
||||
return m.insertRule(ctx, rule)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) FindRule(context.Context, int64) (*promomodel.Rule, error) {
|
||||
func (m fakePromoModel) FindRule(ctx context.Context, id int64) (*promomodel.Rule, error) {
|
||||
if m.findRule != nil {
|
||||
return m.findRule(ctx, id)
|
||||
}
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (fakePromoModel) UpdateRule(context.Context, *promomodel.Rule) error {
|
||||
func (m fakePromoModel) UpdateRule(ctx context.Context, rule *promomodel.Rule) error {
|
||||
if m.updateRule != nil {
|
||||
return m.updateRule(ctx, rule)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -54,7 +67,7 @@ func (fakePromoModel) DeletePrice(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promomodel.SubscribePromo, error) {
|
||||
func (fakePromoModel) QueryPriceList(context.Context, promomodel.PriceFilter) (int64, []*promomodel.SubscribePromo, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ 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"
|
||||
@@ -25,7 +26,12 @@ func NewGetPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetP
|
||||
}
|
||||
|
||||
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))
|
||||
total, list, err := l.svcCtx.PromoModel.QueryPriceList(l.ctx, promomodel.PriceFilter{
|
||||
Page: int(req.Page),
|
||||
Size: int(req.Size),
|
||||
RuleId: req.RuleId,
|
||||
SubscribeId: req.SubscribeId,
|
||||
})
|
||||
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())
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
pkgerrors "github.com/pkg/errors"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestCreateRuleAcceptsMillisecondTimestamps(t *testing.T) {
|
||||
startTime := int64(1777618800000)
|
||||
endTime := int64(1782802800000)
|
||||
var inserted *promomodel.Rule
|
||||
|
||||
svcCtx := &svc.ServiceContext{
|
||||
Redis: redis.NewClient(&redis.Options{Addr: "127.0.0.1:0"}),
|
||||
PromoModel: fakePromoModel{
|
||||
insertRule: func(_ context.Context, rule *promomodel.Rule) error {
|
||||
inserted = rule
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := NewCreateRuleLogic(context.Background(), svcCtx).CreateRule(&types.CreatePromoRuleRequest{
|
||||
Name: "618活动",
|
||||
Type: promomodel.RuleTypeInactiveUser,
|
||||
Params: map[string]interface{}{"inactive_months": float64(1)},
|
||||
Priority: 0,
|
||||
StartTime: &startTime,
|
||||
EndTime: &endTime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateRule returned error: %v", err)
|
||||
}
|
||||
if inserted == nil {
|
||||
t.Fatal("rule was not inserted")
|
||||
}
|
||||
assertPromoRuleTime(t, inserted.StartTime, time.UnixMilli(startTime))
|
||||
assertPromoRuleTime(t, inserted.EndTime, time.UnixMilli(endTime))
|
||||
}
|
||||
|
||||
func TestUpdateRuleAcceptsMillisecondTimestamps(t *testing.T) {
|
||||
startTime := int64(1777618800000)
|
||||
endTime := int64(1782802800000)
|
||||
existing := &promomodel.Rule{Id: 9, Enabled: true}
|
||||
var updated *promomodel.Rule
|
||||
|
||||
svcCtx := &svc.ServiceContext{
|
||||
Redis: redis.NewClient(&redis.Options{Addr: "127.0.0.1:0"}),
|
||||
PromoModel: fakePromoModel{
|
||||
findRule: func(_ context.Context, id int64) (*promomodel.Rule, error) {
|
||||
if id != existing.Id {
|
||||
t.Fatalf("FindRule id = %d, want %d", id, existing.Id)
|
||||
}
|
||||
return existing, nil
|
||||
},
|
||||
updateRule: func(_ context.Context, rule *promomodel.Rule) error {
|
||||
updated = rule
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := NewUpdateRuleLogic(context.Background(), svcCtx).UpdateRule(&types.UpdatePromoRuleRequest{
|
||||
Id: existing.Id,
|
||||
Name: "618活动",
|
||||
Type: promomodel.RuleTypeInactiveUser,
|
||||
Params: map[string]interface{}{"inactive_months": float64(1)},
|
||||
Priority: 0,
|
||||
StartTime: &startTime,
|
||||
EndTime: &endTime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateRule returned error: %v", err)
|
||||
}
|
||||
if updated == nil {
|
||||
t.Fatal("rule was not updated")
|
||||
}
|
||||
assertPromoRuleTime(t, updated.StartTime, time.UnixMilli(startTime))
|
||||
assertPromoRuleTime(t, updated.EndTime, time.UnixMilli(endTime))
|
||||
}
|
||||
|
||||
func TestRuleRejectsOutOfRangeTimestamp(t *testing.T) {
|
||||
startTime := int64(253402300800000)
|
||||
endTime := int64(253402304400000)
|
||||
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{
|
||||
insertRule: func(context.Context, *promomodel.Rule) error {
|
||||
t.Fatal("InsertRule should not be called for invalid timestamp")
|
||||
return nil
|
||||
},
|
||||
}}
|
||||
|
||||
_, err := NewCreateRuleLogic(context.Background(), svcCtx).CreateRule(&types.CreatePromoRuleRequest{
|
||||
Name: "bad time",
|
||||
Type: promomodel.RuleTypeInactiveUser,
|
||||
Params: map[string]interface{}{"inactive_months": float64(1)},
|
||||
Priority: 0,
|
||||
StartTime: &startTime,
|
||||
EndTime: &endTime,
|
||||
})
|
||||
assertInvalidParams(t, err)
|
||||
}
|
||||
|
||||
func assertPromoRuleTime(t *testing.T, got *time.Time, want time.Time) {
|
||||
t.Helper()
|
||||
if got == nil {
|
||||
t.Fatalf("time is nil, want %v", want)
|
||||
}
|
||||
if !got.Equal(want) {
|
||||
t.Fatalf("time = %v, want %v", *got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertInvalidParams(t *testing.T, err error) {
|
||||
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 != xerr.InvalidParams {
|
||||
t.Fatalf("error code = %d, want %d", got, xerr.InvalidParams)
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,24 @@ const (
|
||||
subscribeCachePref = "promo:subscribe:"
|
||||
)
|
||||
|
||||
var (
|
||||
minPromoRuleTime = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
maxPromoRuleTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
|
||||
)
|
||||
|
||||
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 {
|
||||
startAt, err := normalizeRuleTimestamp(startTime)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid start_time")
|
||||
}
|
||||
endAt, err := normalizeRuleTimestamp(endTime)
|
||||
if err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid end_time")
|
||||
}
|
||||
if startAt != nil && endAt != nil && !startAt.Before(*endAt) {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "start_time must be less than end_time")
|
||||
}
|
||||
switch ruleType {
|
||||
@@ -93,12 +106,29 @@ func parseParams(data string) map[string]interface{} {
|
||||
return params
|
||||
}
|
||||
|
||||
func unixPtrToTimePtr(ts *int64) *time.Time {
|
||||
func normalizeRuleTimestamp(ts *int64) (*time.Time, error) {
|
||||
if ts == nil || *ts == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
value := *ts
|
||||
var t time.Time
|
||||
if value >= 1_000_000_000_000 || value <= -1_000_000_000_000 {
|
||||
t = time.UnixMilli(value)
|
||||
} else {
|
||||
t = time.Unix(value, 0)
|
||||
}
|
||||
if t.Before(minPromoRuleTime) || t.After(maxPromoRuleTime) {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "timestamp out of range")
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func unixPtrToTimePtr(ts *int64) *time.Time {
|
||||
t, err := normalizeRuleTimestamp(ts)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
t := time.Unix(*ts, 0)
|
||||
return &t
|
||||
return t
|
||||
}
|
||||
|
||||
func timePtrToUnixPtr(t *time.Time) *int64 {
|
||||
|
||||
@@ -49,7 +49,7 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
|
||||
var rows []InvitedUser
|
||||
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").
|
||||
Select("u.id, u.avatar, u.enable, CAST(UNIX_TIMESTAMP(u.created_at) AS SIGNED) 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), req).
|
||||
Order("u.created_at DESC").
|
||||
Limit(req.Size).
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// HasPaidSubscription reports whether the user owns at least one paid
|
||||
// subscription record — order-backed (order_id > 0) or Apple-IAP-backed
|
||||
// (token LIKE 'iap:%'). Returns false when userID or db are not usable so
|
||||
// callers can fall back to the "first purchase" branch safely.
|
||||
//
|
||||
// This mirrors the predicate used to route /v1/public/order/purchase requests
|
||||
// to renewal semantics. Keep both in sync.
|
||||
func HasPaidSubscription(ctx context.Context, db *gorm.DB, userID int64) (bool, error) {
|
||||
if userID <= 0 || db == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%')", userID).
|
||||
Limit(1).
|
||||
Count(&count).Error; err != nil {
|
||||
return false, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query paid subscription failed: %v", err.Error())
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
@@ -28,9 +28,18 @@ type promoRuleParams struct {
|
||||
InactiveMonths int `json:"inactive_months"`
|
||||
}
|
||||
|
||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
|
||||
// EvaluatePromo decides whether the given (user, subscribe, quantity) tuple
|
||||
// qualifies for any active promo rule. Each rule type has its own gating:
|
||||
// - new_user: requires isFirstPurchase=true (no prior paid subscription)
|
||||
// - inactive_user: requires a previously expired subscription (rule self-check)
|
||||
// - campaign: applies unconditionally within the configured time window
|
||||
//
|
||||
// Pass isFirstPurchase=true on order paths where the request is being routed
|
||||
// as a brand-new purchase; pass false when the user already has a paid
|
||||
// subscription (including expired ones) so NewUser cannot be reused.
|
||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64, isFirstPurchase bool) (*PromoResult, error) {
|
||||
result := &PromoResult{}
|
||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 || quantity <= 0 {
|
||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || subscribeID <= 0 || quantity <= 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -59,7 +68,7 @@ func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64
|
||||
}
|
||||
}
|
||||
|
||||
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, ¤tUser, now)
|
||||
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, isFirstPurchase, ¤tUser, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -96,13 +105,20 @@ func evaluatePromoRule(
|
||||
rule *promo.RuleWithPrice,
|
||||
params promoRuleParams,
|
||||
userID int64,
|
||||
isFirstPurchase bool,
|
||||
currentUser *user.User,
|
||||
now time.Time,
|
||||
) (bool, time.Time, error) {
|
||||
switch rule.Type {
|
||||
case promo.RuleTypeNewUser:
|
||||
if userID <= 0 || !isFirstPurchase {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
|
||||
case promo.RuleTypeInactiveUser:
|
||||
if userID <= 0 {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
|
||||
case promo.RuleTypeCampaign:
|
||||
return true, promoRuleExpiresAt(rule), nil
|
||||
@@ -159,7 +175,7 @@ func evaluateInactiveUserPromo(
|
||||
Take(&lastSub).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return true, ruleExpiresAt, nil
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
|
||||
}
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"gorm.io/driver/mysql"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestEvaluateInactiveUserExpire(t *testing.T) {
|
||||
@@ -44,3 +53,202 @@ func TestEvaluateInactiveUserExpire(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluatePromoAllowsAnonymousCampaign(t *testing.T) {
|
||||
end := time.Now().Add(time.Hour)
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 3,
|
||||
Name: "campaign",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
EndTime: &end,
|
||||
},
|
||||
PromoPrice: 199,
|
||||
},
|
||||
}}
|
||||
|
||||
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 0, 7, 12, true)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluatePromo returned error: %v", err)
|
||||
}
|
||||
if !got.Eligible {
|
||||
t.Fatal("anonymous campaign promo should be eligible")
|
||||
}
|
||||
if got.RuleID != 3 {
|
||||
t.Fatalf("RuleID = %d, want 3", got.RuleID)
|
||||
}
|
||||
if got.PromoPrice != 199 {
|
||||
t.Fatalf("PromoPrice = %d, want 199", got.PromoPrice)
|
||||
}
|
||||
if model.lastSubscribeID != 7 {
|
||||
t.Fatalf("lastSubscribeID = %d, want 7", model.lastSubscribeID)
|
||||
}
|
||||
if model.lastQuantity != 12 {
|
||||
t.Fatalf("lastQuantity = %d, want 12", model.lastQuantity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluatePromoCampaignAppliesToReturningUsers(t *testing.T) {
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 4,
|
||||
Name: "campaign",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
},
|
||||
PromoPrice: 299,
|
||||
},
|
||||
}}
|
||||
|
||||
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 42, 7, 1, false)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluatePromo returned error: %v", err)
|
||||
}
|
||||
if !got.Eligible {
|
||||
t.Fatal("campaign promo should remain eligible for returning users (isFirstPurchase=false)")
|
||||
}
|
||||
if got.PromoPrice != 299 {
|
||||
t.Fatalf("PromoPrice = %d, want 299", got.PromoPrice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluatePromoNewUserRequiresFirstPurchase(t *testing.T) {
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 5,
|
||||
Name: "new user",
|
||||
Type: promo.RuleTypeNewUser,
|
||||
Enabled: true,
|
||||
Params: `{"window_hours": 72}`,
|
||||
},
|
||||
PromoPrice: 99,
|
||||
},
|
||||
}}
|
||||
|
||||
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 42, 7, 1, false)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluatePromo returned error: %v", err)
|
||||
}
|
||||
if got.Eligible {
|
||||
t.Fatal("new-user promo must be gated out when isFirstPurchase=false (user already has paid subscriptions)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluatePromoRejectsInactiveRuleWhenUserHasNoSubscription(t *testing.T) {
|
||||
db, mock, cleanup := newCommonPromoTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 9,
|
||||
Name: "inactive",
|
||||
Type: promo.RuleTypeInactiveUser,
|
||||
Params: `{"inactive_months":3}`,
|
||||
Enabled: true,
|
||||
},
|
||||
PromoPrice: 100,
|
||||
},
|
||||
}}
|
||||
|
||||
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `user_subscribe` WHERE user_id = ? ORDER BY CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC LIMIT ?")).
|
||||
WithArgs(int64(51640), time.UnixMilli(0), 1).
|
||||
WillReturnError(gorm.ErrRecordNotFound)
|
||||
|
||||
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: db, PromoModel: model}, 51640, 1, 30, true)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluatePromo returned error: %v", err)
|
||||
}
|
||||
if got.Eligible {
|
||||
t.Fatal("new user without subscription history should not be eligible for inactive promo")
|
||||
}
|
||||
if got.RuleID != 0 || got.PromoPrice != 0 {
|
||||
t.Fatalf("promo fields = (%d, %d), want zero values", got.RuleID, got.PromoPrice)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet db expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakePromoModel struct {
|
||||
rules []*promo.RuleWithPrice
|
||||
lastSubscribeID int64
|
||||
lastQuantity int64
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
|
||||
m.lastSubscribeID = subscribeID
|
||||
m.lastQuantity = quantity
|
||||
return m.rules, nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
||||
return nil, 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, promo.PriceFilter) (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 newCommonPromoTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) {
|
||||
t.Helper()
|
||||
|
||||
sqlDB, mock, err := sqlmock.New()
|
||||
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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/model/payment"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -22,6 +23,47 @@ import (
|
||||
queueType "github.com/perfect-panel/server/queue/types"
|
||||
)
|
||||
|
||||
// epayNotifyTradeNotSuccess identifies the "buyer paid but trade not in TRADE_SUCCESS
|
||||
// terminal state" branch in metrics / log search. EPay is told 200 here so it will
|
||||
// not retry; we still want it visible for monitoring (HIF-135 / HIF-136).
|
||||
const epayNotifyTradeNotSuccess = "epay_notify_trade_not_success"
|
||||
|
||||
// epayNotifyDecision encodes the post-parse decision so the branching logic can be
|
||||
// unit-tested without spinning up a real OrderModel / Redis / asynq stack.
|
||||
type epayNotifyDecision int
|
||||
|
||||
const (
|
||||
// epayNotifyDecisionRejectSign: signature is invalid and debug bypass is off.
|
||||
// Caller MUST return an error so the handler responds non-200 and EPay retries.
|
||||
epayNotifyDecisionRejectSign epayNotifyDecision = iota
|
||||
// epayNotifyDecisionAckTradeNotSuccess: trade_status != TRADE_SUCCESS
|
||||
// (user cancelled / failed at gateway). Acknowledge with 200 "success" and emit
|
||||
// a metric-named log for monitoring.
|
||||
epayNotifyDecisionAckTradeNotSuccess
|
||||
// epayNotifyDecisionAckIdempotent: order already at Finished (status=5).
|
||||
// Repeat callback — ack with 200 "success", do not re-enqueue activation.
|
||||
epayNotifyDecisionAckIdempotent
|
||||
// epayNotifyDecisionProcess: happy path. Write trade_no, flip status to Paid,
|
||||
// enqueue activation task.
|
||||
epayNotifyDecisionProcess
|
||||
)
|
||||
|
||||
// evaluateEPayNotify is a pure decision function so each branch can be unit-tested
|
||||
// without DB/Redis. Caller has already located the order; orderStatus is the
|
||||
// current status from the DB row.
|
||||
func evaluateEPayNotify(signValid, debugBypass bool, tradeStatus string, orderStatus uint8) epayNotifyDecision {
|
||||
if !signValid && !debugBypass {
|
||||
return epayNotifyDecisionRejectSign
|
||||
}
|
||||
if tradeStatus != "TRADE_SUCCESS" {
|
||||
return epayNotifyDecisionAckTradeNotSuccess
|
||||
}
|
||||
if orderStatus == 5 {
|
||||
return epayNotifyDecisionAckIdempotent
|
||||
}
|
||||
return epayNotifyDecisionProcess
|
||||
}
|
||||
|
||||
type EPayNotifyLogic struct {
|
||||
logger.Logger
|
||||
ctx *gin.Context
|
||||
@@ -47,6 +89,8 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
|
||||
}
|
||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OutTradeNo)
|
||||
if err != nil {
|
||||
// HIF-136 P02: order missing must propagate as error so EPay retries instead
|
||||
// of being silently lost (was previously masked by a `return nil` further down).
|
||||
l.Logger.Error("[EPayNotify] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OutTradeNo))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", req.OutTradeNo)
|
||||
}
|
||||
@@ -65,17 +109,54 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
|
||||
}
|
||||
// Verify sign
|
||||
client := epay.NewClient(config.Pid, config.Url, config.Key, config.Type)
|
||||
if !client.VerifySign(urlParamsToMap(l.ctx.Request.URL.RawQuery)) && !l.svcCtx.Config.Debug {
|
||||
l.Logger.Error("[EPayNotify] Verify sign failed")
|
||||
signValid := client.VerifySign(urlParamsToMap(l.ctx.Request.URL.RawQuery))
|
||||
|
||||
decision := evaluateEPayNotify(signValid, l.svcCtx.Config.Debug, req.TradeStatus, orderInfo.Status)
|
||||
switch decision {
|
||||
case epayNotifyDecisionRejectSign:
|
||||
// HIF-136 P01: previously `return nil` here let EPay see 200 and stop retrying;
|
||||
// caller still left order at status=1, which DeferCloseOrder then closed.
|
||||
// Return error so handler responds non-200 and EPay retries.
|
||||
l.Logger.Error("[EPayNotify] Verify sign failed",
|
||||
logger.Field("order_no", req.OutTradeNo),
|
||||
logger.Field("trade_no", req.TradeNo),
|
||||
logger.Field("raw_query", l.ctx.Request.URL.RawQuery),
|
||||
)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.SignatureInvalid), "verify sign failed: %v", req.OutTradeNo)
|
||||
case epayNotifyDecisionAckTradeNotSuccess:
|
||||
// User cancelled / gateway-side failure: ack 200 to stop retries, but keep
|
||||
// the path observable under metric name `epay_notify_trade_not_success`.
|
||||
l.Logger.Info("[EPayNotify] Trade status not success",
|
||||
logger.Field("order_no", req.OutTradeNo),
|
||||
logger.Field("trade_status", req.TradeStatus),
|
||||
logger.Field("metric", epayNotifyTradeNotSuccess),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
if req.TradeStatus != "TRADE_SUCCESS" {
|
||||
l.Logger.Error("[EPayNotify] Trade status is not success", logger.Field("orderNo", req.OutTradeNo), logger.Field("tradeStatus", req.TradeStatus))
|
||||
case epayNotifyDecisionAckIdempotent:
|
||||
// Order already Finished — repeat callback is expected, ack with 200.
|
||||
return nil
|
||||
case epayNotifyDecisionProcess:
|
||||
// fall through
|
||||
}
|
||||
if orderInfo.Status == 5 {
|
||||
return nil
|
||||
|
||||
// HIF-136 P03: persist gateway trade_no BEFORE flipping status so post-mortems can
|
||||
// reverse-lookup EPay flows to ppanel orders. Raw gorm write is acceptable here —
|
||||
// the subsequent UpdateOrderStatus will invalidate the cache key (keys are by
|
||||
// order_no / id, both stable across this field write).
|
||||
if req.TradeNo != "" {
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&order.Order{}).
|
||||
Where("order_no = ?", req.OutTradeNo).
|
||||
Update("trade_no", req.TradeNo).Error; err != nil {
|
||||
l.Logger.Error("[EPayNotify] Update trade_no failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("order_no", req.OutTradeNo),
|
||||
logger.Field("trade_no", req.TradeNo),
|
||||
)
|
||||
return errors.Wrapf(err, "update trade_no failed: %v", req.OutTradeNo)
|
||||
}
|
||||
}
|
||||
|
||||
// Update order status
|
||||
err = l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, req.OutTradeNo, 2)
|
||||
if err != nil {
|
||||
@@ -86,6 +167,7 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
|
||||
"[SubscriptionFlow] epay notify marked order as paid",
|
||||
append(commonLogic.OrderTraceFields(orderInfo),
|
||||
logger.Field("payment_platform", data.Platform),
|
||||
logger.Field("trade_no", req.TradeNo),
|
||||
)...,
|
||||
)
|
||||
// Create activate order task
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestEvaluateEPayNotify_RejectsInvalidSign covers HIF-136 P01: sign invalid +
|
||||
// debug bypass off must return rejectSign so the handler responds non-200 and
|
||||
// EPay retries (was previously a silent `return nil` → 200 → no retry).
|
||||
func TestEvaluateEPayNotify_RejectsInvalidSign(t *testing.T) {
|
||||
got := evaluateEPayNotify(false, false, "TRADE_SUCCESS", 1)
|
||||
if got != epayNotifyDecisionRejectSign {
|
||||
t.Fatalf("evaluateEPayNotify(invalid sign): got %v want %v", got, epayNotifyDecisionRejectSign)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvaluateEPayNotify_DebugBypassAllowsInvalidSign documents the debug-mode
|
||||
// escape hatch the issue calls out: production runs with Debug=false so this
|
||||
// branch is never taken in prod, but local/dev should still flow through.
|
||||
func TestEvaluateEPayNotify_DebugBypassAllowsInvalidSign(t *testing.T) {
|
||||
got := evaluateEPayNotify(false, true, "TRADE_SUCCESS", 1)
|
||||
if got != epayNotifyDecisionProcess {
|
||||
t.Fatalf("evaluateEPayNotify(invalid sign + debug): got %v want %v", got, epayNotifyDecisionProcess)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvaluateEPayNotify_TradeNotSuccess covers the user-cancelled / gateway-failure
|
||||
// branch: behaviour unchanged (return nil → 200), but caller must now emit the
|
||||
// `epay_notify_trade_not_success` metric-named log instead of an Error-level one.
|
||||
func TestEvaluateEPayNotify_TradeNotSuccess(t *testing.T) {
|
||||
tests := []string{"TRADE_FAILED", "WAIT_BUYER_PAY", ""}
|
||||
for _, ts := range tests {
|
||||
t.Run(ts, func(t *testing.T) {
|
||||
got := evaluateEPayNotify(true, false, ts, 1)
|
||||
if got != epayNotifyDecisionAckTradeNotSuccess {
|
||||
t.Fatalf("evaluateEPayNotify(trade_status=%q): got %v want %v",
|
||||
ts, got, epayNotifyDecisionAckTradeNotSuccess)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvaluateEPayNotify_IdempotentForFinishedOrder covers the only legitimate
|
||||
// `return nil` short-circuit retained by HIF-136: duplicate callback for an
|
||||
// already Finished (status=5) order is acknowledged with 200 instead of being
|
||||
// re-processed.
|
||||
func TestEvaluateEPayNotify_IdempotentForFinishedOrder(t *testing.T) {
|
||||
got := evaluateEPayNotify(true, false, "TRADE_SUCCESS", 5)
|
||||
if got != epayNotifyDecisionAckIdempotent {
|
||||
t.Fatalf("evaluateEPayNotify(status=5): got %v want %v", got, epayNotifyDecisionAckIdempotent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvaluateEPayNotify_HappyPath covers the normal success branch: valid sign,
|
||||
// trade_status=TRADE_SUCCESS, order not yet Finished → proceed to write trade_no
|
||||
// + flip status + enqueue activation.
|
||||
func TestEvaluateEPayNotify_HappyPath(t *testing.T) {
|
||||
statuses := []uint8{1, 2, 3, 4} // anything but Finished(5)
|
||||
for _, s := range statuses {
|
||||
got := evaluateEPayNotify(true, false, "TRADE_SUCCESS", s)
|
||||
if got != epayNotifyDecisionProcess {
|
||||
t.Fatalf("evaluateEPayNotify(status=%d): got %v want %v", s, got, epayNotifyDecisionProcess)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvaluateEPayNotify_SignTakesPrecedenceOverIdempotency guards against a
|
||||
// regression where a duplicate callback with a forged signature gets quietly
|
||||
// acked because status==5 was checked before sign.
|
||||
func TestEvaluateEPayNotify_SignTakesPrecedenceOverIdempotency(t *testing.T) {
|
||||
got := evaluateEPayNotify(false, false, "TRADE_SUCCESS", 5)
|
||||
if got != epayNotifyDecisionRejectSign {
|
||||
t.Fatalf("evaluateEPayNotify(invalid sign + status=5): got %v want %v",
|
||||
got, epayNotifyDecisionRejectSign)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUrlParamsToMap verifies the helper used to feed VerifySign — collapses
|
||||
// each query parameter to its first value and treats absent params as missing.
|
||||
func TestUrlParamsToMap(t *testing.T) {
|
||||
got := urlParamsToMap("pid=1001&out_trade_no=ORD-1&trade_no=EPAY-9&sign=abc&trade_status=TRADE_SUCCESS")
|
||||
want := map[string]string{
|
||||
"pid": "1001",
|
||||
"out_trade_no": "ORD-1",
|
||||
"trade_no": "EPAY-9",
|
||||
"sign": "abc",
|
||||
"trade_status": "TRADE_SUCCESS",
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("urlParamsToMap len = %d want %d (got=%v)", len(got), len(want), got)
|
||||
}
|
||||
for k, v := range want {
|
||||
if got[k] != v {
|
||||
t.Fatalf("urlParamsToMap[%q] = %q want %q", k, got[k], v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEPayNotify_TradeNoRawWrite verifies HIF-136 P03 at the SQL boundary: the
|
||||
// raw gorm write hits the `order` table with the exact `trade_no` from the
|
||||
// EPay request, scoped by `order_no`, and surfaces driver errors back to the
|
||||
// caller (so they propagate as non-200 and EPay retries).
|
||||
func TestEPayNotify_TradeNoRawWrite(t *testing.T) {
|
||||
db, mock, cleanup := newEPayNotifyTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
const (
|
||||
orderNo = "202606010001"
|
||||
tradeNo = "EPAY-202606010001"
|
||||
)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE `order` SET `trade_no`").
|
||||
WithArgs(tradeNo, sqlmock.AnyArg(), orderNo).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
err := db.WithContext(context.Background()).
|
||||
Model(&order.Order{}).
|
||||
Where("order_no = ?", orderNo).
|
||||
Update("trade_no", tradeNo).Error
|
||||
if err != nil {
|
||||
t.Fatalf("raw trade_no update: %v", err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEPayNotify_TradeNoRawWritePropagatesError ensures a DB-side failure during
|
||||
// the trade_no backfill is not swallowed — caller returns the error so EPay
|
||||
// retries instead of silently flipping status without trade_no being written.
|
||||
func TestEPayNotify_TradeNoRawWritePropagatesError(t *testing.T) {
|
||||
db, mock, cleanup := newEPayNotifyTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE `order` SET `trade_no`").
|
||||
WillReturnError(fmt.Errorf("deadlock detected"))
|
||||
mock.ExpectRollback()
|
||||
|
||||
err := db.WithContext(context.Background()).
|
||||
Model(&order.Order{}).
|
||||
Where("order_no = ?", "ORD-2").
|
||||
Update("trade_no", "EPAY-2").Error
|
||||
if err == nil {
|
||||
t.Fatalf("expected error from raw trade_no update, got nil")
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newEPayNotifyTestDB(t *testing.T) (*gorm.DB, 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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func paidSubscriptionQuery(ctx context.Context, db *gorm.DB, userID int64) *gorm.DB {
|
||||
return db.WithContext(ctx).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%')", userID).
|
||||
Order("expire_time DESC").
|
||||
Order("updated_at DESC").
|
||||
Order("id DESC")
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestPaidSubscriptionQueryIncludesOrderBackedSubscriptionWithoutToken(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 sub user.Subscribe
|
||||
tx := paidSubscriptionQuery(context.Background(), db, 510).First(&sub)
|
||||
sql := tx.Statement.SQL.String()
|
||||
|
||||
if strings.Contains(sql, "token != ''") {
|
||||
t.Fatalf("paid subscription query should not require non-empty token: %s", sql)
|
||||
}
|
||||
if !strings.Contains(sql, "order_id > 0 OR token LIKE 'iap:%'") {
|
||||
t.Fatalf("paid subscription query should include order-backed or iap-backed subscriptions: %s", sql)
|
||||
}
|
||||
}
|
||||
@@ -88,13 +88,8 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
// 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 != "" {
|
||||
if e := paidSubscriptionQuery(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID).
|
||||
First(&existSub).Error; e == nil && existSub.Id > 0 {
|
||||
orderType = 2
|
||||
l.Infow("[PreCreateOrder] purchase preview routed to renewal because an existing subscription was found",
|
||||
logger.Field("route_mode", "global_single_subscription"),
|
||||
|
||||
@@ -27,7 +27,7 @@ func calculatePurchasePrice(
|
||||
quantity int64,
|
||||
discounts []types.SubscribeDiscount,
|
||||
eligibleForDiscount bool,
|
||||
allowPromo bool,
|
||||
isFirstPurchase bool,
|
||||
) (*orderPriceResult, error) {
|
||||
originalPrice := unitPrice * quantity
|
||||
result := &orderPriceResult{
|
||||
@@ -35,21 +35,19 @@ func calculatePurchasePrice(
|
||||
PayableBase: originalPrice,
|
||||
}
|
||||
|
||||
if allowPromo {
|
||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
if result.PromoDiscount < 0 {
|
||||
result.PromoDiscount = 0
|
||||
}
|
||||
return result, nil
|
||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity, isFirstPurchase)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
if result.PromoDiscount < 0 {
|
||||
result.PromoDiscount = 0
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
discount := float64(1)
|
||||
|
||||
@@ -63,7 +63,7 @@ func (m *fakePromoModel) DeletePrice(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promo.SubscribePromo, error) {
|
||||
func (m *fakePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
@@ -221,3 +221,79 @@ func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
|
||||
t.Fatalf("PromoRuleId = %d, want 11", result.PromoRuleId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculatePurchasePriceCampaignAppliesToReturningUsers(t *testing.T) {
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 12,
|
||||
Name: "campaign",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
},
|
||||
PromoPrice: 400,
|
||||
},
|
||||
}}
|
||||
svcCtx := &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}
|
||||
|
||||
// isFirstPurchase=false simulates a returning user routed to renewal; the
|
||||
// Campaign promo must still apply because it has no first-purchase gate.
|
||||
result, err := calculatePurchasePrice(
|
||||
context.Background(),
|
||||
svcCtx,
|
||||
42,
|
||||
2,
|
||||
1000,
|
||||
1,
|
||||
nil,
|
||||
false,
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
||||
}
|
||||
if result.PromoRuleId != 12 {
|
||||
t.Fatalf("PromoRuleId = %d, want 12 (campaign should apply to returning users)", result.PromoRuleId)
|
||||
}
|
||||
if result.PayableBase != 400 {
|
||||
t.Fatalf("PayableBase = %d, want 400", result.PayableBase)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculatePurchasePriceNewUserGatedByFirstPurchase(t *testing.T) {
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 13,
|
||||
Name: "new user",
|
||||
Type: promo.RuleTypeNewUser,
|
||||
Enabled: true,
|
||||
Params: `{"window_hours": 72}`,
|
||||
},
|
||||
PromoPrice: 200,
|
||||
},
|
||||
}}
|
||||
svcCtx := &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}
|
||||
|
||||
// isFirstPurchase=false → NewUser rule must be skipped, regular discount applies.
|
||||
result, err := calculatePurchasePrice(
|
||||
context.Background(),
|
||||
svcCtx,
|
||||
42,
|
||||
2,
|
||||
1000,
|
||||
1,
|
||||
[]types.SubscribeDiscount{{Quantity: 1, Discount: 90}},
|
||||
true,
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
||||
}
|
||||
if result.PromoRuleId != 0 || result.PromoDiscount != 0 {
|
||||
t.Fatalf("promo fields = (%d, %d), want (0, 0) when isFirstPurchase=false", result.PromoRuleId, result.PromoDiscount)
|
||||
}
|
||||
if result.PayableBase != 900 {
|
||||
t.Fatalf("PayableBase = %d, want 900 (regular 90%% discount)", result.PayableBase)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,13 +129,8 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
||||
// 防止不同套餐购买创建第二条订阅。
|
||||
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 != "" {
|
||||
if e := paidSubscriptionQuery(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID).
|
||||
First(&existSub).Error; e == nil && existSub.Id > 0 {
|
||||
orderType = 2
|
||||
parentOrderID = existSub.OrderId
|
||||
subscribeToken = existSub.Token
|
||||
@@ -194,11 +189,12 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeOutOfStock), "subscribe out of stock")
|
||||
}
|
||||
|
||||
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("[Purchase] Database query error resolving new user eligibility",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("user_id", u.Id),
|
||||
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
@@ -206,7 +202,7 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
||||
priceResult, err := calculatePurchasePrice(
|
||||
l.ctx,
|
||||
l.svcCtx,
|
||||
u.Id,
|
||||
entitlement.EffectiveUserID,
|
||||
targetSubscribeID,
|
||||
sub.UnitPrice,
|
||||
req.Quantity,
|
||||
@@ -218,6 +214,7 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
||||
l.Errorw("[Purchase] Promo price calculation error",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("user_id", u.Id),
|
||||
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
||||
logger.Field("subscribe_id", targetSubscribeID),
|
||||
)
|
||||
return nil, err
|
||||
|
||||
@@ -2,12 +2,12 @@ package subscribe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -35,11 +34,6 @@ type subscribePromoCandidate struct {
|
||||
EndTime *time.Time `gorm:"column:end_time"`
|
||||
}
|
||||
|
||||
type promoRuleParams struct {
|
||||
WindowHours int64 `json:"window_hours"`
|
||||
InactiveMonths int `json:"inactive_months"`
|
||||
}
|
||||
|
||||
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
|
||||
result := make(map[int64]map[int64]*types.SubscribePromo)
|
||||
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
||||
@@ -47,6 +41,22 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
||||
}
|
||||
|
||||
userInfo, _ := ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
userID := int64(0)
|
||||
isFirstPurchase := true
|
||||
if userInfo != nil {
|
||||
entitlement, err := commonLogic.ResolveEntitlementUser(ctx, svcCtx.DB, userInfo.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userID = entitlement.EffectiveUserID
|
||||
|
||||
hasPaid, err := commonLogic.HasPaidSubscription(ctx, svcCtx.DB, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
isFirstPurchase = !hasPaid
|
||||
}
|
||||
|
||||
candidates, err := querySubscribePromoCandidates(ctx, svcCtx, subscribeIDs, userInfo != nil)
|
||||
if err != nil {
|
||||
if isMissingPromoTableError(err) {
|
||||
@@ -55,8 +65,6 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
||||
return nil, err
|
||||
}
|
||||
|
||||
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
||||
now := time.Now()
|
||||
for _, candidate := range candidates {
|
||||
if candidate.Quantity <= 0 {
|
||||
continue
|
||||
@@ -67,21 +75,18 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
||||
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
|
||||
continue
|
||||
}
|
||||
if !candidate.isActive(now) {
|
||||
continue
|
||||
}
|
||||
ok, expiresAt, err := evaluator.match(candidate, now)
|
||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, candidate.SubscribeId, candidate.Quantity, isFirstPurchase)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
if promoResult == nil || !promoResult.Eligible {
|
||||
continue
|
||||
}
|
||||
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
|
||||
RuleName: candidate.RuleName,
|
||||
RuleType: candidate.RuleType,
|
||||
PromoPrice: candidate.PromoPrice,
|
||||
ExpiresAt: unixSeconds(expiresAt),
|
||||
RuleName: promoResult.RuleName,
|
||||
RuleType: promoResult.RuleType,
|
||||
PromoPrice: promoResult.PromoPrice,
|
||||
ExpiresAt: unixSeconds(promoResult.ExpiresAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,121 +119,6 @@ func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeID
|
||||
Order("pr.id ASC")
|
||||
}
|
||||
|
||||
func (c subscribePromoCandidate) isActive(now time.Time) bool {
|
||||
if c.PromoPrice <= 0 {
|
||||
return false
|
||||
}
|
||||
if c.StartTime != nil && now.Before(*c.StartTime) {
|
||||
return false
|
||||
}
|
||||
if c.EndTime != nil && now.After(*c.EndTime) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type promoEligibilityEvaluator struct {
|
||||
ctx context.Context
|
||||
db *gorm.DB
|
||||
userInfo *user.User
|
||||
lastExpire *time.Time
|
||||
}
|
||||
|
||||
func (e *promoEligibilityEvaluator) match(candidate subscribePromoCandidate, now time.Time) (bool, time.Time, error) {
|
||||
switch candidate.RuleType {
|
||||
case promoRuleTypeCampaign:
|
||||
return true, candidate.expiresAt(), nil
|
||||
case promoRuleTypeNewUser:
|
||||
if e.userInfo == nil {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
params, err := candidate.params()
|
||||
if err != nil {
|
||||
return false, time.Time{}, err
|
||||
}
|
||||
if params.WindowHours <= 0 || e.userInfo.CreatedAt.IsZero() {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
expiresAt := e.userInfo.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
||||
return now.Before(expiresAt), expiresAt, nil
|
||||
case promoRuleTypeInactiveUser:
|
||||
if e.userInfo == nil {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
params, err := candidate.params()
|
||||
if err != nil {
|
||||
return false, time.Time{}, err
|
||||
}
|
||||
if params.InactiveMonths <= 0 {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
lastExpire, err := e.lastSubscribeExpireAt()
|
||||
if err != nil {
|
||||
return false, time.Time{}, err
|
||||
}
|
||||
if lastExpire.Equal(time.UnixMilli(0)) || lastExpire.After(now) {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
if lastExpire.IsZero() {
|
||||
return true, candidate.expiresAt(), nil
|
||||
}
|
||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
||||
return !lastExpire.After(threshold), candidate.expiresAt(), nil
|
||||
default:
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
||||
if e.lastExpire != nil {
|
||||
return *e.lastExpire, nil
|
||||
}
|
||||
var item user.Subscribe
|
||||
err := e.lastSubscribeExpireQuery().
|
||||
Limit(1).
|
||||
Take(&item).Error
|
||||
if err != nil {
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
zero := time.Time{}
|
||||
e.lastExpire = &zero
|
||||
return zero, nil
|
||||
}
|
||||
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
|
||||
}
|
||||
e.lastExpire = &item.ExpireTime
|
||||
return item.ExpireTime, nil
|
||||
}
|
||||
|
||||
func (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{}
|
||||
}
|
||||
return *c.EndTime
|
||||
}
|
||||
|
||||
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
|
||||
if c.Params == "" {
|
||||
return promoRuleParams{}, nil
|
||||
}
|
||||
var params promoRuleParams
|
||||
if err := json.Unmarshal([]byte(c.Params), ¶ms); err != nil {
|
||||
return promoRuleParams{}, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "parse promo rule params failed")
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func unixSeconds(t time.Time) int64 {
|
||||
if t.IsZero() {
|
||||
return 0
|
||||
|
||||
@@ -2,114 +2,21 @@ package subscribe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/constant"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
||||
now := time.Unix(1710000000, 0)
|
||||
campaignEnd := now.Add(2 * time.Hour)
|
||||
|
||||
campaign := subscribePromoCandidate{
|
||||
RuleName: "限时活动",
|
||||
RuleType: promoRuleTypeCampaign,
|
||||
PromoPrice: 99,
|
||||
EndTime: &campaignEnd,
|
||||
}
|
||||
ok, expiresAt, err := (&promoEligibilityEvaluator{}).match(campaign, now)
|
||||
if err != nil {
|
||||
t.Fatalf("campaign match error: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("campaign promo should match without login")
|
||||
}
|
||||
if got, want := unixSeconds(expiresAt), campaignEnd.Unix(); got != want {
|
||||
t.Fatalf("campaign expires_at = %d, want %d", got, want)
|
||||
}
|
||||
|
||||
newUser := subscribePromoCandidate{
|
||||
RuleName: "新客7天优惠",
|
||||
RuleType: promoRuleTypeNewUser,
|
||||
PromoPrice: 279,
|
||||
Params: `{"window_hours":168}`,
|
||||
}
|
||||
ok, _, err = (&promoEligibilityEvaluator{}).match(newUser, now)
|
||||
if err != nil {
|
||||
t.Fatalf("anonymous new_user match error: %v", err)
|
||||
}
|
||||
if ok {
|
||||
t.Fatal("new_user promo should not match without login")
|
||||
}
|
||||
|
||||
userInfo := &user.User{Id: 1, CreatedAt: now.Add(-24 * time.Hour)}
|
||||
ok, expiresAt, err = (&promoEligibilityEvaluator{userInfo: userInfo}).match(newUser, now)
|
||||
if err != nil {
|
||||
t.Fatalf("logged-in new_user match error: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("new_user promo should match inside window")
|
||||
}
|
||||
if got, want := unixSeconds(expiresAt), userInfo.CreatedAt.Add(168*time.Hour).Unix(); got != want {
|
||||
t.Fatalf("new_user expires_at = %d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
|
||||
now := time.Unix(1710000000, 0)
|
||||
start := now.Add(-time.Hour)
|
||||
end := now.Add(time.Hour)
|
||||
|
||||
if !(subscribePromoCandidate{PromoPrice: 1, StartTime: &start, EndTime: &end}).isActive(now) {
|
||||
t.Fatal("candidate inside active window should be active")
|
||||
}
|
||||
if (subscribePromoCandidate{PromoPrice: 0, StartTime: &start, EndTime: &end}).isActive(now) {
|
||||
t.Fatal("candidate with zero promo price should not be active")
|
||||
}
|
||||
if (subscribePromoCandidate{PromoPrice: 1, StartTime: &end}).isActive(now) {
|
||||
t.Fatal("candidate before start time should not be active")
|
||||
}
|
||||
if (subscribePromoCandidate{PromoPrice: 1, EndTime: &start}).isActive(now) {
|
||||
t.Fatal("candidate after end time should not be active")
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
@@ -131,6 +38,202 @@ func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSubscribePromoMapUsesCommonPromoEvaluation(t *testing.T) {
|
||||
db, mock, cleanup := newSubscribePromoTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
end := time.Now().Add(time.Hour)
|
||||
mock.ExpectQuery("FROM subscribe_promo AS sp").
|
||||
WillReturnRows(sqlmock.NewRows([]string{
|
||||
"subscribe_id", "quantity", "rule_name", "rule_type", "promo_price", "params", "start_time", "end_time",
|
||||
}).AddRow(11, 3, "old name", promoRuleTypeCampaign, 999, "", nil, end))
|
||||
|
||||
promoModel := &fakeSubscribePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 8,
|
||||
Name: "公共活动价",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
EndTime: &end,
|
||||
},
|
||||
PromoPrice: 888,
|
||||
},
|
||||
}}
|
||||
|
||||
got, err := loadSubscribePromoMap(context.Background(), &svc.ServiceContext{DB: db, PromoModel: promoModel}, []int64{11})
|
||||
if err != nil {
|
||||
t.Fatalf("loadSubscribePromoMap returned error: %v", err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("sql expectations: %v", err)
|
||||
}
|
||||
if promoModel.lastSubscribeID != 11 {
|
||||
t.Fatalf("promo subscribe id = %d, want 11", promoModel.lastSubscribeID)
|
||||
}
|
||||
if promoModel.lastQuantity != 3 {
|
||||
t.Fatalf("promo quantity = %d, want 3", promoModel.lastQuantity)
|
||||
}
|
||||
|
||||
item := got[11][3]
|
||||
if item == nil {
|
||||
t.Fatal("quantity 3 promo should be present")
|
||||
}
|
||||
if item.RuleName != "公共活动价" {
|
||||
t.Fatalf("RuleName = %q, want 公共活动价", item.RuleName)
|
||||
}
|
||||
if item.PromoPrice != 888 {
|
||||
t.Fatalf("PromoPrice = %d, want 888", item.PromoPrice)
|
||||
}
|
||||
if item.ExpiresAt != end.Unix() {
|
||||
t.Fatalf("ExpiresAt = %d, want %d", item.ExpiresAt, end.Unix())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSubscribePromoMapUsesFamilyOwnerForInactivePromo(t *testing.T) {
|
||||
db, mock, cleanup := newSubscribePromoTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
memberUserID := int64(51637)
|
||||
ownerUserID := int64(510)
|
||||
subscribeID := int64(11)
|
||||
quantity := int64(30)
|
||||
now := time.Now()
|
||||
end := now.Add(24 * time.Hour)
|
||||
|
||||
mock.ExpectQuery("FROM `user_family_member`").
|
||||
WithArgs(memberUserID, user.FamilyMemberActive, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"role", "family_status", "owner_user_id"}).
|
||||
AddRow(user.FamilyRoleMember, user.FamilyStatusActive, ownerUserID))
|
||||
mock.ExpectQuery("SELECT count(*) FROM `user_subscribe`").
|
||||
WithArgs(ownerUserID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0))
|
||||
mock.ExpectQuery("FROM subscribe_promo AS sp").
|
||||
WillReturnRows(sqlmock.NewRows([]string{
|
||||
"subscribe_id", "quantity", "rule_name", "rule_type", "promo_price", "params", "start_time", "end_time",
|
||||
}).AddRow(subscribeID, quantity, "回归用户01", promoRuleTypeInactiveUser, 100, `{"inactive_months":1}`, nil, end))
|
||||
mock.ExpectQuery("FROM `user_subscribe`").
|
||||
WithArgs(ownerUserID, time.UnixMilli(0), 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "subscribe_id", "expire_time"}).
|
||||
AddRow(131, ownerUserID, 1, now.AddDate(0, 1, 0)))
|
||||
|
||||
ctx := context.WithValue(context.Background(), constant.CtxKeyUser, &user.User{Id: memberUserID})
|
||||
promoModel := &fakeSubscribePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 8,
|
||||
Name: "回归用户01",
|
||||
Type: promo.RuleTypeInactiveUser,
|
||||
Enabled: true,
|
||||
Params: `{"inactive_months":1}`,
|
||||
EndTime: &end,
|
||||
},
|
||||
PromoPrice: 100,
|
||||
},
|
||||
}}
|
||||
|
||||
got, err := loadSubscribePromoMap(ctx, &svc.ServiceContext{DB: db, PromoModel: promoModel}, []int64{subscribeID})
|
||||
if err != nil {
|
||||
t.Fatalf("loadSubscribePromoMap returned error: %v", err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("sql expectations: %v", err)
|
||||
}
|
||||
if promoModel.lastSubscribeID != subscribeID {
|
||||
t.Fatalf("promo subscribe id = %d, want %d", promoModel.lastSubscribeID, subscribeID)
|
||||
}
|
||||
if promoModel.lastQuantity != quantity {
|
||||
t.Fatalf("promo quantity = %d, want %d", promoModel.lastQuantity, quantity)
|
||||
}
|
||||
if got[subscribeID][quantity] != nil {
|
||||
t.Fatalf("family member should not receive inactive promo when owner has active subscription, got %+v", got[subscribeID][quantity])
|
||||
}
|
||||
}
|
||||
|
||||
type fakeSubscribePromoModel struct {
|
||||
rules []*promo.RuleWithPrice
|
||||
lastSubscribeID int64
|
||||
lastQuantity int64
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
|
||||
m.lastSubscribeID = subscribeID
|
||||
m.lastQuantity = quantity
|
||||
return m.rules, nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) DeleteRule(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) DeletePrice(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (m *fakeSubscribePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func newSubscribePromoTestDB(t *testing.T) (*gorm.DB, 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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
|
||||
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
|
||||
{Quantity: 1},
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type CommissionWithdrawLogic struct {
|
||||
@@ -29,7 +30,7 @@ func NewCommissionWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext)
|
||||
}
|
||||
|
||||
func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdrawRequest) (resp *types.WithdrawalLog, err error) {
|
||||
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
ctxUser, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
if !ok {
|
||||
logger.Error("current user is not found in context")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||
@@ -51,28 +52,38 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
|
||||
}
|
||||
}
|
||||
|
||||
// Sum all pending (status=0) withdrawals to compute available balance.
|
||||
// Available = commission - pendingTotal; commission is only deducted on approval.
|
||||
var pendingTotal int64
|
||||
if err = l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.Withdrawal{}).
|
||||
Where("user_id = ? AND status = ?", u.Id, user.WithdrawalStatusPending).
|
||||
Select("COALESCE(SUM(amount), 0)").
|
||||
Scan(&pendingTotal).Error; err != nil {
|
||||
l.Errorf("Failed to query pending withdrawals for user %d: %v", u.Id, err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Failed to query pending withdrawals for user %d", u.Id)
|
||||
}
|
||||
|
||||
if u.Commission < req.Amount+pendingTotal {
|
||||
logger.Errorf("User %d insufficient available commission: total=%d pending=%d requested=%d",
|
||||
u.Id, u.Commission, pendingTotal, req.Amount)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "User %d has insufficient commission balance", u.Id)
|
||||
}
|
||||
|
||||
// HIF-139: read commission and pending total directly from DB inside a
|
||||
// transaction, FOR UPDATE on the user row. The ctxUser snapshot may be
|
||||
// served from cache and can be stale (the original bug allowed a user
|
||||
// with cached commission=996900 to submit a withdrawal while DB said 0,
|
||||
// which then failed admin approval with 20010). Approve already locks
|
||||
// the user row this way; aligning submission closes the gap.
|
||||
var w user.Withdrawal
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var dbUser user.User
|
||||
if txErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("id = ?", ctxUser.Id).First(&dbUser).Error; txErr != nil {
|
||||
l.Errorf("Failed to lock user %d for withdrawal: %v", ctxUser.Id, txErr)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Failed to lock user %d: %v", ctxUser.Id, txErr)
|
||||
}
|
||||
|
||||
var pendingTotal int64
|
||||
if txErr := tx.Model(&user.Withdrawal{}).
|
||||
Where("user_id = ? AND status = ?", ctxUser.Id, user.WithdrawalStatusPending).
|
||||
Select("COALESCE(SUM(amount), 0)").
|
||||
Scan(&pendingTotal).Error; txErr != nil {
|
||||
l.Errorf("Failed to query pending withdrawals for user %d: %v", ctxUser.Id, txErr)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Failed to query pending withdrawals for user %d", ctxUser.Id)
|
||||
}
|
||||
|
||||
if dbUser.Commission < req.Amount+pendingTotal {
|
||||
logger.Errorf("User %d insufficient available commission: db_commission=%d pending=%d requested=%d",
|
||||
ctxUser.Id, dbUser.Commission, pendingTotal, req.Amount)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "User %d has insufficient commission balance", ctxUser.Id)
|
||||
}
|
||||
|
||||
w = user.Withdrawal{
|
||||
UserId: u.Id,
|
||||
UserId: ctxUser.Id,
|
||||
Amount: req.Amount,
|
||||
Content: req.Content,
|
||||
Status: user.WithdrawalStatusPending,
|
||||
@@ -81,16 +92,19 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
|
||||
Account: req.Account,
|
||||
QrCodeUrl: req.QrCodeUrl,
|
||||
}
|
||||
return tx.Create(&w).Error
|
||||
if txErr := tx.Create(&w).Error; txErr != nil {
|
||||
l.Errorf("Failed to create withdrawal for user %d: %v", ctxUser.Id, txErr)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create withdrawal for user %d: %v", ctxUser.Id, txErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorf("Failed to create withdrawal for user %d: %v", u.Id, err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create withdrawal for user %d: %v", u.Id, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &types.WithdrawalLog{
|
||||
Id: w.Id,
|
||||
UserId: u.Id,
|
||||
UserId: ctxUser.Id,
|
||||
Amount: req.Amount,
|
||||
Content: req.Content,
|
||||
Status: user.WithdrawalStatusPending,
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"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/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TestCommissionWithdraw_StaleCacheRejected 覆盖 HIF-139 修复:
|
||||
// ctxUser(来自 auth middleware 的 cache-aside FindOne)即使 Commission=996900,
|
||||
// 只要事务内 FOR UPDATE 读出的 DB 真值 Commission < 申请金额 + pendingTotal,
|
||||
// 申请就必须被拒(UserCommissionNotEnough),且不得 INSERT 任何 withdrawal。
|
||||
func TestCommissionWithdraw_StaleCacheRejected(t *testing.T) {
|
||||
const userID = int64(510)
|
||||
|
||||
db, mock, cleanup := newWithdrawTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
// FOR UPDATE 锁 user 行 → DB 真值 commission=0
|
||||
mock.ExpectQuery("FROM `user`").
|
||||
WithArgs(userID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "commission"}).AddRow(userID, int64(0)))
|
||||
// pendingTotal=0
|
||||
mock.ExpectQuery("FROM `withdrawals`").
|
||||
WithArgs(userID, uint8(modeluser.WithdrawalStatusPending)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"coalesce"}).AddRow(int64(0)))
|
||||
// 校验失败 → ROLLBACK,不得 INSERT
|
||||
mock.ExpectRollback()
|
||||
|
||||
// ctxUser 故意带一个虚高 commission,模拟陈旧 cache
|
||||
logic := newTestCommissionWithdrawLogic(t, db, &modeluser.User{Id: userID, Commission: 996900})
|
||||
_, err := logic.CommissionWithdraw(&types.CommissionWithdrawRequest{
|
||||
Amount: 3000,
|
||||
Method: modeluser.WithdrawalMethodBank,
|
||||
Account: "222",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("CommissionWithdraw expected error, got nil")
|
||||
}
|
||||
if !isWithdrawErrCode(err, xerr.UserCommissionNotEnough) {
|
||||
t.Fatalf("CommissionWithdraw error code = %v, want UserCommissionNotEnough; raw=%v", withdrawErrCodeOf(err), err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommissionWithdraw_HappyPath 覆盖申请成功路径:DB 真值充足 → INSERT withdrawal。
|
||||
func TestCommissionWithdraw_HappyPath(t *testing.T) {
|
||||
const userID = int64(72)
|
||||
|
||||
db, mock, cleanup := newWithdrawTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery("FROM `user`").
|
||||
WithArgs(userID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "commission"}).AddRow(userID, int64(10000)))
|
||||
mock.ExpectQuery("FROM `withdrawals`").
|
||||
WithArgs(userID, uint8(modeluser.WithdrawalStatusPending)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"coalesce"}).AddRow(int64(2000)))
|
||||
// 10000 >= 3000 + 2000 → INSERT
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO `withdrawals`")).
|
||||
WillReturnResult(sqlmock.NewResult(99, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
logic := newTestCommissionWithdrawLogic(t, db, &modeluser.User{Id: userID, Commission: 10000})
|
||||
resp, err := logic.CommissionWithdraw(&types.CommissionWithdrawRequest{
|
||||
Amount: 3000,
|
||||
Method: modeluser.WithdrawalMethodBank,
|
||||
Account: "acc",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CommissionWithdraw unexpected error: %v", err)
|
||||
}
|
||||
if resp == nil || resp.Amount != 3000 || resp.Status != modeluser.WithdrawalStatusPending {
|
||||
t.Fatalf("unexpected response: %+v", resp)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommissionWithdraw_PendingTotalExhausts 覆盖 pendingTotal 把可用额度吃光的场景:
|
||||
// DB commission=5000、pending=4000、申请=2000 → 5000 < 6000 → 20010,不得 INSERT。
|
||||
func TestCommissionWithdraw_PendingTotalExhausts(t *testing.T) {
|
||||
const userID = int64(88)
|
||||
|
||||
db, mock, cleanup := newWithdrawTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery("FROM `user`").
|
||||
WithArgs(userID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "commission"}).AddRow(userID, int64(5000)))
|
||||
mock.ExpectQuery("FROM `withdrawals`").
|
||||
WithArgs(userID, uint8(modeluser.WithdrawalStatusPending)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"coalesce"}).AddRow(int64(4000)))
|
||||
mock.ExpectRollback()
|
||||
|
||||
logic := newTestCommissionWithdrawLogic(t, db, &modeluser.User{Id: userID, Commission: 5000})
|
||||
_, err := logic.CommissionWithdraw(&types.CommissionWithdrawRequest{
|
||||
Amount: 2000,
|
||||
Method: modeluser.WithdrawalMethodBank,
|
||||
Account: "acc",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("CommissionWithdraw expected error, got nil")
|
||||
}
|
||||
if !isWithdrawErrCode(err, xerr.UserCommissionNotEnough) {
|
||||
t.Fatalf("error code = %v, want UserCommissionNotEnough; raw=%v", withdrawErrCodeOf(err), err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommissionWithdraw_LockUserMissing 覆盖事务内 FOR UPDATE 找不到 user 的场景(user 已删/不存在)→ DatabaseQueryError。
|
||||
func TestCommissionWithdraw_LockUserMissing(t *testing.T) {
|
||||
const userID = int64(999999)
|
||||
|
||||
db, mock, cleanup := newWithdrawTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery("FROM `user`").
|
||||
WithArgs(userID, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "commission"}))
|
||||
mock.ExpectRollback()
|
||||
|
||||
logic := newTestCommissionWithdrawLogic(t, db, &modeluser.User{Id: userID, Commission: 999})
|
||||
_, err := logic.CommissionWithdraw(&types.CommissionWithdrawRequest{
|
||||
Amount: 100,
|
||||
Method: modeluser.WithdrawalMethodBank,
|
||||
Account: "acc",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("CommissionWithdraw expected error, got nil")
|
||||
}
|
||||
if !isWithdrawErrCode(err, xerr.DatabaseQueryError) {
|
||||
t.Fatalf("error code = %v, want DatabaseQueryError; raw=%v", withdrawErrCodeOf(err), err)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newWithdrawTestDB(t *testing.T) (*gorm.DB, 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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func newTestCommissionWithdrawLogic(t *testing.T, db *gorm.DB, ctxUser *modeluser.User) *CommissionWithdrawLogic {
|
||||
t.Helper()
|
||||
ctx := context.WithValue(context.Background(), constant.CtxKeyUser, ctxUser)
|
||||
return &CommissionWithdrawLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: &svc.ServiceContext{DB: db},
|
||||
}
|
||||
}
|
||||
|
||||
func withdrawErrCodeOf(err error) uint32 {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
type coder interface {
|
||||
GetErrCode() uint32
|
||||
}
|
||||
cause := errors.Cause(err)
|
||||
if c, ok := cause.(coder); ok {
|
||||
return c.GetErrCode()
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func isWithdrawErrCode(err error, code uint32) bool {
|
||||
return withdrawErrCodeOf(err) == code
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"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"
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -45,8 +45,10 @@ type parsedInviteRecordLog struct {
|
||||
}
|
||||
|
||||
type inviteOrderUser struct {
|
||||
OrderNo string `gorm:"column:order_no"`
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
OrderNo string `gorm:"column:order_no"`
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
SubscriptionUserId int64 `gorm:"column:subscription_user_id"`
|
||||
RefererId int64 `gorm:"column:referer_id"`
|
||||
}
|
||||
|
||||
// Get invite gift records
|
||||
@@ -67,9 +69,17 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
|
||||
|
||||
normalizeInviteRecordsPagination(req)
|
||||
|
||||
visibleUserIds, err := l.resolveInviteRecordVisibleUserIds(u.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[GetInviteRecords] resolve visible users failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "resolve visible users failed: %v", err.Error())
|
||||
}
|
||||
|
||||
query := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("system_logs").
|
||||
Where("type = ? AND object_id = ?", logmodel.TypeGift.Uint8(), u.Id).
|
||||
Where("type = ? AND object_id IN ?", logmodel.TypeGift.Uint8(), visibleUserIds).
|
||||
Where("JSON_VALID(content) = 1").
|
||||
Where("JSON_UNQUOTE(JSON_EXTRACT(content, '$.remark')) = ?", "邀请赠送")
|
||||
if req.StartTime > 0 {
|
||||
@@ -79,20 +89,10 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
|
||||
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()),
|
||||
@@ -102,7 +102,7 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
|
||||
|
||||
parsedLogs, orderNos := l.parseInviteRecordContents(logs)
|
||||
if len(logs) == 0 || len(parsedLogs) == 0 {
|
||||
return &types.GetInviteRecordsResponse{Total: total, List: []types.InviteRecord{}}, nil
|
||||
return &types.GetInviteRecordsResponse{Total: 0, List: []types.InviteRecord{}}, nil
|
||||
}
|
||||
|
||||
orders, err := l.queryInviteRecordOrders(orderNos)
|
||||
@@ -113,10 +113,20 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query orders failed: %v", err.Error())
|
||||
}
|
||||
|
||||
list := make([]types.InviteRecord, 0, len(parsedLogs))
|
||||
visibleUserIdSet := make(map[int64]struct{}, len(visibleUserIds))
|
||||
for _, userId := range visibleUserIds {
|
||||
visibleUserIdSet[userId] = struct{}{}
|
||||
}
|
||||
|
||||
allRecords := make([]types.InviteRecord, 0, len(parsedLogs))
|
||||
for _, parsed := range parsedLogs {
|
||||
content := parsed.content
|
||||
logItem := parsed.log
|
||||
orderInfo, hasOrder := orders[content.OrderNo]
|
||||
if !l.canViewInviteRecord(u.Id, logItem.ObjectId, visibleUserIdSet, hasOrder, orderInfo) {
|
||||
continue
|
||||
}
|
||||
|
||||
record := types.InviteRecord{
|
||||
Role: inviteRecordRoleInviter,
|
||||
GiftDays: content.Amount,
|
||||
@@ -124,7 +134,7 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
|
||||
CreatedAt: logItem.CreatedAt,
|
||||
}
|
||||
|
||||
if orderInfo, ok := orders[content.OrderNo]; ok {
|
||||
if hasOrder {
|
||||
peerId := orderInfo.UserId
|
||||
if orderInfo.UserId == u.Id {
|
||||
record.Role = inviteRecordRoleInvitee
|
||||
@@ -135,15 +145,56 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
|
||||
}
|
||||
}
|
||||
|
||||
list = append(list, record)
|
||||
allRecords = append(allRecords, record)
|
||||
}
|
||||
|
||||
total := int64(len(allRecords))
|
||||
list := paginateInviteRecords(allRecords, req.Page, req.Size)
|
||||
return &types.GetInviteRecordsResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l *GetInviteRecordsLogic) resolveInviteRecordVisibleUserIds(currentUserId int64) ([]int64, error) {
|
||||
visibleUserIds := []int64{currentUserId}
|
||||
|
||||
var relation struct {
|
||||
FamilyId int64 `gorm:"column:family_id"`
|
||||
Role uint8 `gorm:"column:role"`
|
||||
OwnerUserId int64 `gorm:"column:owner_user_id"`
|
||||
}
|
||||
err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.UserFamilyMember{}).
|
||||
Select("user_family_member.family_id, user_family_member.role, user_family.owner_user_id").
|
||||
Joins("JOIN user_family ON user_family.id = user_family_member.family_id AND user_family.deleted_at IS NULL AND user_family.status = ?", user.FamilyStatusActive).
|
||||
Where("user_family_member.user_id = ? AND user_family_member.status = ? AND user_family_member.deleted_at IS NULL", currentUserId, user.FamilyMemberActive).
|
||||
First(&relation).Error
|
||||
if err == nil {
|
||||
if relation.Role != user.FamilyRoleOwner && relation.OwnerUserId > 0 && relation.OwnerUserId != currentUserId {
|
||||
visibleUserIds = append(visibleUserIds, relation.OwnerUserId)
|
||||
}
|
||||
return visibleUserIds, nil
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return visibleUserIds, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (l *GetInviteRecordsLogic) canViewInviteRecord(currentUserId, logObjectId int64, visibleUserIds map[int64]struct{}, hasOrder bool, orderInfo inviteOrderUser) bool {
|
||||
if _, ok := visibleUserIds[logObjectId]; !ok {
|
||||
return false
|
||||
}
|
||||
if logObjectId == currentUserId {
|
||||
if hasOrder {
|
||||
return orderInfo.UserId == currentUserId || orderInfo.RefererId == currentUserId
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func normalizeInviteRecordsPagination(req *types.GetInviteRecordsRequest) {
|
||||
if req.Page < 1 {
|
||||
req.Page = 1
|
||||
@@ -156,6 +207,18 @@ func normalizeInviteRecordsPagination(req *types.GetInviteRecordsRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
func paginateInviteRecords(records []types.InviteRecord, page, size int) []types.InviteRecord {
|
||||
start := (page - 1) * size
|
||||
if start >= len(records) {
|
||||
return []types.InviteRecord{}
|
||||
}
|
||||
end := start + size
|
||||
if end > len(records) {
|
||||
end = len(records)
|
||||
}
|
||||
return records[start:end]
|
||||
}
|
||||
|
||||
func (l *GetInviteRecordsLogic) parseInviteRecordContents(logs []inviteRecordLog) ([]parsedInviteRecordLog, []string) {
|
||||
parsedLogs := make([]parsedInviteRecordLog, 0, len(logs))
|
||||
orderNos := make([]string, 0, len(logs))
|
||||
@@ -183,9 +246,10 @@ func (l *GetInviteRecordsLogic) queryInviteRecordOrders(orderNos []string) (map[
|
||||
|
||||
var orderData []inviteOrderUser
|
||||
err := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&ordermodel.Order{}).
|
||||
Select("order_no, user_id").
|
||||
Where("order_no IN ?", orderNos).
|
||||
Table("`order`").
|
||||
Select("`order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id").
|
||||
Joins("LEFT JOIN user invitee ON invitee.id = `order`.user_id").
|
||||
Where("`order`.order_no IN ?", orderNos).
|
||||
Scan(&orderData).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -20,16 +20,14 @@ 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))
|
||||
expectNoInviteRecordsFamily(t, mock, 100)
|
||||
mock.ExpectQuery("SELECT id, object_id, content").
|
||||
WithArgs(34, int64(100), "邀请赠送", 10).
|
||||
WithArgs(34, int64(100), "邀请赠送").
|
||||
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`").
|
||||
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
|
||||
WithArgs("order-1").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id"}).AddRow("order-1", 200))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("order-1", 200, 200, 100))
|
||||
|
||||
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(100, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
|
||||
if err != nil {
|
||||
@@ -49,16 +47,14 @@ 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))
|
||||
expectNoInviteRecordsFamily(t, mock, 200)
|
||||
mock.ExpectQuery("SELECT id, object_id, content").
|
||||
WithArgs(34, int64(200), "邀请赠送", 10).
|
||||
WithArgs(34, int64(200), "邀请赠送").
|
||||
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`").
|
||||
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
|
||||
WithArgs("order-2").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id"}).AddRow("order-2", 200))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("order-2", 200, 200, 100))
|
||||
|
||||
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(200, 100), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
|
||||
if err != nil {
|
||||
@@ -78,16 +74,14 @@ 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))
|
||||
expectNoInviteRecordsFamily(t, mock, 100)
|
||||
mock.ExpectQuery("SELECT id, object_id, content").
|
||||
WithArgs(34, int64(100), "邀请赠送", 10).
|
||||
WithArgs(34, int64(100), "邀请赠送").
|
||||
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`").
|
||||
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
|
||||
WithArgs("missing-order").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id"}))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}))
|
||||
|
||||
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(100, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
|
||||
if err != nil {
|
||||
@@ -102,6 +96,89 @@ func TestGetInviteRecordsMissingOrderReturnsDirtyRecord(t *testing.T) {
|
||||
assertInviteRecordsExpectations(t, mock)
|
||||
}
|
||||
|
||||
func TestGetInviteRecordsFamilyMemberSeesOwnerGiftLog(t *testing.T) {
|
||||
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
|
||||
defer cleanup()
|
||||
|
||||
expectInviteRecordsFamilyMember(t, mock, 200, 900)
|
||||
mock.ExpectQuery("SELECT id, object_id, content").
|
||||
WithArgs(34, int64(200), int64(900), "邀请赠送").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
|
||||
AddRow(4, 900, `{"order_no":"family-order","amount":7,"remark":"邀请赠送"}`, 1779934610000))
|
||||
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
|
||||
WithArgs("family-order").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("family-order", 200, 900, 100))
|
||||
|
||||
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: "family-order",
|
||||
CreatedAt: 1779934610000,
|
||||
})
|
||||
assertInviteRecordsExpectations(t, mock)
|
||||
}
|
||||
|
||||
func TestGetInviteRecordsFamilyMemberSeesAllOwnerGiftLogs(t *testing.T) {
|
||||
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
|
||||
defer cleanup()
|
||||
|
||||
expectInviteRecordsFamilyMember(t, mock, 51637, 510)
|
||||
mock.ExpectQuery("SELECT id, object_id, content").
|
||||
WithArgs(34, int64(51637), int64(510), "邀请赠送").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
|
||||
AddRow(6, 510, `{"order_no":"owner-order","amount":7,"remark":"邀请赠送"}`, 1779934630000))
|
||||
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
|
||||
WithArgs("owner-order").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("owner-order", 571, 571, 510))
|
||||
|
||||
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(51637, 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(571),
|
||||
GiftDays: 7,
|
||||
OrderNo: "owner-order",
|
||||
CreatedAt: 1779934630000,
|
||||
})
|
||||
assertInviteRecordsExpectations(t, mock)
|
||||
}
|
||||
|
||||
func TestGetInviteRecordsOwnerDoesNotSeeMemberGiftLog(t *testing.T) {
|
||||
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
|
||||
defer cleanup()
|
||||
|
||||
expectInviteRecordsFamilyOwner(t, mock, 900)
|
||||
mock.ExpectQuery("SELECT id, object_id, content").
|
||||
WithArgs(34, int64(900), "邀请赠送").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
|
||||
AddRow(5, 900, `{"order_no":"member-order","amount":7,"remark":"邀请赠送"}`, 1779934620000))
|
||||
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
|
||||
WithArgs("member-order").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("member-order", 200, 900, 100))
|
||||
|
||||
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(900, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("GetInviteRecords returned error: %v", err)
|
||||
}
|
||||
if resp == nil {
|
||||
t.Fatal("response is nil")
|
||||
}
|
||||
if resp.Total != 0 {
|
||||
t.Fatalf("Total = %d, want 0", resp.Total)
|
||||
}
|
||||
if len(resp.List) != 0 {
|
||||
t.Fatalf("len(List) = %d, want 0", len(resp.List))
|
||||
}
|
||||
assertInviteRecordsExpectations(t, mock)
|
||||
}
|
||||
|
||||
func newInviteRecordsTestSvc(t *testing.T) (*svc.ServiceContext, sqlmock.Sqlmock, func()) {
|
||||
t.Helper()
|
||||
|
||||
@@ -126,6 +203,27 @@ func newInviteRecordsTestSvc(t *testing.T) (*svc.ServiceContext, sqlmock.Sqlmock
|
||||
}
|
||||
}
|
||||
|
||||
func expectNoInviteRecordsFamily(t *testing.T, mock sqlmock.Sqlmock, userId int64) {
|
||||
t.Helper()
|
||||
mock.ExpectQuery("FROM `user_family_member` JOIN user_family").
|
||||
WithArgs(1, userId, 1, 1).
|
||||
WillReturnError(gorm.ErrRecordNotFound)
|
||||
}
|
||||
|
||||
func expectInviteRecordsFamilyMember(t *testing.T, mock sqlmock.Sqlmock, userId, ownerUserId int64) {
|
||||
t.Helper()
|
||||
mock.ExpectQuery("FROM `user_family_member` JOIN user_family").
|
||||
WithArgs(1, userId, 1, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"family_id", "role", "owner_user_id"}).AddRow(800, 2, ownerUserId))
|
||||
}
|
||||
|
||||
func expectInviteRecordsFamilyOwner(t *testing.T, mock sqlmock.Sqlmock, userId int64) {
|
||||
t.Helper()
|
||||
mock.ExpectQuery("FROM `user_family_member` JOIN user_family").
|
||||
WithArgs(1, userId, 1, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"family_id", "role", "owner_user_id"}).AddRow(800, 1, userId))
|
||||
}
|
||||
|
||||
func inviteRecordsContext(userId, refererId int64) context.Context {
|
||||
return context.WithValue(context.Background(), constant.CtxKeyUser, &modeluser.User{
|
||||
Id: userId,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// HasRefundCommissionLog 判断指定订单号是否已写入 333 退款佣金日志。
|
||||
// 用于 refund 主流程做幂等校验,以及 stuck-order recovery / activate worker
|
||||
// 区分「已退款」(terminal)与「短暂 claimed」(transient)这两种共用 status=6
|
||||
// 的语义。
|
||||
//
|
||||
// 实现细节:
|
||||
// 1. type=33 + content LIKE '%"order_no":"<orderNo>"%' 先走索引粗筛;
|
||||
// 2. 命中项再用 JSON 反序列化精确比对 content.type==333 与 content.order_no,
|
||||
// 避免 order_no 出现在其它字段子串里产生误判。
|
||||
func HasRefundCommissionLog(tx *gorm.DB, orderNo string) (bool, error) {
|
||||
if orderNo == "" {
|
||||
return false, nil
|
||||
}
|
||||
var logs []SystemLog
|
||||
if err := tx.Model(&SystemLog{}).
|
||||
Where("type = ? AND content LIKE ?", TypeCommission.Uint8(), fmt.Sprintf("%%\"order_no\":\"%s\"%%", orderNo)).
|
||||
Find(&logs).Error; err != nil {
|
||||
return false, fmt.Errorf("query refund commission log failed: %w", err)
|
||||
}
|
||||
for _, item := range logs {
|
||||
var content Commission
|
||||
if err := content.Unmarshal([]byte(item.Content)); err != nil {
|
||||
continue
|
||||
}
|
||||
if content.Type == CommissionTypeRefund && content.OrderNo == orderNo {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestHasRefundCommissionLog(t *testing.T) {
|
||||
const orderNo = "ORD-REFUND-1"
|
||||
|
||||
t.Run("returns true when 333 log exists for the order", func(t *testing.T) {
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
|
||||
AddRow(1, fmt.Sprintf(`{"type":331,"order_no":"%s","amount":100}`, orderNo)).
|
||||
AddRow(2, fmt.Sprintf(`{"type":333,"order_no":"%s","amount":-100}`, orderNo)))
|
||||
|
||||
got, err := HasRefundCommissionLog(db, orderNo)
|
||||
if err != nil {
|
||||
t.Fatalf("HasRefundCommissionLog error: %v", err)
|
||||
}
|
||||
if !got {
|
||||
t.Fatalf("HasRefundCommissionLog = false, want true")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
|
||||
t.Run("returns false when only 331/332 logs exist", func(t *testing.T) {
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
|
||||
AddRow(1, fmt.Sprintf(`{"type":331,"order_no":"%s","amount":100}`, orderNo)).
|
||||
AddRow(2, fmt.Sprintf(`{"type":332,"order_no":"%s","amount":50}`, orderNo)))
|
||||
|
||||
got, err := HasRefundCommissionLog(db, orderNo)
|
||||
if err != nil {
|
||||
t.Fatalf("HasRefundCommissionLog error: %v", err)
|
||||
}
|
||||
if got {
|
||||
t.Fatalf("HasRefundCommissionLog = true, want false")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
|
||||
t.Run("returns false when no log exists for the order", func(t *testing.T) {
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}))
|
||||
|
||||
got, err := HasRefundCommissionLog(db, orderNo)
|
||||
if err != nil {
|
||||
t.Fatalf("HasRefundCommissionLog error: %v", err)
|
||||
}
|
||||
if got {
|
||||
t.Fatalf("HasRefundCommissionLog = true, want false")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
|
||||
t.Run("returns false for empty order_no without querying", func(t *testing.T) {
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
got, err := HasRefundCommissionLog(db, "")
|
||||
if err != nil {
|
||||
t.Fatalf("HasRefundCommissionLog error: %v", err)
|
||||
}
|
||||
if got {
|
||||
t.Fatalf("HasRefundCommissionLog = true, want false")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
|
||||
t.Run("ignores 333 log when order_no in content does not match", func(t *testing.T) {
|
||||
// Defensive: LIKE pattern may match a substring; JSON match catches it.
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
|
||||
AddRow(1, `{"type":333,"order_no":"OTHER","amount":-100}`))
|
||||
|
||||
got, err := HasRefundCommissionLog(db, orderNo)
|
||||
if err != nil {
|
||||
t.Fatalf("HasRefundCommissionLog error: %v", err)
|
||||
}
|
||||
if got {
|
||||
t.Fatalf("HasRefundCommissionLog = true, want false (different order_no)")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
|
||||
t.Run("ignores malformed json content", func(t *testing.T) {
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
|
||||
AddRow(1, `not a json`).
|
||||
AddRow(2, fmt.Sprintf(`{"type":333,"order_no":"%s","amount":-100}`, orderNo)))
|
||||
|
||||
got, err := HasRefundCommissionLog(db, orderNo)
|
||||
if err != nil {
|
||||
t.Fatalf("HasRefundCommissionLog error: %v", err)
|
||||
}
|
||||
if !got {
|
||||
t.Fatalf("HasRefundCommissionLog = false, want true")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
|
||||
t.Run("returns error when db query fails", func(t *testing.T) {
|
||||
db, mock, cleanup := newRefundLogTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
mock.ExpectQuery("FROM `system_logs`").
|
||||
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
|
||||
WillReturnError(fmt.Errorf("connection lost"))
|
||||
|
||||
if _, err := HasRefundCommissionLog(db, orderNo); err == nil {
|
||||
t.Fatalf("expected error, got nil")
|
||||
}
|
||||
assertRefundLogExpectations(t, mock)
|
||||
})
|
||||
}
|
||||
|
||||
func newRefundLogTestDB(t *testing.T) (*gorm.DB, 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 db, mock, func() {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func assertRefundLogExpectations(t *testing.T, mock sqlmock.Sqlmock) {
|
||||
t.Helper()
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet sql expectations: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ type Model interface {
|
||||
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)
|
||||
QueryPriceList(ctx context.Context, params PriceFilter) (int64, []*SubscribePromo, error)
|
||||
QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error)
|
||||
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
|
||||
}
|
||||
@@ -38,6 +38,13 @@ type UsageFilter struct {
|
||||
OrderNo string
|
||||
}
|
||||
|
||||
type PriceFilter struct {
|
||||
Page int
|
||||
Size int
|
||||
RuleId int64
|
||||
SubscribeId int64
|
||||
}
|
||||
|
||||
type defaultPromoModel struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
@@ -164,20 +171,26 @@ 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
|
||||
func (m *defaultPromoModel) QueryPriceList(ctx context.Context, params PriceFilter) (int64, []*SubscribePromo, error) {
|
||||
if params.Page <= 0 {
|
||||
params.Page = 1
|
||||
}
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
if params.Size <= 0 {
|
||||
params.Size = 10
|
||||
}
|
||||
var total int64
|
||||
var list []*SubscribePromo
|
||||
db := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("promo_rule_id = ?", ruleId)
|
||||
db := m.db.WithContext(ctx).Model(&SubscribePromo{})
|
||||
if params.RuleId > 0 {
|
||||
db = db.Where("promo_rule_id = ?", params.RuleId)
|
||||
}
|
||||
if params.SubscribeId > 0 {
|
||||
db = db.Where("subscribe_id = ?", params.SubscribeId)
|
||||
}
|
||||
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
|
||||
err := db.Order("id DESC").Limit(params.Size).Offset((params.Page - 1) * params.Size).Find(&list).Error
|
||||
return total, list, err
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ func (m *defaultUserModel) FindSingleModeAnchorSubscribe(ctx context.Context, us
|
||||
var data Subscribe
|
||||
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, _ interface{}) error {
|
||||
return conn.Model(&Subscribe{}).
|
||||
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%') AND `status` IN ?", userId, []int64{0, 1, 2, 3, 4, 5}).
|
||||
Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%') AND `status` IN ?", userId, []int64{0, 1, 2, 3, 4, 5}).
|
||||
Order("expire_time DESC").
|
||||
Order("updated_at DESC").
|
||||
Order("id DESC").
|
||||
|
||||
@@ -34,9 +34,9 @@ func TestPromoListPageSizeLimit(t *testing.T) {
|
||||
{
|
||||
name: "price list",
|
||||
req: GetPromoPriceListRequest{
|
||||
PromoRuleId: 1,
|
||||
Page: 1,
|
||||
Size: 201,
|
||||
RuleId: 1,
|
||||
Page: 1,
|
||||
Size: 201,
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
+284
-270
@@ -3,15 +3,21 @@
|
||||
|
||||
package types
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type ActivateOrderRequest struct {
|
||||
OrderNo string `json:"order_no" validate:"required"`
|
||||
}
|
||||
|
||||
type RefundOrderRequest struct {
|
||||
Id int64 `json:"id" validate:"required"`
|
||||
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
|
||||
type AdminInvitedUser struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type Ads struct {
|
||||
@@ -126,6 +132,10 @@ type ApplicationVersion struct {
|
||||
IsDefault bool `json:"is_default"`
|
||||
}
|
||||
|
||||
type ApproveWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type AttachAppleTransactionByIdRequest struct {
|
||||
OrderNo string `json:"order_no" validate:"required"`
|
||||
TransactionId string `json:"transaction_id" validate:"required"`
|
||||
@@ -251,6 +261,10 @@ type BindTelegramResponse struct {
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
}
|
||||
|
||||
type CancelWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type CheckUserRequest struct {
|
||||
Email string `form:"email" validate:"required"`
|
||||
}
|
||||
@@ -316,45 +330,6 @@ type ContactRequest struct {
|
||||
Notes string `json:"notes" validate:"max=2000"`
|
||||
}
|
||||
|
||||
type PromoPrice struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type PromoPriceItem struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type PromoRule struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type PromoUsage struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
PromoRuleId int64 `json:"promo_rule_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
type Coupon struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -414,16 +389,6 @@ type CreateCouponRequest struct {
|
||||
Enable *bool `json:"enable,omitempty"`
|
||||
}
|
||||
|
||||
type CreatePromoRuleRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type CreateDocumentRequest struct {
|
||||
Title string `json:"title" validate:"required"`
|
||||
Content string `json:"content" validate:"required"`
|
||||
@@ -485,6 +450,16 @@ type CreatePaymentMethodRequest struct {
|
||||
Enable *bool `json:"enable" validate:"required"`
|
||||
}
|
||||
|
||||
type CreatePromoRuleRequest struct {
|
||||
Name string `json:"name" validate:"required,max=100"`
|
||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||
Params 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"`
|
||||
}
|
||||
|
||||
type CreateQuotaTaskRequest struct {
|
||||
Subscribers []int64 `json:"subscribers"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
@@ -668,6 +643,14 @@ type DeletePaymentMethodRequest struct {
|
||||
Id int64 `json:"id" validate:"required"`
|
||||
}
|
||||
|
||||
type DeletePromoPriceRequest struct {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type DeletePromoRuleRequest struct {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type DeleteRedemptionCodeRequest struct {
|
||||
Id int64 `json:"id" validate:"required"`
|
||||
}
|
||||
@@ -823,14 +806,6 @@ type FamilySummary struct {
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
type FileUploadRequest struct {
|
||||
BizType string `form:"biz_type" validate:"required"`
|
||||
}
|
||||
|
||||
type FileUploadResponse struct {
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
type FileUploadCompleteRequest struct {
|
||||
FileId string `json:"file_id" validate:"required"`
|
||||
}
|
||||
@@ -856,6 +831,14 @@ type FileUploadInitResponse struct {
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
}
|
||||
|
||||
type FileUploadRequest struct {
|
||||
BizType string `form:"biz_type" validate:"required"`
|
||||
}
|
||||
|
||||
type FileUploadResponse struct {
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
type FilterBalanceLogRequest struct {
|
||||
FilterLogParams
|
||||
UserId int64 `form:"user_id,optional"`
|
||||
@@ -876,17 +859,6 @@ type FilterCommissionLogResponse struct {
|
||||
List []CommissionLog `json:"list"`
|
||||
}
|
||||
|
||||
type FilterOrderRefundLogRequest struct {
|
||||
FilterLogParams
|
||||
OrderId int64 `form:"order_id,optional"`
|
||||
UserId int64 `form:"user_id,optional"`
|
||||
}
|
||||
|
||||
type FilterOrderRefundLogResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []OrderRefundLog `json:"list"`
|
||||
}
|
||||
|
||||
type FilterEmailLogResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []MessageLog `json:"list"`
|
||||
@@ -936,6 +908,17 @@ type FilterNodeListResponse struct {
|
||||
List []Node `json:"list"`
|
||||
}
|
||||
|
||||
type FilterOrderRefundLogRequest struct {
|
||||
FilterLogParams
|
||||
OrderId int64 `form:"order_id,optional"`
|
||||
UserId int64 `form:"user_id,optional"`
|
||||
}
|
||||
|
||||
type FilterOrderRefundLogResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []OrderRefundLog `json:"list"`
|
||||
}
|
||||
|
||||
type FilterRegisterLogRequest struct {
|
||||
FilterLogParams
|
||||
UserId int64 `form:"user_id,optional"`
|
||||
@@ -1027,6 +1010,32 @@ type GenerateCaptchaResponse struct {
|
||||
BlockImage string `json:"block_image,omitempty"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteListRequest struct {
|
||||
UserId int64 `form:"user_id" validate:"required"`
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
Search string `form:"search"`
|
||||
Enable *int `form:"enable"`
|
||||
UserIdSearch int64 `form:"user_id_search"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []AdminInvitedUser `json:"list"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteStatsRequest struct {
|
||||
UserId int64 `form:"user_id" validate:"required"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteStatsResponse struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetAdsDetailRequest struct {
|
||||
Id int64 `form:"id"`
|
||||
}
|
||||
@@ -1145,48 +1154,6 @@ type GetCouponListResponse struct {
|
||||
List []Coupon `json:"list"`
|
||||
}
|
||||
|
||||
type GetPromoPriceListRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetPromoPriceListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoPrice `json:"list"`
|
||||
}
|
||||
|
||||
type GetPromoRuleDetailRequest struct {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type GetPromoRuleListRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetPromoRuleListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoRule `json:"list"`
|
||||
}
|
||||
|
||||
type GetPromoUsageListRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetPromoUsageListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoUsage `json:"list"`
|
||||
}
|
||||
|
||||
type GetDetailRequest struct {
|
||||
Id int64 `form:"id" validate:"required"`
|
||||
}
|
||||
@@ -1327,6 +1294,19 @@ type GetGroupHistoryResponse struct {
|
||||
List []GroupHistory `json:"list"`
|
||||
}
|
||||
|
||||
type GetInviteManageListRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
Search string `form:"search"`
|
||||
InviterId int64 `form:"inviter_id"`
|
||||
InviteeId int64 `form:"invitee_id"`
|
||||
}
|
||||
|
||||
type GetInviteManageListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []InviteManageRecord `json:"list"`
|
||||
}
|
||||
|
||||
type GetInviteRecordsRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
@@ -1339,6 +1319,44 @@ type GetInviteRecordsResponse struct {
|
||||
List []InviteRecord `json:"list"`
|
||||
}
|
||||
|
||||
type GetInviteSalesRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
StartTime int64 `form:"start_time"`
|
||||
EndTime int64 `form:"end_time"`
|
||||
}
|
||||
|
||||
type GetInviteSalesResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []InvitedUserSale `json:"list"`
|
||||
}
|
||||
|
||||
type GetLogMessageRawRequest struct {
|
||||
Id int64 `form:"id" validate:"required"`
|
||||
}
|
||||
|
||||
type GetLogMessageRawResponse struct {
|
||||
Id int64 `json:"id"`
|
||||
Platform string `json:"platform"`
|
||||
AppVersion string `json:"app_version"`
|
||||
OsName string `json:"os_name"`
|
||||
OsVersion string `json:"os_version"`
|
||||
DeviceId string `json:"device_id"`
|
||||
UserId *int64 `json:"user_id"`
|
||||
SessionId string `json:"session_id"`
|
||||
Level uint8 `json:"level"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
Message string `json:"message"`
|
||||
Stack string `json:"stack"`
|
||||
Context interface{} `json:"context"`
|
||||
ClientIP string `json:"client_ip"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Locale string `json:"locale"`
|
||||
Digest string `json:"digest"`
|
||||
OccurredAt int64 `json:"occurred_at"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
type GetLoginLogRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
@@ -1417,6 +1435,49 @@ type GetPreSendEmailCountResponse struct {
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
type GetPromoPriceListRequest struct {
|
||||
Page int64 `form:"page" validate:"required,gt=0"`
|
||||
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
|
||||
RuleId int64 `form:"rule_id,omitempty"`
|
||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
||||
}
|
||||
|
||||
type GetPromoPriceListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoPrice `json:"list"`
|
||||
}
|
||||
|
||||
type GetPromoRuleDetailRequest struct {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type GetPromoRuleListRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetPromoRuleListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoRule `json:"list"`
|
||||
}
|
||||
|
||||
type GetPromoUsageListRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetPromoUsageListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoUsage `json:"list"`
|
||||
}
|
||||
|
||||
type GetRedemptionCodeListRequest struct {
|
||||
Page int64 `form:"page" validate:"required"`
|
||||
Size int64 `form:"size" validate:"required"`
|
||||
@@ -1708,6 +1769,19 @@ type GetUserTrafficStatsResponse struct {
|
||||
TotalTraffic int64 `json:"total_traffic"`
|
||||
}
|
||||
|
||||
type GetWithdrawalListRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
UserId *int64 `form:"user_id,omitempty"`
|
||||
Status *uint8 `form:"status,omitempty"`
|
||||
Method *uint8 `form:"method,omitempty"`
|
||||
}
|
||||
|
||||
type GetWithdrawalListResponse struct {
|
||||
List []WithdrawalLog `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type GiftLog struct {
|
||||
Type uint16 `json:"type"`
|
||||
UserId int64 `json:"user_id"`
|
||||
@@ -1768,6 +1842,21 @@ type InviteConfig struct {
|
||||
GiftDays int64 `json:"gift_days"`
|
||||
}
|
||||
|
||||
type InviteManageRecord struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type InviteRecord struct {
|
||||
Role string `json:"role"`
|
||||
PeerHash string `json:"peer_hash"`
|
||||
@@ -1776,6 +1865,13 @@ type InviteRecord struct {
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
type InvitedUserSale struct {
|
||||
Amount float64 `json:"amount"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
UserHash string `json:"user_hash"`
|
||||
ProductName string `json:"product_name"`
|
||||
}
|
||||
|
||||
type KickOfflineRequest struct {
|
||||
Id int64 `json:"id"`
|
||||
}
|
||||
@@ -1949,8 +2045,6 @@ type Order struct {
|
||||
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"`
|
||||
@@ -1974,8 +2068,6 @@ type OrderDetail struct {
|
||||
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"`
|
||||
@@ -2158,6 +2250,45 @@ type PrivacyPolicyConfig struct {
|
||||
PrivacyPolicy string `json:"privacy_policy"`
|
||||
}
|
||||
|
||||
type PromoPrice struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type PromoPriceItem struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type PromoRule struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type PromoUsage struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
PromoRuleId int64 `json:"promo_rule_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
type Protocol struct {
|
||||
Type string `json:"type"`
|
||||
Port uint16 `json:"port"`
|
||||
@@ -2406,10 +2537,6 @@ type QueryUserSubscribeNodeListResponse struct {
|
||||
List []UserSubscribeInfo `json:"list"`
|
||||
}
|
||||
|
||||
type CancelWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type QueryWithdrawalLogListRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
@@ -2420,28 +2547,6 @@ type QueryWithdrawalLogListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type GetWithdrawalListRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
UserId *int64 `form:"user_id,omitempty"`
|
||||
Status *uint8 `form:"status,omitempty"`
|
||||
Method *uint8 `form:"method,omitempty"`
|
||||
}
|
||||
|
||||
type GetWithdrawalListResponse struct {
|
||||
List []WithdrawalLog `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type ApproveWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type RejectWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
Reason string `json:"reason" validate:"required,max=500"`
|
||||
}
|
||||
|
||||
type QuotaTask struct {
|
||||
Id int64 `json:"id"`
|
||||
Subscribers []int64 `json:"subscribers"`
|
||||
@@ -2528,6 +2633,11 @@ type RedemptionRecord struct {
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
type RefundOrderRequest struct {
|
||||
Id int64 `json:"id" validate:"required"`
|
||||
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
|
||||
}
|
||||
|
||||
type RegisterConfig struct {
|
||||
StopRegister bool `json:"stop_register"`
|
||||
EnableTrial bool `json:"enable_trial"`
|
||||
@@ -2551,6 +2661,11 @@ type RegisterLog struct {
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type RejectWithdrawalRequest struct {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
Reason string `json:"reason" validate:"required,max=500"`
|
||||
}
|
||||
|
||||
type RemoveFamilyMemberRequest struct {
|
||||
FamilyId int64 `json:"family_id" validate:"required,gt=0"`
|
||||
UserId int64 `json:"user_id" validate:"required,gt=0"`
|
||||
@@ -2809,6 +2924,11 @@ type SetNodeMultiplierRequest struct {
|
||||
Periods []TimePeriod `json:"periods"`
|
||||
}
|
||||
|
||||
type SetPromoPriceRequest struct {
|
||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
|
||||
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"`
|
||||
}
|
||||
|
||||
type Shadowsocks struct {
|
||||
Method string `json:"method" validate:"required"`
|
||||
Port int `json:"port" validate:"required"`
|
||||
@@ -2866,13 +2986,6 @@ type StripePayment struct {
|
||||
PublishableKey string `json:"publishable_key"`
|
||||
}
|
||||
|
||||
type SubscribePromo struct {
|
||||
RuleName string `json:"rule_name"`
|
||||
RuleType string `json:"rule_type"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
type Subscribe struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -2975,6 +3088,13 @@ type SubscribeLog struct {
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type SubscribePromo struct {
|
||||
RuleName string `json:"rule_name"`
|
||||
RuleType string `json:"rule_type"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
type SubscribeSortRequest struct {
|
||||
Sort []SortItem `json:"sort"`
|
||||
}
|
||||
@@ -3222,30 +3342,6 @@ type UpdateCouponRequest struct {
|
||||
Enable *bool `json:"enable,omitempty"`
|
||||
}
|
||||
|
||||
type SetPromoPriceRequest struct {
|
||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
|
||||
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"`
|
||||
}
|
||||
|
||||
type DeletePromoPriceRequest struct {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type DeletePromoRuleRequest struct {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type UpdatePromoRuleRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type UpdateDocumentRequest struct {
|
||||
Id int64 `json:"id" validate:"required"`
|
||||
Title string `json:"title" validate:"required"`
|
||||
@@ -3312,6 +3408,17 @@ type UpdatePaymentMethodRequest struct {
|
||||
Enable *bool `json:"enable" validate:"required"`
|
||||
}
|
||||
|
||||
type UpdatePromoRuleRequest struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type UpdateRedemptionCodeRequest struct {
|
||||
Id int64 `json:"id" validate:"required"`
|
||||
TotalCount int64 `json:"total_count,omitempty"`
|
||||
@@ -3470,7 +3577,7 @@ type User struct {
|
||||
EnableLoginNotify bool `json:"enable_login_notify"`
|
||||
EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
|
||||
EnableTradeNotify bool `json:"enable_trade_notify"`
|
||||
UseStatus bool `json:"use_status"`
|
||||
UseStatus bool `json:"use_status"` // Whether to show the "bind email to get free trial" prompt
|
||||
AuthMethods []UserAuthMethod `json:"auth_methods"`
|
||||
UserDevices []UserDevice `json:"user_devices"`
|
||||
Rules []string `json:"rules"`
|
||||
@@ -3787,96 +3894,3 @@ type WithdrawalLog struct {
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteStatsRequest struct {
|
||||
UserId int64 `form:"user_id" validate:"required"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteStatsResponse struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteListRequest struct {
|
||||
UserId int64 `form:"user_id" validate:"required"`
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
Search string `form:"search"`
|
||||
Enable *int `form:"enable"`
|
||||
UserIdSearch int64 `form:"user_id_search"`
|
||||
}
|
||||
|
||||
type AdminInvitedUser struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetAdminUserInviteListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []AdminInvitedUser `json:"list"`
|
||||
}
|
||||
|
||||
type GetInviteManageListRequest struct {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
Search string `form:"search"`
|
||||
InviterId int64 `form:"inviter_id"`
|
||||
InviteeId int64 `form:"invitee_id"`
|
||||
}
|
||||
|
||||
type InviteManageRecord struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
type GetInviteManageListResponse struct {
|
||||
Total int64 `json:"total"`
|
||||
List []InviteManageRecord `json:"list"`
|
||||
}
|
||||
|
||||
type GetLogMessageRawRequest struct {
|
||||
Id int64 `form:"id" validate:"required"`
|
||||
}
|
||||
|
||||
type GetLogMessageRawResponse struct {
|
||||
Id int64 `json:"id"`
|
||||
Platform string `json:"platform"`
|
||||
AppVersion string `json:"app_version"`
|
||||
OsName string `json:"os_name"`
|
||||
OsVersion string `json:"os_version"`
|
||||
DeviceId string `json:"device_id"`
|
||||
UserId *int64 `json:"user_id"`
|
||||
SessionId string `json:"session_id"`
|
||||
Level uint8 `json:"level"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
Message string `json:"message"`
|
||||
Stack string `json:"stack"`
|
||||
Context json.RawMessage `json:"context"`
|
||||
ClientIP string `json:"client_ip"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Locale string `json:"locale"`
|
||||
Digest string `json:"digest"`
|
||||
OccurredAt int64 `json:"occurred_at"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ import (
|
||||
"apis/admin/marketing.api"
|
||||
"apis/admin/application.api"
|
||||
"apis/admin/group.api"
|
||||
"apis/admin/invite.api"
|
||||
"apis/admin/promo.api"
|
||||
"apis/public/user.api"
|
||||
"apis/public/subscribe.api"
|
||||
"apis/public/redemption.api"
|
||||
|
||||
@@ -272,6 +272,25 @@ func (l *ActivateOrderLogic) claimAndGetOrder(ctx context.Context, orderNo strin
|
||||
}
|
||||
|
||||
func (l *ActivateOrderLogic) releaseClaim(ctx context.Context, orderNo string) error {
|
||||
// 终态守卫:OrderStatusClaimed(6) 与 orderStatusRefunded(6) 共用同一枚举值。
|
||||
// 若已存在 333 退款日志,说明此处的 status=6 是「已退款」,不能再降回 5,
|
||||
// 否则下次 activate 会重新激活订阅、且管理员可二次触发退款导致佣金被多次扣减。
|
||||
// 详见 HIF-131 / HIF-132。
|
||||
refunded, err := log.HasRefundCommissionLog(l.svc.DB.WithContext(ctx), orderNo)
|
||||
if err != nil {
|
||||
logger.WithContext(ctx).Error("Check refund log before release claim failed",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("order_no", orderNo),
|
||||
)
|
||||
return fmt.Errorf("check refund log failed for order %s: %w", orderNo, err)
|
||||
}
|
||||
if refunded {
|
||||
logger.WithContext(ctx).Info("Skip release claim for refunded order (status=6 + refund log)",
|
||||
logger.Field("order_no", orderNo),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := l.svc.DB.WithContext(ctx).
|
||||
Model(&order.Order{}).
|
||||
Where("order_no = ? AND status = ?", orderNo, OrderStatusClaimed).
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
logmodel "github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
@@ -54,6 +55,25 @@ func (l *StuckOrderRecoveryLogic) ProcessTask(ctx context.Context, _ *asynq.Task
|
||||
for i := range stuckOrders {
|
||||
o := &stuckOrders[i]
|
||||
|
||||
// 终态守卫:OrderStatusClaimed(6) 与 orderStatusRefunded(6) 共用同一枚举值,
|
||||
// 若该订单已写入 333 退款佣金日志,说明状态 6 表示「已退款」而非「短暂 claim」,
|
||||
// 必须跳过,否则会把已退款订单重置为 5 + 重新入队 activate,导致重复退款。
|
||||
// 详见 HIF-131 / HIF-132。
|
||||
refunded, err := logmodel.HasRefundCommissionLog(l.svc.DB.WithContext(ctx), o.OrderNo)
|
||||
if err != nil {
|
||||
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to check refund log",
|
||||
logger.Field("order_no", o.OrderNo),
|
||||
logger.Field("error", err.Error()),
|
||||
)
|
||||
continue
|
||||
}
|
||||
if refunded {
|
||||
logger.WithContext(ctx).Info("[StuckOrderRecovery] Skip refunded order (status=6 + refund log)",
|
||||
logger.Field("order_no", o.OrderNo),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
result := l.svc.DB.WithContext(ctx).
|
||||
Model(&order.Order{}).
|
||||
Where("order_no = ? AND status = ?", o.OrderNo, OrderStatusClaimed).
|
||||
|
||||
Reference in New Issue
Block a user