Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ea586e3ba2 |
@@ -0,0 +1,155 @@
|
|||||||
|
syntax = "v1"
|
||||||
|
|
||||||
|
info (
|
||||||
|
title: "Promo API"
|
||||||
|
desc: "API for ppanel"
|
||||||
|
author: "Tension"
|
||||||
|
email: "tension@ppanel.com"
|
||||||
|
version: "0.0.1"
|
||||||
|
)
|
||||||
|
|
||||||
|
import "../types.api"
|
||||||
|
|
||||||
|
type (
|
||||||
|
PromoRule {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Params interface{} `json:"params"`
|
||||||
|
Priority int64 `json:"priority"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
StartTime int64 `json:"start_time"`
|
||||||
|
EndTime int64 `json:"end_time"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
|
}
|
||||||
|
CreatePromoRuleRequest {
|
||||||
|
Name string `json:"name" validate:"required,max=100"`
|
||||||
|
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||||
|
Params interface{} `json:"params" validate:"required"`
|
||||||
|
Priority int64 `json:"priority" validate:"gte=0"`
|
||||||
|
Enabled *bool `json:"enabled" validate:"required"`
|
||||||
|
StartTime int64 `json:"start_time" validate:"required"`
|
||||||
|
EndTime int64 `json:"end_time" validate:"required"`
|
||||||
|
}
|
||||||
|
UpdatePromoRuleRequest {
|
||||||
|
Id int64 `json:"id" validate:"required"`
|
||||||
|
Name string `json:"name" validate:"required,max=100"`
|
||||||
|
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||||
|
Params interface{} `json:"params" validate:"required"`
|
||||||
|
Priority int64 `json:"priority" validate:"gte=0"`
|
||||||
|
Enabled *bool `json:"enabled" validate:"required"`
|
||||||
|
StartTime int64 `json:"start_time" validate:"required"`
|
||||||
|
EndTime int64 `json:"end_time" validate:"required"`
|
||||||
|
}
|
||||||
|
DeletePromoRuleRequest {
|
||||||
|
Id int64 `path:"id" validate:"required"`
|
||||||
|
}
|
||||||
|
GetPromoRuleDetailRequest {
|
||||||
|
Id int64 `path:"id" validate:"required"`
|
||||||
|
}
|
||||||
|
GetPromoRuleListRequest {
|
||||||
|
Page int64 `form:"page" validate:"required"`
|
||||||
|
Size int64 `form:"size" validate:"required"`
|
||||||
|
Type string `form:"type,omitempty" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
||||||
|
Enabled *bool `form:"enabled,omitempty"`
|
||||||
|
Search string `form:"search,omitempty"`
|
||||||
|
}
|
||||||
|
GetPromoRuleListResponse {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []PromoRule `json:"list"`
|
||||||
|
}
|
||||||
|
PromoPriceInput {
|
||||||
|
SubscribeId int64 `json:"subscribe_id" validate:"required"`
|
||||||
|
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
||||||
|
}
|
||||||
|
PromoPrice {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
|
PromoRuleId int64 `json:"promo_rule_id"`
|
||||||
|
PromoPrice int64 `json:"promo_price"`
|
||||||
|
UnitPrice int64 `json:"unit_price"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
|
}
|
||||||
|
CreatePromoPriceRequest {
|
||||||
|
PromoRuleId int64 `json:"promo_rule_id" validate:"required"`
|
||||||
|
Items []PromoPriceInput `json:"items" validate:"required,dive"`
|
||||||
|
}
|
||||||
|
GetPromoPriceListRequest {
|
||||||
|
Page int64 `form:"page" validate:"required"`
|
||||||
|
Size int64 `form:"size" validate:"required"`
|
||||||
|
PromoRuleId int64 `form:"promo_rule_id" validate:"required"`
|
||||||
|
}
|
||||||
|
GetPromoPriceListResponse {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []PromoPrice `json:"list"`
|
||||||
|
}
|
||||||
|
DeletePromoPriceRequest {
|
||||||
|
Id int64 `path:"id" validate:"required"`
|
||||||
|
}
|
||||||
|
PromoUsage {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
UserId int64 `json:"user_id"`
|
||||||
|
PromoRuleId int64 `json:"promo_rule_id"`
|
||||||
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
|
OrderNo string `json:"order_no"`
|
||||||
|
PromoPrice int64 `json:"promo_price"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
GetPromoUsageListRequest {
|
||||||
|
Page int64 `form:"page" validate:"required"`
|
||||||
|
Size int64 `form:"size" validate:"required"`
|
||||||
|
PromoRuleId int64 `form:"rule_id,omitempty"`
|
||||||
|
UserId int64 `form:"user_id,omitempty"`
|
||||||
|
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
||||||
|
OrderNo string `form:"order_no,omitempty"`
|
||||||
|
}
|
||||||
|
GetPromoUsageListResponse {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []PromoUsage `json:"list"`
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@server (
|
||||||
|
prefix: v1/admin/promo
|
||||||
|
group: admin/promo
|
||||||
|
middleware: AuthMiddleware
|
||||||
|
)
|
||||||
|
service ppanel {
|
||||||
|
@doc "Create promo rule"
|
||||||
|
@handler CreatePromoRule
|
||||||
|
post /rule (CreatePromoRuleRequest) returns (PromoRule)
|
||||||
|
|
||||||
|
@doc "Get promo rule list"
|
||||||
|
@handler GetPromoRuleList
|
||||||
|
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
|
||||||
|
|
||||||
|
@doc "Get promo rule detail"
|
||||||
|
@handler GetPromoRuleDetail
|
||||||
|
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
|
||||||
|
|
||||||
|
@doc "Update promo rule"
|
||||||
|
@handler UpdatePromoRule
|
||||||
|
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
|
||||||
|
|
||||||
|
@doc "Delete promo rule"
|
||||||
|
@handler DeletePromoRule
|
||||||
|
delete /rule/:id (DeletePromoRuleRequest)
|
||||||
|
|
||||||
|
@doc "Batch set promo price"
|
||||||
|
@handler CreatePromoPrice
|
||||||
|
post /price (CreatePromoPriceRequest)
|
||||||
|
|
||||||
|
@doc "Get promo price list"
|
||||||
|
@handler GetPromoPriceList
|
||||||
|
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
|
||||||
|
|
||||||
|
@doc "Delete promo price"
|
||||||
|
@handler DeletePromoPrice
|
||||||
|
delete /price/:id (DeletePromoPriceRequest)
|
||||||
|
|
||||||
|
@doc "Get promo usage list"
|
||||||
|
@handler GetPromoUsageList
|
||||||
|
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
|
||||||
|
}
|
||||||
+13
-2
@@ -16,7 +16,13 @@ type (
|
|||||||
}
|
}
|
||||||
|
|
||||||
FileUploadResponse {
|
FileUploadResponse {
|
||||||
Url string `json:"url"`
|
FileId string `json:"file_id"`
|
||||||
|
FileName string `json:"file_name"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Etag string `json:"etag"`
|
||||||
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
|
|
||||||
FileUploadInitRequest {
|
FileUploadInitRequest {
|
||||||
@@ -41,7 +47,12 @@ type (
|
|||||||
}
|
}
|
||||||
|
|
||||||
FileUploadCompleteResponse {
|
FileUploadCompleteResponse {
|
||||||
Url string `json:"url"`
|
FileId string `json:"file_id"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Etag string `json:"etag"`
|
||||||
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -26,5 +26,6 @@ import (
|
|||||||
"./admin/ads.api"
|
"./admin/ads.api"
|
||||||
"./admin/marketing.api"
|
"./admin/marketing.api"
|
||||||
"./admin/application.api"
|
"./admin/application.api"
|
||||||
|
"./admin/group.api"
|
||||||
|
"./admin/promo.api"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -229,7 +229,6 @@ type (
|
|||||||
Quantity int64 `json:"quantity"`
|
Quantity int64 `json:"quantity"`
|
||||||
Discount float64 `json:"discount"`
|
Discount float64 `json:"discount"`
|
||||||
MapApple string `json:"map_apple"`
|
MapApple string `json:"map_apple"`
|
||||||
Promo *SubscribePromo `json:"promo"`
|
|
||||||
}
|
}
|
||||||
SubscribePromo {
|
SubscribePromo {
|
||||||
RuleName string `json:"rule_name"`
|
RuleName string `json:"rule_name"`
|
||||||
@@ -251,6 +250,7 @@ type (
|
|||||||
UnitPrice int64 `json:"unit_price"`
|
UnitPrice int64 `json:"unit_price"`
|
||||||
UnitTime string `json:"unit_time"`
|
UnitTime string `json:"unit_time"`
|
||||||
Discount []SubscribeDiscount `json:"discount"`
|
Discount []SubscribeDiscount `json:"discount"`
|
||||||
|
Promo *SubscribePromo `json:"promo"`
|
||||||
NodeCount int64 `json:"node_count"`
|
NodeCount int64 `json:"node_count"`
|
||||||
Replacement int64 `json:"replacement"`
|
Replacement int64 `json:"replacement"`
|
||||||
Inventory int64 `json:"inventory"`
|
Inventory int64 `json:"inventory"`
|
||||||
|
|||||||
@@ -4316,9 +4316,6 @@
|
|||||||
"discount": {
|
"discount": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
"format": "double"
|
"format": "double"
|
||||||
},
|
|
||||||
"promo": {
|
|
||||||
"$ref": "#/definitions/SubscribePromo"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"title": "SubscribeDiscount",
|
"title": "SubscribeDiscount",
|
||||||
|
|||||||
@@ -1,560 +0,0 @@
|
|||||||
# 提现 & 文件上传 & 日志上报 — 用户端 API 接口文档
|
|
||||||
|
|
||||||
> 基于 ppanel-server 源码整理,所有时间戳均为**秒级 Unix**。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 目录
|
|
||||||
|
|
||||||
- [一、提现接口](#一提现接口)
|
|
||||||
- [1.1 申请提现](#11-申请提现)
|
|
||||||
- [1.2 取消提现](#12-取消提现)
|
|
||||||
- [1.3 查询提现记录](#13-查询提现记录)
|
|
||||||
- [二、枚举值与状态流转](#二枚举值与状态流转)
|
|
||||||
- [三、文件上传接口](#三文件上传接口)
|
|
||||||
- [3.1 直传文件(小文件)](#31-直传文件小文件)
|
|
||||||
- [3.2 初始化上传(大文件 — 预签名)](#32-初始化上传大文件--预签名)
|
|
||||||
- [3.3 确认上传完成](#33-确认上传完成)
|
|
||||||
- [四、日志查询接口 (Admin)](#四日志查询接口-admin)
|
|
||||||
- [4.1 错误日志列表](#41-错误日志列表)
|
|
||||||
- [4.2 错误日志详情](#42-错误日志详情)
|
|
||||||
- [4.3 日志消息原始详情](#43-日志消息原始详情)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 一、提现接口
|
|
||||||
|
|
||||||
> 认证方式: JWT(用户登录态)
|
|
||||||
>
|
|
||||||
> 路由前缀: `/v1/public/user`
|
|
||||||
|
|
||||||
### 1.1 申请提现
|
|
||||||
|
|
||||||
提交佣金提现申请,创建一条待审核的提现记录。
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /v1/public/user/commission_withdraw
|
|
||||||
```
|
|
||||||
|
|
||||||
**Request Body**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
|
||||||
|------|------|------|------|------|
|
|
||||||
| `amount` | int64 | 是 | — | 提现金额(分) |
|
|
||||||
| `method` | uint8 | 是 | `oneof=0 1 2 3` | 收款方式(见枚举表) |
|
|
||||||
| `content` | string | 否 | — | 提现备注 |
|
|
||||||
| `account` | string | 条件必填 | — | 收款账号 |
|
|
||||||
| `qr_code_url` | string | 条件必填 | — | 收款码图片 URL |
|
|
||||||
|
|
||||||
**各收款方式的必填字段**
|
|
||||||
|
|
||||||
| method | 收款方式 | 必填字段 |
|
|
||||||
|--------|---------|---------|
|
|
||||||
| `1` 支付宝 | `qr_code_url` | 收款码图片 |
|
|
||||||
| `2` 微信 | `qr_code_url` | 收款码图片 |
|
|
||||||
| `3` 银行卡 | `account` | 收款账号 |
|
|
||||||
| `0` 其他 | `account` 必填 |
|
|
||||||
|
|
||||||
**Request 示例**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"amount": 5000,
|
|
||||||
"content": "提现到支付宝",
|
|
||||||
"method": 1,
|
|
||||||
"account": "user@example.com",
|
|
||||||
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**: [`WithdrawalLog`](#withdrawallog-对象)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 1.2 取消提现
|
|
||||||
|
|
||||||
用户取消自己的待审核提现申请,佣金退回账户。
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /v1/public/user/withdrawal_cancel
|
|
||||||
```
|
|
||||||
|
|
||||||
**Request Body**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
|
||||||
|------|------|------|------|------|
|
|
||||||
| `withdrawal_id` | int64 | 是 | `required,gt=0` | 提现记录 ID |
|
|
||||||
|
|
||||||
**Request 示例**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"withdrawal_id": 123
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**: [`WithdrawalLog`](#withdrawallog-对象)(状态已变为 `3=已取消`)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 1.3 查询提现记录
|
|
||||||
|
|
||||||
分页查询当前用户的提现记录(自动按 JWT 中的 userId 过滤)。
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /v1/public/user/withdrawal_log
|
|
||||||
```
|
|
||||||
|
|
||||||
**Query 参数**
|
|
||||||
|
|
||||||
| 参数 | 类型 | 必填 | 说明 |
|
|
||||||
|------|------|------|------|
|
|
||||||
| `page` | int | 否 | 页码,默认 1 |
|
|
||||||
| `size` | int | 否 | 每页条数,默认 10 |
|
|
||||||
|
|
||||||
**Request 示例**
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /v1/public/user/withdrawal_log?page=1&size=10
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"list": [WithdrawalLog, ...],
|
|
||||||
"total": 25
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 二、枚举值与状态流转
|
|
||||||
|
|
||||||
### 提现状态 (`status`)
|
|
||||||
|
|
||||||
| 值 | 说明 |
|
|
||||||
|----|------|
|
|
||||||
| 0 | 待审核 |
|
|
||||||
| 1 | 已通过 |
|
|
||||||
| 2 | 已拒绝 |
|
|
||||||
| 3 | 已取消 |
|
|
||||||
|
|
||||||
### 收款方式 (`method`)
|
|
||||||
|
|
||||||
| 值 | 说明 |
|
|
||||||
|----|------|
|
|
||||||
| 0 | 其他 |
|
|
||||||
| 1 | 支付宝 |
|
|
||||||
| 2 | 微信 |
|
|
||||||
| 3 | 银行卡 |
|
|
||||||
|
|
||||||
### 状态流转
|
|
||||||
|
|
||||||
```
|
|
||||||
┌── 管理员通过 ──▶ 已通过 (1)
|
|
||||||
│
|
|
||||||
待审核 (0) ──────┼── 管理员拒绝 ──▶ 已拒绝 (2)
|
|
||||||
│
|
|
||||||
└── 用户取消 ───▶ 已取消 (3)
|
|
||||||
```
|
|
||||||
|
|
||||||
### WithdrawalLog 对象
|
|
||||||
|
|
||||||
所有提现接口共用的响应结构:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"user_id": 100,
|
|
||||||
"amount": 5000,
|
|
||||||
"content": "提现备注",
|
|
||||||
"status": 0,
|
|
||||||
"reason": "",
|
|
||||||
"method": 1,
|
|
||||||
"account": "user@example.com",
|
|
||||||
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png",
|
|
||||||
"created_at": 1716700000,
|
|
||||||
"updated_at": 1716700000
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `id` | int64 | 提现记录 ID |
|
|
||||||
| `user_id` | int64 | 用户 ID |
|
|
||||||
| `amount` | int64 | 提现金额(分) |
|
|
||||||
| `content` | string | 提现备注 |
|
|
||||||
| `status` | uint8 | 状态(见枚举表) |
|
|
||||||
| `reason` | string | 拒绝原因(仅 status=2 时有值,其余 omitempty) |
|
|
||||||
| `method` | uint8 | 收款方式(见枚举表) |
|
|
||||||
| `account` | string | 收款账号 |
|
|
||||||
| `qr_code_url` | string | 收款码图片 URL |
|
|
||||||
| `created_at` | int64 | 创建时间(秒级 Unix) |
|
|
||||||
| `updated_at` | int64 | 更新时间(秒级 Unix) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 三、文件上传接口
|
|
||||||
|
|
||||||
> 认证方式: JWT + DeviceMiddleware(用户登录态 + 设备认证)
|
|
||||||
>
|
|
||||||
> 路由前缀: `/v1/public/file`
|
|
||||||
>
|
|
||||||
> 存储后端: S3 兼容(RustFS)
|
|
||||||
|
|
||||||
提供两种上传方式:
|
|
||||||
|
|
||||||
| 方式 | 适用场景 | 流程 |
|
|
||||||
|------|---------|------|
|
|
||||||
| **直传** | 小文件(收款码等) | 1 次请求,`multipart/form-data` 直接上传 |
|
|
||||||
| **预签名** | 大文件 / 客户端直传 S3 | init → 客户端 PUT 到预签名 URL → complete 确认 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.1 直传文件(小文件)
|
|
||||||
|
|
||||||
通过 `multipart/form-data` 直接上传文件到服务端,服务端转存至 S3。
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /v1/public/file/upload
|
|
||||||
Content-Type: multipart/form-data
|
|
||||||
```
|
|
||||||
|
|
||||||
**Form 参数**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 必填 | 说明 |
|
|
||||||
|------|------|------|------|
|
|
||||||
| `biz_type` | string | 是 | 业务类型(如 `withdrawal_qrcode`、`avatar` 等) |
|
|
||||||
| `file` | file | 是 | 上传的文件(multipart) |
|
|
||||||
|
|
||||||
**cURL 示例**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -X POST /v1/public/file/upload \
|
|
||||||
-H "Authorization: Bearer <token>" \
|
|
||||||
-F "biz_type=withdrawal_qrcode" \
|
|
||||||
-F "file=@/path/to/alipay_qr.png"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"file_id": "a1b2c3d4e5f678901234",
|
|
||||||
"file_name": "alipay_qr.png",
|
|
||||||
"object_key": "app-upload/2026/05/27/100/alipay_qr.png__a1b2c3d4e5f678901234",
|
|
||||||
"size": 52480,
|
|
||||||
"content_type": "image/png",
|
|
||||||
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
|
|
||||||
"status": "completed"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**FileUploadResponse 字段说明**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `file_id` | string | 文件唯一 ID(24 字符 hex) |
|
|
||||||
| `file_name` | string | 原始文件名 |
|
|
||||||
| `object_key` | string | S3 对象路径 |
|
|
||||||
| `size` | int64 | 文件大小(字节) |
|
|
||||||
| `content_type` | string | MIME 类型 |
|
|
||||||
| `etag` | string | S3 ETag |
|
|
||||||
| `status` | string | 状态,直传成功即 `completed` |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.2 初始化上传(大文件 — 预签名)
|
|
||||||
|
|
||||||
获取 S3 预签名 URL,客户端直接 PUT 到 S3,避免文件经过服务端。
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /v1/public/file/upload/init
|
|
||||||
```
|
|
||||||
|
|
||||||
**Request Body**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
|
||||||
|------|------|------|------|------|
|
|
||||||
| `biz_type` | string | 是 | `required` | 业务类型 |
|
|
||||||
| `file_name` | string | 是 | `required` | 文件名 |
|
|
||||||
| `content_type` | string | 是 | `required` | MIME 类型(如 `image/png`) |
|
|
||||||
| `size` | int64 | 是 | `required` | 文件大小(字节) |
|
|
||||||
| `sha256` | string | 否 | — | 文件 SHA256(可选校验) |
|
|
||||||
|
|
||||||
**Request 示例**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"biz_type": "withdrawal_qrcode",
|
|
||||||
"file_name": "wechat_qr.png",
|
|
||||||
"content_type": "image/png",
|
|
||||||
"size": 102400,
|
|
||||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb924..."
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"file_id": "b2c3d4e5f6789012345a",
|
|
||||||
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
|
|
||||||
"upload_url": "https://s3.example.com/bucket/app-upload/...?X-Amz-Signature=...",
|
|
||||||
"method": "PUT",
|
|
||||||
"headers": {
|
|
||||||
"Content-Type": "image/png"
|
|
||||||
},
|
|
||||||
"expired_at": 1716700300
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**FileUploadInitResponse 字段说明**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `file_id` | string | 文件唯一 ID |
|
|
||||||
| `object_key` | string | S3 对象路径 |
|
|
||||||
| `upload_url` | string | 预签名上传 URL |
|
|
||||||
| `method` | string | HTTP 方法(`PUT`) |
|
|
||||||
| `headers` | map | 上传时需携带的请求头 |
|
|
||||||
| `expired_at` | int64 | 预签名过期时间(秒级 Unix,默认 300 秒) |
|
|
||||||
|
|
||||||
**客户端上传流程**
|
|
||||||
|
|
||||||
```
|
|
||||||
1. 调用 /upload/init 获取 upload_url
|
|
||||||
2. 用返回的 method + headers 直接上传文件到 upload_url
|
|
||||||
3. 上传成功后调用 /upload/complete 确认
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3.3 确认上传完成
|
|
||||||
|
|
||||||
客户端通过预签名 URL 上传完成后,调用此接口确认文件状态。
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /v1/public/file/upload/complete
|
|
||||||
```
|
|
||||||
|
|
||||||
**Request Body**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
|
||||||
|------|------|------|------|------|
|
|
||||||
| `file_id` | string | 是 | `required` | init 返回的 file_id |
|
|
||||||
|
|
||||||
**Request 示例**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"file_id": "b2c3d4e5f6789012345a"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"file_id": "b2c3d4e5f6789012345a",
|
|
||||||
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
|
|
||||||
"size": 102400,
|
|
||||||
"content_type": "image/png",
|
|
||||||
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
|
|
||||||
"status": "completed"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**FileUploadCompleteResponse 字段说明**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `file_id` | string | 文件唯一 ID |
|
|
||||||
| `object_key` | string | S3 对象路径 |
|
|
||||||
| `size` | int64 | 实际文件大小(S3 HeadObject 获取) |
|
|
||||||
| `content_type` | string | MIME 类型 |
|
|
||||||
| `etag` | string | S3 ETag |
|
|
||||||
| `status` | string | `completed` |
|
|
||||||
|
|
||||||
**校验规则**
|
|
||||||
|
|
||||||
- 文件大小不能超过配置的 `S3.MaxUploadSize`
|
|
||||||
- Content-Type 必须在配置的 `S3.AllowedContentTypes` 白名单内(若配置了)
|
|
||||||
- complete 时会校验 S3 上的实际文件大小是否与 init 声明的一致
|
|
||||||
- 只能确认自己发起的上传(userId 校验)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 四、日志查询接口 (Admin)
|
|
||||||
|
|
||||||
> 认证方式: AuthMiddleware(管理员权限)
|
|
||||||
>
|
|
||||||
> 路由前缀: `/v1/admin/log`
|
|
||||||
>
|
|
||||||
> 数据来源: `log_message` 表(客户端上报的错误/崩溃日志)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 4.1 错误日志列表
|
|
||||||
|
|
||||||
分页查询客户端上报的错误日志,支持多维度筛选。
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /v1/admin/log/error_message/list
|
|
||||||
```
|
|
||||||
|
|
||||||
**Query 参数**
|
|
||||||
|
|
||||||
| 参数 | 类型 | 必填 | 说明 |
|
|
||||||
|------|------|------|------|
|
|
||||||
| `page` | int | 是 | 页码 |
|
|
||||||
| `size` | int | 是 | 每页条数 |
|
|
||||||
| `platform` | string | 否 | 平台筛选(ios / android / windows / mac / harmony) |
|
|
||||||
| `level` | uint8 | 否 | 日志级别 |
|
|
||||||
| `user_id` | int64 | 否 | 用户 ID |
|
|
||||||
| `device_id` | string | 否 | 设备 ID |
|
|
||||||
| `error_code` | string | 否 | 错误码 |
|
|
||||||
| `keyword` | string | 否 | 关键字搜索(匹配 message) |
|
|
||||||
| `start` | int64 | 否 | 开始时间(秒级 Unix) |
|
|
||||||
| `end` | int64 | 否 | 结束时间(秒级 Unix) |
|
|
||||||
|
|
||||||
**Request 示例**
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /v1/admin/log/error_message/list?page=1&size=20&platform=ios&start=1716600000&end=1716700000
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"total": 50,
|
|
||||||
"list": [
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"platform": "ios",
|
|
||||||
"app_version": "2.1.0",
|
|
||||||
"os_name": "iOS",
|
|
||||||
"os_version": "17.5",
|
|
||||||
"device_id": "A1B2C3D4",
|
|
||||||
"user_id": 100,
|
|
||||||
"session_id": "sess_xxx",
|
|
||||||
"level": 3,
|
|
||||||
"error_code": "VPN_CONNECT_FAIL",
|
|
||||||
"message": "Failed to establish VPN tunnel",
|
|
||||||
"created_at": 1716700000
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**ErrorLogMessage 字段说明**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `id` | int64 | 日志 ID |
|
|
||||||
| `platform` | string | 平台 |
|
|
||||||
| `app_version` | string | 客户端版本 |
|
|
||||||
| `os_name` | string | 操作系统名称 |
|
|
||||||
| `os_version` | string | 操作系统版本 |
|
|
||||||
| `device_id` | string | 设备 ID |
|
|
||||||
| `user_id` | int64 | 用户 ID |
|
|
||||||
| `session_id` | string | 会话 ID |
|
|
||||||
| `level` | uint8 | 日志级别 |
|
|
||||||
| `error_code` | string | 错误码 |
|
|
||||||
| `message` | string | 错误消息 |
|
|
||||||
| `created_at` | int64 | 创建时间(秒级 Unix) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 4.2 错误日志详情
|
|
||||||
|
|
||||||
获取单条错误日志的完整详情(列表字段 + 堆栈/IP/UA 等扩展信息)。
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /v1/admin/log/error_message/detail
|
|
||||||
```
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"platform": "ios",
|
|
||||||
"app_version": "2.1.0",
|
|
||||||
"os_name": "iOS",
|
|
||||||
"os_version": "17.5",
|
|
||||||
"device_id": "A1B2C3D4",
|
|
||||||
"user_id": 100,
|
|
||||||
"session_id": "sess_xxx",
|
|
||||||
"level": 3,
|
|
||||||
"error_code": "VPN_CONNECT_FAIL",
|
|
||||||
"message": "Failed to establish VPN tunnel",
|
|
||||||
"stack": "at VPNManager.connect() line 42\nat ...",
|
|
||||||
"client_ip": "1.2.3.4",
|
|
||||||
"user_agent": "PPanel/2.1.0 iOS/17.5",
|
|
||||||
"locale": "zh-CN",
|
|
||||||
"occurred_at": 1716700000,
|
|
||||||
"created_at": 1716700000
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**相比列表额外返回的字段**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `stack` | string | 堆栈信息 |
|
|
||||||
| `client_ip` | string | 客户端 IP |
|
|
||||||
| `user_agent` | string | User-Agent |
|
|
||||||
| `locale` | string | 客户端语言/地区 |
|
|
||||||
| `occurred_at` | int64 | 错误发生时间(秒级 Unix) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 4.3 日志消息原始详情
|
|
||||||
|
|
||||||
获取单条 `log_message` 的完整原始数据(含 context、digest 等全量字段)。
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /v1/admin/log/message/detail
|
|
||||||
```
|
|
||||||
|
|
||||||
**Query 参数**
|
|
||||||
|
|
||||||
| 参数 | 类型 | 必填 | 说明 |
|
|
||||||
|------|------|------|------|
|
|
||||||
| `id` | int64 | 是 | 日志消息 ID |
|
|
||||||
|
|
||||||
**Response**
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"platform": "ios",
|
|
||||||
"app_version": "2.1.0",
|
|
||||||
"os_name": "iOS",
|
|
||||||
"os_version": "17.5",
|
|
||||||
"device_id": "A1B2C3D4",
|
|
||||||
"user_id": 100,
|
|
||||||
"session_id": "sess_xxx",
|
|
||||||
"level": 3,
|
|
||||||
"error_code": "VPN_CONNECT_FAIL",
|
|
||||||
"message": "Failed to establish VPN tunnel",
|
|
||||||
"stack": "at VPNManager.connect() line 42\nat ...",
|
|
||||||
"context": { "server_id": 5, "protocol": "vmess" },
|
|
||||||
"client_ip": "1.2.3.4",
|
|
||||||
"user_agent": "PPanel/2.1.0 iOS/17.5",
|
|
||||||
"locale": "zh-CN",
|
|
||||||
"digest": "sha256_abc123...",
|
|
||||||
"occurred_at": 1716700000,
|
|
||||||
"created_at": 1716700000
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**相比详情额外返回的字段**
|
|
||||||
|
|
||||||
| 字段 | 类型 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| `context` | any | 附加上下文(原始 JSON) |
|
|
||||||
| `digest` | string | 内容摘要(用于去重) |
|
|
||||||
@@ -1,10 +1,4 @@
|
|||||||
SELECT COUNT(*) INTO @col_exists FROM INFORMATION_SCHEMA.COLUMNS
|
ALTER TABLE `withdrawals`
|
||||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'withdrawals' AND COLUMN_NAME = 'method';
|
ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '收款方式 0:其他 1:支付宝 2:微信 3:银行卡' AFTER `content`,
|
||||||
|
ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '收款账号' AFTER `method`,
|
||||||
SET @ddl = IF(@col_exists = 0,
|
ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '收款码图片URL' AFTER `account`;
|
||||||
'ALTER TABLE `withdrawals` ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 AFTER `content`, ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '''' AFTER `method`, ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '''' AFTER `account`',
|
|
||||||
'SELECT 1');
|
|
||||||
|
|
||||||
PREPARE stmt FROM @ddl;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|||||||
@@ -11,158 +11,22 @@ CREATE TABLE IF NOT EXISTS `promo_rule` (
|
|||||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)
|
KEY `idx_enabled_priority` (`enabled`, `priority` DESC),
|
||||||
|
KEY `idx_deleted_at` (`deleted_at`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
||||||
|
|
||||||
SET @index_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.STATISTICS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'promo_rule'
|
|
||||||
AND INDEX_NAME = 'idx_enabled_priority'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@index_exists = 1,
|
|
||||||
'ALTER TABLE `promo_rule` DROP INDEX `idx_enabled_priority`',
|
|
||||||
'SELECT ''Index idx_enabled_priority does not exist on promo_rule table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @index_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.STATISTICS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'promo_rule'
|
|
||||||
AND INDEX_NAME = 'idx_deleted_at'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@index_exists = 1,
|
|
||||||
'ALTER TABLE `promo_rule` DROP INDEX `idx_deleted_at`',
|
|
||||||
'SELECT ''Index idx_deleted_at does not exist on promo_rule table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @index_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.STATISTICS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'promo_rule'
|
|
||||||
AND INDEX_NAME = 'idx_enabled_priority_deleted'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@index_exists = 0,
|
|
||||||
'ALTER TABLE `promo_rule` ADD KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)',
|
|
||||||
'SELECT ''Index idx_enabled_priority_deleted already exists on promo_rule table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
|
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
|
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
|
||||||
`quantity` BIGINT NOT NULL DEFAULT 1 COMMENT '购买数量',
|
|
||||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
|
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
|
||||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
|
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
|
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
|
||||||
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
||||||
|
|
||||||
SET @column_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'subscribe_promo'
|
|
||||||
AND COLUMN_NAME = 'quantity'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
|
|
||||||
'SELECT ''Column quantity already exists in subscribe_promo table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 1,
|
|
||||||
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
|
|
||||||
'SELECT ''Column quantity does not exist in subscribe_promo table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @index_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.STATISTICS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'subscribe_promo'
|
|
||||||
AND INDEX_NAME = 'uk_subscribe_rule'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@index_exists = 1,
|
|
||||||
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
|
|
||||||
'SELECT ''Index uk_subscribe_rule does not exist on subscribe_promo table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @index_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.STATISTICS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'subscribe_promo'
|
|
||||||
AND INDEX_NAME = 'uk_subscribe_qty_rule'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@index_exists = 1,
|
|
||||||
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
|
|
||||||
'SELECT ''Index uk_subscribe_qty_rule does not exist on subscribe_promo table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @index_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.STATISTICS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'subscribe_promo'
|
|
||||||
AND INDEX_NAME = 'uk_subscribe_quantity_rule'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@index_exists = 0,
|
|
||||||
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
|
|
||||||
'SELECT ''Index uk_subscribe_quantity_rule already exists on subscribe_promo table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `promo_usage` (
|
CREATE TABLE IF NOT EXISTS `promo_usage` (
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
|
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Batch set promo price
|
||||||
|
func CreatePromoPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.CreatePromoPriceRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewCreatePromoPriceLogic(c.Request.Context(), svcCtx)
|
||||||
|
err := l.CreatePromoPrice(&req)
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Create promo rule
|
||||||
|
func CreatePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.CreatePromoRuleRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewCreatePromoRuleLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.CreatePromoRule(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Delete promo price
|
||||||
|
func DeletePromoPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.DeletePromoPriceRequest
|
||||||
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.String(http.StatusBadRequest, "Invalid Params")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Id = id
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewDeletePromoPriceLogic(c.Request.Context(), svcCtx)
|
||||||
|
err = l.DeletePromoPrice(&req)
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Delete promo rule
|
||||||
|
func DeletePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.DeletePromoRuleRequest
|
||||||
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.String(http.StatusBadRequest, "Invalid Params")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Id = id
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewDeletePromoRuleLogic(c.Request.Context(), svcCtx)
|
||||||
|
err = l.DeletePromoRule(&req)
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get promo price list
|
||||||
|
func GetPromoPriceListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.GetPromoPriceListRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewGetPromoPriceListLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.GetPromoPriceList(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get promo rule detail
|
||||||
|
func GetPromoRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.GetPromoRuleDetailRequest
|
||||||
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.String(http.StatusBadRequest, "Invalid Params")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Id = id
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewGetPromoRuleDetailLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.GetPromoRuleDetail(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get promo rule list
|
||||||
|
func GetPromoRuleListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.GetPromoRuleListRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewGetPromoRuleListLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.GetPromoRuleList(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get promo usage list
|
||||||
|
func GetPromoUsageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.GetPromoUsageListRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewGetPromoUsageListLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.GetPromoUsageList(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Update promo rule
|
||||||
|
func UpdatePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.UpdatePromoRuleRequest
|
||||||
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.String(http.StatusBadRequest, "Invalid Params")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
req.Id = id
|
||||||
|
if err := svcCtx.Validate(&req); err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := promo.NewUpdatePromoRuleLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.UpdatePromoRule(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import (
|
|||||||
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
||||||
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
||||||
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
||||||
|
adminPromo "github.com/perfect-panel/server/internal/handler/admin/promo"
|
||||||
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
||||||
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
||||||
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
||||||
@@ -374,6 +375,38 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
adminPromoGroupRouter := router.Group("/v1/admin/promo")
|
||||||
|
adminPromoGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||||
|
|
||||||
|
{
|
||||||
|
// Create promo rule
|
||||||
|
adminPromoGroupRouter.POST("/rule", adminPromo.CreatePromoRuleHandler(serverCtx))
|
||||||
|
|
||||||
|
// Get promo rule list
|
||||||
|
adminPromoGroupRouter.GET("/rule/list", adminPromo.GetPromoRuleListHandler(serverCtx))
|
||||||
|
|
||||||
|
// Get promo rule detail
|
||||||
|
adminPromoGroupRouter.GET("/rule/:id", adminPromo.GetPromoRuleDetailHandler(serverCtx))
|
||||||
|
|
||||||
|
// Update promo rule
|
||||||
|
adminPromoGroupRouter.PUT("/rule/:id", adminPromo.UpdatePromoRuleHandler(serverCtx))
|
||||||
|
|
||||||
|
// Delete promo rule
|
||||||
|
adminPromoGroupRouter.DELETE("/rule/:id", adminPromo.DeletePromoRuleHandler(serverCtx))
|
||||||
|
|
||||||
|
// Batch set promo price
|
||||||
|
adminPromoGroupRouter.POST("/price", adminPromo.CreatePromoPriceHandler(serverCtx))
|
||||||
|
|
||||||
|
// Get promo price list
|
||||||
|
adminPromoGroupRouter.GET("/price/list", adminPromo.GetPromoPriceListHandler(serverCtx))
|
||||||
|
|
||||||
|
// Delete promo price
|
||||||
|
adminPromoGroupRouter.DELETE("/price/:id", adminPromo.DeletePromoPriceHandler(serverCtx))
|
||||||
|
|
||||||
|
// Get promo usage list
|
||||||
|
adminPromoGroupRouter.GET("/usage/list", adminPromo.GetPromoUsageListHandler(serverCtx))
|
||||||
|
}
|
||||||
|
|
||||||
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
||||||
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
enabledRulesCacheKey = "promo:rules:enabled"
|
||||||
|
subscribePromoKeyFmt = "promo:subscribe:%d"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ruleParams struct {
|
||||||
|
WindowHours int `json:"window_hours"`
|
||||||
|
InactiveMonths int `json:"inactive_months"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRulePayload(ruleType string, params json.RawMessage, priority, startTime, endTime int64) error {
|
||||||
|
if priority < 0 {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "priority must be greater than or equal to 0")
|
||||||
|
}
|
||||||
|
if startTime >= endTime {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "start_time must be less than end_time")
|
||||||
|
}
|
||||||
|
|
||||||
|
var p ruleParams
|
||||||
|
if len(params) == 0 || !json.Valid(params) {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params must be valid json")
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(params, &p); err != nil {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params must be valid json object")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ruleType {
|
||||||
|
case promoModel.RuleTypeNewUser:
|
||||||
|
if p.WindowHours <= 0 {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params.window_hours must be greater than 0")
|
||||||
|
}
|
||||||
|
case promoModel.RuleTypeInactiveUser:
|
||||||
|
if p.InactiveMonths <= 0 {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params.inactive_months must be greater than 0")
|
||||||
|
}
|
||||||
|
case promoModel.RuleTypeCampaign:
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "type must be new_user, inactive_user or campaign")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func toRuleResponse(data *promoModel.Rule) types.PromoRule {
|
||||||
|
resp := types.PromoRule{
|
||||||
|
Id: data.Id,
|
||||||
|
Name: data.Name,
|
||||||
|
Type: data.Type,
|
||||||
|
Params: json.RawMessage(data.Params),
|
||||||
|
Priority: data.Priority,
|
||||||
|
Enabled: data.Enabled,
|
||||||
|
CreatedAt: data.CreatedAt.UnixMilli(),
|
||||||
|
UpdatedAt: data.UpdatedAt.UnixMilli(),
|
||||||
|
}
|
||||||
|
if data.StartTime != nil {
|
||||||
|
resp.StartTime = data.StartTime.UnixMilli()
|
||||||
|
}
|
||||||
|
if data.EndTime != nil {
|
||||||
|
resp.EndTime = data.EndTime.UnixMilli()
|
||||||
|
}
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
func toPriceResponse(data *promoModel.SubscribePromo, unitPrice int64) types.PromoPrice {
|
||||||
|
return types.PromoPrice{
|
||||||
|
Id: data.Id,
|
||||||
|
SubscribeId: data.SubscribeId,
|
||||||
|
PromoRuleId: data.PromoRuleId,
|
||||||
|
PromoPrice: data.PromoPrice,
|
||||||
|
UnitPrice: unitPrice,
|
||||||
|
CreatedAt: data.CreatedAt.UnixMilli(),
|
||||||
|
UpdatedAt: data.UpdatedAt.UnixMilli(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func toUsageResponse(data *promoModel.Usage) types.PromoUsage {
|
||||||
|
return types.PromoUsage{
|
||||||
|
Id: data.Id,
|
||||||
|
UserId: data.UserId,
|
||||||
|
PromoRuleId: data.PromoRuleId,
|
||||||
|
SubscribeId: data.SubscribeId,
|
||||||
|
OrderNo: data.OrderNo,
|
||||||
|
PromoPrice: data.PromoPrice,
|
||||||
|
CreatedAt: data.CreatedAt.UnixMilli(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ruleTimes(startTime, endTime int64) (*time.Time, *time.Time) {
|
||||||
|
start := time.UnixMilli(startTime)
|
||||||
|
end := time.UnixMilli(endTime)
|
||||||
|
return &start, &end
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearRuleCache(ctx context.Context, svcCtx *svc.ServiceContext) {
|
||||||
|
if svcCtx != nil && svcCtx.Redis != nil {
|
||||||
|
_ = svcCtx.Redis.Del(ctx, enabledRulesCacheKey).Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearSubscribePromoCache(ctx context.Context, svcCtx *svc.ServiceContext, ids ...int64) {
|
||||||
|
if svcCtx == nil || svcCtx.Redis == nil || len(ids) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(ids))
|
||||||
|
for _, id := range ids {
|
||||||
|
keys = append(keys, fmt.Sprintf(subscribePromoKeyFmt, id))
|
||||||
|
}
|
||||||
|
_ = svcCtx.Redis.Del(ctx, keys...).Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func wrapQueryError(msg string, err error) error {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "%s: %v", msg, err.Error())
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CreatePromoPriceLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Batch set promo price
|
||||||
|
func NewCreatePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoPriceLogic {
|
||||||
|
return &CreatePromoPriceLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *CreatePromoPriceLogic) CreatePromoPrice(req *types.CreatePromoPriceRequest) error {
|
||||||
|
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
|
||||||
|
if promoModel.IsNotFound(err) {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
||||||
|
}
|
||||||
|
l.Errorw("[CreatePromoPrice] Query Rule Error", logger.Field("error", err.Error()))
|
||||||
|
return wrapQueryError("get promo rule failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := make([]*promoModel.SubscribePromo, 0, len(req.Items))
|
||||||
|
subscribeIds := make([]int64, 0, len(req.Items))
|
||||||
|
for _, item := range req.Items {
|
||||||
|
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
||||||
|
if err != nil {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "subscribe not found")
|
||||||
|
}
|
||||||
|
if item.PromoPrice >= sub.UnitPrice {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo_price must be less than unit_price")
|
||||||
|
}
|
||||||
|
data = append(data, &promoModel.SubscribePromo{
|
||||||
|
SubscribeId: item.SubscribeId,
|
||||||
|
PromoRuleId: req.PromoRuleId,
|
||||||
|
PromoPrice: item.PromoPrice,
|
||||||
|
})
|
||||||
|
subscribeIds = append(subscribeIds, item.SubscribeId)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := l.svcCtx.PromoModel.UpsertSubscribePromos(l.ctx, data); err != nil {
|
||||||
|
l.Errorw("[CreatePromoPrice] Database Error", logger.Field("error", err.Error()))
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "set promo price failed: %v", err.Error())
|
||||||
|
}
|
||||||
|
clearSubscribePromoCache(l.ctx, l.svcCtx, subscribeIds...)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CreatePromoRuleLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create promo rule
|
||||||
|
func NewCreatePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoRuleLogic {
|
||||||
|
return &CreatePromoRuleLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *CreatePromoRuleLogic) CreatePromoRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
|
||||||
|
if err := validateRulePayload(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
start, end := ruleTimes(req.StartTime, req.EndTime)
|
||||||
|
data := &promoModel.Rule{
|
||||||
|
Name: req.Name,
|
||||||
|
Type: req.Type,
|
||||||
|
Params: string(req.Params),
|
||||||
|
Priority: req.Priority,
|
||||||
|
Enabled: *req.Enabled,
|
||||||
|
StartTime: start,
|
||||||
|
EndTime: end,
|
||||||
|
}
|
||||||
|
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, data); err != nil {
|
||||||
|
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule failed: %v", err.Error())
|
||||||
|
}
|
||||||
|
clearRuleCache(l.ctx, l.svcCtx)
|
||||||
|
resp := toRuleResponse(data)
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DeletePromoPriceLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete promo price
|
||||||
|
func NewDeletePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePromoPriceLogic {
|
||||||
|
return &DeletePromoPriceLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *DeletePromoPriceLogic) DeletePromoPrice(req *types.DeletePromoPriceRequest) error {
|
||||||
|
data, err := l.svcCtx.PromoModel.FindSubscribePromo(l.ctx, req.Id)
|
||||||
|
if err != nil {
|
||||||
|
if promoModel.IsNotFound(err) {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo price not found")
|
||||||
|
}
|
||||||
|
l.Errorw("[DeletePromoPrice] Database Query Error", logger.Field("error", err.Error()))
|
||||||
|
return wrapQueryError("get promo price failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = l.svcCtx.PromoModel.DeleteSubscribePromo(l.ctx, req.Id); err != nil {
|
||||||
|
l.Errorw("[DeletePromoPrice] Database Delete Error", logger.Field("error", err.Error()))
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price failed: %v", err.Error())
|
||||||
|
}
|
||||||
|
clearSubscribePromoCache(l.ctx, l.svcCtx, data.SubscribeId)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DeletePromoRuleLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete promo rule
|
||||||
|
func NewDeletePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePromoRuleLogic {
|
||||||
|
return &DeletePromoRuleLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *DeletePromoRuleLogic) DeletePromoRule(req *types.DeletePromoRuleRequest) error {
|
||||||
|
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
|
||||||
|
if promoModel.IsNotFound(err) {
|
||||||
|
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
||||||
|
}
|
||||||
|
l.Errorw("[DeletePromoRule] Database Delete Error", logger.Field("error", err.Error()))
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule failed: %v", err.Error())
|
||||||
|
}
|
||||||
|
clearRuleCache(l.ctx, l.svcCtx)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetPromoPriceListLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get promo price list
|
||||||
|
func NewGetPromoPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoPriceListLogic {
|
||||||
|
return &GetPromoPriceListLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *GetPromoPriceListLogic) GetPromoPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
|
||||||
|
total, list, err := l.svcCtx.PromoModel.QuerySubscribePromoList(l.ctx, promoModel.SubscribePromoFilter{
|
||||||
|
Page: int(req.Page),
|
||||||
|
Size: int(req.Size),
|
||||||
|
PromoRuleId: req.PromoRuleId,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, wrapQueryError("get promo price list failed", err)
|
||||||
|
}
|
||||||
|
resp := &types.GetPromoPriceListResponse{
|
||||||
|
Total: total,
|
||||||
|
List: make([]types.PromoPrice, 0, len(list)),
|
||||||
|
}
|
||||||
|
for _, item := range list {
|
||||||
|
var unitPrice int64
|
||||||
|
sub, subErr := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
||||||
|
if subErr == nil {
|
||||||
|
unitPrice = sub.UnitPrice
|
||||||
|
}
|
||||||
|
resp.List = append(resp.List, toPriceResponse(item, unitPrice))
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetPromoRuleDetailLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get promo rule detail
|
||||||
|
func NewGetPromoRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoRuleDetailLogic {
|
||||||
|
return &GetPromoRuleDetailLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *GetPromoRuleDetailLogic) GetPromoRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
|
||||||
|
data, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
||||||
|
if err != nil {
|
||||||
|
if promoModel.IsNotFound(err) {
|
||||||
|
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
||||||
|
}
|
||||||
|
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, wrapQueryError("get promo rule detail failed", err)
|
||||||
|
}
|
||||||
|
resp := toRuleResponse(data)
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetPromoRuleListLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get promo rule list
|
||||||
|
func NewGetPromoRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoRuleListLogic {
|
||||||
|
return &GetPromoRuleListLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *GetPromoRuleListLogic) GetPromoRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
|
||||||
|
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, promoModel.RuleFilter{
|
||||||
|
Page: int(req.Page),
|
||||||
|
Size: int(req.Size),
|
||||||
|
Type: req.Type,
|
||||||
|
Enabled: req.Enabled,
|
||||||
|
Search: req.Search,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, wrapQueryError("get promo rule list failed", err)
|
||||||
|
}
|
||||||
|
resp := &types.GetPromoRuleListResponse{
|
||||||
|
Total: total,
|
||||||
|
List: make([]types.PromoRule, 0, len(list)),
|
||||||
|
}
|
||||||
|
for _, item := range list {
|
||||||
|
resp.List = append(resp.List, toRuleResponse(item))
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetPromoUsageListLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get promo usage list
|
||||||
|
func NewGetPromoUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoUsageListLogic {
|
||||||
|
return &GetPromoUsageListLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *GetPromoUsageListLogic) GetPromoUsageList(req *types.GetPromoUsageListRequest) (*types.GetPromoUsageListResponse, error) {
|
||||||
|
total, list, err := l.svcCtx.PromoModel.QueryUsageList(l.ctx, promoModel.UsageFilter{
|
||||||
|
Page: int(req.Page),
|
||||||
|
Size: int(req.Size),
|
||||||
|
PromoRuleId: req.PromoRuleId,
|
||||||
|
UserId: req.UserId,
|
||||||
|
SubscribeId: req.SubscribeId,
|
||||||
|
OrderNo: req.OrderNo,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, wrapQueryError("get promo usage list failed", err)
|
||||||
|
}
|
||||||
|
resp := &types.GetPromoUsageListResponse{
|
||||||
|
Total: total,
|
||||||
|
List: make([]types.PromoUsage, 0, len(list)),
|
||||||
|
}
|
||||||
|
for _, item := range list {
|
||||||
|
resp.List = append(resp.List, toUsageResponse(item))
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UpdatePromoRuleLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update promo rule
|
||||||
|
func NewUpdatePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePromoRuleLogic {
|
||||||
|
return &UpdatePromoRuleLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *UpdatePromoRuleLogic) UpdatePromoRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
|
||||||
|
if err := validateRulePayload(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
||||||
|
if err != nil {
|
||||||
|
if promoModel.IsNotFound(err) {
|
||||||
|
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
||||||
|
}
|
||||||
|
l.Errorw("[UpdatePromoRule] Database Query Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, wrapQueryError("get promo rule failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
start, end := ruleTimes(req.StartTime, req.EndTime)
|
||||||
|
data.Name = req.Name
|
||||||
|
data.Type = req.Type
|
||||||
|
data.Params = string(req.Params)
|
||||||
|
data.Priority = req.Priority
|
||||||
|
data.Enabled = *req.Enabled
|
||||||
|
data.StartTime = start
|
||||||
|
data.EndTime = end
|
||||||
|
|
||||||
|
if err = l.svcCtx.PromoModel.UpdateRule(l.ctx, data); err != nil {
|
||||||
|
l.Errorw("[UpdatePromoRule] Database Update Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule failed: %v", err.Error())
|
||||||
|
}
|
||||||
|
clearRuleCache(l.ctx, l.svcCtx)
|
||||||
|
resp := toRuleResponse(data)
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type PromoResult struct {
|
type PromoResult struct {
|
||||||
@@ -28,13 +27,13 @@ type promoRuleParams struct {
|
|||||||
InactiveMonths int `json:"inactive_months"`
|
InactiveMonths int `json:"inactive_months"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
|
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64) (*PromoResult, error) {
|
||||||
result := &PromoResult{}
|
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 || userID <= 0 || subscribeID <= 0 {
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID, quantity)
|
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
|
||||||
}
|
}
|
||||||
@@ -149,12 +148,7 @@ func evaluateInactiveUserPromo(
|
|||||||
err := db.WithContext(ctx).
|
err := db.WithContext(ctx).
|
||||||
Model(&user.Subscribe{}).
|
Model(&user.Subscribe{}).
|
||||||
Where("user_id = ?", userID).
|
Where("user_id = ?", userID).
|
||||||
Order(clause.OrderBy{
|
Order("expire_time DESC").
|
||||||
Expression: clause.Expr{
|
|
||||||
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
|
|
||||||
Vars: []interface{}{time.UnixMilli(0)},
|
|
||||||
},
|
|
||||||
}).
|
|
||||||
Limit(1).
|
Limit(1).
|
||||||
Take(&lastSub).Error
|
Take(&lastSub).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -164,16 +158,8 @@ func evaluateInactiveUserPromo(
|
|||||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
|
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
return evaluateInactiveUserExpire(lastSub.ExpireTime, params, now), ruleExpiresAt, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluateInactiveUserExpire(lastExpire time.Time, params promoRuleParams, now time.Time) bool {
|
|
||||||
if lastExpire.Equal(time.UnixMilli(0)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
||||||
return lastExpire.Before(threshold) || lastExpire.Equal(threshold)
|
return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
|
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
package common
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestEvaluateInactiveUserExpire(t *testing.T) {
|
|
||||||
now := time.Date(2026, 5, 27, 8, 0, 0, 0, time.UTC)
|
|
||||||
params := promoRuleParams{InactiveMonths: 3}
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
lastExpire time.Time
|
|
||||||
want bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "permanent subscription is not inactive",
|
|
||||||
lastExpire: time.UnixMilli(0),
|
|
||||||
want: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "active subscription is not inactive",
|
|
||||||
lastExpire: now.Add(time.Hour),
|
|
||||||
want: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "expire at threshold is inactive",
|
|
||||||
lastExpire: now.AddDate(0, -3, 0),
|
|
||||||
want: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "expire before threshold is inactive",
|
|
||||||
lastExpire: now.AddDate(0, -3, -1),
|
|
||||||
want: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
if got := evaluateInactiveUserExpire(tt.lastExpire, params, now); got != tt.want {
|
|
||||||
t.Fatalf("evaluateInactiveUserExpire() = %v, want %v", got, tt.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -61,6 +61,11 @@ func (l *FileUploadCompleteLogic) FileUploadComplete(req *types.FileUploadComple
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &types.FileUploadCompleteResponse{
|
return &types.FileUploadCompleteResponse{
|
||||||
Url: l.svcCtx.S3Store.BuildObjectURL(meta.ObjectKey),
|
FileId: meta.FileID,
|
||||||
|
ObjectKey: meta.ObjectKey,
|
||||||
|
Size: head.ContentLength,
|
||||||
|
ContentType: head.ContentType,
|
||||||
|
Etag: head.ETag,
|
||||||
|
Status: meta.Status,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,13 +52,20 @@ func (l *FileUploadLogic) FileUpload(req *types.FileUploadRequest, fileHeader *m
|
|||||||
fileID := buildFileID(u.Id, req.BizType, fileHeader.Filename)
|
fileID := buildFileID(u.Id, req.BizType, fileHeader.Filename)
|
||||||
objectKey := buildObjectKey(l.svcCtx.Config.S3.Prefix, u.Id, req.BizType, fileID, fileHeader.Filename, now)
|
objectKey := buildObjectKey(l.svcCtx.Config.S3.Prefix, u.Id, req.BizType, fileID, fileHeader.Filename, now)
|
||||||
|
|
||||||
if _, err := l.svcCtx.S3Store.PutObject(l.ctx, objectKey, file, fileHeader.Size, contentType); err != nil {
|
putResult, err := l.svcCtx.S3Store.PutObject(l.ctx, objectKey, file, fileHeader.Size, contentType)
|
||||||
|
if err != nil {
|
||||||
l.Errorw("put object failed", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("file_id", fileID))
|
l.Errorw("put object failed", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("file_id", fileID))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &types.FileUploadResponse{
|
return &types.FileUploadResponse{
|
||||||
Url: l.svcCtx.S3Store.BuildObjectURL(objectKey),
|
FileId: fileID,
|
||||||
|
FileName: fileHeader.Filename,
|
||||||
|
ObjectKey: objectKey,
|
||||||
|
Size: fileHeader.Size,
|
||||||
|
ContentType: contentType,
|
||||||
|
Etag: putResult.ETag,
|
||||||
|
Status: fileUploadCompleteStatus,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,18 +47,13 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1")
|
l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1")
|
||||||
req.Quantity = 1
|
req.Quantity = 1
|
||||||
}
|
}
|
||||||
entitlement, entErr := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, u.Id)
|
|
||||||
if entErr != nil {
|
|
||||||
return nil, entErr
|
|
||||||
}
|
|
||||||
|
|
||||||
targetSubscribeID := req.SubscribeId
|
targetSubscribeID := req.SubscribeId
|
||||||
orderType := uint8(1)
|
|
||||||
isSingleModeRenewal := false
|
isSingleModeRenewal := false
|
||||||
decision, routeErr := commonLogic.ResolvePurchaseRoute(
|
decision, routeErr := commonLogic.ResolvePurchaseRoute(
|
||||||
l.ctx,
|
l.ctx,
|
||||||
l.svcCtx.Config.Subscribe.SingleModel,
|
l.svcCtx.Config.Subscribe.SingleModel,
|
||||||
entitlement.EffectiveUserID,
|
u.Id,
|
||||||
req.SubscribeId,
|
req.SubscribeId,
|
||||||
l.svcCtx.UserModel.FindSingleModeAnchorSubscribe,
|
l.svcCtx.UserModel.FindSingleModeAnchorSubscribe,
|
||||||
)
|
)
|
||||||
@@ -73,44 +68,15 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
targetSubscribeID = decision.ResolvedSubscribeID
|
targetSubscribeID = decision.ResolvedSubscribeID
|
||||||
isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal
|
isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal
|
||||||
if isSingleModeRenewal && decision.Anchor != nil {
|
if isSingleModeRenewal && decision.Anchor != nil {
|
||||||
orderType = 2
|
|
||||||
l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview",
|
l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview",
|
||||||
logger.Field("mode", "single"),
|
logger.Field("mode", "single"),
|
||||||
logger.Field("route", "purchase_to_renewal"),
|
logger.Field("route", "purchase_to_renewal"),
|
||||||
logger.Field("anchor_user_subscribe_id", decision.Anchor.Id),
|
logger.Field("anchor_user_subscribe_id", decision.Anchor.Id),
|
||||||
logger.Field("user_id", u.Id),
|
logger.Field("user_id", u.Id),
|
||||||
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep promo eligibility preview aligned with Purchase: an existing paid subscription
|
|
||||||
// routes the request to renewal semantics, where first-purchase promos are disabled.
|
|
||||||
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
|
|
||||||
var existSub user.Subscribe
|
|
||||||
if e := l.svcCtx.DB.WithContext(l.ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%')", entitlement.EffectiveUserID).
|
|
||||||
Order("expire_time DESC").
|
|
||||||
Order("updated_at DESC").
|
|
||||||
Order("id DESC").
|
|
||||||
First(&existSub).Error; e == nil && existSub.Id > 0 && existSub.Token != "" {
|
|
||||||
orderType = 2
|
|
||||||
l.Infow("[PreCreateOrder] purchase preview routed to renewal because an existing subscription was found",
|
|
||||||
logger.Field("route_mode", "global_single_subscription"),
|
|
||||||
logger.Field("route", "purchase_to_existing_subscription"),
|
|
||||||
logger.Field("existing_subscribe_id", existSub.Id),
|
|
||||||
logger.Field("existing_status", existSub.Status),
|
|
||||||
logger.Field("user_id", u.Id),
|
|
||||||
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
|
||||||
logger.Field("resolved_subscribe_id", targetSubscribeID),
|
|
||||||
)
|
|
||||||
} else if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) {
|
|
||||||
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", e.Error()), logger.Field("user_id", u.Id))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find existing subscription error: %v", e.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// find subscribe plan
|
// find subscribe plan
|
||||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID)
|
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -120,7 +86,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
|
|
||||||
// check subscribe plan quota limit for new purchase flow only
|
// check subscribe plan quota limit for new purchase flow only
|
||||||
if !isSingleModeRenewal && sub.Quota > 0 {
|
if !isSingleModeRenewal && sub.Quota > 0 {
|
||||||
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, entitlement.EffectiveUserID)
|
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
|
||||||
@@ -136,7 +102,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount)
|
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility",
|
l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility",
|
||||||
logger.Field("error", err.Error()),
|
logger.Field("error", err.Error()),
|
||||||
@@ -151,13 +117,13 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
priceResult, err := calculatePurchasePrice(
|
priceResult, err := calculatePurchasePrice(
|
||||||
l.ctx,
|
l.ctx,
|
||||||
l.svcCtx,
|
l.svcCtx,
|
||||||
entitlement.EffectiveUserID,
|
u.Id,
|
||||||
targetSubscribeID,
|
targetSubscribeID,
|
||||||
sub.UnitPrice,
|
sub.UnitPrice,
|
||||||
req.Quantity,
|
req.Quantity,
|
||||||
newUserDiscount.Discounts,
|
newUserDiscount.Discounts,
|
||||||
newUserDiscount.EligibleForDiscount,
|
newUserDiscount.EligibleForDiscount,
|
||||||
orderType == 1,
|
!isSingleModeRenewal,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[PreCreateOrder] Promo price calculation error",
|
l.Errorw("[PreCreateOrder] Promo price calculation error",
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func calculatePurchasePrice(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if allowPromo {
|
if allowPromo {
|
||||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity)
|
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,41 +11,71 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type fakePromoModel struct {
|
type fakePromoModel struct {
|
||||||
rules []*promo.RuleWithPrice
|
rules []*promo.RuleWithPrice
|
||||||
lastSubscribeID int64
|
|
||||||
lastQuantity int64
|
|
||||||
requireQuantity int64
|
|
||||||
quantityMismatch []*promo.RuleWithPrice
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
|
func (m fakePromoModel) QueryEligibleRules(context.Context, int64) ([]*promo.RuleWithPrice, error) {
|
||||||
m.lastSubscribeID = subscribeID
|
|
||||||
m.lastQuantity = quantity
|
|
||||||
if m.requireQuantity > 0 && quantity != m.requireQuantity {
|
|
||||||
return m.quantityMismatch, nil
|
|
||||||
}
|
|
||||||
return m.rules, nil
|
return m.rules, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
func (m fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) DeleteRule(context.Context, int64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) QueryRuleList(context.Context, promo.RuleFilter) (int64, []*promo.Rule, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) UpsertSubscribePromos(context.Context, []*promo.SubscribePromo) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) FindSubscribePromo(context.Context, int64) (*promo.SubscribePromo, error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) DeleteSubscribePromo(context.Context, int64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) QuerySubscribePromoList(context.Context, promo.SubscribePromoFilter) (int64, []*promo.SubscribePromo, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
|
func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
|
||||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 9,
|
|
||||||
Name: "campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 600,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
svcCtx := &svc.ServiceContext{
|
svcCtx := &svc.ServiceContext{
|
||||||
DB: &gorm.DB{},
|
DB: &gorm.DB{},
|
||||||
PromoModel: model,
|
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||||
|
{
|
||||||
|
Rule: promo.Rule{
|
||||||
|
Id: 9,
|
||||||
|
Name: "campaign",
|
||||||
|
Type: promo.RuleTypeCampaign,
|
||||||
|
Enabled: true,
|
||||||
|
},
|
||||||
|
PromoPrice: 600,
|
||||||
|
},
|
||||||
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
result, err := calculatePurchasePrice(
|
||||||
@@ -78,26 +108,22 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
|
|||||||
if result.PromoDiscount != 1200 {
|
if result.PromoDiscount != 1200 {
|
||||||
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
|
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
|
||||||
}
|
}
|
||||||
if model.lastQuantity != 3 {
|
|
||||||
t.Fatalf("promo query quantity = %d, want 3", model.lastQuantity)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
||||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 10,
|
|
||||||
Name: "invalid campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 1000,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
svcCtx := &svc.ServiceContext{
|
svcCtx := &svc.ServiceContext{
|
||||||
DB: &gorm.DB{},
|
DB: &gorm.DB{},
|
||||||
PromoModel: model,
|
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||||
|
{
|
||||||
|
Rule: promo.Rule{
|
||||||
|
Id: 10,
|
||||||
|
Name: "invalid campaign",
|
||||||
|
Type: promo.RuleTypeCampaign,
|
||||||
|
Enabled: true,
|
||||||
|
},
|
||||||
|
PromoPrice: 1000,
|
||||||
|
},
|
||||||
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
result, err := calculatePurchasePrice(
|
||||||
@@ -125,52 +151,3 @@ func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
|||||||
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
|
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
|
|
||||||
promoModel := &fakePromoModel{
|
|
||||||
requireQuantity: 6,
|
|
||||||
rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 11,
|
|
||||||
Name: "quantity campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 500,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: promoModel,
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
|
||||||
context.Background(),
|
|
||||||
svcCtx,
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
1000,
|
|
||||||
6,
|
|
||||||
[]types.SubscribeDiscount{{Quantity: 6, Discount: 80}},
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if promoModel.lastSubscribeID != 2 {
|
|
||||||
t.Fatalf("lastSubscribeID = %d, want 2", promoModel.lastSubscribeID)
|
|
||||||
}
|
|
||||||
if promoModel.lastQuantity != 6 {
|
|
||||||
t.Fatalf("lastQuantity = %d, want 6", promoModel.lastQuantity)
|
|
||||||
}
|
|
||||||
if result.PayableBase != 3000 {
|
|
||||||
t.Fatalf("PayableBase = %d, want 3000", result.PayableBase)
|
|
||||||
}
|
|
||||||
if result.PromoRuleId != 11 {
|
|
||||||
t.Fatalf("PromoRuleId = %d, want 11", result.PromoRuleId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -26,7 +25,6 @@ const (
|
|||||||
|
|
||||||
type subscribePromoCandidate struct {
|
type subscribePromoCandidate struct {
|
||||||
SubscribeId int64 `gorm:"column:subscribe_id"`
|
SubscribeId int64 `gorm:"column:subscribe_id"`
|
||||||
Quantity int64 `gorm:"column:quantity"`
|
|
||||||
RuleName string `gorm:"column:rule_name"`
|
RuleName string `gorm:"column:rule_name"`
|
||||||
RuleType string `gorm:"column:rule_type"`
|
RuleType string `gorm:"column:rule_type"`
|
||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
PromoPrice int64 `gorm:"column:promo_price"`
|
||||||
@@ -40,8 +38,8 @@ type promoRuleParams struct {
|
|||||||
InactiveMonths int `json:"inactive_months"`
|
InactiveMonths int `json:"inactive_months"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
|
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]*types.SubscribePromo, error) {
|
||||||
result := make(map[int64]map[int64]*types.SubscribePromo)
|
result := make(map[int64]*types.SubscribePromo)
|
||||||
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
@@ -58,13 +56,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
|||||||
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for _, candidate := range candidates {
|
for _, candidate := range candidates {
|
||||||
if candidate.Quantity <= 0 {
|
if _, exists := result[candidate.SubscribeId]; exists {
|
||||||
continue
|
|
||||||
}
|
|
||||||
if result[candidate.SubscribeId] == nil {
|
|
||||||
result[candidate.SubscribeId] = make(map[int64]*types.SubscribePromo)
|
|
||||||
}
|
|
||||||
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !candidate.isActive(now) {
|
if !candidate.isActive(now) {
|
||||||
@@ -77,7 +69,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
|||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
|
result[candidate.SubscribeId] = &types.SubscribePromo{
|
||||||
RuleName: candidate.RuleName,
|
RuleName: candidate.RuleName,
|
||||||
RuleType: candidate.RuleType,
|
RuleType: candidate.RuleType,
|
||||||
PromoPrice: candidate.PromoPrice,
|
PromoPrice: candidate.PromoPrice,
|
||||||
@@ -90,28 +82,23 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
|||||||
|
|
||||||
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
|
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
|
||||||
var candidates []subscribePromoCandidate
|
var candidates []subscribePromoCandidate
|
||||||
err := subscribePromoCandidatesQuery(ctx, svcCtx.DB, subscribeIDs, loggedIn).
|
query := svcCtx.DB.WithContext(ctx).
|
||||||
Scan(&candidates).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
|
|
||||||
}
|
|
||||||
return candidates, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeIDs []int64, loggedIn bool) *gorm.DB {
|
|
||||||
query := db.WithContext(ctx).
|
|
||||||
Table("subscribe_promo AS sp").
|
Table("subscribe_promo AS sp").
|
||||||
Select("sp.subscribe_id, sp.quantity, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
|
Select("sp.subscribe_id, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
|
||||||
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
|
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
|
||||||
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
|
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
|
||||||
if !loggedIn {
|
if !loggedIn {
|
||||||
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
|
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
|
||||||
}
|
}
|
||||||
return query.
|
err := query.
|
||||||
Order("sp.subscribe_id ASC").
|
Order("sp.subscribe_id ASC").
|
||||||
Order("sp.quantity ASC").
|
|
||||||
Order("pr.priority DESC").
|
Order("pr.priority DESC").
|
||||||
Order("pr.id ASC")
|
Order("pr.id ASC").
|
||||||
|
Scan(&candidates).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
|
||||||
|
}
|
||||||
|
return candidates, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c subscribePromoCandidate) isActive(now time.Time) bool {
|
func (c subscribePromoCandidate) isActive(now time.Time) bool {
|
||||||
@@ -184,7 +171,11 @@ func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
|||||||
return *e.lastExpire, nil
|
return *e.lastExpire, nil
|
||||||
}
|
}
|
||||||
var item user.Subscribe
|
var item user.Subscribe
|
||||||
err := e.lastSubscribeExpireQuery().
|
err := e.db.WithContext(e.ctx).
|
||||||
|
Model(&user.Subscribe{}).
|
||||||
|
Where("user_id = ?", e.userInfo.Id).
|
||||||
|
Where("expire_time != ?", time.UnixMilli(0)).
|
||||||
|
Order("expire_time DESC").
|
||||||
Limit(1).
|
Limit(1).
|
||||||
Take(&item).Error
|
Take(&item).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -199,18 +190,6 @@ func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
|||||||
return item.ExpireTime, nil
|
return item.ExpireTime, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireQuery() *gorm.DB {
|
|
||||||
return e.db.WithContext(e.ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ?", e.userInfo.Id).
|
|
||||||
Order(clause.OrderBy{
|
|
||||||
Expression: clause.Expr{
|
|
||||||
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
|
|
||||||
Vars: []interface{}{time.UnixMilli(0)},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) expiresAt() time.Time {
|
func (c subscribePromoCandidate) expiresAt() time.Time {
|
||||||
if c.EndTime == nil {
|
if c.EndTime == nil {
|
||||||
return time.Time{}
|
return time.Time{}
|
||||||
|
|||||||
@@ -1,15 +1,10 @@
|
|||||||
package subscribe
|
package subscribe
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"gorm.io/driver/mysql"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
||||||
@@ -78,83 +73,3 @@ func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
|
|||||||
t.Fatal("candidate after end time should not be active")
|
t.Fatal("candidate after end time should not be active")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLastSubscribeExpireAtPrioritizesPermanentSubscription(t *testing.T) {
|
|
||||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
|
||||||
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
|
||||||
SkipInitializeWithVersion: true,
|
|
||||||
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open dry-run db: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
evaluator := &promoEligibilityEvaluator{
|
|
||||||
db: db,
|
|
||||||
userInfo: &user.User{Id: 7},
|
|
||||||
}
|
|
||||||
var item user.Subscribe
|
|
||||||
tx := evaluator.lastSubscribeExpireQuery().Limit(1).Take(&item)
|
|
||||||
|
|
||||||
sql := tx.Statement.SQL.String()
|
|
||||||
if !strings.Contains(sql, "CASE WHEN expire_time = ? THEN 0 ELSE 1 END") {
|
|
||||||
t.Fatalf("SQL missing permanent subscription priority order: %s", sql)
|
|
||||||
}
|
|
||||||
if strings.Contains(sql, "expire_time !=") {
|
|
||||||
t.Fatalf("SQL should not filter out permanent subscriptions: %s", sql)
|
|
||||||
}
|
|
||||||
if len(tx.Statement.Vars) < 2 {
|
|
||||||
t.Fatalf("SQL vars length = %d, want at least 2; vars=%v", len(tx.Statement.Vars), tx.Statement.Vars)
|
|
||||||
}
|
|
||||||
if got, want := tx.Statement.Vars[1], time.UnixMilli(0); got != want {
|
|
||||||
t.Fatalf("permanent subscription order var = %v, want %v; vars=%v", got, want, tx.Statement.Vars)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
|
|
||||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
|
||||||
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
|
||||||
SkipInitializeWithVersion: true,
|
|
||||||
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open dry-run db: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var candidates []subscribePromoCandidate
|
|
||||||
tx := subscribePromoCandidatesQuery(context.Background(), db, []int64{11, 12}, true).Scan(&candidates)
|
|
||||||
stmt := tx.Statement
|
|
||||||
sql := stmt.SQL.String()
|
|
||||||
if !strings.Contains(sql, "sp.subscribe_id, sp.quantity, sp.promo_price") {
|
|
||||||
t.Fatalf("SQL missing quantity select: %s", sql)
|
|
||||||
}
|
|
||||||
if !strings.Contains(sql, "ORDER BY sp.subscribe_id ASC,sp.quantity ASC,pr.priority DESC,pr.id ASC") {
|
|
||||||
t.Fatalf("SQL missing quantity order: %s", sql)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
|
|
||||||
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
|
|
||||||
{Quantity: 1},
|
|
||||||
{Quantity: 12},
|
|
||||||
}}
|
|
||||||
promos := map[int64]*types.SubscribePromo{
|
|
||||||
3: {RuleName: "季度优惠", PromoPrice: 2900},
|
|
||||||
12: {RuleName: "年度优惠", PromoPrice: 9900},
|
|
||||||
}
|
|
||||||
|
|
||||||
applySubscribeDiscountPromos(&subscribe, promos)
|
|
||||||
if subscribe.Discount[0].Promo != nil {
|
|
||||||
t.Fatalf("quantity 1 promo should be nil, got %+v", subscribe.Discount[0].Promo)
|
|
||||||
}
|
|
||||||
if subscribe.Discount[1].Promo == nil {
|
|
||||||
t.Fatal("quantity 12 promo should match")
|
|
||||||
}
|
|
||||||
if got, want := subscribe.Discount[1].Promo.RuleName, "年度优惠"; got != want {
|
|
||||||
t.Fatalf("promo rule name = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
subscribe = types.Subscribe{Discount: []types.SubscribeDiscount{{Quantity: 6}}}
|
|
||||||
applySubscribeDiscountPromos(&subscribe, promos)
|
|
||||||
if subscribe.Discount[0].Promo != nil {
|
|
||||||
t.Fatalf("promo should be nil when quantity does not match, got %+v", subscribe.Discount[0].Promo)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -56,19 +56,11 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
var discount []types.SubscribeDiscount
|
var discount []types.SubscribeDiscount
|
||||||
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
||||||
sub.Discount = discount
|
sub.Discount = discount
|
||||||
|
list[i] = sub
|
||||||
}
|
}
|
||||||
list[i] = sub
|
list[i] = sub
|
||||||
}
|
}
|
||||||
|
|
||||||
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for i := range list {
|
|
||||||
applySubscribeDiscountPromos(&list[i], promos[list[i].Id])
|
|
||||||
}
|
|
||||||
|
|
||||||
// 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个
|
// 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个
|
||||||
hasAppId, _ := l.ctx.Value(constant.CtxKeyHasAppId).(bool)
|
hasAppId, _ := l.ctx.Value(constant.CtxKeyHasAppId).(bool)
|
||||||
if !hasAppId {
|
if !hasAppId {
|
||||||
@@ -79,13 +71,16 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range list {
|
||||||
|
list[i].Promo = promos[list[i].Id]
|
||||||
|
}
|
||||||
|
|
||||||
resp.List = list
|
resp.List = list
|
||||||
resp.Total = int64(len(list))
|
resp.Total = int64(len(list))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func applySubscribeDiscountPromos(subscribe *types.Subscribe, promoByQuantity map[int64]*types.SubscribePromo) {
|
|
||||||
for i := range subscribe.Discount {
|
|
||||||
subscribe.Discount[i].Promo = promoByQuantity[subscribe.Discount[i].Quantity]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -46,8 +46,8 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for bank transfer")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for bank transfer")
|
||||||
}
|
}
|
||||||
default: // WithdrawalMethodOther
|
default: // WithdrawalMethodOther
|
||||||
if req.Account == "" {
|
if req.Account == "" && req.Content == "" {
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for other methods")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account or content is required for other methods")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+176
-10
@@ -2,9 +2,11 @@ package promo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RuleWithPrice struct {
|
type RuleWithPrice struct {
|
||||||
@@ -12,9 +14,42 @@ type RuleWithPrice struct {
|
|||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
PromoPrice int64 `gorm:"column:promo_price"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RuleFilter struct {
|
||||||
|
Page int
|
||||||
|
Size int
|
||||||
|
Type string
|
||||||
|
Enabled *bool
|
||||||
|
Search string
|
||||||
|
}
|
||||||
|
|
||||||
|
type SubscribePromoFilter struct {
|
||||||
|
Page int
|
||||||
|
Size int
|
||||||
|
PromoRuleId int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type UsageFilter struct {
|
||||||
|
Page int
|
||||||
|
Size int
|
||||||
|
PromoRuleId int64
|
||||||
|
UserId int64
|
||||||
|
SubscribeId int64
|
||||||
|
OrderNo string
|
||||||
|
}
|
||||||
|
|
||||||
type Model interface {
|
type Model interface {
|
||||||
QueryEligibleRules(ctx context.Context, subscribeId int64, quantity int64) ([]*RuleWithPrice, error)
|
QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error)
|
||||||
InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error
|
InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error
|
||||||
|
InsertRule(ctx context.Context, data *Rule) error
|
||||||
|
FindRule(ctx context.Context, id int64) (*Rule, error)
|
||||||
|
UpdateRule(ctx context.Context, data *Rule) error
|
||||||
|
DeleteRule(ctx context.Context, id int64) error
|
||||||
|
QueryRuleList(ctx context.Context, filter RuleFilter) (int64, []*Rule, error)
|
||||||
|
UpsertSubscribePromos(ctx context.Context, data []*SubscribePromo) error
|
||||||
|
FindSubscribePromo(ctx context.Context, id int64) (*SubscribePromo, error)
|
||||||
|
DeleteSubscribePromo(ctx context.Context, id int64) error
|
||||||
|
QuerySubscribePromoList(ctx context.Context, filter SubscribePromoFilter) (int64, []*SubscribePromo, error)
|
||||||
|
QueryUsageList(ctx context.Context, filter UsageFilter) (int64, []*Usage, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type defaultPromoModel struct {
|
type defaultPromoModel struct {
|
||||||
@@ -25,22 +60,31 @@ func NewModel(db *gorm.DB, _ *redis.Client) Model {
|
|||||||
return &defaultPromoModel{db: db}
|
return &defaultPromoModel{db: db}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64, quantity int64) ([]*RuleWithPrice, error) {
|
func normalizePage(page, size int) (int, int) {
|
||||||
var list []*RuleWithPrice
|
if page <= 0 {
|
||||||
err := m.eligibleRulesQuery(ctx, subscribeId, quantity).
|
page = 1
|
||||||
Find(&list).Error
|
}
|
||||||
return list, err
|
if size <= 0 {
|
||||||
|
size = 10
|
||||||
|
}
|
||||||
|
if size > 100 {
|
||||||
|
size = 100
|
||||||
|
}
|
||||||
|
return page, size
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *defaultPromoModel) eligibleRulesQuery(ctx context.Context, subscribeId int64, quantity int64) *gorm.DB {
|
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) {
|
||||||
return m.db.WithContext(ctx).
|
var list []*RuleWithPrice
|
||||||
|
err := m.db.WithContext(ctx).
|
||||||
Table("promo_rule AS pr").
|
Table("promo_rule AS pr").
|
||||||
Select("pr.*, sp.promo_price").
|
Select("pr.*, sp.promo_price").
|
||||||
Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id AND sp.quantity = ?", quantity).
|
Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id").
|
||||||
Where("sp.subscribe_id = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, true).
|
Where("sp.subscribe_id = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, true).
|
||||||
Where("pr.deleted_at IS NULL").
|
Where("pr.deleted_at IS NULL").
|
||||||
Order("pr.priority DESC").
|
Order("pr.priority DESC").
|
||||||
Order("pr.id ASC")
|
Order("pr.id ASC").
|
||||||
|
Find(&list).Error
|
||||||
|
return list, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error {
|
func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error {
|
||||||
@@ -50,3 +94,125 @@ func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...
|
|||||||
}
|
}
|
||||||
return db.Model(&Usage{}).Create(data).Error
|
return db.Model(&Usage{}).Create(data).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) InsertRule(ctx context.Context, data *Rule) error {
|
||||||
|
return m.db.WithContext(ctx).Create(data).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) FindRule(ctx context.Context, id int64) (*Rule, error) {
|
||||||
|
var data Rule
|
||||||
|
err := m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", id).First(&data).Error
|
||||||
|
return &data, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
|
||||||
|
return m.db.WithContext(ctx).Save(data).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
|
||||||
|
result := m.db.WithContext(ctx).Delete(&Rule{}, id)
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected == 0 {
|
||||||
|
return gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) QueryRuleList(ctx context.Context, filter RuleFilter) (int64, []*Rule, error) {
|
||||||
|
page, size := normalizePage(filter.Page, filter.Size)
|
||||||
|
var total int64
|
||||||
|
var list []*Rule
|
||||||
|
|
||||||
|
query := m.db.WithContext(ctx).Model(&Rule{})
|
||||||
|
if filter.Type != "" {
|
||||||
|
query = query.Where("type = ?", filter.Type)
|
||||||
|
}
|
||||||
|
if filter.Enabled != nil {
|
||||||
|
query = query.Where("enabled = ?", *filter.Enabled)
|
||||||
|
}
|
||||||
|
if filter.Search != "" {
|
||||||
|
search := "%" + filter.Search + "%"
|
||||||
|
query = query.Where("name LIKE ?", search)
|
||||||
|
}
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
err := query.Order("priority DESC").Order("id DESC").
|
||||||
|
Limit(size).Offset((page - 1) * size).
|
||||||
|
Find(&list).Error
|
||||||
|
return total, list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) UpsertSubscribePromos(ctx context.Context, data []*SubscribePromo) error {
|
||||||
|
if len(data) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return m.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||||
|
Columns: []clause.Column{{Name: "subscribe_id"}, {Name: "promo_rule_id"}},
|
||||||
|
DoUpdates: clause.AssignmentColumns([]string{"promo_price", "updated_at"}),
|
||||||
|
}).Create(&data).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) FindSubscribePromo(ctx context.Context, id int64) (*SubscribePromo, error) {
|
||||||
|
var data SubscribePromo
|
||||||
|
err := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("id = ?", id).First(&data).Error
|
||||||
|
return &data, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) DeleteSubscribePromo(ctx context.Context, id int64) error {
|
||||||
|
result := m.db.WithContext(ctx).Delete(&SubscribePromo{}, id)
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected == 0 {
|
||||||
|
return gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) QuerySubscribePromoList(ctx context.Context, filter SubscribePromoFilter) (int64, []*SubscribePromo, error) {
|
||||||
|
page, size := normalizePage(filter.Page, filter.Size)
|
||||||
|
var total int64
|
||||||
|
var list []*SubscribePromo
|
||||||
|
|
||||||
|
query := m.db.WithContext(ctx).Model(&SubscribePromo{})
|
||||||
|
if filter.PromoRuleId > 0 {
|
||||||
|
query = query.Where("promo_rule_id = ?", filter.PromoRuleId)
|
||||||
|
}
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
||||||
|
return total, list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoModel) QueryUsageList(ctx context.Context, filter UsageFilter) (int64, []*Usage, error) {
|
||||||
|
page, size := normalizePage(filter.Page, filter.Size)
|
||||||
|
var total int64
|
||||||
|
var list []*Usage
|
||||||
|
|
||||||
|
query := m.db.WithContext(ctx).Model(&Usage{})
|
||||||
|
if filter.PromoRuleId > 0 {
|
||||||
|
query = query.Where("promo_rule_id = ?", filter.PromoRuleId)
|
||||||
|
}
|
||||||
|
if filter.UserId > 0 {
|
||||||
|
query = query.Where("user_id = ?", filter.UserId)
|
||||||
|
}
|
||||||
|
if filter.SubscribeId > 0 {
|
||||||
|
query = query.Where("subscribe_id = ?", filter.SubscribeId)
|
||||||
|
}
|
||||||
|
if filter.OrderNo != "" {
|
||||||
|
query = query.Where("order_no LIKE ?", "%"+filter.OrderNo+"%")
|
||||||
|
}
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
||||||
|
return total, list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
return errors.Is(err, gorm.ErrRecordNotFound)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gorm.io/driver/mysql"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestQueryEligibleRulesFiltersByQuantity(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)
|
|
||||||
}
|
|
||||||
|
|
||||||
model := &defaultPromoModel{db: db}
|
|
||||||
var list []*RuleWithPrice
|
|
||||||
tx := model.eligibleRulesQuery(context.Background(), 11, 3).Find(&list)
|
|
||||||
stmt := tx.Statement
|
|
||||||
sql := stmt.SQL.String()
|
|
||||||
if !strings.Contains(sql, "JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id AND sp.quantity = ?") {
|
|
||||||
t.Fatalf("SQL missing quantity join condition: %s", sql)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(stmt.Vars) < 2 {
|
|
||||||
t.Fatalf("SQL vars length = %d, want at least 2; vars=%v", len(stmt.Vars), stmt.Vars)
|
|
||||||
}
|
|
||||||
if got, want := stmt.Vars[0], int64(3); got != want {
|
|
||||||
t.Fatalf("first SQL var = %v, want quantity %d; vars=%v", got, want, stmt.Vars)
|
|
||||||
}
|
|
||||||
if got, want := stmt.Vars[1], int64(11); got != want {
|
|
||||||
t.Fatalf("second SQL var = %v, want subscribe_id %d; vars=%v", got, want, stmt.Vars)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -33,7 +33,6 @@ func (Rule) TableName() string {
|
|||||||
type SubscribePromo struct {
|
type SubscribePromo struct {
|
||||||
Id int64 `gorm:"primaryKey"`
|
Id int64 `gorm:"primaryKey"`
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
||||||
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
|
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
||||||
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||||
|
|||||||
+132
-7
@@ -436,6 +436,21 @@ type CreatePaymentMethodRequest struct {
|
|||||||
Enable *bool `json:"enable" validate:"required"`
|
Enable *bool `json:"enable" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CreatePromoRuleRequest struct {
|
||||||
|
Name string `json:"name" validate:"required,max=100"`
|
||||||
|
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||||
|
Params json.RawMessage `json:"params" validate:"required"`
|
||||||
|
Priority int64 `json:"priority" validate:"gte=0"`
|
||||||
|
Enabled *bool `json:"enabled" validate:"required"`
|
||||||
|
StartTime int64 `json:"start_time" validate:"required"`
|
||||||
|
EndTime int64 `json:"end_time" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreatePromoPriceRequest struct {
|
||||||
|
PromoRuleId int64 `json:"promo_rule_id" validate:"required"`
|
||||||
|
Items []PromoPriceInput `json:"items" validate:"required,dive"`
|
||||||
|
}
|
||||||
|
|
||||||
type CreateQuotaTaskRequest struct {
|
type CreateQuotaTaskRequest struct {
|
||||||
Subscribers []int64 `json:"subscribers"`
|
Subscribers []int64 `json:"subscribers"`
|
||||||
IsActive *bool `json:"is_active"`
|
IsActive *bool `json:"is_active"`
|
||||||
@@ -619,6 +634,14 @@ type DeletePaymentMethodRequest struct {
|
|||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DeletePromoPriceRequest struct {
|
||||||
|
Id int64 `path:"id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeletePromoRuleRequest struct {
|
||||||
|
Id int64 `path:"id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
type DeleteRedemptionCodeRequest struct {
|
type DeleteRedemptionCodeRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -779,7 +802,13 @@ type FileUploadRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type FileUploadResponse struct {
|
type FileUploadResponse struct {
|
||||||
Url string `json:"url"`
|
FileId string `json:"file_id"`
|
||||||
|
FileName string `json:"file_name"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Etag string `json:"etag"`
|
||||||
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type FileUploadCompleteRequest struct {
|
type FileUploadCompleteRequest struct {
|
||||||
@@ -787,7 +816,12 @@ type FileUploadCompleteRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type FileUploadCompleteResponse struct {
|
type FileUploadCompleteResponse struct {
|
||||||
Url string `json:"url"`
|
FileId string `json:"file_id"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Etag string `json:"etag"`
|
||||||
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type FileUploadInitRequest struct {
|
type FileUploadInitRequest struct {
|
||||||
@@ -1316,6 +1350,48 @@ type GetPaymentMethodListResponse struct {
|
|||||||
List []PaymentMethodDetail `json:"list"`
|
List []PaymentMethodDetail `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GetPromoPriceListRequest struct {
|
||||||
|
Page int64 `form:"page" validate:"required"`
|
||||||
|
Size int64 `form:"size" validate:"required"`
|
||||||
|
PromoRuleId int64 `form:"promo_rule_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetPromoPriceListResponse struct {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []PromoPrice `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetPromoRuleDetailRequest struct {
|
||||||
|
Id int64 `path:"id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetPromoRuleListRequest struct {
|
||||||
|
Page int64 `form:"page" validate:"required"`
|
||||||
|
Size int64 `form:"size" validate:"required"`
|
||||||
|
Type string `form:"type,omitempty" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
||||||
|
Enabled *bool `form:"enabled,omitempty"`
|
||||||
|
Search string `form:"search,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetPromoRuleListResponse struct {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []PromoRule `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetPromoUsageListRequest struct {
|
||||||
|
Page int64 `form:"page" validate:"required"`
|
||||||
|
Size int64 `form:"size" validate:"required"`
|
||||||
|
PromoRuleId int64 `form:"rule_id,omitempty"`
|
||||||
|
UserId int64 `form:"user_id,omitempty"`
|
||||||
|
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
||||||
|
OrderNo string `form:"order_no,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetPromoUsageListResponse struct {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []PromoUsage `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
type GetPreSendEmailCountRequest struct {
|
type GetPreSendEmailCountRequest struct {
|
||||||
Scope int8 `json:"scope"`
|
Scope int8 `json:"scope"`
|
||||||
RegisterStartTime int64 `json:"register_start_time,omitempty"`
|
RegisterStartTime int64 `json:"register_start_time,omitempty"`
|
||||||
@@ -2028,6 +2104,44 @@ type PrePurchaseOrderResponse struct {
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type PromoPrice struct {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
|
PromoRuleId int64 `json:"promo_rule_id"`
|
||||||
|
PromoPrice int64 `json:"promo_price"`
|
||||||
|
UnitPrice int64 `json:"unit_price"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromoPriceInput struct {
|
||||||
|
SubscribeId int64 `json:"subscribe_id" validate:"required"`
|
||||||
|
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromoRule struct {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Params json.RawMessage `json:"params"`
|
||||||
|
Priority int64 `json:"priority"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
StartTime int64 `json:"start_time"`
|
||||||
|
EndTime int64 `json:"end_time"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromoUsage struct {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
UserId int64 `json:"user_id"`
|
||||||
|
PromoRuleId int64 `json:"promo_rule_id"`
|
||||||
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
|
OrderNo string `json:"order_no"`
|
||||||
|
PromoPrice int64 `json:"promo_price"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
type PreRenewalOrderResponse struct {
|
type PreRenewalOrderResponse struct {
|
||||||
OrderNo string `json:"orderNo"`
|
OrderNo string `json:"orderNo"`
|
||||||
}
|
}
|
||||||
@@ -2789,6 +2903,7 @@ type Subscribe struct {
|
|||||||
UnitPrice int64 `json:"unit_price"`
|
UnitPrice int64 `json:"unit_price"`
|
||||||
UnitTime string `json:"unit_time"`
|
UnitTime string `json:"unit_time"`
|
||||||
Discount []SubscribeDiscount `json:"discount"`
|
Discount []SubscribeDiscount `json:"discount"`
|
||||||
|
Promo *SubscribePromo `json:"promo"`
|
||||||
NodeCount int64 `json:"node_count"`
|
NodeCount int64 `json:"node_count"`
|
||||||
Replacement int64 `json:"replacement"`
|
Replacement int64 `json:"replacement"`
|
||||||
Inventory int64 `json:"inventory"`
|
Inventory int64 `json:"inventory"`
|
||||||
@@ -2849,11 +2964,10 @@ type SubscribeConfig struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SubscribeDiscount struct {
|
type SubscribeDiscount struct {
|
||||||
Quantity int64 `json:"quantity"`
|
Quantity int64 `json:"quantity"`
|
||||||
Discount float64 `json:"discount"`
|
Discount float64 `json:"discount"`
|
||||||
NewUserOnly bool `json:"new_user_only"`
|
NewUserOnly bool `json:"new_user_only"`
|
||||||
MapApple string `json:"map_apple"`
|
MapApple string `json:"map_apple"`
|
||||||
Promo *SubscribePromo `json:"promo"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscribeGroup struct {
|
type SubscribeGroup struct {
|
||||||
@@ -3196,6 +3310,17 @@ type UpdatePaymentMethodRequest struct {
|
|||||||
Enable *bool `json:"enable" validate:"required"`
|
Enable *bool `json:"enable" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UpdatePromoRuleRequest struct {
|
||||||
|
Id int64 `json:"id" validate:"required"`
|
||||||
|
Name string `json:"name" validate:"required,max=100"`
|
||||||
|
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||||
|
Params json.RawMessage `json:"params" validate:"required"`
|
||||||
|
Priority int64 `json:"priority" validate:"gte=0"`
|
||||||
|
Enabled *bool `json:"enabled" validate:"required"`
|
||||||
|
StartTime int64 `json:"start_time" validate:"required"`
|
||||||
|
EndTime int64 `json:"end_time" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
type UpdateRedemptionCodeRequest struct {
|
type UpdateRedemptionCodeRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
TotalCount int64 `json:"total_count,omitempty"`
|
TotalCount int64 `json:"total_count,omitempty"`
|
||||||
|
|||||||
@@ -3680,9 +3680,6 @@
|
|||||||
"discount": {
|
"discount": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
"format": "double"
|
"format": "double"
|
||||||
},
|
|
||||||
"promo": {
|
|
||||||
"$ref": "#/definitions/SubscribePromo"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"title": "SubscribeDiscount",
|
"title": "SubscribeDiscount",
|
||||||
|
|||||||
+1
-1
@@ -31,6 +31,7 @@ import (
|
|||||||
"apis/admin/marketing.api"
|
"apis/admin/marketing.api"
|
||||||
"apis/admin/application.api"
|
"apis/admin/application.api"
|
||||||
"apis/admin/group.api"
|
"apis/admin/group.api"
|
||||||
|
"apis/admin/promo.api"
|
||||||
"apis/public/user.api"
|
"apis/public/user.api"
|
||||||
"apis/public/subscribe.api"
|
"apis/public/subscribe.api"
|
||||||
"apis/public/redemption.api"
|
"apis/public/redemption.api"
|
||||||
@@ -44,4 +45,3 @@ import (
|
|||||||
"apis/public/portal.api"
|
"apis/public/portal.api"
|
||||||
"apis/public/iap.api"
|
"apis/public/iap.api"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -149,20 +149,7 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = l.recordPromoUsage(ctx, orderInfo); err != nil {
|
l.recordPromoUsage(ctx, orderInfo)
|
||||||
if releaseErr := l.releaseClaim(ctx, orderInfo.OrderNo); releaseErr != nil {
|
|
||||||
logger.WithContext(ctx).Error("[ActivateOrderLogic] releaseClaim also failed, stuck recovery will handle",
|
|
||||||
logger.Field("order_no", orderInfo.OrderNo),
|
|
||||||
logger.Field("release_error", releaseErr.Error()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
logger.WithContext(ctx).Error("[ActivateOrderLogic] 促销使用记录写入失败,将重试",
|
|
||||||
logger.Field("order_no", orderInfo.OrderNo),
|
|
||||||
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
l.finalizeCouponAndOrder(ctx, orderInfo)
|
l.finalizeCouponAndOrder(ctx, orderInfo)
|
||||||
|
|
||||||
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished",
|
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished",
|
||||||
@@ -172,9 +159,9 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) error {
|
func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) {
|
||||||
if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" {
|
if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" {
|
||||||
return nil
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
promoPrice := int64(0)
|
promoPrice := int64(0)
|
||||||
@@ -182,10 +169,10 @@ func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *or
|
|||||||
promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity
|
promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity
|
||||||
}
|
}
|
||||||
if promoPrice <= 0 {
|
if promoPrice <= 0 {
|
||||||
return nil
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
return l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var count int64
|
var count int64
|
||||||
if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil {
|
if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil {
|
||||||
return e
|
return e
|
||||||
@@ -201,6 +188,13 @@ func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *or
|
|||||||
PromoPrice: promoPrice,
|
PromoPrice: promoPrice,
|
||||||
}, tx)
|
}, tx)
|
||||||
})
|
})
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(ctx).Error("Insert promo usage failed",
|
||||||
|
logger.Field("error", err.Error()),
|
||||||
|
logger.Field("order_no", orderInfo.OrderNo),
|
||||||
|
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePayload unMarshals the task payload into a structured format
|
// parsePayload unMarshals the task payload into a structured format
|
||||||
|
|||||||
Reference in New Issue
Block a user