Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e61988d78f |
@@ -1,121 +0,0 @@
|
|||||||
syntax = "v1"
|
|
||||||
|
|
||||||
info (
|
|
||||||
title: "promo admin API"
|
|
||||||
desc: "API for ppanel"
|
|
||||||
author: "Tension"
|
|
||||||
email: "tension@ppanel.com"
|
|
||||||
version: "0.0.1"
|
|
||||||
)
|
|
||||||
|
|
||||||
import "../types.api"
|
|
||||||
|
|
||||||
type (
|
|
||||||
CreatePromoRuleRequest {
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params map[string]interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled"`
|
|
||||||
StartTime *int64 `json:"start_time"`
|
|
||||||
EndTime *int64 `json:"end_time"`
|
|
||||||
}
|
|
||||||
UpdatePromoRuleRequest {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params map[string]interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled"`
|
|
||||||
StartTime *int64 `json:"start_time"`
|
|
||||||
EndTime *int64 `json:"end_time"`
|
|
||||||
}
|
|
||||||
GetPromoRuleDetailRequest {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
DeletePromoRuleRequest {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
GetPromoRuleListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
|
||||||
Enabled *bool `form:"enabled"`
|
|
||||||
Search string `form:"search,omitempty"`
|
|
||||||
}
|
|
||||||
GetPromoRuleListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoRule `json:"list"`
|
|
||||||
}
|
|
||||||
SetPromoPriceRequest {
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
|
|
||||||
Items []PromoPriceItem `json:"items" validate:"required,dive"`
|
|
||||||
}
|
|
||||||
GetPromoPriceListRequest {
|
|
||||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"`
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoPriceListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoPrice `json:"list"`
|
|
||||||
}
|
|
||||||
DeletePromoPriceRequest {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
GetPromoUsageListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
RuleId int64 `form:"rule_id,omitempty"`
|
|
||||||
UserId int64 `form:"user_id,omitempty"`
|
|
||||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
|
||||||
OrderNo string `form:"order_no,omitempty"`
|
|
||||||
}
|
|
||||||
GetPromoUsageListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoUsage `json:"list"`
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
@server (
|
|
||||||
prefix: v1/admin/promo
|
|
||||||
group: admin/promo
|
|
||||||
middleware: AuthMiddleware
|
|
||||||
)
|
|
||||||
service ppanel {
|
|
||||||
@doc "Create promo rule"
|
|
||||||
@handler CreateRule
|
|
||||||
post /rule (CreatePromoRuleRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Get promo rule list"
|
|
||||||
@handler GetRuleList
|
|
||||||
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
|
|
||||||
|
|
||||||
@doc "Get promo rule detail"
|
|
||||||
@handler GetRuleDetail
|
|
||||||
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Update promo rule"
|
|
||||||
@handler UpdateRule
|
|
||||||
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Delete promo rule"
|
|
||||||
@handler DeleteRule
|
|
||||||
delete /rule/:id (DeletePromoRuleRequest)
|
|
||||||
|
|
||||||
@doc "Set promo prices"
|
|
||||||
@handler SetPrice
|
|
||||||
post /price (SetPromoPriceRequest)
|
|
||||||
|
|
||||||
@doc "Get promo price list"
|
|
||||||
@handler GetPriceList
|
|
||||||
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
|
|
||||||
|
|
||||||
@doc "Delete promo price"
|
|
||||||
@handler DeletePrice
|
|
||||||
delete /price/:id (DeletePromoPriceRequest)
|
|
||||||
|
|
||||||
@doc "Get promo usage list"
|
|
||||||
@handler GetUsageList
|
|
||||||
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
|
|
||||||
}
|
|
||||||
+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"`
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -230,47 +230,6 @@ type (
|
|||||||
Discount float64 `json:"discount"`
|
Discount float64 `json:"discount"`
|
||||||
MapApple string `json:"map_apple"`
|
MapApple string `json:"map_apple"`
|
||||||
}
|
}
|
||||||
PromoPrice {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
Quantity int64 `json:"quantity"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
PromoPriceItem {
|
|
||||||
SubscribeId int64 `json:"subscribe_id" validate:"required,gt=0"`
|
|
||||||
Quantity int64 `json:"quantity" validate:"required,gt=0,lte=1000"`
|
|
||||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
PromoRule {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Params map[string]interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
StartTime *int64 `json:"start_time"`
|
|
||||||
EndTime *int64 `json:"end_time"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
PromoUsage {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"user_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
SubscribePromo {
|
|
||||||
RuleName string `json:"rule_name"`
|
|
||||||
RuleType string `json:"rule_type"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
|
||||||
}
|
|
||||||
TrafficLimit {
|
TrafficLimit {
|
||||||
StatType string `json:"stat_type"`
|
StatType string `json:"stat_type"`
|
||||||
StatValue int64 `json:"stat_value"`
|
StatValue int64 `json:"stat_value"`
|
||||||
@@ -285,7 +244,6 @@ type (
|
|||||||
UnitPrice int64 `json:"unit_price"`
|
UnitPrice int64 `json:"unit_price"`
|
||||||
UnitTime string `json:"unit_time"`
|
UnitTime string `json:"unit_time"`
|
||||||
Discount []SubscribeDiscount `json:"discount"`
|
Discount []SubscribeDiscount `json:"discount"`
|
||||||
Promo *SubscribePromo `json:"promo"`
|
|
||||||
NodeCount int64 `json:"node_count"`
|
NodeCount int64 `json:"node_count"`
|
||||||
Replacement int64 `json:"replacement"`
|
Replacement int64 `json:"replacement"`
|
||||||
Inventory int64 `json:"inventory"`
|
Inventory int64 `json:"inventory"`
|
||||||
@@ -750,7 +708,6 @@ type (
|
|||||||
Price int64 `json:"price"`
|
Price int64 `json:"price"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
|
|||||||
@@ -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;
|
|
||||||
|
|||||||
@@ -1,38 +1,6 @@
|
|||||||
SET @column_exists = (
|
ALTER TABLE `order`
|
||||||
SELECT COUNT(*)
|
DROP COLUMN IF EXISTS `promo_discount`,
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
DROP COLUMN IF EXISTS `promo_rule_id`;
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_discount'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 1,
|
|
||||||
'ALTER TABLE `order` DROP COLUMN `promo_discount`',
|
|
||||||
'SELECT ''Column promo_discount does not exist in order table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
SET @column_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_rule_id'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 1,
|
|
||||||
'ALTER TABLE `order` DROP COLUMN `promo_rule_id`',
|
|
||||||
'SELECT ''Column promo_rule_id does not exist in order table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
|
|
||||||
DROP TABLE IF EXISTS `promo_usage`;
|
DROP TABLE IF EXISTS `promo_usage`;
|
||||||
DROP TABLE IF EXISTS `subscribe_promo`;
|
DROP TABLE IF EXISTS `subscribe_promo`;
|
||||||
|
|||||||
@@ -1,29 +1,28 @@
|
|||||||
CREATE TABLE IF NOT EXISTS `promo_rule` (
|
CREATE TABLE IF NOT EXISTS `promo_rule` (
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称',
|
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称,如"新客7天优惠"',
|
||||||
`type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型:new_user / inactive_user / campaign',
|
`type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型:new_user / inactive_user / campaign',
|
||||||
`params` JSON NOT NULL COMMENT '类型专属参数',
|
`params` JSON NOT NULL COMMENT '类型专属参数',
|
||||||
`priority` INT NOT NULL DEFAULT 0 COMMENT '优先级,数值越大越优先匹配',
|
`priority` INT NOT NULL DEFAULT 0 COMMENT '优先级,数值越大越优先匹配',
|
||||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
||||||
`start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间',
|
`start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间,NULL=立即生效',
|
||||||
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间',
|
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间,NULL=永不过期',
|
||||||
`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,
|
||||||
`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)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
||||||
|
|
||||||
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` INT NOT NULL DEFAULT 0 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_qty_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='规格促销价表';
|
||||||
|
|
||||||
@@ -40,38 +39,14 @@ CREATE TABLE IF NOT EXISTS `promo_usage` (
|
|||||||
KEY `idx_order_no` (`order_no`)
|
KEY `idx_order_no` (`order_no`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
|
||||||
|
|
||||||
SET @column_exists = (
|
SET @promo_rule_id_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'promo_rule_id');
|
||||||
SELECT COUNT(*)
|
SET @promo_rule_id_sql = IF(@promo_rule_id_exists = 0, 'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`', 'SELECT 1');
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
PREPARE stmt FROM @promo_rule_id_sql;
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_rule_id'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`',
|
|
||||||
'SELECT ''Column promo_rule_id already exists in order table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
EXECUTE stmt;
|
||||||
DEALLOCATE PREPARE stmt;
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
SET @column_exists = (
|
SET @promo_discount_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'promo_discount');
|
||||||
SELECT COUNT(*)
|
SET @promo_discount_sql = IF(@promo_discount_exists = 0, 'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`', 'SELECT 1');
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
PREPARE stmt FROM @promo_discount_sql;
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'order'
|
|
||||||
AND COLUMN_NAME = 'promo_discount'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`',
|
|
||||||
'SELECT ''Column promo_discount already exists in order table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
EXECUTE stmt;
|
||||||
DEALLOCATE PREPARE stmt;
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func CreateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.CreatePromoRuleRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewCreateRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.CreateRule(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func DeletePriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.DeletePromoPriceRequest
|
|
||||||
if err := c.ShouldBindUri(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewDeletePriceLogic(c.Request.Context(), svcCtx)
|
|
||||||
err := l.DeletePrice(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func DeleteRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.DeletePromoRuleRequest
|
|
||||||
if err := c.ShouldBindUri(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewDeleteRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
err := l.DeleteRule(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetPriceListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoPriceListRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewGetPriceListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPriceList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoRuleDetailRequest
|
|
||||||
if err := c.ShouldBindUri(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewGetRuleDetailLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetRuleDetail(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetRuleListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoRuleListRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewGetRuleListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetRuleList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetUsageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoUsageListRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewGetUsageListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetUsageList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SetPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.SetPromoPriceRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewSetPriceLogic(c.Request.Context(), svcCtx)
|
|
||||||
err := l.SetPrice(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func UpdateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.UpdatePromoRuleRequest
|
|
||||||
if err := c.ShouldBindUri(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l := promo.NewUpdateRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.UpdateRule(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,6 @@ import (
|
|||||||
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
||||||
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
||||||
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
||||||
adminPromo "github.com/perfect-panel/server/internal/handler/admin/promo"
|
|
||||||
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
||||||
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
||||||
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
||||||
@@ -375,38 +374,6 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
adminPromoGroupRouter := router.Group("/v1/admin/promo")
|
|
||||||
adminPromoGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
|
||||||
|
|
||||||
{
|
|
||||||
// Create promo rule
|
|
||||||
adminPromoGroupRouter.POST("/rule", adminPromo.CreateRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
adminPromoGroupRouter.GET("/rule/list", adminPromo.GetRuleListHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
adminPromoGroupRouter.GET("/rule/:id", adminPromo.GetRuleDetailHandler(serverCtx))
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
adminPromoGroupRouter.PUT("/rule/:id", adminPromo.UpdateRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
adminPromoGroupRouter.DELETE("/rule/:id", adminPromo.DeleteRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Set promo prices
|
|
||||||
adminPromoGroupRouter.POST("/price", adminPromo.SetPriceHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
adminPromoGroupRouter.GET("/price/list", adminPromo.GetPriceListHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
adminPromoGroupRouter.DELETE("/price/:id", adminPromo.DeletePriceHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
adminPromoGroupRouter.GET("/usage/list", adminPromo.GetUsageListHandler(serverCtx))
|
|
||||||
}
|
|
||||||
|
|
||||||
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
||||||
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||||
|
|
||||||
@@ -1011,16 +978,17 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
||||||
|
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
{
|
{
|
||||||
// Get subscribe list
|
// Get subscribe list
|
||||||
publicSubscribeGroupRouter.GET("/list", middleware.OptionalAuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/list", publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
||||||
|
|
||||||
// Get user subscribe node info
|
// Get user subscribe node info
|
||||||
publicSubscribeGroupRouter.GET("/node/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/node/list", publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
||||||
|
|
||||||
// Get subscribe group list
|
// Get subscribe group list
|
||||||
publicSubscribeGroupRouter.GET("/group/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/group/list", publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ func (l *DeleteSubscribeApplicationLogic) DeleteSubscribeApplication(req *types.
|
|||||||
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CreateRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCreateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRuleLogic {
|
|
||||||
return &CreateRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *CreateRuleLogic) CreateRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
|
|
||||||
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
params, err := paramsToString(req.Params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
enabled := true
|
|
||||||
if req.Enabled != nil {
|
|
||||||
enabled = *req.Enabled
|
|
||||||
}
|
|
||||||
rule := &promomodel.Rule{
|
|
||||||
Name: req.Name,
|
|
||||||
Type: req.Type,
|
|
||||||
Params: params,
|
|
||||||
Priority: req.Priority,
|
|
||||||
Enabled: enabled,
|
|
||||||
StartTime: unixPtrToTimePtr(req.StartTime),
|
|
||||||
EndTime: unixPtrToTimePtr(req.EndTime),
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, rule); err != nil {
|
|
||||||
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule error: %v", err.Error())
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
|
|
||||||
l.Errorw("[CreatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
|
|
||||||
}
|
|
||||||
resp := convertRule(rule)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DeletePriceLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDeletePriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePriceLogic {
|
|
||||||
return &DeletePriceLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error {
|
|
||||||
price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error())
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.PromoModel.DeletePrice(l.ctx, req.Id); err != nil {
|
|
||||||
l.Errorw("[DeletePromoPrice] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price error: %v", err.Error())
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.Redis.Del(l.ctx, subscribePromoCacheKey(price.SubscribeId)).Err(); err != nil {
|
|
||||||
l.Errorw("[DeletePromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DeleteRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDeleteRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRuleLogic {
|
|
||||||
return &DeleteRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error {
|
|
||||||
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
|
|
||||||
l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error())
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
|
|
||||||
l.Errorw("[DeletePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPriceListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGetPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPriceListLogic {
|
|
||||||
return &GetPriceListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPriceListLogic) GetPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QueryPriceList(l.ctx, req.PromoRuleId, int(req.Page), int(req.Size))
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo price list error: %v", err.Error())
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoPriceListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoPrice, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, convertPrice(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetRuleDetailLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGetRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleDetailLogic {
|
|
||||||
return &GetRuleDetailLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetRuleDetailLogic) GetRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
|
|
||||||
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule detail error: %v", err.Error())
|
|
||||||
}
|
|
||||||
resp := convertRule(rule)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetRuleListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGetRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleListLogic {
|
|
||||||
return &GetRuleListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetRuleListLogic) GetRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, int(req.Page), int(req.Size), req.Type, req.Enabled, req.Search)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule list error: %v", err.Error())
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoRuleListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoRule, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, convertRule(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetUsageListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGetUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUsageListLogic {
|
|
||||||
return &GetUsageListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetUsageListLogic) GetUsageList(req *types.GetPromoUsageListRequest) (*types.GetPromoUsageListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QueryUsageList(l.ctx, promomodel.UsageFilter{
|
|
||||||
Page: int(req.Page),
|
|
||||||
Size: int(req.Size),
|
|
||||||
RuleId: req.RuleId,
|
|
||||||
UserId: req.UserId,
|
|
||||||
SubscribeId: req.SubscribeId,
|
|
||||||
OrderNo: req.OrderNo,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo usage list error: %v", err.Error())
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoUsageListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoUsage, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, convertUsage(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SetPriceLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSetPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetPriceLogic {
|
|
||||||
return &SetPriceLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *SetPriceLogic) SetPrice(req *types.SetPromoPriceRequest) error {
|
|
||||||
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
|
|
||||||
l.Errorw("[SetPromoPrice] Find Rule Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
|
|
||||||
}
|
|
||||||
items := make([]*promomodel.SubscribePromo, 0, len(req.Items))
|
|
||||||
cacheKeys := make([]string, 0, len(req.Items))
|
|
||||||
for _, item := range req.Items {
|
|
||||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "subscribe plan not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[SetPromoPrice] Find Subscribe Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
|
||||||
}
|
|
||||||
originPrice := sub.UnitPrice * item.Quantity
|
|
||||||
if item.PromoPrice >= originPrice {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "promo_price must be less than unit_price * quantity")
|
|
||||||
}
|
|
||||||
items = append(items, &promomodel.SubscribePromo{
|
|
||||||
SubscribeId: item.SubscribeId,
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
Quantity: item.Quantity,
|
|
||||||
PromoPrice: item.PromoPrice,
|
|
||||||
})
|
|
||||||
cacheKeys = append(cacheKeys, subscribePromoCacheKey(item.SubscribeId))
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.PromoModel.UpsertPrices(l.ctx, req.PromoRuleId, items); err != nil {
|
|
||||||
l.Errorw("[SetPromoPrice] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "set promo price error: %v", err.Error())
|
|
||||||
}
|
|
||||||
if len(cacheKeys) > 0 {
|
|
||||||
if err := l.svcCtx.Redis.Del(l.ctx, cacheKeys...).Err(); err != nil {
|
|
||||||
l.Errorw("[SetPromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"math"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
ruleCacheKey = "promo:rules:enabled"
|
|
||||||
subscribeCachePref = "promo:subscribe:"
|
|
||||||
)
|
|
||||||
|
|
||||||
func validateRuleInput(ruleType string, params map[string]interface{}, priority int64, startTime, endTime *int64) error {
|
|
||||||
if priority < 0 {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "priority must be greater than or equal to 0")
|
|
||||||
}
|
|
||||||
if startTime != nil && endTime != nil && *startTime >= *endTime {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "start_time must be less than end_time")
|
|
||||||
}
|
|
||||||
switch ruleType {
|
|
||||||
case "new_user":
|
|
||||||
windowHours, ok := numberParam(params, "window_hours")
|
|
||||||
if !ok || windowHours <= 0 {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.window_hours must be greater than 0")
|
|
||||||
}
|
|
||||||
case "inactive_user":
|
|
||||||
inactiveMonths, ok := numberParam(params, "inactive_months")
|
|
||||||
if !ok || inactiveMonths <= 0 {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.inactive_months must be greater than 0")
|
|
||||||
}
|
|
||||||
case "campaign":
|
|
||||||
if params == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "unsupported promo rule type")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func numberParam(params map[string]interface{}, key string) (int64, bool) {
|
|
||||||
if params == nil {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
value, ok := params[key]
|
|
||||||
if !ok {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
switch v := value.(type) {
|
|
||||||
case float64:
|
|
||||||
if math.Trunc(v) != v {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
return int64(v), true
|
|
||||||
case int64:
|
|
||||||
return v, true
|
|
||||||
case int:
|
|
||||||
return int64(v), true
|
|
||||||
case json.Number:
|
|
||||||
n, err := v.Int64()
|
|
||||||
return n, err == nil
|
|
||||||
default:
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func paramsToString(params map[string]interface{}) (string, error) {
|
|
||||||
if params == nil {
|
|
||||||
params = map[string]interface{}{}
|
|
||||||
}
|
|
||||||
b, err := json.Marshal(params)
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid params")
|
|
||||||
}
|
|
||||||
return string(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseParams(data string) map[string]interface{} {
|
|
||||||
if data == "" {
|
|
||||||
return map[string]interface{}{}
|
|
||||||
}
|
|
||||||
var params map[string]interface{}
|
|
||||||
if err := json.Unmarshal([]byte(data), ¶ms); err != nil {
|
|
||||||
return map[string]interface{}{}
|
|
||||||
}
|
|
||||||
return params
|
|
||||||
}
|
|
||||||
|
|
||||||
func unixPtrToTimePtr(ts *int64) *time.Time {
|
|
||||||
if ts == nil || *ts == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
t := time.Unix(*ts, 0)
|
|
||||||
return &t
|
|
||||||
}
|
|
||||||
|
|
||||||
func timePtrToUnixPtr(t *time.Time) *int64 {
|
|
||||||
if t == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
ts := t.Unix()
|
|
||||||
return &ts
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertRule(item *promomodel.Rule) types.PromoRule {
|
|
||||||
if item == nil {
|
|
||||||
return types.PromoRule{}
|
|
||||||
}
|
|
||||||
return types.PromoRule{
|
|
||||||
Id: item.Id,
|
|
||||||
Name: item.Name,
|
|
||||||
Type: item.Type,
|
|
||||||
Params: parseParams(item.Params),
|
|
||||||
Priority: item.Priority,
|
|
||||||
Enabled: item.Enabled,
|
|
||||||
StartTime: timePtrToUnixPtr(item.StartTime),
|
|
||||||
EndTime: timePtrToUnixPtr(item.EndTime),
|
|
||||||
CreatedAt: item.CreatedAt.Unix(),
|
|
||||||
UpdatedAt: item.UpdatedAt.Unix(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertPrice(item *promomodel.SubscribePromo) types.PromoPrice {
|
|
||||||
if item == nil {
|
|
||||||
return types.PromoPrice{}
|
|
||||||
}
|
|
||||||
return types.PromoPrice{
|
|
||||||
Id: item.Id,
|
|
||||||
SubscribeId: item.SubscribeId,
|
|
||||||
PromoRuleId: item.PromoRuleId,
|
|
||||||
Quantity: item.Quantity,
|
|
||||||
PromoPrice: item.PromoPrice,
|
|
||||||
CreatedAt: item.CreatedAt.Unix(),
|
|
||||||
UpdatedAt: item.UpdatedAt.Unix(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertUsage(item *promomodel.Usage) types.PromoUsage {
|
|
||||||
if item == nil {
|
|
||||||
return types.PromoUsage{}
|
|
||||||
}
|
|
||||||
return types.PromoUsage{
|
|
||||||
Id: item.Id,
|
|
||||||
UserId: item.UserId,
|
|
||||||
PromoRuleId: item.PromoRuleId,
|
|
||||||
SubscribeId: item.SubscribeId,
|
|
||||||
OrderNo: item.OrderNo,
|
|
||||||
PromoPrice: item.PromoPrice,
|
|
||||||
CreatedAt: item.CreatedAt.Unix(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func subscribePromoCacheKey(subscribeId int64) string {
|
|
||||||
return fmt.Sprintf("%s%d", subscribeCachePref, subscribeId)
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UpdateRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUpdateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRuleLogic {
|
|
||||||
return &UpdateRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *UpdateRuleLogic) UpdateRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
|
|
||||||
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[UpdatePromoRule] Find Rule Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
|
|
||||||
}
|
|
||||||
params, err := paramsToString(req.Params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
enabled := rule.Enabled
|
|
||||||
if req.Enabled != nil {
|
|
||||||
enabled = *req.Enabled
|
|
||||||
}
|
|
||||||
rule.Name = req.Name
|
|
||||||
rule.Type = req.Type
|
|
||||||
rule.Params = params
|
|
||||||
rule.Priority = req.Priority
|
|
||||||
rule.Enabled = enabled
|
|
||||||
rule.StartTime = unixPtrToTimePtr(req.StartTime)
|
|
||||||
rule.EndTime = unixPtrToTimePtr(req.EndTime)
|
|
||||||
if err := l.svcCtx.PromoModel.UpdateRule(l.ctx, rule); err != nil {
|
|
||||||
l.Errorw("[UpdatePromoRule] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule error: %v", err.Error())
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
|
|
||||||
l.Errorw("[UpdatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
|
|
||||||
}
|
|
||||||
resp := convertRule(rule)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithNodeLogic) ResetSortWithNode(req *types.ResetSortRequest)
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithServerLogic) ResetSortWithServer(req *types.ResetSortReque
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,170 +0,0 @@
|
|||||||
package common
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type PromoResult struct {
|
|
||||||
Eligible bool
|
|
||||||
RuleID int64
|
|
||||||
RuleName string
|
|
||||||
RuleType string
|
|
||||||
PromoPrice int64
|
|
||||||
ExpiresAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoRuleParams struct {
|
|
||||||
WindowHours int `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
|
|
||||||
result := &PromoResult{}
|
|
||||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 || quantity <= 0 {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID, quantity)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
if len(rules) == 0 {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var currentUser user.User
|
|
||||||
now := time.Now()
|
|
||||||
for _, rule := range rules {
|
|
||||||
if rule == nil || !isPromoRuleInTimeWindow(rule, now) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if rule.PromoPrice <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
params := promoRuleParams{}
|
|
||||||
if rule.Params != "" {
|
|
||||||
if err = json.Unmarshal([]byte(rule.Params), ¶ms); err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, ¤tUser, now)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !eligible {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return &PromoResult{
|
|
||||||
Eligible: true,
|
|
||||||
RuleID: rule.Id,
|
|
||||||
RuleName: rule.Name,
|
|
||||||
RuleType: rule.Type,
|
|
||||||
PromoPrice: rule.PromoPrice,
|
|
||||||
ExpiresAt: expiresAt,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPromoRuleInTimeWindow(rule *promo.RuleWithPrice, now time.Time) bool {
|
|
||||||
if rule.StartTime != nil && !rule.StartTime.IsZero() && now.Before(*rule.StartTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if rule.EndTime != nil && !rule.EndTime.IsZero() && now.After(*rule.EndTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluatePromoRule(
|
|
||||||
ctx context.Context,
|
|
||||||
db *gorm.DB,
|
|
||||||
rule *promo.RuleWithPrice,
|
|
||||||
params promoRuleParams,
|
|
||||||
userID int64,
|
|
||||||
currentUser *user.User,
|
|
||||||
now time.Time,
|
|
||||||
) (bool, time.Time, error) {
|
|
||||||
switch rule.Type {
|
|
||||||
case promo.RuleTypeNewUser:
|
|
||||||
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
|
|
||||||
case promo.RuleTypeInactiveUser:
|
|
||||||
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
|
|
||||||
case promo.RuleTypeCampaign:
|
|
||||||
return true, promoRuleExpiresAt(rule), nil
|
|
||||||
default:
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluateNewUserPromo(
|
|
||||||
ctx context.Context,
|
|
||||||
db *gorm.DB,
|
|
||||||
params promoRuleParams,
|
|
||||||
userID int64,
|
|
||||||
currentUser *user.User,
|
|
||||||
now time.Time,
|
|
||||||
) (bool, time.Time, error) {
|
|
||||||
if params.WindowHours <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if currentUser.Id == 0 {
|
|
||||||
if err := db.WithContext(ctx).Model(&user.User{}).Where("id = ?", userID).First(currentUser).Error; err != nil {
|
|
||||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expiresAt := currentUser.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
|
||||||
return now.Before(expiresAt), expiresAt, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluateInactiveUserPromo(
|
|
||||||
ctx context.Context,
|
|
||||||
db *gorm.DB,
|
|
||||||
params promoRuleParams,
|
|
||||||
userID int64,
|
|
||||||
ruleExpiresAt time.Time,
|
|
||||||
now time.Time,
|
|
||||||
) (bool, time.Time, error) {
|
|
||||||
if params.InactiveMonths <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var lastSub user.Subscribe
|
|
||||||
err := db.WithContext(ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ?", userID).
|
|
||||||
Order("expire_time DESC").
|
|
||||||
Limit(1).
|
|
||||||
Take(&lastSub).Error
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return true, ruleExpiresAt, nil
|
|
||||||
}
|
|
||||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
|
||||||
return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
|
|
||||||
if rule != nil && rule.EndTime != nil {
|
|
||||||
return *rule.EndTime
|
|
||||||
}
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package order
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"math"
|
||||||
|
|
||||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
@@ -114,28 +115,14 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
||||||
}
|
}
|
||||||
|
|
||||||
priceResult, err := calculatePurchasePrice(
|
var discount float64 = 1
|
||||||
l.ctx,
|
if len(newUserDiscount.Discounts) > 0 {
|
||||||
l.svcCtx,
|
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||||
u.Id,
|
|
||||||
targetSubscribeID,
|
|
||||||
sub.UnitPrice,
|
|
||||||
req.Quantity,
|
|
||||||
newUserDiscount.Discounts,
|
|
||||||
newUserDiscount.EligibleForDiscount,
|
|
||||||
!isSingleModeRenewal,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[PreCreateOrder] Promo price calculation error",
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
logger.Field("user_id", u.Id),
|
|
||||||
logger.Field("subscribe_id", targetSubscribeID),
|
|
||||||
)
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
price := priceResult.OriginalPrice
|
price := sub.UnitPrice * req.Quantity
|
||||||
amount := priceResult.PayableBase
|
|
||||||
discountAmount := priceResult.DiscountAmount
|
amount := int64(math.Round(float64(price) * discount))
|
||||||
|
discountAmount := price - amount
|
||||||
var couponAmount int64
|
var couponAmount int64
|
||||||
if req.Coupon != "" {
|
if req.Coupon != "" {
|
||||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||||
@@ -198,7 +185,6 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
Price: price,
|
Price: price,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
Discount: discountAmount,
|
Discount: discountAmount,
|
||||||
PromoDiscount: priceResult.PromoDiscount,
|
|
||||||
GiftAmount: deductionAmount,
|
GiftAmount: deductionAmount,
|
||||||
Coupon: req.Coupon,
|
Coupon: req.Coupon,
|
||||||
CouponDiscount: couponAmount,
|
CouponDiscount: couponAmount,
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"math"
|
|
||||||
|
|
||||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
)
|
|
||||||
|
|
||||||
type orderPriceResult struct {
|
|
||||||
OriginalPrice int64
|
|
||||||
PayableBase int64
|
|
||||||
DiscountAmount int64
|
|
||||||
PromoRuleId int64
|
|
||||||
PromoDiscount int64
|
|
||||||
PromoPrice int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func calculatePurchasePrice(
|
|
||||||
ctx context.Context,
|
|
||||||
svcCtx *svc.ServiceContext,
|
|
||||||
userID int64,
|
|
||||||
subscribeID int64,
|
|
||||||
unitPrice int64,
|
|
||||||
quantity int64,
|
|
||||||
discounts []types.SubscribeDiscount,
|
|
||||||
eligibleForDiscount bool,
|
|
||||||
allowPromo bool,
|
|
||||||
) (*orderPriceResult, error) {
|
|
||||||
originalPrice := unitPrice * quantity
|
|
||||||
result := &orderPriceResult{
|
|
||||||
OriginalPrice: originalPrice,
|
|
||||||
PayableBase: originalPrice,
|
|
||||||
}
|
|
||||||
|
|
||||||
if allowPromo {
|
|
||||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < unitPrice {
|
|
||||||
result.PayableBase = promoResult.PromoPrice * quantity
|
|
||||||
result.PromoRuleId = promoResult.RuleID
|
|
||||||
result.PromoDiscount = originalPrice - result.PayableBase
|
|
||||||
result.PromoPrice = promoResult.PromoPrice
|
|
||||||
if result.PromoDiscount < 0 {
|
|
||||||
result.PromoDiscount = 0
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
discount := float64(1)
|
|
||||||
if len(discounts) > 0 {
|
|
||||||
discount = getDiscount(discounts, quantity, eligibleForDiscount)
|
|
||||||
}
|
|
||||||
result.PayableBase = int64(math.Round(float64(originalPrice) * discount))
|
|
||||||
result.DiscountAmount = originalPrice - result.PayableBase
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type fakePromoModel struct {
|
|
||||||
rules []*promo.RuleWithPrice
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promo.RuleWithPrice, error) {
|
|
||||||
return m.rules, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
|
||||||
return nil, gorm.ErrRecordNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) DeleteRule(context.Context, int64) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
|
|
||||||
return nil, gorm.ErrRecordNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) DeletePrice(context.Context, int64) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promo.SubscribePromo, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 9,
|
|
||||||
Name: "campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 600,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
|
||||||
context.Background(),
|
|
||||||
svcCtx,
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
1000,
|
|
||||||
3,
|
|
||||||
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.OriginalPrice != 3000 {
|
|
||||||
t.Fatalf("OriginalPrice = %d, want 3000", result.OriginalPrice)
|
|
||||||
}
|
|
||||||
if result.PayableBase != 1800 {
|
|
||||||
t.Fatalf("PayableBase = %d, want 1800", result.PayableBase)
|
|
||||||
}
|
|
||||||
if result.DiscountAmount != 0 {
|
|
||||||
t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount)
|
|
||||||
}
|
|
||||||
if result.PromoRuleId != 9 {
|
|
||||||
t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId)
|
|
||||||
}
|
|
||||||
if result.PromoDiscount != 1200 {
|
|
||||||
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 10,
|
|
||||||
Name: "invalid campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 1000,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := calculatePurchasePrice(
|
|
||||||
context.Background(),
|
|
||||||
svcCtx,
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
1000,
|
|
||||||
3,
|
|
||||||
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.PayableBase != 1500 {
|
|
||||||
t.Fatalf("PayableBase = %d, want 1500", result.PayableBase)
|
|
||||||
}
|
|
||||||
if result.DiscountAmount != 1500 {
|
|
||||||
t.Fatalf("DiscountAmount = %d, want 1500", result.DiscountAmount)
|
|
||||||
}
|
|
||||||
if result.PromoRuleId != 0 || result.PromoDiscount != 0 {
|
|
||||||
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,7 @@ package order
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"math"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -203,28 +204,14 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
priceResult, err := calculatePurchasePrice(
|
var discount float64 = 1
|
||||||
l.ctx,
|
if len(newUserDiscount.Discounts) > 0 {
|
||||||
l.svcCtx,
|
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||||
u.Id,
|
|
||||||
targetSubscribeID,
|
|
||||||
sub.UnitPrice,
|
|
||||||
req.Quantity,
|
|
||||||
newUserDiscount.Discounts,
|
|
||||||
newUserDiscount.EligibleForDiscount,
|
|
||||||
orderType == 1,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[Purchase] Promo price calculation error",
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
logger.Field("user_id", u.Id),
|
|
||||||
logger.Field("subscribe_id", targetSubscribeID),
|
|
||||||
)
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
price := priceResult.OriginalPrice
|
price := sub.UnitPrice * req.Quantity
|
||||||
amount := priceResult.PayableBase
|
// discount amount
|
||||||
discountAmount := priceResult.DiscountAmount
|
amount := int64(math.Round(float64(price) * discount))
|
||||||
|
discountAmount := price - amount
|
||||||
|
|
||||||
// Validate amount to prevent overflow
|
// Validate amount to prevent overflow
|
||||||
if amount > MaxOrderAmount {
|
if amount > MaxOrderAmount {
|
||||||
@@ -319,8 +306,6 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
Price: price,
|
Price: price,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
Discount: discountAmount,
|
Discount: discountAmount,
|
||||||
PromoRuleId: priceResult.PromoRuleId,
|
|
||||||
PromoDiscount: priceResult.PromoDiscount,
|
|
||||||
GiftAmount: deductionAmount,
|
GiftAmount: deductionAmount,
|
||||||
Coupon: req.Coupon,
|
Coupon: req.Coupon,
|
||||||
CouponDiscount: coupon,
|
CouponDiscount: coupon,
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
package subscribe
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
stderrors "errors"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-sql-driver/mysql"
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/constant"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
promoRuleTypeNewUser = "new_user"
|
|
||||||
promoRuleTypeInactiveUser = "inactive_user"
|
|
||||||
promoRuleTypeCampaign = "campaign"
|
|
||||||
)
|
|
||||||
|
|
||||||
type subscribePromoCandidate struct {
|
|
||||||
SubscribeId int64 `gorm:"column:subscribe_id"`
|
|
||||||
RuleName string `gorm:"column:rule_name"`
|
|
||||||
RuleType string `gorm:"column:rule_type"`
|
|
||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
|
||||||
Params string `gorm:"column:params"`
|
|
||||||
StartTime *time.Time `gorm:"column:start_time"`
|
|
||||||
EndTime *time.Time `gorm:"column:end_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoRuleParams struct {
|
|
||||||
WindowHours int64 `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]*types.SubscribePromo, error) {
|
|
||||||
result := make(map[int64]*types.SubscribePromo)
|
|
||||||
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
userInfo, _ := ctx.Value(constant.CtxKeyUser).(*user.User)
|
|
||||||
candidates, err := querySubscribePromoCandidates(ctx, svcCtx, subscribeIDs, userInfo != nil)
|
|
||||||
if err != nil {
|
|
||||||
if isMissingPromoTableError(err) {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
|
||||||
now := time.Now()
|
|
||||||
for _, candidate := range candidates {
|
|
||||||
if _, exists := result[candidate.SubscribeId]; exists {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !candidate.isActive(now) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ok, expiresAt, err := evaluator.match(candidate, now)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
result[candidate.SubscribeId] = &types.SubscribePromo{
|
|
||||||
RuleName: candidate.RuleName,
|
|
||||||
RuleType: candidate.RuleType,
|
|
||||||
PromoPrice: candidate.PromoPrice,
|
|
||||||
ExpiresAt: unixSeconds(expiresAt),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
|
|
||||||
var candidates []subscribePromoCandidate
|
|
||||||
query := svcCtx.DB.WithContext(ctx).
|
|
||||||
Table("subscribe_promo AS sp").
|
|
||||||
Select("sp.subscribe_id, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
|
|
||||||
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
|
|
||||||
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
|
|
||||||
if !loggedIn {
|
|
||||||
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
|
|
||||||
}
|
|
||||||
err := query.
|
|
||||||
Order("sp.subscribe_id ASC").
|
|
||||||
Order("pr.priority DESC").
|
|
||||||
Order("pr.id ASC").
|
|
||||||
Scan(&candidates).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
|
|
||||||
}
|
|
||||||
return candidates, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) isActive(now time.Time) bool {
|
|
||||||
if c.PromoPrice <= 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if c.StartTime != nil && now.Before(*c.StartTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if c.EndTime != nil && now.After(*c.EndTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoEligibilityEvaluator struct {
|
|
||||||
ctx context.Context
|
|
||||||
db *gorm.DB
|
|
||||||
userInfo *user.User
|
|
||||||
lastExpire *time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) match(candidate subscribePromoCandidate, now time.Time) (bool, time.Time, error) {
|
|
||||||
switch candidate.RuleType {
|
|
||||||
case promoRuleTypeCampaign:
|
|
||||||
return true, candidate.expiresAt(), nil
|
|
||||||
case promoRuleTypeNewUser:
|
|
||||||
if e.userInfo == nil {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
params, err := candidate.params()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if params.WindowHours <= 0 || e.userInfo.CreatedAt.IsZero() {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
expiresAt := e.userInfo.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
|
||||||
return now.Before(expiresAt), expiresAt, nil
|
|
||||||
case promoRuleTypeInactiveUser:
|
|
||||||
if e.userInfo == nil {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
params, err := candidate.params()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if params.InactiveMonths <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
lastExpire, err := e.lastSubscribeExpireAt()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if lastExpire.Equal(time.UnixMilli(0)) || lastExpire.After(now) {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
if lastExpire.IsZero() {
|
|
||||||
return true, candidate.expiresAt(), nil
|
|
||||||
}
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
|
||||||
return !lastExpire.After(threshold), candidate.expiresAt(), nil
|
|
||||||
default:
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
|
||||||
if e.lastExpire != nil {
|
|
||||||
return *e.lastExpire, nil
|
|
||||||
}
|
|
||||||
var item user.Subscribe
|
|
||||||
err := e.db.WithContext(e.ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ?", e.userInfo.Id).
|
|
||||||
Where("expire_time != ?", time.UnixMilli(0)).
|
|
||||||
Order("expire_time DESC").
|
|
||||||
Limit(1).
|
|
||||||
Take(&item).Error
|
|
||||||
if err != nil {
|
|
||||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
zero := time.Time{}
|
|
||||||
e.lastExpire = &zero
|
|
||||||
return zero, nil
|
|
||||||
}
|
|
||||||
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
|
|
||||||
}
|
|
||||||
e.lastExpire = &item.ExpireTime
|
|
||||||
return item.ExpireTime, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) expiresAt() time.Time {
|
|
||||||
if c.EndTime == nil {
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
return *c.EndTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
|
|
||||||
if c.Params == "" {
|
|
||||||
return promoRuleParams{}, nil
|
|
||||||
}
|
|
||||||
var params promoRuleParams
|
|
||||||
if err := json.Unmarshal([]byte(c.Params), ¶ms); err != nil {
|
|
||||||
return promoRuleParams{}, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "parse promo rule params failed")
|
|
||||||
}
|
|
||||||
return params, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func unixSeconds(t time.Time) int64 {
|
|
||||||
if t.IsZero() {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return t.Unix()
|
|
||||||
}
|
|
||||||
|
|
||||||
func isMissingPromoTableError(err error) bool {
|
|
||||||
var mysqlErr *mysql.MySQLError
|
|
||||||
if stderrors.As(err, &mysqlErr) {
|
|
||||||
return mysqlErr.Number == 1146
|
|
||||||
}
|
|
||||||
return strings.Contains(err.Error(), "Error 1146")
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package subscribe
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
campaignEnd := now.Add(2 * time.Hour)
|
|
||||||
|
|
||||||
campaign := subscribePromoCandidate{
|
|
||||||
RuleName: "限时活动",
|
|
||||||
RuleType: promoRuleTypeCampaign,
|
|
||||||
PromoPrice: 99,
|
|
||||||
EndTime: &campaignEnd,
|
|
||||||
}
|
|
||||||
ok, expiresAt, err := (&promoEligibilityEvaluator{}).match(campaign, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("campaign match error: %v", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("campaign promo should match without login")
|
|
||||||
}
|
|
||||||
if got, want := unixSeconds(expiresAt), campaignEnd.Unix(); got != want {
|
|
||||||
t.Fatalf("campaign expires_at = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
newUser := subscribePromoCandidate{
|
|
||||||
RuleName: "新客7天优惠",
|
|
||||||
RuleType: promoRuleTypeNewUser,
|
|
||||||
PromoPrice: 279,
|
|
||||||
Params: `{"window_hours":168}`,
|
|
||||||
}
|
|
||||||
ok, _, err = (&promoEligibilityEvaluator{}).match(newUser, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("anonymous new_user match error: %v", err)
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
t.Fatal("new_user promo should not match without login")
|
|
||||||
}
|
|
||||||
|
|
||||||
userInfo := &user.User{Id: 1, CreatedAt: now.Add(-24 * time.Hour)}
|
|
||||||
ok, expiresAt, err = (&promoEligibilityEvaluator{userInfo: userInfo}).match(newUser, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("logged-in new_user match error: %v", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("new_user promo should match inside window")
|
|
||||||
}
|
|
||||||
if got, want := unixSeconds(expiresAt), userInfo.CreatedAt.Add(168*time.Hour).Unix(); got != want {
|
|
||||||
t.Fatalf("new_user expires_at = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
start := now.Add(-time.Hour)
|
|
||||||
end := now.Add(time.Hour)
|
|
||||||
|
|
||||||
if !(subscribePromoCandidate{PromoPrice: 1, StartTime: &start, EndTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate inside active window should be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 0, StartTime: &start, EndTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate with zero promo price should not be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 1, StartTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate before start time should not be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 1, EndTime: &start}).isActive(now) {
|
|
||||||
t.Fatal("candidate after end time should not be active")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -47,11 +47,9 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
Total: total,
|
Total: total,
|
||||||
}
|
}
|
||||||
list := make([]types.Subscribe, len(data))
|
list := make([]types.Subscribe, len(data))
|
||||||
subscribeIDs := make([]int64, 0, len(data))
|
|
||||||
for i, item := range data {
|
for i, item := range data {
|
||||||
var sub types.Subscribe
|
var sub types.Subscribe
|
||||||
tool.DeepCopy(&sub, item)
|
tool.DeepCopy(&sub, item)
|
||||||
subscribeIDs = append(subscribeIDs, sub.Id)
|
|
||||||
if item.Discount != "" {
|
if item.Discount != "" {
|
||||||
var discount []types.SubscribeDiscount
|
var discount []types.SubscribeDiscount
|
||||||
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
||||||
@@ -71,15 +69,6 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for i := range list {
|
|
||||||
list[i].Promo = promos[list[i].Id]
|
|
||||||
}
|
|
||||||
|
|
||||||
resp.List = list
|
resp.List = list
|
||||||
resp.Total = int64(len(list))
|
resp.Total = int64(len(list))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,14 +39,14 @@ func (l *DeviceWsConnectLogic) DeviceWsConnect(c *gin.Context) error {
|
|||||||
value, _ = c.GetQuery("identifier")
|
value, _ = c.GetQuery("identifier")
|
||||||
if value == nil || value.(string) == "" {
|
if value == nil || value.(string) == "" {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect identifier is empty")
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect identifier is empty")
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.InvalidParams), "identifier is empty")
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "identifier is empty")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
identifier := value.(string)
|
identifier := value.(string)
|
||||||
_, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, identifier)
|
_, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, identifier)
|
||||||
if err != nil && !sysErr.Is(err, gorm.ErrRecordNotFound) {
|
if err != nil && !sysErr.Is(err, gorm.ErrRecordNotFound) {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect FindOneDeviceByIdentifier err: %v", err)
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect FindOneDeviceByIdentifier err: %v", err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
value = l.ctx.Value(constant.CtxKeyUser)
|
value = l.ctx.Value(constant.CtxKeyUser)
|
||||||
@@ -67,7 +67,7 @@ func (l *DeviceWsConnectLogic) DeviceWsConnect(c *gin.Context) error {
|
|||||||
err := l.svcCtx.UserModel.InsertDevice(l.ctx, &device)
|
err := l.svcCtx.UserModel.InsertDevice(l.ctx, &device)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect InsertDevice err: %v", err)
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect InsertDevice err: %v", err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//默认在线设备1
|
//默认在线设备1
|
||||||
|
|||||||
@@ -22,92 +22,77 @@ import (
|
|||||||
|
|
||||||
func AuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
func AuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
if !authenticateRequest(c, svc, c.GetHeader("Authorization"), true) {
|
ctx := c.Request.Context()
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func OptionalAuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
jwtConfig := svc.Config.JwtAuth
|
||||||
return func(c *gin.Context) {
|
// get token from header
|
||||||
token := c.GetHeader("Authorization")
|
token := c.GetHeader("Authorization")
|
||||||
if token == "" {
|
if token == "" {
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !authenticateRequest(c, svc, token, false) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func authenticateRequest(c *gin.Context, svc *svc.ServiceContext, token string, requireToken bool) bool {
|
|
||||||
ctx := c.Request.Context()
|
|
||||||
|
|
||||||
if token == "" {
|
|
||||||
if requireToken {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Token Empty")
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Token Empty")
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenEmpty), "Token Empty"))
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenEmpty), "Token Empty"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// parse token
|
||||||
|
claims, err := jwt.ParseJwtToken(token, jwtConfig.AccessSecret)
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] ParseJwtToken", logger.Field("error", err.Error()), logger.Field("token", token))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenExpire), "Token Invalid"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return !requireToken
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := jwt.ParseJwtToken(token, svc.Config.JwtAuth.AccessSecret)
|
loginType := parseLoginType(claims)
|
||||||
if err != nil {
|
if claims["identifier"] != nil {
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] ParseJwtToken", logger.Field("error", err.Error()), logger.Field("token", token))
|
ctx = context.WithValue(ctx, constant.CtxKeyIdentifier, claims["identifier"].(string))
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenExpire), "Token Invalid"))
|
}
|
||||||
c.Abort()
|
// get user id from token
|
||||||
return false
|
userId := int64(claims["UserId"].(float64))
|
||||||
}
|
// get session id from token
|
||||||
|
sessionId := claims["SessionId"].(string)
|
||||||
|
// get session id from redis
|
||||||
|
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||||
|
value, err := svc.Redis.Get(c, sessionIdCacheKey).Result()
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Redis Get", logger.Field("error", err.Error()), logger.Field("sessionId", sessionId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
loginType := parseLoginType(claims)
|
//verify user id
|
||||||
if claims["identifier"] != nil {
|
if value != fmt.Sprintf("%v", userId) {
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeyIdentifier, claims["identifier"].(string))
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Invalid Access", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
||||||
}
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
userId := int64(claims["UserId"].(float64))
|
c.Abort()
|
||||||
sessionId := claims["SessionId"].(string)
|
return
|
||||||
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
}
|
||||||
value, err := svc.Redis.Get(c, sessionIdCacheKey).Result()
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Redis Get", logger.Field("error", err.Error()), logger.Field("sessionId", sessionId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if value != fmt.Sprintf("%v", userId) {
|
// sliding session: refresh TTL on every active request
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Invalid Access", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
svc.Redis.Expire(c, sessionIdCacheKey, time.Duration(svc.Config.JwtAuth.AccessExpire)*time.Second)
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
userInfo, err := svc.UserModel.FindOne(c, userId)
|
||||||
return false
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] UserModel FindOne", logger.Field("error", err.Error()), logger.Field("userId", userId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// admin verify
|
||||||
|
paths := strings.Split(c.Request.URL.Path, "/")
|
||||||
|
if tool.StringSliceContains(paths, "admin") && !*userInfo.IsAdmin {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Not Admin User", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxLoginType, loginType)
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxKeyUser, userInfo)
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxKeySessionID, sessionId)
|
||||||
|
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
svc.Redis.Expire(c, sessionIdCacheKey, time.Duration(svc.Config.JwtAuth.AccessExpire)*time.Second)
|
|
||||||
|
|
||||||
userInfo, err := svc.UserModel.FindOne(c, userId)
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] UserModel FindOne", logger.Field("error", err.Error()), logger.Field("userId", userId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
paths := strings.Split(c.Request.URL.Path, "/")
|
|
||||||
if tool.StringSliceContains(paths, "admin") && !*userInfo.IsAdmin {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Not Admin User", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxLoginType, loginType)
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeyUser, userInfo)
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeySessionID, sessionId)
|
|
||||||
|
|
||||||
c.Request = c.Request.WithContext(ctx)
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseLoginType(claims map[string]interface{}) string {
|
func parseLoginType(claims map[string]interface{}) string {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ type Details struct {
|
|||||||
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
||||||
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
||||||
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
|
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID"`
|
PromoRuleID int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID, 0 means no promo"`
|
||||||
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
||||||
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
||||||
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
|
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ type Order struct {
|
|||||||
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
||||||
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
|
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
|
||||||
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
|
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID"`
|
PromoRuleID int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID, 0 means no promo"`
|
||||||
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
||||||
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
||||||
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
|
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
|
||||||
|
|||||||
@@ -1,204 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type RuleWithPrice struct {
|
|
||||||
Rule
|
|
||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Model interface {
|
|
||||||
QueryEligibleRules(ctx context.Context, subscribeId int64, quantity int64) ([]*RuleWithPrice, error)
|
|
||||||
InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error
|
|
||||||
InsertRule(ctx context.Context, data *Rule) error
|
|
||||||
FindRule(ctx context.Context, id int64) (*Rule, error)
|
|
||||||
UpdateRule(ctx context.Context, data *Rule) error
|
|
||||||
DeleteRule(ctx context.Context, id int64) error
|
|
||||||
QueryRuleList(ctx context.Context, page, size int, ruleType string, enabled *bool, search string) (int64, []*Rule, error)
|
|
||||||
UpsertPrices(ctx context.Context, ruleId int64, items []*SubscribePromo) error
|
|
||||||
FindPrice(ctx context.Context, id int64) (*SubscribePromo, error)
|
|
||||||
DeletePrice(ctx context.Context, id int64) error
|
|
||||||
QueryPriceList(ctx context.Context, ruleId int64, page, size int) (int64, []*SubscribePromo, error)
|
|
||||||
QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error)
|
|
||||||
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type UsageFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
RuleId int64
|
|
||||||
UserId int64
|
|
||||||
SubscribeId int64
|
|
||||||
OrderNo string
|
|
||||||
}
|
|
||||||
|
|
||||||
type defaultPromoModel struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewModel(db *gorm.DB, _ *redis.Client) Model {
|
|
||||||
return &defaultPromoModel{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64, quantity int64) ([]*RuleWithPrice, error) {
|
|
||||||
var list []*RuleWithPrice
|
|
||||||
err := m.db.WithContext(ctx).
|
|
||||||
Table("promo_rule AS pr").
|
|
||||||
Select("pr.*, sp.promo_price").
|
|
||||||
Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id").
|
|
||||||
Where("sp.subscribe_id = ? AND sp.quantity = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, quantity, true).
|
|
||||||
Where("pr.deleted_at IS NULL").
|
|
||||||
Order("pr.priority DESC").
|
|
||||||
Order("pr.id ASC").
|
|
||||||
Find(&list).Error
|
|
||||||
return list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error {
|
|
||||||
db := m.db.WithContext(ctx)
|
|
||||||
if len(tx) > 0 {
|
|
||||||
db = tx[0].WithContext(ctx)
|
|
||||||
}
|
|
||||||
return db.Model(&Usage{}).Create(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertRule(ctx context.Context, data *Rule) error {
|
|
||||||
return m.db.WithContext(ctx).Create(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) FindRule(ctx context.Context, id int64) (*Rule, error) {
|
|
||||||
var resp Rule
|
|
||||||
if err := m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", id).First(&resp).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
|
|
||||||
return m.db.WithContext(ctx).Save(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
|
|
||||||
return m.db.WithContext(ctx).Delete(&Rule{}, id).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryRuleList(ctx context.Context, page, size int, ruleType string, enabled *bool, search string) (int64, []*Rule, error) {
|
|
||||||
if page <= 0 {
|
|
||||||
page = 1
|
|
||||||
}
|
|
||||||
if size <= 0 {
|
|
||||||
size = 10
|
|
||||||
}
|
|
||||||
var total int64
|
|
||||||
var list []*Rule
|
|
||||||
db := m.db.WithContext(ctx).Model(&Rule{})
|
|
||||||
if ruleType != "" {
|
|
||||||
db = db.Where("type = ?", ruleType)
|
|
||||||
}
|
|
||||||
if enabled != nil {
|
|
||||||
db = db.Where("enabled = ?", *enabled)
|
|
||||||
}
|
|
||||||
if search != "" {
|
|
||||||
db = db.Where("name LIKE ?", "%"+search+"%")
|
|
||||||
}
|
|
||||||
if err := db.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := db.Order("priority DESC").Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) UpsertPrices(ctx context.Context, ruleId int64, items []*SubscribePromo) error {
|
|
||||||
return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
||||||
for _, item := range items {
|
|
||||||
if item == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
item.PromoRuleId = ruleId
|
|
||||||
var existing SubscribePromo
|
|
||||||
err := tx.Model(&SubscribePromo{}).
|
|
||||||
Where("subscribe_id = ? AND quantity = ? AND promo_rule_id = ?", item.SubscribeId, item.Quantity, ruleId).
|
|
||||||
First(&existing).Error
|
|
||||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return tx.Create(item).Error
|
|
||||||
}
|
|
||||||
existing.Quantity = item.Quantity
|
|
||||||
existing.PromoPrice = item.PromoPrice
|
|
||||||
if err := tx.Save(&existing).Error; err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) FindPrice(ctx context.Context, id int64) (*SubscribePromo, error) {
|
|
||||||
var resp SubscribePromo
|
|
||||||
if err := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("id = ?", id).First(&resp).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) DeletePrice(ctx context.Context, id int64) error {
|
|
||||||
return m.db.WithContext(ctx).Delete(&SubscribePromo{}, id).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryPriceList(ctx context.Context, ruleId int64, page, size int) (int64, []*SubscribePromo, error) {
|
|
||||||
if page <= 0 {
|
|
||||||
page = 1
|
|
||||||
}
|
|
||||||
if size <= 0 {
|
|
||||||
size = 10
|
|
||||||
}
|
|
||||||
var total int64
|
|
||||||
var list []*SubscribePromo
|
|
||||||
db := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("promo_rule_id = ?", ruleId)
|
|
||||||
if err := db.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := db.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error) {
|
|
||||||
if params.Page <= 0 {
|
|
||||||
params.Page = 1
|
|
||||||
}
|
|
||||||
if params.Size <= 0 {
|
|
||||||
params.Size = 10
|
|
||||||
}
|
|
||||||
var total int64
|
|
||||||
var list []*Usage
|
|
||||||
db := m.db.WithContext(ctx).Model(&Usage{})
|
|
||||||
if params.RuleId > 0 {
|
|
||||||
db = db.Where("promo_rule_id = ?", params.RuleId)
|
|
||||||
}
|
|
||||||
if params.UserId > 0 {
|
|
||||||
db = db.Where("user_id = ?", params.UserId)
|
|
||||||
}
|
|
||||||
if params.SubscribeId > 0 {
|
|
||||||
db = db.Where("subscribe_id = ?", params.SubscribeId)
|
|
||||||
}
|
|
||||||
if params.OrderNo != "" {
|
|
||||||
db = db.Where("order_no = ?", params.OrderNo)
|
|
||||||
}
|
|
||||||
if err := db.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := db.Order("id DESC").Limit(params.Size).Offset((params.Page - 1) * params.Size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
|
|
||||||
return m.db.WithContext(ctx).Transaction(fn)
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
RuleTypeNewUser = "new_user"
|
|
||||||
RuleTypeInactiveUser = "inactive_user"
|
|
||||||
RuleTypeCampaign = "campaign"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Rule struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
Name string `gorm:"type:varchar(100);not null;default:'';comment:Rule Name"`
|
|
||||||
Type string `gorm:"type:varchar(32);not null;default:'';comment:Rule Type"`
|
|
||||||
Params string `gorm:"type:json;not null;comment:Rule Params"`
|
|
||||||
Priority int64 `gorm:"type:int;not null;default:0;comment:Priority"`
|
|
||||||
Enabled bool `gorm:"type:tinyint(1);not null;default:1;comment:Enabled"`
|
|
||||||
StartTime *time.Time `gorm:"default:null;comment:Start Time"`
|
|
||||||
EndTime *time.Time `gorm:"default:null;comment:End Time"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
DeletedAt gorm.DeletedAt `gorm:"index;comment:Delete Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Rule) TableName() string {
|
|
||||||
return "promo_rule"
|
|
||||||
}
|
|
||||||
|
|
||||||
type SubscribePromo struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
|
||||||
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
|
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
|
||||||
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (SubscribePromo) TableName() string {
|
|
||||||
return "subscribe_promo"
|
|
||||||
}
|
|
||||||
|
|
||||||
type Usage struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
UserId int64 `gorm:"type:bigint unsigned;not null;comment:User ID"`
|
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
|
||||||
OrderNo string `gorm:"type:varchar(255);not null;default:'';comment:Order No"`
|
|
||||||
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Usage) TableName() string {
|
|
||||||
return "promo_usage"
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package promo_rule
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/pkg/cache"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ Model = (*customPromoRuleModel)(nil)
|
||||||
|
|
||||||
|
var cachePromoRuleIdPrefix = "cache:promo_rule:id:"
|
||||||
|
|
||||||
|
type (
|
||||||
|
Model interface {
|
||||||
|
promoRuleModel
|
||||||
|
customPromoRuleLogicModel
|
||||||
|
}
|
||||||
|
|
||||||
|
promoRuleModel interface {
|
||||||
|
Insert(ctx context.Context, data *PromoRule, tx ...*gorm.DB) error
|
||||||
|
FindOne(ctx context.Context, id int64) (*PromoRule, error)
|
||||||
|
Update(ctx context.Context, data *PromoRule, tx ...*gorm.DB) error
|
||||||
|
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
|
||||||
|
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
|
||||||
|
}
|
||||||
|
|
||||||
|
customPromoRuleModel struct {
|
||||||
|
*defaultPromoRuleModel
|
||||||
|
}
|
||||||
|
defaultPromoRuleModel struct {
|
||||||
|
cache.CachedConn
|
||||||
|
table string
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func newPromoRuleModel(db *gorm.DB, c *redis.Client) *defaultPromoRuleModel {
|
||||||
|
return &defaultPromoRuleModel{
|
||||||
|
CachedConn: cache.NewConn(db, c),
|
||||||
|
table: "`promo_rule`",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoRuleModel) getCacheKeys(data *PromoRule) []string {
|
||||||
|
if data == nil {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
return []string{fmt.Sprintf("%s%v", cachePromoRuleIdPrefix, data.Id)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoRuleModel) Insert(ctx context.Context, data *PromoRule, tx ...*gorm.DB) error {
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Create(data).Error
|
||||||
|
}, m.getCacheKeys(data)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoRuleModel) FindOne(ctx context.Context, id int64) (*PromoRule, error) {
|
||||||
|
key := fmt.Sprintf("%s%v", cachePromoRuleIdPrefix, id)
|
||||||
|
var resp PromoRule
|
||||||
|
err := m.QueryCtx(ctx, &resp, key, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&PromoRule{}).Where("`id` = ?", id).First(v).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoRuleModel) Update(ctx context.Context, data *PromoRule, tx ...*gorm.DB) error {
|
||||||
|
old, err := m.FindOne(ctx, data.Id)
|
||||||
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Save(data).Error
|
||||||
|
}, m.getCacheKeys(old)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoRuleModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error {
|
||||||
|
data, err := m.FindOne(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Delete(&PromoRule{}, id).Error
|
||||||
|
}, m.getCacheKeys(data)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoRuleModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
|
||||||
|
return m.TransactCtx(ctx, fn)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package promo_rule
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type customPromoRuleLogicModel interface {
|
||||||
|
QueryEnabledByPriority(ctx context.Context) ([]*PromoRule, error)
|
||||||
|
QueryAvailableByPriority(ctx context.Context, now time.Time) ([]*PromoRule, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewModel(conn *gorm.DB, c *redis.Client) Model {
|
||||||
|
return &customPromoRuleModel{
|
||||||
|
defaultPromoRuleModel: newPromoRuleModel(conn, c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customPromoRuleModel) QueryEnabledByPriority(ctx context.Context) ([]*PromoRule, error) {
|
||||||
|
var list []*PromoRule
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&PromoRule{}).
|
||||||
|
Where("enabled = ?", true).
|
||||||
|
Order("priority DESC, id DESC").
|
||||||
|
Find(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customPromoRuleModel) QueryAvailableByPriority(ctx context.Context, now time.Time) ([]*PromoRule, error) {
|
||||||
|
var list []*PromoRule
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&PromoRule{}).
|
||||||
|
Where("enabled = ?", true).
|
||||||
|
Where("(start_time IS NULL OR start_time <= ?)", now).
|
||||||
|
Where("(end_time IS NULL OR end_time >= ?)", now).
|
||||||
|
Order("priority DESC, id DESC").
|
||||||
|
Find(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package promo_rule
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JSONRawMessage json.RawMessage
|
||||||
|
|
||||||
|
func (j *JSONRawMessage) Scan(value interface{}) error {
|
||||||
|
if value == nil {
|
||||||
|
*j = JSONRawMessage([]byte("{}"))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch v := value.(type) {
|
||||||
|
case []byte:
|
||||||
|
*j = JSONRawMessage(v)
|
||||||
|
case string:
|
||||||
|
*j = JSONRawMessage([]byte(v))
|
||||||
|
default:
|
||||||
|
*j = JSONRawMessage([]byte("{}"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j JSONRawMessage) Value() (driver.Value, error) {
|
||||||
|
if len(j) == 0 {
|
||||||
|
return "{}", nil
|
||||||
|
}
|
||||||
|
data, err := json.RawMessage(j).MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return string(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j JSONRawMessage) MarshalJSON() ([]byte, error) {
|
||||||
|
if len(j) == 0 {
|
||||||
|
return []byte("{}"), nil
|
||||||
|
}
|
||||||
|
return json.RawMessage(j).MarshalJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *JSONRawMessage) UnmarshalJSON(data []byte) error {
|
||||||
|
if len(data) == 0 {
|
||||||
|
*j = JSONRawMessage([]byte("{}"))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
*j = JSONRawMessage(data)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromoRule struct {
|
||||||
|
Id int64 `gorm:"type:bigint unsigned;primaryKey"`
|
||||||
|
Name string `gorm:"type:varchar(100);not null;default:'';comment:Rule Name"`
|
||||||
|
Type string `gorm:"type:varchar(32);not null;default:'';comment:Rule Type: new_user, inactive_user, campaign"`
|
||||||
|
Params JSONRawMessage `gorm:"type:json;not null;comment:Rule Params"`
|
||||||
|
Priority int64 `gorm:"type:int;not null;default:0;index:idx_enabled_priority,priority:2,sort:desc;comment:Priority"`
|
||||||
|
Enabled bool `gorm:"type:tinyint(1);not null;default:1;index:idx_enabled_priority,priority:1;comment:Enabled"`
|
||||||
|
StartTime *time.Time `gorm:"type:datetime;default:null;comment:Start Time"`
|
||||||
|
EndTime *time.Time `gorm:"type:datetime;default:null;comment:End Time"`
|
||||||
|
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||||
|
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index;comment:Delete Time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (PromoRule) TableName() string {
|
||||||
|
return "promo_rule"
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package promo_usage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/pkg/cache"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ Model = (*customPromoUsageModel)(nil)
|
||||||
|
|
||||||
|
var cachePromoUsageIdPrefix = "cache:promo_usage:id:"
|
||||||
|
|
||||||
|
type (
|
||||||
|
Model interface {
|
||||||
|
promoUsageModel
|
||||||
|
customPromoUsageLogicModel
|
||||||
|
}
|
||||||
|
|
||||||
|
promoUsageModel interface {
|
||||||
|
Insert(ctx context.Context, data *PromoUsage, tx ...*gorm.DB) error
|
||||||
|
FindOne(ctx context.Context, id int64) (*PromoUsage, error)
|
||||||
|
Update(ctx context.Context, data *PromoUsage, tx ...*gorm.DB) error
|
||||||
|
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
|
||||||
|
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
|
||||||
|
}
|
||||||
|
|
||||||
|
customPromoUsageModel struct {
|
||||||
|
*defaultPromoUsageModel
|
||||||
|
}
|
||||||
|
defaultPromoUsageModel struct {
|
||||||
|
cache.CachedConn
|
||||||
|
table string
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func newPromoUsageModel(db *gorm.DB, c *redis.Client) *defaultPromoUsageModel {
|
||||||
|
return &defaultPromoUsageModel{
|
||||||
|
CachedConn: cache.NewConn(db, c),
|
||||||
|
table: "`promo_usage`",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoUsageModel) getCacheKeys(data *PromoUsage) []string {
|
||||||
|
if data == nil {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
return []string{fmt.Sprintf("%s%v", cachePromoUsageIdPrefix, data.Id)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoUsageModel) Insert(ctx context.Context, data *PromoUsage, tx ...*gorm.DB) error {
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Create(data).Error
|
||||||
|
}, m.getCacheKeys(data)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoUsageModel) FindOne(ctx context.Context, id int64) (*PromoUsage, error) {
|
||||||
|
key := fmt.Sprintf("%s%v", cachePromoUsageIdPrefix, id)
|
||||||
|
var resp PromoUsage
|
||||||
|
err := m.QueryCtx(ctx, &resp, key, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&PromoUsage{}).Where("`id` = ?", id).First(v).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoUsageModel) Update(ctx context.Context, data *PromoUsage, tx ...*gorm.DB) error {
|
||||||
|
old, err := m.FindOne(ctx, data.Id)
|
||||||
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Save(data).Error
|
||||||
|
}, m.getCacheKeys(old)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoUsageModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error {
|
||||||
|
data, err := m.FindOne(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Delete(&PromoUsage{}, id).Error
|
||||||
|
}, m.getCacheKeys(data)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultPromoUsageModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
|
||||||
|
return m.TransactCtx(ctx, fn)
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package promo_usage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type customPromoUsageLogicModel interface {
|
||||||
|
FindByOrderNo(ctx context.Context, orderNo string) ([]*PromoUsage, error)
|
||||||
|
FindByUserAndRule(ctx context.Context, userId, promoRuleId int64) ([]*PromoUsage, error)
|
||||||
|
QueryListByPage(ctx context.Context, page, size int, userId, promoRuleId, subscribeId int64) (int64, []*PromoUsage, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewModel(conn *gorm.DB, c *redis.Client) Model {
|
||||||
|
return &customPromoUsageModel{
|
||||||
|
defaultPromoUsageModel: newPromoUsageModel(conn, c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customPromoUsageModel) FindByOrderNo(ctx context.Context, orderNo string) ([]*PromoUsage, error) {
|
||||||
|
var list []*PromoUsage
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&PromoUsage{}).
|
||||||
|
Where("order_no = ?", orderNo).
|
||||||
|
Order("id DESC").
|
||||||
|
Find(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customPromoUsageModel) FindByUserAndRule(ctx context.Context, userId, promoRuleId int64) ([]*PromoUsage, error) {
|
||||||
|
var list []*PromoUsage
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&PromoUsage{}).
|
||||||
|
Where("user_id = ? AND promo_rule_id = ?", userId, promoRuleId).
|
||||||
|
Order("id DESC").
|
||||||
|
Find(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customPromoUsageModel) QueryListByPage(ctx context.Context, page, size int, userId, promoRuleId, subscribeId int64) (int64, []*PromoUsage, error) {
|
||||||
|
var list []*PromoUsage
|
||||||
|
var total int64
|
||||||
|
if page <= 0 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if size <= 0 {
|
||||||
|
size = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
db := conn.Model(&PromoUsage{})
|
||||||
|
if userId > 0 {
|
||||||
|
db = db.Where("user_id = ?", userId)
|
||||||
|
}
|
||||||
|
if promoRuleId > 0 {
|
||||||
|
db = db.Where("promo_rule_id = ?", promoRuleId)
|
||||||
|
}
|
||||||
|
if subscribeId > 0 {
|
||||||
|
db = db.Where("subscribe_id = ?", subscribeId)
|
||||||
|
}
|
||||||
|
if err := db.Count(&total).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return db.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(v).Error
|
||||||
|
})
|
||||||
|
return total, list, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package promo_usage
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type PromoUsage struct {
|
||||||
|
Id int64 `gorm:"type:bigint unsigned;primaryKey"`
|
||||||
|
UserId int64 `gorm:"type:bigint unsigned;not null;index:idx_user_rule,priority:1;comment:User Id"`
|
||||||
|
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;index:idx_user_rule,priority:2;comment:Promo Rule Id"`
|
||||||
|
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe Id"`
|
||||||
|
OrderNo string `gorm:"type:varchar(255);not null;default:'';index:idx_order_no;comment:Order No"`
|
||||||
|
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
||||||
|
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (PromoUsage) TableName() string {
|
||||||
|
return "promo_usage"
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package subscribe_promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/pkg/cache"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ Model = (*customSubscribePromoModel)(nil)
|
||||||
|
|
||||||
|
var cacheSubscribePromoIdPrefix = "cache:subscribe_promo:id:"
|
||||||
|
|
||||||
|
type (
|
||||||
|
Model interface {
|
||||||
|
subscribePromoModel
|
||||||
|
customSubscribePromoLogicModel
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribePromoModel interface {
|
||||||
|
Insert(ctx context.Context, data *SubscribePromo, tx ...*gorm.DB) error
|
||||||
|
FindOne(ctx context.Context, id int64) (*SubscribePromo, error)
|
||||||
|
Update(ctx context.Context, data *SubscribePromo, tx ...*gorm.DB) error
|
||||||
|
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
|
||||||
|
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
|
||||||
|
}
|
||||||
|
|
||||||
|
customSubscribePromoModel struct {
|
||||||
|
*defaultSubscribePromoModel
|
||||||
|
}
|
||||||
|
defaultSubscribePromoModel struct {
|
||||||
|
cache.CachedConn
|
||||||
|
table string
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func newSubscribePromoModel(db *gorm.DB, c *redis.Client) *defaultSubscribePromoModel {
|
||||||
|
return &defaultSubscribePromoModel{
|
||||||
|
CachedConn: cache.NewConn(db, c),
|
||||||
|
table: "`subscribe_promo`",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultSubscribePromoModel) getCacheKeys(data *SubscribePromo) []string {
|
||||||
|
if data == nil {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
return []string{fmt.Sprintf("%s%v", cacheSubscribePromoIdPrefix, data.Id)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultSubscribePromoModel) Insert(ctx context.Context, data *SubscribePromo, tx ...*gorm.DB) error {
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Create(data).Error
|
||||||
|
}, m.getCacheKeys(data)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultSubscribePromoModel) FindOne(ctx context.Context, id int64) (*SubscribePromo, error) {
|
||||||
|
key := fmt.Sprintf("%s%v", cacheSubscribePromoIdPrefix, id)
|
||||||
|
var resp SubscribePromo
|
||||||
|
err := m.QueryCtx(ctx, &resp, key, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&SubscribePromo{}).Where("`id` = ?", id).First(v).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultSubscribePromoModel) Update(ctx context.Context, data *SubscribePromo, tx ...*gorm.DB) error {
|
||||||
|
old, err := m.FindOne(ctx, data.Id)
|
||||||
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Save(data).Error
|
||||||
|
}, m.getCacheKeys(old)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultSubscribePromoModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error {
|
||||||
|
data, err := m.FindOne(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
|
if len(tx) > 0 {
|
||||||
|
conn = tx[0]
|
||||||
|
}
|
||||||
|
return conn.Delete(&SubscribePromo{}, id).Error
|
||||||
|
}, m.getCacheKeys(data)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *defaultSubscribePromoModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
|
||||||
|
return m.TransactCtx(ctx, fn)
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package subscribe_promo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/model/promo_rule"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RulePromo struct {
|
||||||
|
Id int64
|
||||||
|
SubscribeId int64
|
||||||
|
PromoRuleId int64
|
||||||
|
PromoPrice int64
|
||||||
|
RuleName string
|
||||||
|
RuleType string
|
||||||
|
Params promo_rule.JSONRawMessage
|
||||||
|
Priority int64
|
||||||
|
StartTime *time.Time
|
||||||
|
EndTime *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type customSubscribePromoLogicModel interface {
|
||||||
|
FindOneBySubscribeAndRule(ctx context.Context, subscribeId, promoRuleId int64) (*SubscribePromo, error)
|
||||||
|
FindBySubscribeId(ctx context.Context, subscribeId int64) ([]*SubscribePromo, error)
|
||||||
|
FindByPromoRuleId(ctx context.Context, promoRuleId int64) ([]*SubscribePromo, error)
|
||||||
|
QueryEnabledBySubscribeId(ctx context.Context, subscribeId int64) ([]*RulePromo, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewModel(conn *gorm.DB, c *redis.Client) Model {
|
||||||
|
return &customSubscribePromoModel{
|
||||||
|
defaultSubscribePromoModel: newSubscribePromoModel(conn, c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customSubscribePromoModel) FindOneBySubscribeAndRule(ctx context.Context, subscribeId, promoRuleId int64) (*SubscribePromo, error) {
|
||||||
|
var resp SubscribePromo
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &resp, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&SubscribePromo{}).
|
||||||
|
Where("subscribe_id = ? AND promo_rule_id = ?", subscribeId, promoRuleId).
|
||||||
|
First(v).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customSubscribePromoModel) FindBySubscribeId(ctx context.Context, subscribeId int64) ([]*SubscribePromo, error) {
|
||||||
|
var list []*SubscribePromo
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&SubscribePromo{}).
|
||||||
|
Where("subscribe_id = ?", subscribeId).
|
||||||
|
Order("id DESC").
|
||||||
|
Find(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customSubscribePromoModel) FindByPromoRuleId(ctx context.Context, promoRuleId int64) ([]*SubscribePromo, error) {
|
||||||
|
var list []*SubscribePromo
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Model(&SubscribePromo{}).
|
||||||
|
Where("promo_rule_id = ?", promoRuleId).
|
||||||
|
Order("id DESC").
|
||||||
|
Find(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *customSubscribePromoModel) QueryEnabledBySubscribeId(ctx context.Context, subscribeId int64) ([]*RulePromo, error) {
|
||||||
|
var list []*RulePromo
|
||||||
|
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
|
||||||
|
return conn.Table("subscribe_promo AS sp").
|
||||||
|
Select("sp.id, sp.subscribe_id, sp.promo_rule_id, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.priority, pr.start_time, pr.end_time").
|
||||||
|
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
|
||||||
|
Where("sp.subscribe_id = ? AND pr.enabled = ?", subscribeId, true).
|
||||||
|
Order("pr.priority DESC, pr.id DESC").
|
||||||
|
Scan(v).Error
|
||||||
|
})
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package subscribe_promo
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type SubscribePromo struct {
|
||||||
|
Id int64 `gorm:"type:bigint unsigned;primaryKey"`
|
||||||
|
SubscribeId int64 `gorm:"type:bigint unsigned;not null;index:uk_subscribe_rule,unique,priority:1;comment:Subscribe Id"`
|
||||||
|
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;index:uk_subscribe_rule,unique,priority:2;index:idx_promo_rule_id;comment:Promo Rule Id"`
|
||||||
|
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
||||||
|
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||||
|
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (SubscribePromo) TableName() string {
|
||||||
|
return "subscribe_promo"
|
||||||
|
}
|
||||||
@@ -21,8 +21,10 @@ import (
|
|||||||
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
"github.com/perfect-panel/server/internal/model/payment"
|
"github.com/perfect-panel/server/internal/model/payment"
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
"github.com/perfect-panel/server/internal/model/promo_rule"
|
||||||
|
"github.com/perfect-panel/server/internal/model/promo_usage"
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
|
"github.com/perfect-panel/server/internal/model/subscribe_promo"
|
||||||
"github.com/perfect-panel/server/internal/model/system"
|
"github.com/perfect-panel/server/internal/model/system"
|
||||||
"github.com/perfect-panel/server/internal/model/ticket"
|
"github.com/perfect-panel/server/internal/model/ticket"
|
||||||
"github.com/perfect-panel/server/internal/model/traffic"
|
"github.com/perfect-panel/server/internal/model/traffic"
|
||||||
@@ -64,9 +66,11 @@ type ServiceContext struct {
|
|||||||
RedemptionCodeModel redemption.RedemptionCodeModel
|
RedemptionCodeModel redemption.RedemptionCodeModel
|
||||||
RedemptionRecordModel redemption.RedemptionRecordModel
|
RedemptionRecordModel redemption.RedemptionRecordModel
|
||||||
PaymentModel payment.Model
|
PaymentModel payment.Model
|
||||||
PromoModel promo.Model
|
|
||||||
DocumentModel document.Model
|
DocumentModel document.Model
|
||||||
SubscribeModel subscribe.Model
|
SubscribeModel subscribe.Model
|
||||||
|
PromoRuleModel promo_rule.Model
|
||||||
|
SubscribePromoModel subscribe_promo.Model
|
||||||
|
PromoUsageModel promo_usage.Model
|
||||||
TrafficLogModel traffic.Model
|
TrafficLogModel traffic.Model
|
||||||
AnnouncementModel announcement.Model
|
AnnouncementModel announcement.Model
|
||||||
IAPAppleTransactionModel iapapple.Model
|
IAPAppleTransactionModel iapapple.Model
|
||||||
@@ -140,9 +144,11 @@ func NewServiceContext(c config.Config) *ServiceContext {
|
|||||||
RedemptionCodeModel: redemption.NewRedemptionCodeModel(db, rds),
|
RedemptionCodeModel: redemption.NewRedemptionCodeModel(db, rds),
|
||||||
RedemptionRecordModel: redemption.NewRedemptionRecordModel(db, rds),
|
RedemptionRecordModel: redemption.NewRedemptionRecordModel(db, rds),
|
||||||
PaymentModel: payment.NewModel(db, rds),
|
PaymentModel: payment.NewModel(db, rds),
|
||||||
PromoModel: promo.NewModel(db, rds),
|
|
||||||
DocumentModel: document.NewModel(db, rds),
|
DocumentModel: document.NewModel(db, rds),
|
||||||
SubscribeModel: subscribe.NewModel(db, rds),
|
SubscribeModel: subscribe.NewModel(db, rds),
|
||||||
|
PromoRuleModel: promo_rule.NewModel(db, rds),
|
||||||
|
SubscribePromoModel: subscribe_promo.NewModel(db, rds),
|
||||||
|
PromoUsageModel: promo_usage.NewModel(db, rds),
|
||||||
TrafficLogModel: traffic.NewModel(db),
|
TrafficLogModel: traffic.NewModel(db),
|
||||||
AnnouncementModel: announcement.NewModel(db, rds),
|
AnnouncementModel: announcement.NewModel(db, rds),
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-130
@@ -316,45 +316,6 @@ type ContactRequest struct {
|
|||||||
Notes string `json:"notes" validate:"max=2000"`
|
Notes string `json:"notes" validate:"max=2000"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PromoPrice struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
Quantity int64 `json:"quantity"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoPriceItem struct {
|
|
||||||
SubscribeId int64 `json:"subscribe_id" validate:"required,gt=0"`
|
|
||||||
Quantity int64 `json:"quantity" validate:"required,gt=0,lte=1000"`
|
|
||||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoRule struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Params map[string]interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
StartTime *int64 `json:"start_time"`
|
|
||||||
EndTime *int64 `json:"end_time"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoUsage struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"user_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Coupon struct {
|
type Coupon struct {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -414,16 +375,6 @@ type CreateCouponRequest struct {
|
|||||||
Enable *bool `json:"enable,omitempty"`
|
Enable *bool `json:"enable,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreatePromoRuleRequest struct {
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params map[string]interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled"`
|
|
||||||
StartTime *int64 `json:"start_time"`
|
|
||||||
EndTime *int64 `json:"end_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreateDocumentRequest struct {
|
type CreateDocumentRequest struct {
|
||||||
Title string `json:"title" validate:"required"`
|
Title string `json:"title" validate:"required"`
|
||||||
Content string `json:"content" validate:"required"`
|
Content string `json:"content" validate:"required"`
|
||||||
@@ -828,7 +779,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 {
|
||||||
@@ -836,7 +793,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 {
|
||||||
@@ -1145,48 +1107,6 @@ type GetCouponListResponse struct {
|
|||||||
List []Coupon `json:"list"`
|
List []Coupon `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetPromoPriceListRequest struct {
|
|
||||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"`
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoPriceListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoPrice `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleDetailRequest struct {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
|
||||||
Enabled *bool `form:"enabled"`
|
|
||||||
Search string `form:"search,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoRule `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoUsageListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
RuleId int64 `form:"rule_id,omitempty"`
|
|
||||||
UserId int64 `form:"user_id,omitempty"`
|
|
||||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
|
||||||
OrderNo string `form:"order_no,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoUsageListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoUsage `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetDetailRequest struct {
|
type GetDetailRequest struct {
|
||||||
Id int64 `form:"id" validate:"required"`
|
Id int64 `form:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -1948,8 +1868,6 @@ type Order struct {
|
|||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
Commission int64 `json:"commission,omitempty"`
|
Commission int64 `json:"commission,omitempty"`
|
||||||
@@ -1973,8 +1891,6 @@ type OrderDetail struct {
|
|||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
Commission int64 `json:"commission,omitempty"`
|
Commission int64 `json:"commission,omitempty"`
|
||||||
@@ -2096,7 +2012,6 @@ type PreOrderResponse struct {
|
|||||||
Price int64 `json:"price"`
|
Price int64 `json:"price"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
@@ -2865,13 +2780,6 @@ type StripePayment struct {
|
|||||||
PublishableKey string `json:"publishable_key"`
|
PublishableKey string `json:"publishable_key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscribePromo struct {
|
|
||||||
RuleName string `json:"rule_name"`
|
|
||||||
RuleType string `json:"rule_type"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Subscribe struct {
|
type Subscribe struct {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -2880,7 +2788,6 @@ type Subscribe struct {
|
|||||||
UnitPrice int64 `json:"unit_price"`
|
UnitPrice int64 `json:"unit_price"`
|
||||||
UnitTime string `json:"unit_time"`
|
UnitTime string `json:"unit_time"`
|
||||||
Discount []SubscribeDiscount `json:"discount"`
|
Discount []SubscribeDiscount `json:"discount"`
|
||||||
Promo *SubscribePromo `json:"promo"`
|
|
||||||
NodeCount int64 `json:"node_count"`
|
NodeCount int64 `json:"node_count"`
|
||||||
Replacement int64 `json:"replacement"`
|
Replacement int64 `json:"replacement"`
|
||||||
Inventory int64 `json:"inventory"`
|
Inventory int64 `json:"inventory"`
|
||||||
@@ -3221,30 +3128,6 @@ type UpdateCouponRequest struct {
|
|||||||
Enable *bool `json:"enable,omitempty"`
|
Enable *bool `json:"enable,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SetPromoPriceRequest struct {
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
|
|
||||||
Items []PromoPriceItem `json:"items" validate:"required,dive"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeletePromoPriceRequest struct {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeletePromoRuleRequest struct {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdatePromoRuleRequest struct {
|
|
||||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params map[string]interface{} `json:"params"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled"`
|
|
||||||
StartTime *int64 `json:"start_time"`
|
|
||||||
EndTime *int64 `json:"end_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateDocumentRequest struct {
|
type UpdateDocumentRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
Title string `json:"title" validate:"required"`
|
Title string `json:"title" validate:"required"`
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/hibiken/asynq"
|
"github.com/hibiken/asynq"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/model/redemption"
|
"github.com/perfect-panel/server/internal/model/redemption"
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
@@ -149,7 +148,6 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
l.recordPromoUsage(ctx, orderInfo)
|
|
||||||
l.finalizeCouponAndOrder(ctx, orderInfo)
|
l.finalizeCouponAndOrder(ctx, orderInfo)
|
||||||
|
|
||||||
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished",
|
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished",
|
||||||
@@ -159,44 +157,6 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) {
|
|
||||||
if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
promoPrice := int64(0)
|
|
||||||
if orderInfo.Price > orderInfo.PromoDiscount {
|
|
||||||
promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity
|
|
||||||
}
|
|
||||||
if promoPrice <= 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
||||||
var count int64
|
|
||||||
if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil {
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
if count > 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return l.svc.PromoModel.InsertUsage(ctx, &promo.Usage{
|
|
||||||
UserId: orderInfo.UserId,
|
|
||||||
PromoRuleId: orderInfo.PromoRuleId,
|
|
||||||
SubscribeId: orderInfo.SubscribeId,
|
|
||||||
OrderNo: orderInfo.OrderNo,
|
|
||||||
PromoPrice: promoPrice,
|
|
||||||
}, tx)
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(ctx).Error("Insert promo usage failed",
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
logger.Field("order_no", orderInfo.OrderNo),
|
|
||||||
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parsePayload unMarshals the task payload into a structured format
|
// parsePayload unMarshals the task payload into a structured format
|
||||||
func (l *ActivateOrderLogic) parsePayload(ctx context.Context, payload []byte) (*queueTypes.ForthwithActivateOrderPayload, error) {
|
func (l *ActivateOrderLogic) parsePayload(ctx context.Context, payload []byte) (*queueTypes.ForthwithActivateOrderPayload, error) {
|
||||||
var p queueTypes.ForthwithActivateOrderPayload
|
var p queueTypes.ForthwithActivateOrderPayload
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
//go:build ignore
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
// Package scripts keeps standalone maintenance tools out of normal package
|
|
||||||
// builds. Run individual tools with go run scripts/<tool>.go.
|
|
||||||
package scripts
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
//go:build ignore
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
Reference in New Issue
Block a user