Compare commits
12 Commits
v1.1.0
...
9d996acf5f
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d996acf5f | |||
| 99853b8514 | |||
| efce18e6f5 | |||
| 3dc9bc5b1d | |||
| 7fe415de63 | |||
| 8e42fad8aa | |||
| 7a3c47f1d4 | |||
| dfbb3a9acc | |||
| 19fa8b381c | |||
| b7a9682552 | |||
| f638baec64 | |||
| 1262a8dae4 |
@@ -2,7 +2,7 @@ name: Docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
branches: ["v*"]
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
@@ -10,14 +10,12 @@ env:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
23
README.md
23
README.md
@@ -1,5 +1,7 @@
|
||||
## TODO
|
||||
|
||||
后端默认用户名不能是完整手机号
|
||||
|
||||
前端需要 token 化改造,以避免每次 basic 认证流程中 bcrypt 对比导致的性能对比
|
||||
|
||||
优化中间件,配置通用限速
|
||||
@@ -40,12 +42,27 @@ http 调用 clients 的初始化函数
|
||||
jsonb 类型转换问题,考虑一个高效的 any 到 struct 转换工具
|
||||
|
||||
慢速请求底层调用埋点监控
|
||||
|
||||
- redis
|
||||
- gorm
|
||||
- 三方接口
|
||||
|
||||
冷数据迁移方案
|
||||
|
||||
|
||||
## 开发环境
|
||||
|
||||
### 更新表结构的流程
|
||||
|
||||
1. 编辑 `scripts/sql/init.sql` 文件,参照原有格式,需要注意:
|
||||
- 先写 drop table if exists 语句,确保脚本可以幂等执行
|
||||
- 编写 create table 语句,按需添加审计字段和软删除字段 (created_at, updated_at, deleted_at)
|
||||
- 为有必要的字段添加索引
|
||||
- 为数据表及其字段添加注释
|
||||
- 在文件末尾创建数据表流程全部结束后,为字段添加外键
|
||||
2. 建议用数据库工具检查差异并增量更新,或者手动增量更新
|
||||
3. 创建 model 文件,并将其添加到 gen 代码中
|
||||
4. 生成查询文件
|
||||
|
||||
## 业务逻辑
|
||||
|
||||
### 订单关闭的几种方式
|
||||
@@ -64,7 +81,8 @@ jsonb 类型转换问题,考虑一个高效的 any 到 struct 转换工具
|
||||
|
||||
### 节点分配与存储逻辑
|
||||
|
||||
提取:
|
||||
提取:
|
||||
|
||||
- 检查用户套餐与白名单
|
||||
- 选中代理
|
||||
- 找到当前可用端口最多的代理
|
||||
@@ -76,6 +94,7 @@ jsonb 类型转换问题,考虑一个高效的 any 到 struct 转换工具
|
||||
- 分别提交连接与配置请求
|
||||
|
||||
释放:
|
||||
|
||||
- 根据批次查出所有端口与相关节点
|
||||
- 分别提交断开与关闭请求
|
||||
- 释放端口
|
||||
|
||||
@@ -51,6 +51,8 @@ func main() {
|
||||
m.LogsUserUsage{},
|
||||
m.Permission{},
|
||||
m.Product{},
|
||||
m.ProductSku{},
|
||||
m.ProductSkuUser{},
|
||||
m.Proxy{},
|
||||
m.Refund{},
|
||||
m.Resource{},
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
# Docker 部署说明
|
||||
|
||||
本文档说明如何使用 Docker 构建和部署平台服务。
|
||||
|
||||
## 构建镜像
|
||||
|
||||
在项目根目录下执行以下命令构建 Docker 镜像:
|
||||
|
||||
```bash
|
||||
docker build -t platform:latest .
|
||||
```
|
||||
|
||||
## 生产环境部署
|
||||
|
||||
由于涉及敏感的 `.pem` 证书文件,这些文件不包含在代码库或 Docker 镜像中,而是在运行时通过卷挂载的方式提供。
|
||||
|
||||
### 准备证书文件
|
||||
|
||||
1. 在生产服务器上创建一个目录用于存放证书文件,例如:`/path/to/certs/`
|
||||
2. 将必要的证书文件放入此目录:
|
||||
- `pub_key.pem`
|
||||
- `apiclient_key.pem`
|
||||
|
||||
### 运行容器
|
||||
|
||||
使用以下命令运行容器,挂载证书目录:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name platform \
|
||||
-p 8080:8080 \
|
||||
-e APP_PORT=8080 \
|
||||
-v /path/to/certs:/app/certs \
|
||||
platform:latest
|
||||
```
|
||||
|
||||
### 环境变量
|
||||
|
||||
可以通过环境变量来配置应用程序:
|
||||
|
||||
- `APP_PORT`: 应用监听的端口号(默认: 8080)
|
||||
- 其他应用相关的环境变量可以通过 `-e` 参数添加
|
||||
|
||||
### 证书路径配置
|
||||
|
||||
如果应用程序需要知道证书的路径,可以通过环境变量配置:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name platform \
|
||||
-p 8080:8080 \
|
||||
-e APP_PORT=8080 \
|
||||
-e PUB_KEY_PATH=/app/certs/pub_key.pem \
|
||||
-e APICLIENT_KEY_PATH=/app/certs/apiclient_key.pem \
|
||||
-v /path/to/certs:/app/certs \
|
||||
platform:latest
|
||||
```
|
||||
|
||||
## 使用 Docker Compose
|
||||
|
||||
也可以通过 Docker Compose 进行部署,创建 `docker-compose.yml` 文件:
|
||||
|
||||
```yaml
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
platform:
|
||||
image: platform:latest
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
- APP_PORT=8080
|
||||
- PUB_KEY_PATH=/app/certs/pub_key.pem
|
||||
- APICLIENT_KEY_PATH=/app/certs/apiclient_key.pem
|
||||
volumes:
|
||||
- /path/to/certs:/app/certs
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
然后执行:
|
||||
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
## 安全建议
|
||||
|
||||
1. 确保证书文件的权限设置正确,仅允许必要的用户访问
|
||||
2. 在生产环境中考虑使用 Docker Secrets 或 Kubernetes Secrets 来管理敏感信息
|
||||
3. 定期更新证书和密钥
|
||||
3
go.mod
3
go.mod
@@ -11,6 +11,7 @@ require (
|
||||
github.com/go-redsync/redsync/v4 v4.14.1
|
||||
github.com/gofiber/contrib/otelfiber/v2 v2.2.3
|
||||
github.com/gofiber/fiber/v2 v2.52.10
|
||||
github.com/gofiber/template/html/v2 v2.1.3
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/hibiken/asynq v0.25.1
|
||||
github.com/jdcloud-api/jdcloud-sdk-go v1.64.0
|
||||
@@ -54,6 +55,8 @@ require (
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-sql-driver/mysql v1.9.3 // indirect
|
||||
github.com/gofiber/template v1.8.3 // indirect
|
||||
github.com/gofiber/utils v1.1.0 // indirect
|
||||
github.com/gofrs/uuid v4.4.0+incompatible // indirect
|
||||
github.com/gomodule/redigo v2.0.0+incompatible // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
|
||||
|
||||
6
go.sum
6
go.sum
@@ -115,6 +115,12 @@ github.com/gofiber/contrib/otelfiber/v2 v2.2.3 h1:WKW1XezHFAoohGZwnvC0R8TFJcNkab
|
||||
github.com/gofiber/contrib/otelfiber/v2 v2.2.3/go.mod h1:WdQ1tYbL83IYC6oBaWvKBMVGSAYvSTRuUWTcr0wK1T4=
|
||||
github.com/gofiber/fiber/v2 v2.52.10 h1:jRHROi2BuNti6NYXmZ6gbNSfT3zj/8c0xy94GOU5elY=
|
||||
github.com/gofiber/fiber/v2 v2.52.10/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
||||
github.com/gofiber/template v1.8.3 h1:hzHdvMwMo/T2kouz2pPCA0zGiLCeMnoGsQZBTSYgZxc=
|
||||
github.com/gofiber/template v1.8.3/go.mod h1:bs/2n0pSNPOkRa5VJ8zTIvedcI/lEYxzV3+YPXdBvq8=
|
||||
github.com/gofiber/template/html/v2 v2.1.3 h1:n1LYBtmr9C0V/k/3qBblXyMxV5B0o/gpb6dFLp8ea+o=
|
||||
github.com/gofiber/template/html/v2 v2.1.3/go.mod h1:U5Fxgc5KpyujU9OqKzy6Kn6Qup6Tm7zdsISR+VpnHRE=
|
||||
github.com/gofiber/utils v1.1.0 h1:vdEBpn7AzIUJRhe+CiTOJdUcTg4Q9RK+pEa0KPbLdrM=
|
||||
github.com/gofiber/utils v1.1.0/go.mod h1:poZpsnhBykfnY1Mc0KeEa6mSHrS3dV0+oBWyeQmb2e0=
|
||||
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
|
||||
github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
|
||||
|
||||
16
publish.ps1
Normal file
16
publish.ps1
Normal file
@@ -0,0 +1,16 @@
|
||||
if (-not $args) {
|
||||
Write-Error "需要指定版本号"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$confrim = Read-Host "构建版本为 [platform:$($args[0])],是否继续?(y/n)"
|
||||
if ($confrim -ne "y") {
|
||||
Write-Host "已取消构建"
|
||||
exit 0
|
||||
}
|
||||
|
||||
docker build -t 43.226.58.254:53000/lanhu/platform:latest .
|
||||
docker build -t 43.226.58.254:53000/lanhu/platform:$($args[0]) .
|
||||
|
||||
docker push 43.226.58.254:53000/lanhu/platform:latest
|
||||
docker push 43.226.58.254:53000/lanhu/platform:$($args[0])
|
||||
@@ -2,11 +2,115 @@
|
||||
-- region 填充数据
|
||||
-- ====================
|
||||
|
||||
insert into client (
|
||||
client_id, client_secret, redirect_uri, spec, name, type
|
||||
)
|
||||
values (
|
||||
'web', '$2a$10$Ss12mXQgpYyo1CKIZ3URouDm.Lc2KcYJzsvEK2PTIXlv6fHQht45a', '', 3, 'web', 1
|
||||
);
|
||||
insert into client
|
||||
(client_id, client_secret, redirect_uri, spec, name, type)
|
||||
values
|
||||
('web', '$2a$10$Ss12mXQgpYyo1CKIZ3URouDm.Lc2KcYJzsvEK2PTIXlv6fHQht45a', '', 3, 'web', 1);
|
||||
|
||||
with pid as (
|
||||
insert into app.public.product
|
||||
(code, name, description)
|
||||
values
|
||||
('dynamic-short', '短效动态', '短效动态')
|
||||
returning id
|
||||
)
|
||||
insert into app.public.product_sku
|
||||
(product_id, code, name, price, discount)
|
||||
select pid.id, 'mode=quota,live=3,expire=0', '短效动态包量 3 分钟', 50, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=5,expire=0', '短效动态包量 5 分钟', 100, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=10,expire=0', '短效动态包量 10 分钟', 200, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=20,expire=0', '短效动态包量 20 分钟', 300, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=30,expire=0', '短效动态包量 30 分钟', 600, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=3,expire=7', '短效动态包时 7 天 3 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=3,expire=15', '短效动态包时 15 天 3 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=3,expire=30', '短效动态包时 30 天 3 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=3,expire=90', '短效动态包时 90 天 3 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=3,expire=180', '短效动态包时 180 天 3 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=3,expire=365', '短效动态包时 365 天 3 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=5,expire=7', '短效动态包时 7 天 5 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=5,expire=15', '短效动态包时 15 天 5 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=5,expire=30', '短效动态包时 30 天 5 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=5,expire=90', '短效动态包时 90 天 5 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=5,expire=180', '短效动态包时 180 天 5 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=5,expire=365', '短效动态包时 365 天 5 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=10,expire=7', '短效动态包时 7 天 10 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=10,expire=15', '短效动态包时 15 天 10 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=10,expire=30', '短效动态包时 30 天 10 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=10,expire=90', '短效动态包时 90 天 10 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=10,expire=180', '短效动态包时 180 天 10 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=10,expire=365', '短效动态包时 365 天 10 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=20,expire=7', '短效动态包时 7 天 20 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=20,expire=15', '短效动态包时 15 天 20 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=20,expire=30', '短效动态包时 30 天 20 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=20,expire=90', '短效动态包时 90 天 20 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=20,expire=180', '短效动态包时 180 天 20 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=20,expire=365', '短效动态包时 365 天 20 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=30,expire=7', '短效动态包时 7 天 30 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=30,expire=15', '短效动态包时 15 天 30 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=30,expire=30', '短效动态包时 30 天 30 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=30,expire=90', '短效动态包时 90 天 30 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=30,expire=180', '短效动态包时 180 天 30 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=30,expire=365', '短效动态包时 365 天 30 分钟', 1642.5, 1 from pid
|
||||
;
|
||||
|
||||
with pid as (
|
||||
insert into app.public.product
|
||||
(code, name, description)
|
||||
values
|
||||
('dynamic-long', '长效动态', '长效动态')
|
||||
returning id
|
||||
)
|
||||
insert into app.public.product_sku
|
||||
(product_id, code, name, price, discount)
|
||||
select pid.id, 'mode=quota,live=60,expire=0', '长效动态包量 60 分钟', 50, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=240,expire=0', '长效动态包量 240 分钟', 100, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=480,expire=0', '长效动态包量 480 分钟', 200, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=720,expire=0', '长效动态包量 720 分钟', 300, 1 from pid
|
||||
union all select pid.id, 'mode=quota,live=1440,expire=0', '长效动态包量 1440 分钟', 600, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=60,expire=7', '长效动态包时 7 天 60 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=60,expire=15', '长效动态包时 15 天 60 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=60,expire=30', '长效动态包时 30 天 60 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=60,expire=90', '长效动态包时 90 天 60 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=60,expire=180', '长效动态包时 180 天 60 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=60,expire=365', '长效动态包时 365 天 60 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=240,expire=7', '长效动态包时 7 天 240 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=240,expire=15', '长效动态包时 15 天 240 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=240,expire=30', '长效动态包时 30 天 240 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=240,expire=90', '长效动态包时 90 天 240 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=240,expire=180', '长效动态包时 180 天 240 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=240,expire=365', '长效动态包时 365 天 240 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=480,expire=7', '长效动态包时 7 天 480 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=480,expire=15', '长效动态包时 15 天 480 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=480,expire=30', '长效动态包时 30 天 480 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=480,expire=90', '长效动态包时 90 天 480 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=480,expire=180', '长效动态包时 180 天 480 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=480,expire=365', '长效动态包时 365 天 480 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=720,expire=7', '长效动态包时 7 天 720 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=720,expire=15', '长效动态包时 15 天 720 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=720,expire=30', '长效动态包时 30 天 720 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=720,expire=90', '长效动态包时 90 天 720 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=720,expire=180', '长效动态包时 180 天 720 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=720,expire=365', '长效动态包时 365 天 720 分钟', 1642.5, 1 from pid
|
||||
|
||||
union all select pid.id, 'mode=time,live=1440,expire=7', '长效动态包时 7 天 1440 分钟', 56, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=1440,expire=15', '长效动态包时 15 天 1440 分钟', 90, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=1440,expire=30', '长效动态包时 30 天 1440 分钟', 180, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=1440,expire=90', '长效动态包时 90 天 1440 分钟', 450, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=1440,expire=180', '长效动态包时 180 天 1440 分钟', 900, 1 from pid
|
||||
union all select pid.id, 'mode=time,live=1440,expire=365', '长效动态包时 365 天 1440 分钟', 1642.5, 1 from pid
|
||||
;
|
||||
|
||||
insert into app.public.product
|
||||
(code, name, description)
|
||||
values
|
||||
('static', '长效静态', '长效静态');
|
||||
-- endregion
|
||||
|
||||
@@ -720,6 +720,58 @@ comment on column product.created_at is '创建时间';
|
||||
comment on column product.updated_at is '更新时间';
|
||||
comment on column product.deleted_at is '删除时间';
|
||||
|
||||
-- product_sku
|
||||
drop table if exists product_sku cascade;
|
||||
create table product_sku (
|
||||
id int generated by default as identity primary key,
|
||||
product_id int not null,
|
||||
code text not null,
|
||||
name text not null,
|
||||
price decimal not null,
|
||||
discount float not null,
|
||||
created_at timestamptz default current_timestamp,
|
||||
updated_at timestamptz default current_timestamp,
|
||||
deleted_at timestamptz
|
||||
);
|
||||
create index idx_product_sku_product_id on product_sku (product_id) where deleted_at is null;
|
||||
create index idx_product_sku_code on product_sku (code) where deleted_at is null;
|
||||
|
||||
-- product_sku表字段注释
|
||||
comment on table product_sku is '产品SKU表';
|
||||
comment on column product_sku.id is 'SKU ID';
|
||||
comment on column product_sku.product_id is '产品ID';
|
||||
comment on column product_sku.code is 'SKU 代码:格式为 key=value,key=value,...,其中,key:value 是 SKU 的属性,多个属性用逗号分隔';
|
||||
comment on column product_sku.name is 'SKU 可读名称';
|
||||
comment on column product_sku.price is '定价';
|
||||
comment on column product_sku.discount is '折扣,0 - 1 的小数,表示 xx 折';
|
||||
comment on column product_sku.created_at is '创建时间';
|
||||
comment on column product_sku.updated_at is '更新时间';
|
||||
comment on column product_sku.deleted_at is '删除时间';
|
||||
|
||||
-- product_sku_user
|
||||
drop table if exists product_sku_user cascade;
|
||||
create table product_sku_user (
|
||||
id int generated by default as identity primary key,
|
||||
user_id int not null,
|
||||
product_sku_id int not null,
|
||||
price decimal,
|
||||
discount float,
|
||||
created_at timestamptz default current_timestamp,
|
||||
updated_at timestamptz default current_timestamp
|
||||
);
|
||||
create index idx_product_sku_user_user_id on product_sku_user (user_id);
|
||||
create index idx_product_sku_user_product_sku_id on product_sku_user (product_sku_id);
|
||||
|
||||
-- product_sku_user表字段注释
|
||||
comment on table product_sku_user is '用户产品SKU表';
|
||||
comment on column product_sku_user.id is 'ID';
|
||||
comment on column product_sku_user.user_id is '用户ID';
|
||||
comment on column product_sku_user.product_sku_id is '产品SKU ID';
|
||||
comment on column product_sku_user.price is '定价';
|
||||
comment on column product_sku_user.discount is '折扣,0 - 1 的小数,表示 xx 折';
|
||||
comment on column product_sku_user.created_at is '创建时间';
|
||||
comment on column product_sku_user.updated_at is '更新时间';
|
||||
|
||||
-- resource
|
||||
drop table if exists resource cascade;
|
||||
create table resource (
|
||||
@@ -1058,4 +1110,14 @@ alter table bill
|
||||
alter table coupon
|
||||
add constraint fk_coupon_user_id foreign key (user_id) references "user" (id) on delete cascade;
|
||||
|
||||
-- product_sku表外键
|
||||
alter table product_sku
|
||||
add constraint fk_product_sku_product_id foreign key (product_id) references product (id) on delete cascade;
|
||||
|
||||
-- product_sku_user表外键
|
||||
alter table product_sku_user
|
||||
add constraint fk_product_sku_user_user_id foreign key (user_id) references "user" (id) on delete cascade;
|
||||
alter table product_sku_user
|
||||
add constraint fk_product_sku_user_product_sku_id foreign key (product_sku_id) references product_sku (id) on delete cascade;
|
||||
|
||||
-- endregion
|
||||
|
||||
156
web/auth/account.go
Normal file
156
web/auth/account.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"platform/pkg/u"
|
||||
"platform/web/core"
|
||||
m "platform/web/models"
|
||||
q "platform/web/queries"
|
||||
s "platform/web/services"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func authClient(clientId string, clientSecrets ...string) (*m.Client, error) {
|
||||
|
||||
// 获取客户端信息
|
||||
client, err := q.Client.
|
||||
Where(
|
||||
q.Client.ClientID.Eq(clientId),
|
||||
q.Client.Status.Eq(1)).
|
||||
Take()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 检查客户端密钥
|
||||
if client.Spec == m.ClientSpecWeb || client.Spec == m.ClientSpecAPI {
|
||||
if len(clientSecrets) == 0 {
|
||||
return nil, errors.New("客户端密钥错误")
|
||||
}
|
||||
clientSecret := clientSecrets[0]
|
||||
if bcrypt.CompareHashAndPassword([]byte(client.ClientSecret), []byte(clientSecret)) != nil {
|
||||
return nil, errors.New("客户端密钥错误")
|
||||
}
|
||||
}
|
||||
|
||||
// todo 查询客户端关联权限
|
||||
|
||||
// 组织授权信息(一次性请求)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func authUser(loginType PwdLoginType, username, password string) (user *m.User, err error) {
|
||||
switch loginType {
|
||||
case PwdLoginByPhone:
|
||||
user, err = authUserBySms(q.Q, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user == nil {
|
||||
user = &m.User{
|
||||
Phone: username,
|
||||
Username: u.P(username),
|
||||
Status: m.UserStatusEnabled,
|
||||
}
|
||||
}
|
||||
case PwdLoginByEmail:
|
||||
user, err = authUserByEmail(q.Q, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case PwdLoginByPassword:
|
||||
user, err = authUserByPassword(q.Q, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, ErrAuthorizeInvalidRequest
|
||||
}
|
||||
|
||||
// 账户状态
|
||||
if user.Status == m.UserStatusDisabled {
|
||||
return nil, core.NewBizErr("账号已禁用")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func authUserBySms(tx *q.Query, username, code string) (*m.User, error) {
|
||||
// 验证验证码
|
||||
err := s.Verifier.VerifySms(context.Background(), username, code)
|
||||
if err != nil {
|
||||
return nil, core.NewBizErr("短信认证失败", err)
|
||||
}
|
||||
|
||||
// 查找用户
|
||||
return tx.User.Where(tx.User.Phone.Eq(username)).Take()
|
||||
}
|
||||
|
||||
func authUserByEmail(tx *q.Query, username, code string) (*m.User, error) {
|
||||
return nil, core.NewServErr("邮箱登录不可用")
|
||||
}
|
||||
|
||||
func authUserByPassword(tx *q.Query, username, password string) (*m.User, error) {
|
||||
user, err := tx.User.
|
||||
Where(tx.User.Phone.Eq(username)).
|
||||
Or(tx.User.Email.Eq(username)).
|
||||
Or(tx.User.Username.Eq(username)).
|
||||
Take()
|
||||
if err != nil {
|
||||
slog.Debug("查找用户失败", "error", err)
|
||||
return nil, core.NewBizErr("用户不存在或密码错误")
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if user.Password == nil || *user.Password == "" {
|
||||
slog.Debug("用户未设置密码", "username", username)
|
||||
return nil, core.NewBizErr("用户不存在或密码错误")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(*user.Password), []byte(password)) != nil {
|
||||
slog.Debug("密码验证失败", "username", username)
|
||||
return nil, core.NewBizErr("用户不存在或密码错误")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func authAdmin(loginType PwdLoginType, username, password string) (admin *m.Admin, err error) {
|
||||
switch loginType {
|
||||
case PwdLoginByPhone, PwdLoginByEmail:
|
||||
return nil, core.NewServErr("不支持的登录方式:" + string(loginType))
|
||||
case PwdLoginByPassword:
|
||||
admin, err = authAdminByPassword(q.Q, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, ErrAuthorizeInvalidRequest
|
||||
}
|
||||
|
||||
// 账户状态
|
||||
if admin.Status == m.AdminStatusDisabled {
|
||||
return nil, core.NewBizErr("账号已禁用")
|
||||
}
|
||||
|
||||
return admin, nil
|
||||
}
|
||||
|
||||
func authAdminByPassword(tx *q.Query, username, password string) (*m.Admin, error) {
|
||||
admin, err := tx.Admin.Where(tx.Admin.Username.Eq(username)).Take()
|
||||
if err != nil {
|
||||
return nil, core.NewBizErr("账号不存在或密码错误")
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if admin.Password == "" {
|
||||
return nil, core.NewBizErr("账号不存在或密码错误")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(password)) != nil {
|
||||
return nil, core.NewBizErr("账号不存在或密码错误")
|
||||
}
|
||||
|
||||
return admin, nil
|
||||
}
|
||||
@@ -6,10 +6,8 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"platform/pkg/env"
|
||||
"platform/pkg/u"
|
||||
"platform/web/core"
|
||||
g "platform/web/globals"
|
||||
"platform/web/globals/orm"
|
||||
m "platform/web/models"
|
||||
@@ -22,67 +20,52 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type GrantType string
|
||||
// AuthorizeGet 授权端点
|
||||
func AuthorizeGet(ctx *fiber.Ctx) error {
|
||||
|
||||
const (
|
||||
GrantAuthorizationCode = GrantType("authorization_code") // 授权码模式
|
||||
GrantClientCredentials = GrantType("client_credentials") // 客户端凭证模式
|
||||
GrantRefreshToken = GrantType("refresh_token") // 刷新令牌模式
|
||||
GrantPassword = GrantType("password") // 密码模式(私有扩展)
|
||||
)
|
||||
// 检查请求
|
||||
req := new(AuthorizeGetReq)
|
||||
if err := g.Validator.ParseQuery(ctx, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type PasswordGrantType string
|
||||
// 检查客户端
|
||||
client, err := authClient(req.ClientID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
const (
|
||||
GrantPasswordSecret = PasswordGrantType("password") // 账号密码
|
||||
GrantPasswordPhone = PasswordGrantType("phone_code") // 手机验证码
|
||||
GrantPasswordEmail = PasswordGrantType("email_code") // 邮箱验证码
|
||||
)
|
||||
if client.RedirectURI == nil || *client.RedirectURI != req.RedirectURI {
|
||||
return errors.New("客户端重定向URI错误")
|
||||
}
|
||||
|
||||
type TokenReq struct {
|
||||
GrantType GrantType `json:"grant_type" form:"grant_type"`
|
||||
ClientID string `json:"client_id" form:"client_id"`
|
||||
ClientSecret string `json:"client_secret" form:"client_secret"`
|
||||
Scope string `json:"scope" form:"scope"`
|
||||
GrantCodeData
|
||||
GrantClientData
|
||||
GrantRefreshData
|
||||
GrantPasswordData
|
||||
// todo 检查 scope
|
||||
|
||||
// 授权确认页面
|
||||
return nil
|
||||
}
|
||||
|
||||
type GrantCodeData struct {
|
||||
Code string `json:"code" form:"code"`
|
||||
RedirectURI string `json:"redirect_uri" form:"redirect_uri"`
|
||||
CodeVerifier string `json:"code_verifier" form:"code_verifier"`
|
||||
type AuthorizeGetReq struct {
|
||||
ResponseType string `json:"response_type" validate:"eq=code"`
|
||||
ClientID string `json:"client_id" validate:"required"`
|
||||
RedirectURI string `json:"redirect_uri" validate:"required"`
|
||||
Scope string `json:"scope"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type GrantClientData struct {
|
||||
func AuthorizePost(ctx *fiber.Ctx) error {
|
||||
|
||||
// todo 解析用户授权的范围
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type GrantRefreshData struct {
|
||||
RefreshToken string `json:"refresh_token" form:"refresh_token"`
|
||||
}
|
||||
|
||||
type GrantPasswordData struct {
|
||||
LoginType PasswordGrantType `json:"login_type" form:"login_type"`
|
||||
Username string `json:"username" form:"username"`
|
||||
Password string `json:"password" form:"password"`
|
||||
Remember bool `json:"remember" form:"remember"`
|
||||
}
|
||||
|
||||
type TokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
TokenType string `json:"token_type"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
}
|
||||
|
||||
type TokenErrResp struct {
|
||||
Error string `json:"error"`
|
||||
Description string `json:"error_description,omitempty"`
|
||||
type AuthorizePostReq struct {
|
||||
Accept bool `json:"accept"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
// Token 令牌端点
|
||||
func Token(c *fiber.Ctx) error {
|
||||
now := time.Now()
|
||||
|
||||
@@ -165,6 +148,75 @@ func Token(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
type TokenReq struct {
|
||||
GrantType GrantType `json:"grant_type" form:"grant_type"`
|
||||
ClientID string `json:"client_id" form:"client_id"`
|
||||
ClientSecret string `json:"client_secret" form:"client_secret"`
|
||||
Scope string `json:"scope" form:"scope"`
|
||||
GrantCodeData
|
||||
GrantClientData
|
||||
GrantRefreshData
|
||||
GrantPasswordData
|
||||
}
|
||||
|
||||
type GrantCodeData struct {
|
||||
Code string `json:"code" form:"code"`
|
||||
RedirectURI string `json:"redirect_uri" form:"redirect_uri"`
|
||||
CodeVerifier string `json:"code_verifier" form:"code_verifier"`
|
||||
}
|
||||
|
||||
type GrantClientData struct {
|
||||
}
|
||||
|
||||
type GrantRefreshData struct {
|
||||
RefreshToken string `json:"refresh_token" form:"refresh_token"`
|
||||
}
|
||||
|
||||
type GrantPasswordData struct {
|
||||
LoginType PwdLoginType `json:"login_type" form:"login_type"`
|
||||
LoginPool PwdLoginPool `json:"login_pool" form:"login_pool"`
|
||||
Username string `json:"username" form:"username"`
|
||||
Password string `json:"password" form:"password"`
|
||||
Remember bool `json:"remember" form:"remember"`
|
||||
}
|
||||
|
||||
type GrantType string
|
||||
|
||||
const (
|
||||
GrantAuthorizationCode = GrantType("authorization_code") // 授权码模式
|
||||
GrantClientCredentials = GrantType("client_credentials") // 客户端凭证模式
|
||||
GrantRefreshToken = GrantType("refresh_token") // 刷新令牌模式
|
||||
GrantPassword = GrantType("password") // 密码模式(私有扩展)
|
||||
)
|
||||
|
||||
type PwdLoginType string
|
||||
|
||||
const (
|
||||
PwdLoginByPassword = PwdLoginType("password") // 账号密码
|
||||
PwdLoginByPhone = PwdLoginType("phone_code") // 手机验证码
|
||||
PwdLoginByEmail = PwdLoginType("email_code") // 邮箱验证码
|
||||
)
|
||||
|
||||
type PwdLoginPool string
|
||||
|
||||
const (
|
||||
PwdLoginAsUser = PwdLoginPool("user") // 用户池
|
||||
PwdLoginAsAdmin = PwdLoginPool("admin") // 管理员池
|
||||
)
|
||||
|
||||
type TokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
TokenType string `json:"token_type"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
}
|
||||
|
||||
type TokenErrResp struct {
|
||||
Error string `json:"error"`
|
||||
Description string `json:"error_description,omitempty"`
|
||||
}
|
||||
|
||||
func authAuthorizationCode(c *fiber.Ctx, auth *AuthCtx, req *TokenReq, now time.Time) (*m.Session, error) {
|
||||
|
||||
// 检查 code 获取用户授权信息
|
||||
@@ -226,7 +278,7 @@ func authAuthorizationCode(c *fiber.Ctx, auth *AuthCtx, req *TokenReq, now time.
|
||||
session.RefreshTokenExpires = u.P(now.Add(time.Duration(env.SessionRefreshExpire) * time.Second))
|
||||
}
|
||||
|
||||
err = SaveSession(session)
|
||||
err = SaveSession(q.Q, session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -249,7 +301,7 @@ func authClientCredential(c *fiber.Ctx, auth *AuthCtx, _ *TokenReq, now time.Tim
|
||||
}
|
||||
|
||||
// 保存会话
|
||||
err := SaveSession(session)
|
||||
err := SaveSession(q.Q, session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -261,71 +313,85 @@ func authPassword(c *fiber.Ctx, auth *AuthCtx, req *TokenReq, now time.Time) (*m
|
||||
ip, _ := orm.ParseInet(c.IP()) // 可空字段,忽略异常
|
||||
ua := u.X(c.Get(fiber.HeaderUserAgent))
|
||||
|
||||
// 分池认证
|
||||
var err error
|
||||
var user *m.User
|
||||
err := q.Q.Transaction(func(tx *q.Query) (err error) {
|
||||
switch req.LoginType {
|
||||
case GrantPasswordPhone:
|
||||
user, err = authUserBySms(tx, req.Username, req.Password)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
if user == nil {
|
||||
user = &m.User{
|
||||
Phone: req.Username,
|
||||
Username: u.P(req.Username),
|
||||
Status: m.UserStatusEnabled,
|
||||
}
|
||||
}
|
||||
case GrantPasswordEmail:
|
||||
user, err = authUserByEmail(tx, req.Username, req.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case GrantPasswordSecret:
|
||||
user, err = authUserByPassword(tx, req.Username, req.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return ErrAuthorizeInvalidRequest
|
||||
}
|
||||
var admin *m.Admin
|
||||
|
||||
// 账户状态
|
||||
if user.Status == m.UserStatusDisabled {
|
||||
slog.Debug("账户状态异常", "username", req.Username, "status", user.Status)
|
||||
return core.NewBizErr("账号无法登录")
|
||||
pool := req.LoginPool
|
||||
if pool == "" {
|
||||
pool = PwdLoginAsUser
|
||||
}
|
||||
switch pool {
|
||||
case PwdLoginAsUser:
|
||||
user, err = authUser(req.LoginType, req.Username, req.Password)
|
||||
if err != nil {
|
||||
if req.LoginType != PwdLoginByPhone || !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 手机号首次登录的自动创建用户
|
||||
user = &m.User{
|
||||
Phone: req.Username,
|
||||
Username: u.P(req.Username),
|
||||
Status: m.UserStatusEnabled,
|
||||
}
|
||||
}
|
||||
|
||||
// 更新用户的登录时间
|
||||
user.LastLogin = u.P(time.Now())
|
||||
user.LastLoginIP = ip
|
||||
user.LastLoginUA = ua
|
||||
if err := tx.User.Save(user); err != nil {
|
||||
return err
|
||||
|
||||
case PwdLoginAsAdmin:
|
||||
admin, err = authAdmin(req.LoginType, req.Username, req.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// 更新管理员登录时间
|
||||
admin.LastLogin = u.P(time.Now())
|
||||
admin.LastLoginIP = ip
|
||||
admin.LastLoginUA = ua
|
||||
|
||||
default:
|
||||
return nil, ErrAuthorizeInvalidRequest
|
||||
}
|
||||
|
||||
// 生成会话
|
||||
session := &m.Session{
|
||||
IP: ip,
|
||||
UA: ua,
|
||||
UserID: &user.ID,
|
||||
ClientID: &auth.Client.ID,
|
||||
Scopes: u.X(req.Scope),
|
||||
AccessToken: uuid.NewString(),
|
||||
AccessTokenExpires: now.Add(time.Duration(env.SessionAccessExpire) * time.Second),
|
||||
}
|
||||
|
||||
if req.Remember {
|
||||
session.RefreshToken = u.P(uuid.NewString())
|
||||
session.RefreshTokenExpires = u.P(now.Add(time.Duration(env.SessionRefreshExpire) * time.Second))
|
||||
}
|
||||
|
||||
err = SaveSession(session)
|
||||
// 保存用户更新和会话
|
||||
err = q.Q.Transaction(func(tx *q.Query) error {
|
||||
if user != nil {
|
||||
if err := tx.User.Save(user); err != nil {
|
||||
return err
|
||||
}
|
||||
session.UserID = &user.ID
|
||||
}
|
||||
if admin != nil {
|
||||
if err := tx.Admin.Save(admin); err != nil {
|
||||
return err
|
||||
}
|
||||
session.AdminID = &admin.ID
|
||||
}
|
||||
if err := SaveSession(tx, session); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -353,7 +419,7 @@ func authRefreshToken(_ *fiber.Ctx, _ *AuthCtx, req *TokenReq, now time.Time) (*
|
||||
}
|
||||
|
||||
// 保存令牌
|
||||
err = SaveSession(session)
|
||||
err = SaveSession(q.Q, session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -394,12 +460,117 @@ func sendError(c *fiber.Ctx, err error, description ...string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func Revoke() error {
|
||||
// Revoke 令牌撤销端点
|
||||
func Revoke(ctx *fiber.Ctx) error {
|
||||
_, err := GetAuthCtx(ctx).PermitUser()
|
||||
if err != nil {
|
||||
// 用户未登录
|
||||
return nil
|
||||
}
|
||||
|
||||
// 解析请求参数
|
||||
req := new(RevokeReq)
|
||||
if err := ctx.BodyParser(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除会话
|
||||
err = RemoveSession(ctx.Context(), req.AccessToken, req.RefreshToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Introspect() error {
|
||||
return nil
|
||||
type RevokeReq struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
// Introspect 令牌检查端点
|
||||
func Introspect(ctx *fiber.Ctx) error {
|
||||
authCtx := GetAuthCtx(ctx)
|
||||
|
||||
// 尝试验证用户权限
|
||||
if _, err := authCtx.PermitUser(); err == nil {
|
||||
return introspectUser(ctx, authCtx)
|
||||
}
|
||||
|
||||
// 尝试验证管理员权限
|
||||
if _, err := authCtx.PermitAdmin(); err == nil {
|
||||
return introspectAdmin(ctx, authCtx)
|
||||
}
|
||||
|
||||
return ErrAuthenticateForbidden
|
||||
}
|
||||
|
||||
// introspectUser 获取并返回用户信息
|
||||
func introspectUser(ctx *fiber.Ctx, authCtx *AuthCtx) error {
|
||||
// 获取用户信息
|
||||
profile, err := q.User.
|
||||
Where(q.User.ID.Eq(authCtx.User.ID)).
|
||||
Omit(q.User.DeletedAt).
|
||||
Take()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查用户是否设置了密码
|
||||
hasPassword := false
|
||||
if profile.Password != nil && *profile.Password != "" {
|
||||
hasPassword = true
|
||||
profile.Password = nil // 不返回密码
|
||||
}
|
||||
|
||||
// 掩码敏感信息
|
||||
if profile.Phone != "" {
|
||||
profile.Phone = maskPhone(profile.Phone)
|
||||
}
|
||||
if profile.IDNo != nil && *profile.IDNo != "" {
|
||||
profile.IDNo = u.P(maskIdNo(*profile.IDNo))
|
||||
}
|
||||
|
||||
return ctx.JSON(struct {
|
||||
m.User
|
||||
HasPassword bool `json:"has_password"` // 是否设置了密码
|
||||
}{*profile, hasPassword})
|
||||
}
|
||||
|
||||
// introspectAdmin 获取并返回管理员信息
|
||||
func introspectAdmin(ctx *fiber.Ctx, authCtx *AuthCtx) error {
|
||||
// 获取管理员信息
|
||||
profile, err := q.Admin.
|
||||
Where(q.Admin.ID.Eq(authCtx.Admin.ID)).
|
||||
Omit(q.Admin.DeletedAt).
|
||||
Take()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 不返回密码
|
||||
profile.Password = ""
|
||||
|
||||
// 掩码敏感信息
|
||||
if profile.Phone != nil && *profile.Phone != "" {
|
||||
profile.Phone = u.P(maskPhone(*profile.Phone))
|
||||
}
|
||||
|
||||
return ctx.JSON(profile)
|
||||
}
|
||||
|
||||
func maskPhone(phone string) string {
|
||||
if len(phone) < 11 {
|
||||
return phone
|
||||
}
|
||||
return phone[:3] + "****" + phone[7:]
|
||||
}
|
||||
|
||||
func maskIdNo(idNo string) string {
|
||||
if len(idNo) < 18 {
|
||||
return idNo
|
||||
}
|
||||
return idNo[:3] + "*********" + idNo[14:]
|
||||
}
|
||||
|
||||
type CodeContext struct {
|
||||
@@ -6,15 +6,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"platform/web/core"
|
||||
m "platform/web/models"
|
||||
q "platform/web/queries"
|
||||
s "platform/web/services"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func Authenticate() fiber.Handler {
|
||||
@@ -123,67 +118,3 @@ func authBasic(_ context.Context, token string) (*AuthCtx, error) {
|
||||
Scopes: []string{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func authClient(clientId, clientSecret string) (*m.Client, error) {
|
||||
|
||||
// 获取客户端信息
|
||||
client, err := q.Client.
|
||||
Where(
|
||||
q.Client.ClientID.Eq(clientId),
|
||||
q.Client.Status.Eq(1)).
|
||||
Take()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 检查客户端密钥
|
||||
if client.Spec == m.ClientSpecWeb || client.Spec == m.ClientSpecAPI {
|
||||
if bcrypt.CompareHashAndPassword([]byte(client.ClientSecret), []byte(clientSecret)) != nil {
|
||||
return nil, errors.New("客户端密钥错误")
|
||||
}
|
||||
}
|
||||
|
||||
// todo 查询客户端关联权限
|
||||
|
||||
// 组织授权信息(一次性请求)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func authUserBySms(tx *q.Query, username, code string) (*m.User, error) {
|
||||
// 验证验证码
|
||||
err := s.Verifier.VerifySms(context.Background(), username, code)
|
||||
if err != nil {
|
||||
return nil, core.NewBizErr("短信认证失败:%w", err)
|
||||
}
|
||||
|
||||
// 查找用户
|
||||
return tx.User.Where(tx.User.Phone.Eq(username)).Take()
|
||||
}
|
||||
|
||||
func authUserByEmail(tx *q.Query, username, code string) (*m.User, error) {
|
||||
return nil, core.NewServErr("邮箱登录不可用")
|
||||
}
|
||||
|
||||
func authUserByPassword(tx *q.Query, username, password string) (*m.User, error) {
|
||||
user, err := tx.User.
|
||||
Where(tx.User.Phone.Eq(username)).
|
||||
Or(tx.User.Email.Eq(username)).
|
||||
Or(tx.User.Username.Eq(username)).
|
||||
Take()
|
||||
if err != nil {
|
||||
slog.Debug("查找用户失败", "error", err)
|
||||
return nil, core.NewBizErr("用户不存在或密码错误")
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if user.Password == nil || *user.Password == "" {
|
||||
slog.Debug("用户未设置密码", "username", username)
|
||||
return nil, core.NewBizErr("用户不存在或密码错误")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(*user.Password), []byte(password)) != nil {
|
||||
slog.Debug("密码验证失败", "username", username)
|
||||
return nil, core.NewBizErr("用户不存在或密码错误")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -29,8 +29,8 @@ func FindSessionByRefresh(refreshToken string, now time.Time) (*m.Session, error
|
||||
).First()
|
||||
}
|
||||
|
||||
func SaveSession(session *m.Session) error {
|
||||
return q.Session.Save(session)
|
||||
func SaveSession(tx *q.Query, session *m.Session) error {
|
||||
return tx.Session.Save(session)
|
||||
}
|
||||
|
||||
func RemoveSession(ctx context.Context, accessToken string, refreshToken string) error {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/h5"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
||||
)
|
||||
@@ -18,6 +19,7 @@ var WechatPay *WechatPayClient
|
||||
|
||||
type WechatPayClient struct {
|
||||
Native *native.NativeApiService
|
||||
H5 *h5.H5ApiService
|
||||
Notify *notify.Handler
|
||||
}
|
||||
|
||||
@@ -71,6 +73,7 @@ func initWechatPay() error {
|
||||
// 创建 WechatPay 服务
|
||||
WechatPay = &WechatPayClient{
|
||||
Native: &native.NativeApiService{Client: client},
|
||||
H5: &h5.H5ApiService{Client: client},
|
||||
Notify: handler,
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"platform/pkg/u"
|
||||
auth2 "platform/web/auth"
|
||||
m "platform/web/models"
|
||||
q "platform/web/queries"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// region /revoke
|
||||
|
||||
type RevokeReq struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
func Revoke(c *fiber.Ctx) error {
|
||||
_, err := auth2.GetAuthCtx(c).PermitUser()
|
||||
if err != nil {
|
||||
// 用户未登录
|
||||
return nil
|
||||
}
|
||||
|
||||
// 解析请求参数
|
||||
req := new(RevokeReq)
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除会话
|
||||
err = auth2.RemoveSession(c.Context(), req.AccessToken, req.RefreshToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region /profile
|
||||
|
||||
type IntrospectResp struct {
|
||||
m.User
|
||||
HasPassword bool `json:"has_password"` // 是否设置了密码
|
||||
}
|
||||
|
||||
func Introspect(c *fiber.Ctx) error {
|
||||
// 验证权限
|
||||
authCtx, err := auth2.GetAuthCtx(c).PermitUser()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
profile, err := q.User.
|
||||
Where(q.User.ID.Eq(authCtx.User.ID)).
|
||||
Omit(q.User.DeletedAt).
|
||||
Take()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查用户是否设置了密码
|
||||
hasPassword := false
|
||||
if profile.Password != nil && *profile.Password != "" {
|
||||
hasPassword = true
|
||||
profile.Password = nil // 不返回密码
|
||||
}
|
||||
|
||||
// 掩码敏感信息
|
||||
if profile.Phone != "" {
|
||||
profile.Phone = maskPhone(profile.Phone)
|
||||
}
|
||||
if profile.IDNo != nil && *profile.IDNo != "" {
|
||||
profile.IDNo = u.P(maskIdNo(*profile.IDNo))
|
||||
}
|
||||
return c.JSON(IntrospectResp{*profile, hasPassword})
|
||||
}
|
||||
|
||||
func maskPhone(phone string) string {
|
||||
if len(phone) < 11 {
|
||||
return phone
|
||||
}
|
||||
return phone[:3] + "****" + phone[7:]
|
||||
}
|
||||
|
||||
func maskIdNo(idNo string) string {
|
||||
if len(idNo) < 18 {
|
||||
return idNo
|
||||
}
|
||||
return idNo[:3] + "*********" + idNo[14:]
|
||||
}
|
||||
|
||||
// endregion
|
||||
@@ -55,3 +55,25 @@ type PageResourceBatchReq struct {
|
||||
TimeStart *time.Time `json:"time_start"`
|
||||
TimeEnd *time.Time `json:"time_end"`
|
||||
}
|
||||
|
||||
// PageBatchByAdmin 分页查询所有提取记录
|
||||
func PageBatchByAdmin(c *fiber.Ctx) error {
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := new(struct{ core.PageReq })
|
||||
if err = g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
list, total, err := q.LogsUserUsage.FindByPage(req.GetOffset(), req.GetLimit())
|
||||
|
||||
return c.JSON(core.PageResp{
|
||||
List: list,
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,20 +3,40 @@ package handlers
|
||||
import (
|
||||
"platform/web/auth"
|
||||
"platform/web/core"
|
||||
g "platform/web/globals"
|
||||
q "platform/web/queries"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// region ListBill
|
||||
// PageBillByAdmin 分页查询全部账单
|
||||
func PageBillByAdmin(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type ListBillReq struct {
|
||||
core.PageReq
|
||||
BillNo *string `json:"bill_no"`
|
||||
Type *int `json:"type"`
|
||||
CreateAfter *time.Time `json:"create_after"`
|
||||
CreateBefore *time.Time `json:"create_before"`
|
||||
// 解析请求参数
|
||||
req := new(core.PageReq)
|
||||
if err := g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 查询用户列表
|
||||
list, total, err := q.Bill.FindByPage(req.GetOffset(), req.GetLimit())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return c.JSON(core.PageResp{
|
||||
List: list,
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
})
|
||||
}
|
||||
|
||||
// ListBill 获取账单列表
|
||||
@@ -79,4 +99,10 @@ func ListBill(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// endregion
|
||||
type ListBillReq struct {
|
||||
core.PageReq
|
||||
BillNo *string `json:"bill_no"`
|
||||
Type *int `json:"type"`
|
||||
CreateAfter *time.Time `json:"create_after"`
|
||||
CreateBefore *time.Time `json:"create_before"`
|
||||
}
|
||||
|
||||
@@ -14,15 +14,36 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// region ListChannels
|
||||
// PageChannelsByAdmin 分页查询所有通道
|
||||
func PageChannelsByAdmin(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type ListChannelsReq struct {
|
||||
core.PageReq
|
||||
AuthType s.ChannelAuthType `json:"auth_type"`
|
||||
ExpireAfter *time.Time `json:"expire_after"`
|
||||
ExpireBefore *time.Time `json:"expire_before"`
|
||||
// 解析请求参数
|
||||
req := new(core.PageReq)
|
||||
if err := g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 查询通道列表
|
||||
list, total, err := q.Channel.FindByPage(req.GetOffset(), req.GetLimit())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return c.JSON(core.PageResp{
|
||||
List: list,
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
})
|
||||
}
|
||||
|
||||
// 分页查询当前用户通道
|
||||
func ListChannels(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authContext, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -86,28 +107,14 @@ func ListChannels(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region CreateChannel
|
||||
|
||||
type CreateChannelReq struct {
|
||||
ResourceId int32 `json:"resource_id" validate:"required"`
|
||||
AuthType s.ChannelAuthType `json:"auth_type" validate:"required"`
|
||||
Protocol int `json:"protocol" validate:"required"`
|
||||
Count int `json:"count" validate:"required"`
|
||||
Prov *string `json:"prov"`
|
||||
City *string `json:"city"`
|
||||
Isp *int `json:"isp"`
|
||||
}
|
||||
|
||||
type CreateChannelRespItem struct {
|
||||
Proto int `json:"-"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
Username *string `json:"username,omitempty"`
|
||||
Password *string `json:"password,omitempty"`
|
||||
type ListChannelsReq struct {
|
||||
core.PageReq
|
||||
AuthType s.ChannelAuthType `json:"auth_type"`
|
||||
ExpireAfter *time.Time `json:"expire_after"`
|
||||
ExpireBefore *time.Time `json:"expire_before"`
|
||||
}
|
||||
|
||||
// 创建新通道
|
||||
func CreateChannel(c *fiber.Ctx) error {
|
||||
|
||||
// 解析参数
|
||||
@@ -154,16 +161,25 @@ func CreateChannel(c *fiber.Ctx) error {
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
type CreateChannelResultType string
|
||||
|
||||
// endregion
|
||||
|
||||
// region RemoveChannels
|
||||
|
||||
type RemoveChannelsReq struct {
|
||||
Batch string `json:"batch" validate:"required"`
|
||||
type CreateChannelReq struct {
|
||||
ResourceId int32 `json:"resource_id" validate:"required"`
|
||||
AuthType s.ChannelAuthType `json:"auth_type" validate:"required"`
|
||||
Protocol int `json:"protocol" validate:"required"`
|
||||
Count int `json:"count" validate:"required"`
|
||||
Prov *string `json:"prov"`
|
||||
City *string `json:"city"`
|
||||
Isp *int `json:"isp"`
|
||||
}
|
||||
|
||||
type CreateChannelRespItem struct {
|
||||
Proto int `json:"-"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
Username *string `json:"username,omitempty"`
|
||||
Password *string `json:"password,omitempty"`
|
||||
}
|
||||
|
||||
// RemoveChannels 删除通道
|
||||
func RemoveChannels(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitOfficialClient()
|
||||
@@ -186,4 +202,6 @@ func RemoveChannels(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
// endregion
|
||||
type RemoveChannelsReq struct {
|
||||
Batch string `json:"batch" validate:"required"`
|
||||
}
|
||||
|
||||
@@ -18,19 +18,7 @@ import (
|
||||
jdclient "github.com/jdcloud-api/jdcloud-sdk-go/services/cloudauth/client"
|
||||
)
|
||||
|
||||
// region Identify
|
||||
|
||||
type IdentifyReq struct {
|
||||
Type int `json:"type" validate:"required,oneof=1 2"`
|
||||
Name string `json:"name" validate:"required"`
|
||||
IdenNo string `json:"iden_no" validate:"required"`
|
||||
}
|
||||
|
||||
type IdentifyRes struct {
|
||||
Identified bool `json:"identified"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
// Identify 发起实名认证
|
||||
func Identify(c *fiber.Ctx) error {
|
||||
|
||||
// 检查权限
|
||||
@@ -99,7 +87,21 @@ func Identify(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// endregion
|
||||
type IdentifyReq struct {
|
||||
Type int `json:"type" validate:"required,oneof=1 2"`
|
||||
Name string `json:"name" validate:"required"`
|
||||
IdenNo string `json:"iden_no" validate:"required"`
|
||||
}
|
||||
|
||||
type IdentifyRes struct {
|
||||
Identified bool `json:"identified"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
type idenResultData struct {
|
||||
Success bool
|
||||
Message string
|
||||
}
|
||||
|
||||
// IdentifyCallbackNew 更新用户实名认证状态
|
||||
func IdentifyCallbackNew(c *fiber.Ctx) error {
|
||||
@@ -110,18 +112,17 @@ func IdentifyCallbackNew(c *fiber.Ctx) error {
|
||||
Success bool `json:"success" validate:"required"`
|
||||
})
|
||||
if err := c.QueryParser(req); err != nil {
|
||||
return core.NewBizErr("解析请求参数失败", err)
|
||||
return renderIdenResult(c, false, "解析请求参数失败")
|
||||
}
|
||||
|
||||
// 获取 token
|
||||
infoStr, err := g.Redis.GetDel(c.Context(), idenKey(req.Id)).Bytes()
|
||||
if err != nil {
|
||||
return core.NewBizErr("实名认证状态已失效", err)
|
||||
return renderIdenResult(c, false, "实名认证状态已失效,请重新发起认证")
|
||||
}
|
||||
info := idenInfo{}
|
||||
err = json.Unmarshal(infoStr, &info)
|
||||
if err != nil {
|
||||
return core.NewServErr("解析实名认证信息失败", err)
|
||||
if err = json.Unmarshal(infoStr, &info); err != nil {
|
||||
return renderIdenResult(c, false, "解析实名认证信息失败,请重新发起认证")
|
||||
}
|
||||
|
||||
// 获取认证结果
|
||||
@@ -131,13 +132,13 @@ func IdentifyCallbackNew(c *fiber.Ctx) error {
|
||||
info.Token,
|
||||
))
|
||||
if err != nil {
|
||||
return core.NewServErr("获取实名认证结果失败", err)
|
||||
return renderIdenResult(c, false, "获取实名认证结果失败,请重新发起认证")
|
||||
}
|
||||
if resp.Error.Code != 0 {
|
||||
return core.NewServErr(fmt.Sprintf("获取实名认证结果失败: %s", resp.Error.Message))
|
||||
return renderIdenResult(c, false, fmt.Sprintf("获取实名认证结果失败:%s", resp.Error.Message))
|
||||
}
|
||||
if resp.Result.H5Result != "ok" || resp.Result.SmResult != "ok" || resp.Result.RxResult != "ok" {
|
||||
return core.NewBizErr(fmt.Sprintf("实名认证失败: %s", resp.Result.Desc))
|
||||
return renderIdenResult(c, false, fmt.Sprintf("实名认证未通过:%s", resp.Result.Desc))
|
||||
}
|
||||
|
||||
// 更新用户实名认证状态
|
||||
@@ -150,11 +151,41 @@ func IdentifyCallbackNew(c *fiber.Ctx) error {
|
||||
q.User.IDToken.Value(info.Token),
|
||||
)
|
||||
if err != nil {
|
||||
return core.NewServErr("更新用户实名信息失败", err)
|
||||
return renderIdenResult(c, false, "保存实名认证信息失败,请联系客服处理")
|
||||
}
|
||||
|
||||
// 返回结果页面
|
||||
return c.SendString("🎉认证成功!现在可以安全关闭这个页面")
|
||||
return renderIdenResult(c, true, "实名认证成功,请在扫码页面点击按钮完成认证")
|
||||
}
|
||||
|
||||
func renderIdenResult(c *fiber.Ctx, success bool, message string) error {
|
||||
return c.Render("views/iden-result", idenResultData{
|
||||
Success: success,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// DebugIdentifyClear 清除用户实名认证状态(调试用)
|
||||
func DebugIdentifyClear(c *fiber.Ctx) error {
|
||||
phone := c.Params("phone")
|
||||
if phone == "" {
|
||||
return core.NewServErr("需要提供手机号")
|
||||
}
|
||||
|
||||
_, err := q.User.
|
||||
Where(
|
||||
q.User.Phone.Eq(phone),
|
||||
).
|
||||
UpdateSimple(
|
||||
q.User.IDType.Value(0),
|
||||
q.User.IDNo.Value(""),
|
||||
q.User.IDToken.Value(""),
|
||||
)
|
||||
if err != nil {
|
||||
return core.NewServErr("清除实名认证失败")
|
||||
}
|
||||
|
||||
return c.SendString("实名信息已清除")
|
||||
}
|
||||
|
||||
func idenKey(id string) string {
|
||||
|
||||
@@ -15,8 +15,8 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// ListResourceShort 分页短效套餐
|
||||
func ListResourceShort(c *fiber.Ctx) error {
|
||||
// PageResourceShort 分页查询当前用户短效套餐
|
||||
func PageResourceShort(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitUser()
|
||||
if err != nil {
|
||||
@@ -24,7 +24,7 @@ func ListResourceShort(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 解析请求参数
|
||||
req := new(ListResourceShortReq)
|
||||
req := new(PageResourceShortReq)
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -55,6 +55,19 @@ func ListResourceShort(c *fiber.Ctx) error {
|
||||
if req.ExpireBefore != nil {
|
||||
do.Where(q.ResourceShort.As(q.Resource.Short.Name()).ExpireAt.Lte(*req.ExpireBefore))
|
||||
}
|
||||
if req.Status != nil {
|
||||
var short = q.ResourceShort.As(q.Resource.Short.Name())
|
||||
switch *req.Status {
|
||||
case 1:
|
||||
var timeCond = q.Resource.Where(short.Type.Eq(int(m.ResourceModeTime)), short.ExpireAt.Gte(time.Now()))
|
||||
var quotaCond = q.Resource.Where(short.Type.Eq(int(m.ResourceModeQuota)), short.Quota.GtCol(short.Used))
|
||||
do.Where(q.Resource.Where(timeCond).Or(quotaCond))
|
||||
case 2:
|
||||
var timeCond = q.Resource.Where(short.Type.Eq(int(m.ResourceModeTime)), short.ExpireAt.Lte(time.Now()))
|
||||
var quotaCond = q.Resource.Where(short.Type.Eq(int(m.ResourceModeQuota)), short.Quota.LteCol(short.Used))
|
||||
do.Where(q.Resource.Where(timeCond).Or(quotaCond))
|
||||
}
|
||||
}
|
||||
|
||||
resource, err := q.Resource.Where(do).
|
||||
Joins(q.Resource.Short).
|
||||
@@ -86,7 +99,7 @@ func ListResourceShort(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
type ListResourceShortReq struct {
|
||||
type PageResourceShortReq struct {
|
||||
core.PageReq
|
||||
ResourceNo *string `json:"resource_no"`
|
||||
Active *bool `json:"active"`
|
||||
@@ -95,10 +108,11 @@ type ListResourceShortReq struct {
|
||||
CreateBefore *time.Time `json:"create_before"`
|
||||
ExpireAfter *time.Time `json:"expire_after"`
|
||||
ExpireBefore *time.Time `json:"expire_before"`
|
||||
Status *int `json:"status"` // 0 - 全部,1 - 有效,2 - 过期
|
||||
}
|
||||
|
||||
// ListResourceLong 分页长效套餐
|
||||
func ListResourceLong(c *fiber.Ctx) error {
|
||||
// PageResourceLong 分页查询当前用户长效套餐
|
||||
func PageResourceLong(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitUser()
|
||||
if err != nil {
|
||||
@@ -106,7 +120,7 @@ func ListResourceLong(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 解析请求参数
|
||||
req := new(ListResourceLongReq)
|
||||
req := new(PageResourceLongReq)
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -137,6 +151,19 @@ func ListResourceLong(c *fiber.Ctx) error {
|
||||
if req.ExpireBefore != nil {
|
||||
do.Where(q.ResourceLong.As(q.Resource.Long.Name()).ExpireAt.Lte(*req.ExpireBefore))
|
||||
}
|
||||
if req.Status != nil {
|
||||
var long = q.ResourceLong.As(q.Resource.Long.Name())
|
||||
switch *req.Status {
|
||||
case 1:
|
||||
var timeCond = q.Resource.Where(long.Type.Eq(int(m.ResourceModeTime)), long.ExpireAt.Gte(time.Now()))
|
||||
var quotaCond = q.Resource.Where(long.Type.Eq(int(m.ResourceModeQuota)), long.Quota.GtCol(long.Used))
|
||||
do.Where(q.Resource.Where(timeCond).Or(quotaCond))
|
||||
case 2:
|
||||
var timeCond = q.Resource.Where(long.Type.Eq(int(m.ResourceModeTime)), long.ExpireAt.Lte(time.Now()))
|
||||
var quotaCond = q.Resource.Where(long.Type.Eq(int(m.ResourceModeQuota)), long.Quota.LteCol(long.Used))
|
||||
do.Where(q.Resource.Where(timeCond).Or(quotaCond))
|
||||
}
|
||||
}
|
||||
|
||||
resource, err := q.Resource.Where(do).
|
||||
Joins(q.Resource.Long).
|
||||
@@ -168,7 +195,7 @@ func ListResourceLong(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
type ListResourceLongReq struct {
|
||||
type PageResourceLongReq struct {
|
||||
core.PageReq
|
||||
ResourceNo *string `json:"resource_no"`
|
||||
Active *bool `json:"active"`
|
||||
@@ -177,6 +204,57 @@ type ListResourceLongReq struct {
|
||||
CreateBefore *time.Time `json:"create_before"`
|
||||
ExpireAfter *time.Time `json:"expire_after"`
|
||||
ExpireBefore *time.Time `json:"expire_before"`
|
||||
Status *int `json:"status"` // 0 - 全部,1 - 有效,2 - 过期
|
||||
}
|
||||
|
||||
// PageResourceShortByAdmin 分页查询全部短效套餐
|
||||
func PageResourceShortByAdmin(c *fiber.Ctx) error {
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := new(struct{ core.PageReq })
|
||||
if err = g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
list, total, err := q.Resource.
|
||||
LeftJoin(q.ResourceShort, q.ResourceShort.ResourceID.EqCol(q.Resource.ID)).
|
||||
Where(q.Resource.Type.Eq(int(m.ResourceTypeShort))).
|
||||
FindByPage(req.GetOffset(), req.GetLimit())
|
||||
|
||||
return c.JSON(core.PageResp{
|
||||
List: list,
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
})
|
||||
}
|
||||
|
||||
// PageResourceLongByAdmin 分页查询全部短效套餐
|
||||
func PageResourceLongByAdmin(c *fiber.Ctx) error {
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req := new(struct{ core.PageReq })
|
||||
if err = g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
list, total, err := q.Resource.
|
||||
LeftJoin(q.ResourceLong, q.ResourceLong.ResourceID.EqCol(q.Resource.ID)).
|
||||
Where(q.Resource.Type.Eq(int(m.ResourceTypeLong))).
|
||||
FindByPage(req.GetOffset(), req.GetLimit())
|
||||
|
||||
return c.JSON(core.PageResp{
|
||||
List: list,
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
})
|
||||
}
|
||||
|
||||
// AllActiveResource 所有可用套餐
|
||||
@@ -438,16 +516,21 @@ func ResourcePrice(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 获取套餐价格
|
||||
amount, err := req.GetAmount()
|
||||
sku, err := s.Resource.GetSku(req.CreateResourceData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
before, after, err := s.Resource.GetPrice(sku, req.Count(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 计算折扣
|
||||
return c.JSON(ResourcePriceResp{
|
||||
Price: amount.StringFixed(2),
|
||||
Discounted: 1,
|
||||
DiscountedPrice: amount.StringFixed(2),
|
||||
Price: before.StringFixed(2),
|
||||
Discounted: sku.Discount,
|
||||
DiscountedPrice: after.StringFixed(2),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"platform/web/core"
|
||||
g "platform/web/globals"
|
||||
m "platform/web/models"
|
||||
q "platform/web/queries"
|
||||
s "platform/web/services"
|
||||
"time"
|
||||
|
||||
@@ -16,18 +17,36 @@ import (
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
type TradeCreateReq struct {
|
||||
s.CreateTradeData
|
||||
Type m.TradeType `json:"type" validate:"required"`
|
||||
Resource *s.CreateResourceData `json:"resource,omitempty"`
|
||||
Recharge *s.RechargeProductInfo `json:"recharge,omitempty"`
|
||||
}
|
||||
|
||||
type TradeCreateResp struct {
|
||||
PayUrl string `json:"pay_url"`
|
||||
TradeNo string `json:"trade_no"`
|
||||
// PageTradeByAdmin 分页查询所有订单
|
||||
func PageTradeByAdmin(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解析请求参数
|
||||
req := new(core.PageReq)
|
||||
if err := g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 查询用户列表
|
||||
list, total, err := q.Trade.FindByPage(req.GetOffset(), req.GetLimit())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return c.JSON(core.PageResp{
|
||||
List: list,
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
})
|
||||
}
|
||||
|
||||
// 创建订单
|
||||
func TradeCreate(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -41,21 +60,25 @@ func TradeCreate(c *fiber.Ctx) error {
|
||||
return err
|
||||
}
|
||||
|
||||
var product s.ProductInfo
|
||||
switch req.Type {
|
||||
case m.TradeTypePurchase:
|
||||
if req.Resource == nil {
|
||||
return core.NewBizErr("购买信息不能为空")
|
||||
}
|
||||
req.Product = req.Resource
|
||||
product, err = s.NewCreateResourceByTradeData(req.Resource)
|
||||
if err != nil {
|
||||
return core.NewServErr("处理购买产品信息失败", err)
|
||||
}
|
||||
case m.TradeTypeRecharge:
|
||||
if req.Recharge == nil {
|
||||
return core.NewBizErr("充值信息不能为空")
|
||||
}
|
||||
req.Product = req.Recharge
|
||||
product = req.Recharge
|
||||
}
|
||||
|
||||
// 创建交易
|
||||
result, err := s.Trade.CreateTrade(authCtx.User.ID, time.Now(), &req.CreateTradeData)
|
||||
result, err := s.Trade.CreateTrade(authCtx.User.ID, time.Now(), &req.CreateTradeData, product)
|
||||
if err != nil {
|
||||
slog.Error("创建交易失败", "error", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "创建交易失败"})
|
||||
@@ -67,10 +90,19 @@ func TradeCreate(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
type TradeCompleteReq struct {
|
||||
s.ModifyTradeData
|
||||
type TradeCreateReq struct {
|
||||
s.CreateTradeData
|
||||
Type m.TradeType `json:"type" validate:"required"`
|
||||
Resource *s.CreateResourceData `json:"resource,omitempty"`
|
||||
Recharge *s.RechargeProductInfo `json:"recharge,omitempty"`
|
||||
}
|
||||
|
||||
type TradeCreateResp struct {
|
||||
PayUrl string `json:"pay_url"`
|
||||
TradeNo string `json:"trade_no"`
|
||||
}
|
||||
|
||||
// 完成订单
|
||||
func TradeComplete(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -93,10 +125,11 @@ func TradeComplete(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
type TradeCancelReq struct {
|
||||
type TradeCompleteReq struct {
|
||||
s.ModifyTradeData
|
||||
}
|
||||
|
||||
// 取消订单
|
||||
func TradeCancel(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -120,10 +153,11 @@ func TradeCancel(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
type TradeCheckReq struct {
|
||||
type TradeCancelReq struct {
|
||||
s.ModifyTradeData
|
||||
}
|
||||
|
||||
// 检查订单
|
||||
func TradeCheck(c *fiber.Ctx) error {
|
||||
// 解析请求参数
|
||||
req := new(TradeCheckReq)
|
||||
@@ -170,3 +204,7 @@ func TradeCheck(c *fiber.Ctx) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type TradeCheckReq struct {
|
||||
s.ModifyTradeData
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package handlers
|
||||
|
||||
import (
|
||||
"platform/web/auth"
|
||||
"platform/web/core"
|
||||
g "platform/web/globals"
|
||||
m "platform/web/models"
|
||||
q "platform/web/queries"
|
||||
s "platform/web/services"
|
||||
@@ -10,15 +12,81 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// region /update
|
||||
// 分页获取用户
|
||||
func PageUserByAdmin(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
_, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type UpdateUserReq struct {
|
||||
Username string `json:"username" validate:"omitempty,min=3,max=20"`
|
||||
Email string `json:"email" validate:"omitempty,email"`
|
||||
ContactQQ string `json:"contact_qq" validate:"omitempty,qq"`
|
||||
ContactWechat string `json:"contact_wechat" validate:"omitempty,wechat"`
|
||||
// 解析请求参数
|
||||
req := new(core.PageReq)
|
||||
if err := g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 查询用户列表
|
||||
users, total, err := q.User.
|
||||
Preload(q.User.Admin).
|
||||
Omit(q.User.Password).
|
||||
FindByPage(req.GetOffset(), req.GetLimit())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, user := range users {
|
||||
if user.Admin != nil {
|
||||
user.Admin = &m.Admin{
|
||||
Name: user.Admin.Name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return c.JSON(core.PageResp{
|
||||
Total: int(total),
|
||||
Page: req.GetPage(),
|
||||
Size: req.GetSize(),
|
||||
List: users,
|
||||
})
|
||||
}
|
||||
|
||||
// 绑定管理员
|
||||
func BindAdmin(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitAdmin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解析请求参数
|
||||
req := new(struct {
|
||||
UserID int `json:"user_id" validate:"required"`
|
||||
})
|
||||
if err := g.Validator.ParseBody(c, req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新用户信息
|
||||
result, err := q.User.Where(
|
||||
q.User.ID.Eq(int32(req.UserID)),
|
||||
q.User.AdminID.IsNull(),
|
||||
).UpdateColumnSimple(
|
||||
q.User.AdminID.Value(authCtx.Admin.ID),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return core.NewBizErr("用户已绑定管理员")
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
// 更新用户
|
||||
func UpdateUser(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -49,15 +117,14 @@ func UpdateUser(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region /update/account
|
||||
|
||||
type UpdateAccountReq struct {
|
||||
Username string `json:"username" validate:"omitempty,min=3,max=20"`
|
||||
Password string `json:"password" validate:"omitempty,min=6,max=20"`
|
||||
type UpdateUserReq struct {
|
||||
Username string `json:"username" validate:"omitempty,min=3,max=20"`
|
||||
Email string `json:"email" validate:"omitempty,email"`
|
||||
ContactQQ string `json:"contact_qq" validate:"omitempty,qq"`
|
||||
ContactWechat string `json:"contact_wechat" validate:"omitempty,wechat"`
|
||||
}
|
||||
|
||||
// 更新账号信息
|
||||
func UpdateAccount(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -86,16 +153,12 @@ func UpdateAccount(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region /update/password
|
||||
|
||||
type UpdatePasswordReq struct {
|
||||
Phone string `json:"phone"`
|
||||
Code string `json:"code"`
|
||||
Password string `json:"password"`
|
||||
type UpdateAccountReq struct {
|
||||
Username string `json:"username" validate:"omitempty,min=3,max=20"`
|
||||
Password string `json:"password" validate:"omitempty,min=6,max=20"`
|
||||
}
|
||||
|
||||
// 更新账号密码
|
||||
func UpdatePassword(c *fiber.Ctx) error {
|
||||
// 检查权限
|
||||
authCtx, err := auth.GetAuthCtx(c).PermitUser()
|
||||
@@ -109,8 +172,13 @@ func UpdatePassword(c *fiber.Ctx) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 验证手机号
|
||||
if req.Phone != authCtx.User.Phone {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "手机号码不正确")
|
||||
}
|
||||
|
||||
// 验证手机令牌
|
||||
if req.Phone == "" || req.Code == "" {
|
||||
if req.Code == "" {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "手机号码和验证码不能为空")
|
||||
}
|
||||
err = s.Verifier.VerifySms(c.Context(), req.Phone, req.Code)
|
||||
@@ -135,4 +203,8 @@ func UpdatePassword(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
// endregion
|
||||
type UpdatePasswordReq struct {
|
||||
Phone string `json:"phone"`
|
||||
Code string `json:"code"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/gofiber/contrib/otelfiber/v2"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/logger"
|
||||
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||
"github.com/gofiber/fiber/v2/middleware/requestid"
|
||||
@@ -19,6 +20,14 @@ func ApplyMiddlewares(app *fiber.App) {
|
||||
EnableStackTrace: true,
|
||||
}))
|
||||
|
||||
// cors
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowCredentials: true,
|
||||
AllowOriginsFunc: func(origin string) bool {
|
||||
return true
|
||||
},
|
||||
}))
|
||||
|
||||
// logger
|
||||
app.Use(logger.New(logger.Config{
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
|
||||
19
web/models/product_sku.go
Normal file
19
web/models/product_sku.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"platform/web/core"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
// ProductSku 产品SKU表
|
||||
type ProductSku struct {
|
||||
core.Model
|
||||
ProductID int32 `json:"product_id" gorm:"column:product_id"` // 产品ID
|
||||
Code string `json:"code" gorm:"column:code"` // SSKU 代码:格式为 key=value,key=value,...,其中,key:value 是 SKU 的属性,多个属性用逗号分隔
|
||||
Name string `json:"name" gorm:"column:name"` // SKU 可读名称
|
||||
Price decimal.Decimal `json:"price" gorm:"column:price"` // 定价
|
||||
Discount float32 `json:"discount" gorm:"column:discount"` // 折扣,0 - 1 的小数,表示 xx 折
|
||||
|
||||
Product *Product `json:"product,omitempty" gorm:"foreignKey:ProductID"`
|
||||
}
|
||||
21
web/models/product_sku_user.go
Normal file
21
web/models/product_sku_user.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
// ProductSkuUser 用户产品SKU表
|
||||
type ProductSkuUser struct {
|
||||
ID int32 `json:"id" gorm:"column:id;primaryKey"`
|
||||
UserID int32 `json:"user_id" gorm:"column:user_id"` // 用户ID
|
||||
ProductSkuID int32 `json:"product_sku_id" gorm:"column:product_sku_id"` // 产品SKU ID
|
||||
Price *decimal.Decimal `json:"price,omitempty" gorm:"column:price"` // 定价(覆盖SKU定价)
|
||||
Discount *float32 `json:"discount,omitempty" gorm:"column:discount"` // 折扣(覆盖SKU折扣)
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
|
||||
|
||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
||||
ProductSku *ProductSku `json:"product_sku,omitempty" gorm:"foreignKey:ProductSkuID"`
|
||||
}
|
||||
@@ -32,3 +32,14 @@ const (
|
||||
ResourceModeTime ResourceMode = 1 // 包时
|
||||
ResourceModeQuota ResourceMode = 2 // 包量
|
||||
)
|
||||
|
||||
func (m ResourceMode) Code() string {
|
||||
switch m {
|
||||
case ResourceModeTime:
|
||||
return "time"
|
||||
case ResourceModeQuota:
|
||||
return "quota"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,8 @@ var (
|
||||
LogsUserUsage *logsUserUsage
|
||||
Permission *permission
|
||||
Product *product
|
||||
ProductSku *productSku
|
||||
ProductSkuUser *productSkuUser
|
||||
Proxy *proxy
|
||||
Refund *refund
|
||||
Resource *resource
|
||||
@@ -71,6 +73,8 @@ func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
|
||||
LogsUserUsage = &Q.LogsUserUsage
|
||||
Permission = &Q.Permission
|
||||
Product = &Q.Product
|
||||
ProductSku = &Q.ProductSku
|
||||
ProductSkuUser = &Q.ProductSkuUser
|
||||
Proxy = &Q.Proxy
|
||||
Refund = &Q.Refund
|
||||
Resource = &Q.Resource
|
||||
@@ -106,6 +110,8 @@ func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
|
||||
LogsUserUsage: newLogsUserUsage(db, opts...),
|
||||
Permission: newPermission(db, opts...),
|
||||
Product: newProduct(db, opts...),
|
||||
ProductSku: newProductSku(db, opts...),
|
||||
ProductSkuUser: newProductSkuUser(db, opts...),
|
||||
Proxy: newProxy(db, opts...),
|
||||
Refund: newRefund(db, opts...),
|
||||
Resource: newResource(db, opts...),
|
||||
@@ -142,6 +148,8 @@ type Query struct {
|
||||
LogsUserUsage logsUserUsage
|
||||
Permission permission
|
||||
Product product
|
||||
ProductSku productSku
|
||||
ProductSkuUser productSkuUser
|
||||
Proxy proxy
|
||||
Refund refund
|
||||
Resource resource
|
||||
@@ -179,6 +187,8 @@ func (q *Query) clone(db *gorm.DB) *Query {
|
||||
LogsUserUsage: q.LogsUserUsage.clone(db),
|
||||
Permission: q.Permission.clone(db),
|
||||
Product: q.Product.clone(db),
|
||||
ProductSku: q.ProductSku.clone(db),
|
||||
ProductSkuUser: q.ProductSkuUser.clone(db),
|
||||
Proxy: q.Proxy.clone(db),
|
||||
Refund: q.Refund.clone(db),
|
||||
Resource: q.Resource.clone(db),
|
||||
@@ -223,6 +233,8 @@ func (q *Query) ReplaceDB(db *gorm.DB) *Query {
|
||||
LogsUserUsage: q.LogsUserUsage.replaceDB(db),
|
||||
Permission: q.Permission.replaceDB(db),
|
||||
Product: q.Product.replaceDB(db),
|
||||
ProductSku: q.ProductSku.replaceDB(db),
|
||||
ProductSkuUser: q.ProductSkuUser.replaceDB(db),
|
||||
Proxy: q.Proxy.replaceDB(db),
|
||||
Refund: q.Refund.replaceDB(db),
|
||||
Resource: q.Resource.replaceDB(db),
|
||||
@@ -257,6 +269,8 @@ type queryCtx struct {
|
||||
LogsUserUsage *logsUserUsageDo
|
||||
Permission *permissionDo
|
||||
Product *productDo
|
||||
ProductSku *productSkuDo
|
||||
ProductSkuUser *productSkuUserDo
|
||||
Proxy *proxyDo
|
||||
Refund *refundDo
|
||||
Resource *resourceDo
|
||||
@@ -291,6 +305,8 @@ func (q *Query) WithContext(ctx context.Context) *queryCtx {
|
||||
LogsUserUsage: q.LogsUserUsage.WithContext(ctx),
|
||||
Permission: q.Permission.WithContext(ctx),
|
||||
Product: q.Product.WithContext(ctx),
|
||||
ProductSku: q.ProductSku.WithContext(ctx),
|
||||
ProductSkuUser: q.ProductSkuUser.WithContext(ctx),
|
||||
Proxy: q.Proxy.WithContext(ctx),
|
||||
Refund: q.Refund.WithContext(ctx),
|
||||
Resource: q.Resource.WithContext(ctx),
|
||||
|
||||
442
web/queries/product_sku.gen.go
Normal file
442
web/queries/product_sku.gen.go
Normal file
@@ -0,0 +1,442 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"platform/web/models"
|
||||
)
|
||||
|
||||
func newProductSku(db *gorm.DB, opts ...gen.DOOption) productSku {
|
||||
_productSku := productSku{}
|
||||
|
||||
_productSku.productSkuDo.UseDB(db, opts...)
|
||||
_productSku.productSkuDo.UseModel(&models.ProductSku{})
|
||||
|
||||
tableName := _productSku.productSkuDo.TableName()
|
||||
_productSku.ALL = field.NewAsterisk(tableName)
|
||||
_productSku.ID = field.NewInt32(tableName, "id")
|
||||
_productSku.CreatedAt = field.NewTime(tableName, "created_at")
|
||||
_productSku.UpdatedAt = field.NewTime(tableName, "updated_at")
|
||||
_productSku.DeletedAt = field.NewField(tableName, "deleted_at")
|
||||
_productSku.ProductID = field.NewInt32(tableName, "product_id")
|
||||
_productSku.Code = field.NewString(tableName, "code")
|
||||
_productSku.Name = field.NewString(tableName, "name")
|
||||
_productSku.Price = field.NewField(tableName, "price")
|
||||
_productSku.Discount = field.NewFloat32(tableName, "discount")
|
||||
_productSku.Product = productSkuBelongsToProduct{
|
||||
db: db.Session(&gorm.Session{}),
|
||||
|
||||
RelationField: field.NewRelation("Product", "models.Product"),
|
||||
}
|
||||
|
||||
_productSku.fillFieldMap()
|
||||
|
||||
return _productSku
|
||||
}
|
||||
|
||||
type productSku struct {
|
||||
productSkuDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Int32
|
||||
CreatedAt field.Time
|
||||
UpdatedAt field.Time
|
||||
DeletedAt field.Field
|
||||
ProductID field.Int32
|
||||
Code field.String
|
||||
Name field.String
|
||||
Price field.Field
|
||||
Discount field.Float32
|
||||
Product productSkuBelongsToProduct
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (p productSku) Table(newTableName string) *productSku {
|
||||
p.productSkuDo.UseTable(newTableName)
|
||||
return p.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (p productSku) As(alias string) *productSku {
|
||||
p.productSkuDo.DO = *(p.productSkuDo.As(alias).(*gen.DO))
|
||||
return p.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (p *productSku) updateTableName(table string) *productSku {
|
||||
p.ALL = field.NewAsterisk(table)
|
||||
p.ID = field.NewInt32(table, "id")
|
||||
p.CreatedAt = field.NewTime(table, "created_at")
|
||||
p.UpdatedAt = field.NewTime(table, "updated_at")
|
||||
p.DeletedAt = field.NewField(table, "deleted_at")
|
||||
p.ProductID = field.NewInt32(table, "product_id")
|
||||
p.Code = field.NewString(table, "code")
|
||||
p.Name = field.NewString(table, "name")
|
||||
p.Price = field.NewField(table, "price")
|
||||
p.Discount = field.NewFloat32(table, "discount")
|
||||
|
||||
p.fillFieldMap()
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *productSku) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := p.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (p *productSku) fillFieldMap() {
|
||||
p.fieldMap = make(map[string]field.Expr, 10)
|
||||
p.fieldMap["id"] = p.ID
|
||||
p.fieldMap["created_at"] = p.CreatedAt
|
||||
p.fieldMap["updated_at"] = p.UpdatedAt
|
||||
p.fieldMap["deleted_at"] = p.DeletedAt
|
||||
p.fieldMap["product_id"] = p.ProductID
|
||||
p.fieldMap["code"] = p.Code
|
||||
p.fieldMap["name"] = p.Name
|
||||
p.fieldMap["price"] = p.Price
|
||||
p.fieldMap["discount"] = p.Discount
|
||||
|
||||
}
|
||||
|
||||
func (p productSku) clone(db *gorm.DB) productSku {
|
||||
p.productSkuDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
p.Product.db = db.Session(&gorm.Session{Initialized: true})
|
||||
p.Product.db.Statement.ConnPool = db.Statement.ConnPool
|
||||
return p
|
||||
}
|
||||
|
||||
func (p productSku) replaceDB(db *gorm.DB) productSku {
|
||||
p.productSkuDo.ReplaceDB(db)
|
||||
p.Product.db = db.Session(&gorm.Session{})
|
||||
return p
|
||||
}
|
||||
|
||||
type productSkuBelongsToProduct struct {
|
||||
db *gorm.DB
|
||||
|
||||
field.RelationField
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProduct) Where(conds ...field.Expr) *productSkuBelongsToProduct {
|
||||
if len(conds) == 0 {
|
||||
return &a
|
||||
}
|
||||
|
||||
exprs := make([]clause.Expression, 0, len(conds))
|
||||
for _, cond := range conds {
|
||||
exprs = append(exprs, cond.BeCond().(clause.Expression))
|
||||
}
|
||||
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProduct) WithContext(ctx context.Context) *productSkuBelongsToProduct {
|
||||
a.db = a.db.WithContext(ctx)
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProduct) Session(session *gorm.Session) *productSkuBelongsToProduct {
|
||||
a.db = a.db.Session(session)
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProduct) Model(m *models.ProductSku) *productSkuBelongsToProductTx {
|
||||
return &productSkuBelongsToProductTx{a.db.Model(m).Association(a.Name())}
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProduct) Unscoped() *productSkuBelongsToProduct {
|
||||
a.db = a.db.Unscoped()
|
||||
return &a
|
||||
}
|
||||
|
||||
type productSkuBelongsToProductTx struct{ tx *gorm.Association }
|
||||
|
||||
func (a productSkuBelongsToProductTx) Find() (result *models.Product, err error) {
|
||||
return result, a.tx.Find(&result)
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProductTx) Append(values ...*models.Product) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Append(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProductTx) Replace(values ...*models.Product) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Replace(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProductTx) Delete(values ...*models.Product) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Delete(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProductTx) Clear() error {
|
||||
return a.tx.Clear()
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProductTx) Count() int64 {
|
||||
return a.tx.Count()
|
||||
}
|
||||
|
||||
func (a productSkuBelongsToProductTx) Unscoped() *productSkuBelongsToProductTx {
|
||||
a.tx = a.tx.Unscoped()
|
||||
return &a
|
||||
}
|
||||
|
||||
type productSkuDo struct{ gen.DO }
|
||||
|
||||
func (p productSkuDo) Debug() *productSkuDo {
|
||||
return p.withDO(p.DO.Debug())
|
||||
}
|
||||
|
||||
func (p productSkuDo) WithContext(ctx context.Context) *productSkuDo {
|
||||
return p.withDO(p.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (p productSkuDo) ReadDB() *productSkuDo {
|
||||
return p.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (p productSkuDo) WriteDB() *productSkuDo {
|
||||
return p.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (p productSkuDo) Session(config *gorm.Session) *productSkuDo {
|
||||
return p.withDO(p.DO.Session(config))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Clauses(conds ...clause.Expression) *productSkuDo {
|
||||
return p.withDO(p.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Returning(value interface{}, columns ...string) *productSkuDo {
|
||||
return p.withDO(p.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Not(conds ...gen.Condition) *productSkuDo {
|
||||
return p.withDO(p.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Or(conds ...gen.Condition) *productSkuDo {
|
||||
return p.withDO(p.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Select(conds ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Where(conds ...gen.Condition) *productSkuDo {
|
||||
return p.withDO(p.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Order(conds ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Distinct(cols ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Omit(cols ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Join(table schema.Tabler, on ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) LeftJoin(table schema.Tabler, on ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) RightJoin(table schema.Tabler, on ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Group(cols ...field.Expr) *productSkuDo {
|
||||
return p.withDO(p.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Having(conds ...gen.Condition) *productSkuDo {
|
||||
return p.withDO(p.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Limit(limit int) *productSkuDo {
|
||||
return p.withDO(p.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Offset(offset int) *productSkuDo {
|
||||
return p.withDO(p.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *productSkuDo {
|
||||
return p.withDO(p.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Unscoped() *productSkuDo {
|
||||
return p.withDO(p.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (p productSkuDo) Create(values ...*models.ProductSku) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return p.DO.Create(values)
|
||||
}
|
||||
|
||||
func (p productSkuDo) CreateInBatches(values []*models.ProductSku, batchSize int) error {
|
||||
return p.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (p productSkuDo) Save(values ...*models.ProductSku) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return p.DO.Save(values)
|
||||
}
|
||||
|
||||
func (p productSkuDo) First() (*models.ProductSku, error) {
|
||||
if result, err := p.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSku), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuDo) Take() (*models.ProductSku, error) {
|
||||
if result, err := p.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSku), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuDo) Last() (*models.ProductSku, error) {
|
||||
if result, err := p.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSku), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuDo) Find() ([]*models.ProductSku, error) {
|
||||
result, err := p.DO.Find()
|
||||
return result.([]*models.ProductSku), err
|
||||
}
|
||||
|
||||
func (p productSkuDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.ProductSku, err error) {
|
||||
buf := make([]*models.ProductSku, 0, batchSize)
|
||||
err = p.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (p productSkuDo) FindInBatches(result *[]*models.ProductSku, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return p.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (p productSkuDo) Attrs(attrs ...field.AssignExpr) *productSkuDo {
|
||||
return p.withDO(p.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Assign(attrs ...field.AssignExpr) *productSkuDo {
|
||||
return p.withDO(p.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (p productSkuDo) Joins(fields ...field.RelationField) *productSkuDo {
|
||||
for _, _f := range fields {
|
||||
p = *p.withDO(p.DO.Joins(_f))
|
||||
}
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p productSkuDo) Preload(fields ...field.RelationField) *productSkuDo {
|
||||
for _, _f := range fields {
|
||||
p = *p.withDO(p.DO.Preload(_f))
|
||||
}
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p productSkuDo) FirstOrInit() (*models.ProductSku, error) {
|
||||
if result, err := p.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSku), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuDo) FirstOrCreate() (*models.ProductSku, error) {
|
||||
if result, err := p.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSku), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuDo) FindByPage(offset int, limit int) (result []*models.ProductSku, count int64, err error) {
|
||||
result, err = p.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = p.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (p productSkuDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = p.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = p.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (p productSkuDo) Scan(result interface{}) (err error) {
|
||||
return p.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (p productSkuDo) Delete(models ...*models.ProductSku) (result gen.ResultInfo, err error) {
|
||||
return p.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (p *productSkuDo) withDO(do gen.Dao) *productSkuDo {
|
||||
p.DO = *do.(*gen.DO)
|
||||
return p
|
||||
}
|
||||
544
web/queries/product_sku_user.gen.go
Normal file
544
web/queries/product_sku_user.gen.go
Normal file
@@ -0,0 +1,544 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"platform/web/models"
|
||||
)
|
||||
|
||||
func newProductSkuUser(db *gorm.DB, opts ...gen.DOOption) productSkuUser {
|
||||
_productSkuUser := productSkuUser{}
|
||||
|
||||
_productSkuUser.productSkuUserDo.UseDB(db, opts...)
|
||||
_productSkuUser.productSkuUserDo.UseModel(&models.ProductSkuUser{})
|
||||
|
||||
tableName := _productSkuUser.productSkuUserDo.TableName()
|
||||
_productSkuUser.ALL = field.NewAsterisk(tableName)
|
||||
_productSkuUser.ID = field.NewInt32(tableName, "id")
|
||||
_productSkuUser.UserID = field.NewInt32(tableName, "user_id")
|
||||
_productSkuUser.ProductSkuID = field.NewInt32(tableName, "product_sku_id")
|
||||
_productSkuUser.Price = field.NewField(tableName, "price")
|
||||
_productSkuUser.Discount = field.NewFloat32(tableName, "discount")
|
||||
_productSkuUser.CreatedAt = field.NewTime(tableName, "created_at")
|
||||
_productSkuUser.UpdatedAt = field.NewTime(tableName, "updated_at")
|
||||
_productSkuUser.User = productSkuUserBelongsToUser{
|
||||
db: db.Session(&gorm.Session{}),
|
||||
|
||||
RelationField: field.NewRelation("User", "models.User"),
|
||||
Admin: struct {
|
||||
field.RelationField
|
||||
}{
|
||||
RelationField: field.NewRelation("User.Admin", "models.Admin"),
|
||||
},
|
||||
}
|
||||
|
||||
_productSkuUser.ProductSku = productSkuUserBelongsToProductSku{
|
||||
db: db.Session(&gorm.Session{}),
|
||||
|
||||
RelationField: field.NewRelation("ProductSku", "models.ProductSku"),
|
||||
Product: struct {
|
||||
field.RelationField
|
||||
}{
|
||||
RelationField: field.NewRelation("ProductSku.Product", "models.Product"),
|
||||
},
|
||||
}
|
||||
|
||||
_productSkuUser.fillFieldMap()
|
||||
|
||||
return _productSkuUser
|
||||
}
|
||||
|
||||
type productSkuUser struct {
|
||||
productSkuUserDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Int32
|
||||
UserID field.Int32
|
||||
ProductSkuID field.Int32
|
||||
Price field.Field
|
||||
Discount field.Float32
|
||||
CreatedAt field.Time
|
||||
UpdatedAt field.Time
|
||||
User productSkuUserBelongsToUser
|
||||
|
||||
ProductSku productSkuUserBelongsToProductSku
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (p productSkuUser) Table(newTableName string) *productSkuUser {
|
||||
p.productSkuUserDo.UseTable(newTableName)
|
||||
return p.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (p productSkuUser) As(alias string) *productSkuUser {
|
||||
p.productSkuUserDo.DO = *(p.productSkuUserDo.As(alias).(*gen.DO))
|
||||
return p.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (p *productSkuUser) updateTableName(table string) *productSkuUser {
|
||||
p.ALL = field.NewAsterisk(table)
|
||||
p.ID = field.NewInt32(table, "id")
|
||||
p.UserID = field.NewInt32(table, "user_id")
|
||||
p.ProductSkuID = field.NewInt32(table, "product_sku_id")
|
||||
p.Price = field.NewField(table, "price")
|
||||
p.Discount = field.NewFloat32(table, "discount")
|
||||
p.CreatedAt = field.NewTime(table, "created_at")
|
||||
p.UpdatedAt = field.NewTime(table, "updated_at")
|
||||
|
||||
p.fillFieldMap()
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *productSkuUser) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := p.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (p *productSkuUser) fillFieldMap() {
|
||||
p.fieldMap = make(map[string]field.Expr, 9)
|
||||
p.fieldMap["id"] = p.ID
|
||||
p.fieldMap["user_id"] = p.UserID
|
||||
p.fieldMap["product_sku_id"] = p.ProductSkuID
|
||||
p.fieldMap["price"] = p.Price
|
||||
p.fieldMap["discount"] = p.Discount
|
||||
p.fieldMap["created_at"] = p.CreatedAt
|
||||
p.fieldMap["updated_at"] = p.UpdatedAt
|
||||
|
||||
}
|
||||
|
||||
func (p productSkuUser) clone(db *gorm.DB) productSkuUser {
|
||||
p.productSkuUserDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
p.User.db = db.Session(&gorm.Session{Initialized: true})
|
||||
p.User.db.Statement.ConnPool = db.Statement.ConnPool
|
||||
p.ProductSku.db = db.Session(&gorm.Session{Initialized: true})
|
||||
p.ProductSku.db.Statement.ConnPool = db.Statement.ConnPool
|
||||
return p
|
||||
}
|
||||
|
||||
func (p productSkuUser) replaceDB(db *gorm.DB) productSkuUser {
|
||||
p.productSkuUserDo.ReplaceDB(db)
|
||||
p.User.db = db.Session(&gorm.Session{})
|
||||
p.ProductSku.db = db.Session(&gorm.Session{})
|
||||
return p
|
||||
}
|
||||
|
||||
type productSkuUserBelongsToUser struct {
|
||||
db *gorm.DB
|
||||
|
||||
field.RelationField
|
||||
|
||||
Admin struct {
|
||||
field.RelationField
|
||||
}
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUser) Where(conds ...field.Expr) *productSkuUserBelongsToUser {
|
||||
if len(conds) == 0 {
|
||||
return &a
|
||||
}
|
||||
|
||||
exprs := make([]clause.Expression, 0, len(conds))
|
||||
for _, cond := range conds {
|
||||
exprs = append(exprs, cond.BeCond().(clause.Expression))
|
||||
}
|
||||
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUser) WithContext(ctx context.Context) *productSkuUserBelongsToUser {
|
||||
a.db = a.db.WithContext(ctx)
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUser) Session(session *gorm.Session) *productSkuUserBelongsToUser {
|
||||
a.db = a.db.Session(session)
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUser) Model(m *models.ProductSkuUser) *productSkuUserBelongsToUserTx {
|
||||
return &productSkuUserBelongsToUserTx{a.db.Model(m).Association(a.Name())}
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUser) Unscoped() *productSkuUserBelongsToUser {
|
||||
a.db = a.db.Unscoped()
|
||||
return &a
|
||||
}
|
||||
|
||||
type productSkuUserBelongsToUserTx struct{ tx *gorm.Association }
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Find() (result *models.User, err error) {
|
||||
return result, a.tx.Find(&result)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Append(values ...*models.User) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Append(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Replace(values ...*models.User) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Replace(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Delete(values ...*models.User) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Delete(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Clear() error {
|
||||
return a.tx.Clear()
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Count() int64 {
|
||||
return a.tx.Count()
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToUserTx) Unscoped() *productSkuUserBelongsToUserTx {
|
||||
a.tx = a.tx.Unscoped()
|
||||
return &a
|
||||
}
|
||||
|
||||
type productSkuUserBelongsToProductSku struct {
|
||||
db *gorm.DB
|
||||
|
||||
field.RelationField
|
||||
|
||||
Product struct {
|
||||
field.RelationField
|
||||
}
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSku) Where(conds ...field.Expr) *productSkuUserBelongsToProductSku {
|
||||
if len(conds) == 0 {
|
||||
return &a
|
||||
}
|
||||
|
||||
exprs := make([]clause.Expression, 0, len(conds))
|
||||
for _, cond := range conds {
|
||||
exprs = append(exprs, cond.BeCond().(clause.Expression))
|
||||
}
|
||||
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSku) WithContext(ctx context.Context) *productSkuUserBelongsToProductSku {
|
||||
a.db = a.db.WithContext(ctx)
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSku) Session(session *gorm.Session) *productSkuUserBelongsToProductSku {
|
||||
a.db = a.db.Session(session)
|
||||
return &a
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSku) Model(m *models.ProductSkuUser) *productSkuUserBelongsToProductSkuTx {
|
||||
return &productSkuUserBelongsToProductSkuTx{a.db.Model(m).Association(a.Name())}
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSku) Unscoped() *productSkuUserBelongsToProductSku {
|
||||
a.db = a.db.Unscoped()
|
||||
return &a
|
||||
}
|
||||
|
||||
type productSkuUserBelongsToProductSkuTx struct{ tx *gorm.Association }
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Find() (result *models.ProductSku, err error) {
|
||||
return result, a.tx.Find(&result)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Append(values ...*models.ProductSku) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Append(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Replace(values ...*models.ProductSku) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Replace(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Delete(values ...*models.ProductSku) (err error) {
|
||||
targetValues := make([]interface{}, len(values))
|
||||
for i, v := range values {
|
||||
targetValues[i] = v
|
||||
}
|
||||
return a.tx.Delete(targetValues...)
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Clear() error {
|
||||
return a.tx.Clear()
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Count() int64 {
|
||||
return a.tx.Count()
|
||||
}
|
||||
|
||||
func (a productSkuUserBelongsToProductSkuTx) Unscoped() *productSkuUserBelongsToProductSkuTx {
|
||||
a.tx = a.tx.Unscoped()
|
||||
return &a
|
||||
}
|
||||
|
||||
type productSkuUserDo struct{ gen.DO }
|
||||
|
||||
func (p productSkuUserDo) Debug() *productSkuUserDo {
|
||||
return p.withDO(p.DO.Debug())
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) WithContext(ctx context.Context) *productSkuUserDo {
|
||||
return p.withDO(p.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) ReadDB() *productSkuUserDo {
|
||||
return p.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) WriteDB() *productSkuUserDo {
|
||||
return p.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Session(config *gorm.Session) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Session(config))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Clauses(conds ...clause.Expression) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Returning(value interface{}, columns ...string) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Not(conds ...gen.Condition) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Or(conds ...gen.Condition) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Select(conds ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Where(conds ...gen.Condition) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Order(conds ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Distinct(cols ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Omit(cols ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Join(table schema.Tabler, on ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) LeftJoin(table schema.Tabler, on ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) RightJoin(table schema.Tabler, on ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Group(cols ...field.Expr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Having(conds ...gen.Condition) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Limit(limit int) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Offset(offset int) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Unscoped() *productSkuUserDo {
|
||||
return p.withDO(p.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Create(values ...*models.ProductSkuUser) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return p.DO.Create(values)
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) CreateInBatches(values []*models.ProductSkuUser, batchSize int) error {
|
||||
return p.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (p productSkuUserDo) Save(values ...*models.ProductSkuUser) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return p.DO.Save(values)
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) First() (*models.ProductSkuUser, error) {
|
||||
if result, err := p.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSkuUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Take() (*models.ProductSkuUser, error) {
|
||||
if result, err := p.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSkuUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Last() (*models.ProductSkuUser, error) {
|
||||
if result, err := p.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSkuUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Find() ([]*models.ProductSkuUser, error) {
|
||||
result, err := p.DO.Find()
|
||||
return result.([]*models.ProductSkuUser), err
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.ProductSkuUser, err error) {
|
||||
buf := make([]*models.ProductSkuUser, 0, batchSize)
|
||||
err = p.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) FindInBatches(result *[]*models.ProductSkuUser, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return p.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Attrs(attrs ...field.AssignExpr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Assign(attrs ...field.AssignExpr) *productSkuUserDo {
|
||||
return p.withDO(p.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Joins(fields ...field.RelationField) *productSkuUserDo {
|
||||
for _, _f := range fields {
|
||||
p = *p.withDO(p.DO.Joins(_f))
|
||||
}
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Preload(fields ...field.RelationField) *productSkuUserDo {
|
||||
for _, _f := range fields {
|
||||
p = *p.withDO(p.DO.Preload(_f))
|
||||
}
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) FirstOrInit() (*models.ProductSkuUser, error) {
|
||||
if result, err := p.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSkuUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) FirstOrCreate() (*models.ProductSkuUser, error) {
|
||||
if result, err := p.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.ProductSkuUser), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) FindByPage(offset int, limit int) (result []*models.ProductSkuUser, count int64, err error) {
|
||||
result, err = p.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = p.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = p.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = p.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Scan(result interface{}) (err error) {
|
||||
return p.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (p productSkuUserDo) Delete(models ...*models.ProductSkuUser) (result gen.ResultInfo, err error) {
|
||||
return p.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (p *productSkuUserDo) withDO(do gen.Dao) *productSkuUserDo {
|
||||
p.DO = *do.(*gen.DO)
|
||||
return p
|
||||
}
|
||||
@@ -10,12 +10,31 @@ import (
|
||||
|
||||
func ApplyRouters(app *fiber.App) {
|
||||
api := app.Group("/api")
|
||||
userRouter(api)
|
||||
adminRouter(api)
|
||||
|
||||
// 回调
|
||||
callbacks := app.Group("/callback")
|
||||
callbacks.Get("/identify", handlers.IdentifyCallbackNew)
|
||||
|
||||
// 临时
|
||||
if env.RunMode == env.RunModeDev {
|
||||
debug := app.Group("/debug")
|
||||
debug.Get("/sms/:phone", handlers.DebugGetSmsCode)
|
||||
debug.Get("/proxy/register", handlers.DebugRegisterProxyBaiYin)
|
||||
debug.Get("/iden/clear/:phone", handlers.DebugIdentifyClear)
|
||||
}
|
||||
}
|
||||
|
||||
// 用户接口路由
|
||||
func userRouter(api fiber.Router) {
|
||||
// 认证
|
||||
auth := api.Group("/auth")
|
||||
auth.Get("/authorize", auth2.AuthorizeGet)
|
||||
auth.Post("/authorize", auth2.AuthorizePost)
|
||||
auth.Post("/token", auth2.Token)
|
||||
auth.Post("/revoke", handlers.Revoke)
|
||||
auth.Post("/introspect", handlers.Introspect)
|
||||
auth.Post("/revoke", auth2.Revoke)
|
||||
auth.Post("/introspect", auth2.Introspect)
|
||||
auth.Post("/verify/sms", handlers.SmsCode)
|
||||
|
||||
// 用户
|
||||
@@ -35,8 +54,8 @@ func ApplyRouters(app *fiber.App) {
|
||||
// 套餐
|
||||
resource := api.Group("/resource")
|
||||
resource.Post("/all", handlers.AllActiveResource)
|
||||
resource.Post("/list/short", handlers.ListResourceShort)
|
||||
resource.Post("/list/long", handlers.ListResourceLong)
|
||||
resource.Post("/list/short", handlers.PageResourceShort)
|
||||
resource.Post("/list/long", handlers.PageResourceLong)
|
||||
resource.Post("/create", handlers.CreateResource)
|
||||
resource.Post("/price", handlers.ResourcePrice)
|
||||
resource.Post("/statistics/free", handlers.StatisticResourceFree)
|
||||
@@ -72,7 +91,7 @@ func ApplyRouters(app *fiber.App) {
|
||||
proxy.Post("/online", handlers.ProxyReportOnline)
|
||||
proxy.Post("/offline", handlers.ProxyReportOffline)
|
||||
proxy.Post("/update", handlers.ProxyReportUpdate)
|
||||
proxy.Post("/register", handlers.ProxyRegisterBaiYin)
|
||||
proxy.Post("/register/baidyin", handlers.ProxyRegisterBaiYin)
|
||||
|
||||
// 节点
|
||||
edge := api.Group("/edge")
|
||||
@@ -82,15 +101,35 @@ func ApplyRouters(app *fiber.App) {
|
||||
// 前台
|
||||
inquiry := api.Group("/inquiry")
|
||||
inquiry.Post("/create", handlers.CreateInquiry)
|
||||
|
||||
// 回调
|
||||
callbacks := app.Group("/callback")
|
||||
callbacks.Get("/identify", handlers.IdentifyCallbackNew)
|
||||
|
||||
// 临时
|
||||
if env.RunMode == env.RunModeDev {
|
||||
debug := app.Group("/debug")
|
||||
debug.Get("/sms/:phone", handlers.DebugGetSmsCode)
|
||||
debug.Get("/proxy/register", handlers.DebugRegisterProxyBaiYin)
|
||||
}
|
||||
}
|
||||
|
||||
// 管理员接口路由
|
||||
func adminRouter(api fiber.Router) {
|
||||
api = api.Group("/admin")
|
||||
|
||||
// user 用户
|
||||
var user = api.Group("/user")
|
||||
user.Post("/page", handlers.PageUserByAdmin)
|
||||
user.Post("/bind", handlers.BindAdmin)
|
||||
|
||||
// resource 套餐
|
||||
var resource = api.Group("/resource")
|
||||
resource.Post("/short/page", handlers.PageResourceShortByAdmin)
|
||||
resource.Post("/long/page", handlers.PageResourceLongByAdmin)
|
||||
|
||||
// batch 批次
|
||||
var usage = api.Group("batch")
|
||||
usage.Post("/page", handlers.PageBatchByAdmin)
|
||||
|
||||
// channel 通道
|
||||
var channel = api.Group("/channel")
|
||||
channel.Post("/page", handlers.PageChannelsByAdmin)
|
||||
|
||||
// trade 交易
|
||||
var trade = api.Group("trade")
|
||||
trade.Post("/page", handlers.PageTradeByAdmin)
|
||||
|
||||
// bill 账单
|
||||
var bill = api.Group("/bill")
|
||||
bill.Post("/page", handlers.PageBillByAdmin)
|
||||
}
|
||||
|
||||
12
web/services/product.go
Normal file
12
web/services/product.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package services
|
||||
|
||||
import q "platform/web/queries"
|
||||
|
||||
var Product = &productService{}
|
||||
|
||||
type productService struct{}
|
||||
|
||||
// 获取产品价格
|
||||
func (s *productService) GetPrice(code string) {
|
||||
q.ProductSku.Where(q.ProductSku.Code.Eq(code)).Find()
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var Resource = &resourceService{}
|
||||
@@ -27,8 +28,14 @@ func (s *resourceService) CreateResourceByBalance(uid int32, now time.Time, data
|
||||
return err
|
||||
}
|
||||
|
||||
// 获取 sku
|
||||
sku, err := s.GetSku(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查余额
|
||||
amount, err := data.GetAmount()
|
||||
_, amount, err := s.GetPrice(sku, data.Count(), &uid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -57,11 +64,7 @@ func (s *resourceService) CreateResourceByBalance(uid int32, now time.Time, data
|
||||
}
|
||||
|
||||
// 生成账单
|
||||
subject, err := data.GetSubject()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = q.Bill.Create(newForConsume(uid, Bill.GenNo(), subject, amount, resource))
|
||||
err = q.Bill.Create(newForConsume(uid, Bill.GenNo(), sku.Name, amount, resource))
|
||||
if err != nil {
|
||||
return core.NewServErr("生成账单失败", err)
|
||||
}
|
||||
@@ -70,7 +73,7 @@ func (s *resourceService) CreateResourceByBalance(uid int32, now time.Time, data
|
||||
})
|
||||
}
|
||||
|
||||
func (s *resourceService) CreateResourceByTrade(uid int32, now time.Time, data *CreateResourceData, trade *m.Trade) error { // 检查交易
|
||||
func (s *resourceService) CreateResourceByTrade(uid int32, now time.Time, data *CreateResourceByTradeData, trade *m.Trade) error { // 检查交易
|
||||
if trade == nil {
|
||||
return core.NewBizErr("交易数据不能为空")
|
||||
}
|
||||
@@ -81,21 +84,13 @@ func (s *resourceService) CreateResourceByTrade(uid int32, now time.Time, data *
|
||||
return q.Q.Transaction(func(q *q.Query) error {
|
||||
|
||||
// 保存套餐
|
||||
resource, err := createResource(q, uid, now, data)
|
||||
resource, err := createResource(q, uid, now, data.Req)
|
||||
if err != nil {
|
||||
return core.NewServErr("创建套餐失败", err)
|
||||
}
|
||||
|
||||
// 生成账单
|
||||
subject, err := data.GetSubject()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amount, err := data.GetAmount()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = q.Bill.Create(newForConsume(uid, Bill.GenNo(), subject, amount, resource, trade))
|
||||
err = q.Bill.Create(newForConsume(uid, Bill.GenNo(), data.GetSubject(), data.GetAmount(), resource, trade))
|
||||
if err != nil {
|
||||
return core.NewServErr("生成账单失败", err)
|
||||
}
|
||||
@@ -164,6 +159,46 @@ func createResource(q *q.Query, uid int32, now time.Time, data *CreateResourceDa
|
||||
return &resource, nil
|
||||
}
|
||||
|
||||
func (s *resourceService) GetSku(data *CreateResourceData) (*m.ProductSku, error) {
|
||||
sku, err := q.ProductSku.Where(q.ProductSku.Code.Eq(data.Code())).Take()
|
||||
if err != nil {
|
||||
return nil, core.NewServErr("产品不可用", err)
|
||||
}
|
||||
|
||||
return sku, nil
|
||||
}
|
||||
|
||||
func (s *resourceService) GetPrice(sku *m.ProductSku, count int32, uid *int32) (decimal.Decimal, decimal.Decimal, error) {
|
||||
|
||||
// 根据用户 id 查询特殊优惠
|
||||
var uSku *m.ProductSkuUser
|
||||
if uid != nil {
|
||||
var err error
|
||||
uSku, err = q.ProductSkuUser.Where(
|
||||
q.ProductSkuUser.UserID.Eq(*uid),
|
||||
q.ProductSkuUser.ProductSkuID.Eq(sku.ID),
|
||||
).Take()
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return decimal.Zero, decimal.Zero, core.NewServErr("客户特殊价查询失败", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 返回计算价格
|
||||
price := sku.Price
|
||||
if uSku != nil && uSku.Price != nil {
|
||||
price = *uSku.Price
|
||||
}
|
||||
|
||||
discount := sku.Discount
|
||||
if uSku != nil && uSku.Discount != nil {
|
||||
discount = *uSku.Discount
|
||||
}
|
||||
|
||||
before := price.Mul(decimal.NewFromInt32(count))
|
||||
after := before.Mul(decimal.NewFromFloat32(discount))
|
||||
return before, after, nil
|
||||
}
|
||||
|
||||
type CreateResourceData struct {
|
||||
Type m.ResourceType `json:"type" validate:"required"`
|
||||
Short *CreateShortResourceData `json:"short,omitempty"`
|
||||
@@ -171,7 +206,7 @@ type CreateResourceData struct {
|
||||
}
|
||||
|
||||
type CreateShortResourceData struct {
|
||||
Live int32 `json:"live" validate:"required,min=180"`
|
||||
Live int32 `json:"live" validate:"required"`
|
||||
Mode m.ResourceMode `json:"mode" validate:"required"`
|
||||
Quota int32 `json:"quota" validate:"required"`
|
||||
Expire *int32 `json:"expire"`
|
||||
@@ -190,31 +225,33 @@ type CreateLongResourceData struct {
|
||||
price *decimal.Decimal
|
||||
}
|
||||
|
||||
func (c *CreateResourceData) GetType() m.TradeType {
|
||||
return m.TradeTypePurchase
|
||||
}
|
||||
|
||||
func (c *CreateResourceData) GetSubject() (string, error) {
|
||||
func (c *CreateResourceData) Count() int32 {
|
||||
switch {
|
||||
default:
|
||||
return "", errors.New("无效的套餐类型")
|
||||
|
||||
return 0
|
||||
case c.Type == m.ResourceTypeShort && c.Short != nil:
|
||||
return c.Short.GetSubject()
|
||||
return c.Short.Quota
|
||||
case c.Type == m.ResourceTypeLong && c.Long != nil:
|
||||
return c.Long.GetSubject()
|
||||
return c.Long.Quota
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CreateResourceData) GetAmount() (decimal.Decimal, error) {
|
||||
func (c *CreateResourceData) Code() string {
|
||||
switch {
|
||||
default:
|
||||
return decimal.Zero, errors.New("无效的套餐类型")
|
||||
return ""
|
||||
|
||||
case c.Type == m.ResourceTypeShort && c.Short != nil:
|
||||
return c.Short.GetAmount()
|
||||
return fmt.Sprintf(
|
||||
"mode=%s,live=%d,expire=%d",
|
||||
c.Short.Mode.Code(), c.Short.Live, u.Else(c.Short.Expire, 0),
|
||||
)
|
||||
|
||||
case c.Type == m.ResourceTypeLong && c.Long != nil:
|
||||
return c.Long.GetAmount()
|
||||
return fmt.Sprintf(
|
||||
"mode=%s,live=%d,expire=%d",
|
||||
c.Long.Mode.Code(), c.Long.Live, u.Else(c.Long.Expire, 0),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,132 +264,63 @@ func (c *CreateResourceData) Deserialize(str string) error {
|
||||
return json.Unmarshal([]byte(str), c)
|
||||
}
|
||||
|
||||
func (data *CreateShortResourceData) GetSubject() (string, error) {
|
||||
if data.name == "" {
|
||||
var mode string
|
||||
switch data.Mode {
|
||||
default:
|
||||
return "", errors.New("无效的套餐模式")
|
||||
|
||||
case m.ResourceModeTime:
|
||||
mode = "包时"
|
||||
case m.ResourceModeQuota:
|
||||
mode = "包量"
|
||||
}
|
||||
|
||||
data.name = fmt.Sprintf("短效动态%s %v 分钟", mode, data.Live/60)
|
||||
}
|
||||
return data.name, nil
|
||||
}
|
||||
|
||||
func (data *CreateShortResourceData) GetAmount() (decimal.Decimal, error) {
|
||||
if data.price == nil {
|
||||
var factor int32
|
||||
switch data.Mode {
|
||||
default:
|
||||
return decimal.Zero, errors.New("无效的套餐模式")
|
||||
|
||||
case m.ResourceModeTime:
|
||||
if data.Expire == nil {
|
||||
return decimal.Zero, errors.New("包时套餐过期时间不能为空")
|
||||
}
|
||||
factor = data.Quota * *data.Expire
|
||||
case m.ResourceModeQuota:
|
||||
factor = data.Quota
|
||||
}
|
||||
|
||||
var base = data.Live
|
||||
if base == 180 {
|
||||
base = 150
|
||||
}
|
||||
|
||||
var dec = decimal.Decimal{}.
|
||||
Add(decimal.NewFromInt32(base * factor)).
|
||||
Div(decimal.NewFromInt(30000))
|
||||
if dec.IsZero() {
|
||||
return decimal.Zero, errors.New("计算金额错误")
|
||||
}
|
||||
|
||||
data.price = &dec
|
||||
}
|
||||
return *data.price, nil
|
||||
}
|
||||
|
||||
func (data *CreateLongResourceData) GetSubject() (string, error) {
|
||||
if data.name == "" {
|
||||
var mode string
|
||||
switch data.Mode {
|
||||
default:
|
||||
return "", errors.New("无效的套餐模式")
|
||||
|
||||
case m.ResourceModeTime:
|
||||
mode = "包时"
|
||||
case m.ResourceModeQuota:
|
||||
mode = "包量"
|
||||
}
|
||||
|
||||
data.name = fmt.Sprintf("长效动态%s %d 小时", mode, data.Live)
|
||||
}
|
||||
return data.name, nil
|
||||
}
|
||||
|
||||
func (data *CreateLongResourceData) GetAmount() (decimal.Decimal, error) {
|
||||
if data.price == nil {
|
||||
var factor int32 = 0
|
||||
switch data.Mode {
|
||||
default:
|
||||
return decimal.Zero, errors.New("无效的套餐模式")
|
||||
|
||||
case m.ResourceModeTime:
|
||||
if data.Expire == nil {
|
||||
return decimal.Zero, errors.New("包时套餐过期时间不能为空")
|
||||
}
|
||||
factor = *data.Expire * data.Quota
|
||||
case m.ResourceModeQuota:
|
||||
factor = data.Quota
|
||||
}
|
||||
|
||||
var base int32
|
||||
switch data.Live {
|
||||
default:
|
||||
return decimal.Zero, errors.New("无效的套餐时长")
|
||||
case 1:
|
||||
base = 30
|
||||
case 4:
|
||||
base = 80
|
||||
case 8:
|
||||
base = 120
|
||||
case 12:
|
||||
base = 180
|
||||
case 24:
|
||||
base = 350
|
||||
}
|
||||
|
||||
// data.price = big.NewRat(int64(base*factor), 100)
|
||||
var dec = decimal.Decimal{}.
|
||||
Add(decimal.NewFromInt32(base * factor)).
|
||||
Div(decimal.NewFromInt(100))
|
||||
if dec.IsZero() {
|
||||
return decimal.Zero, errors.New("计算金额错误")
|
||||
}
|
||||
|
||||
data.price = &dec
|
||||
}
|
||||
return *data.price, nil
|
||||
}
|
||||
|
||||
// 交易后创建套餐
|
||||
type ResourceOnTradeComplete struct{}
|
||||
|
||||
func (r ResourceOnTradeComplete) Check(t m.TradeType) (ProductInfo, bool) {
|
||||
if t == m.TradeTypePurchase {
|
||||
return &CreateResourceData{}, true
|
||||
return &CreateResourceByTradeData{}, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (r ResourceOnTradeComplete) OnTradeComplete(info ProductInfo, trade *m.Trade) error {
|
||||
return Resource.CreateResourceByTrade(trade.UserID, time.Time(*trade.CompletedAt), info.(*CreateResourceData), trade)
|
||||
return Resource.CreateResourceByTrade(trade.UserID, time.Time(*trade.CompletedAt), info.(*CreateResourceByTradeData), trade)
|
||||
}
|
||||
|
||||
type CreateResourceByTradeData struct {
|
||||
Subject string `json:"subject"`
|
||||
Amount decimal.Decimal `json:"amount"`
|
||||
Req *CreateResourceData `json:"data"`
|
||||
}
|
||||
|
||||
func (e CreateResourceByTradeData) GetType() m.TradeType {
|
||||
return m.TradeTypePurchase
|
||||
}
|
||||
|
||||
func (e CreateResourceByTradeData) GetSubject() string {
|
||||
return e.Subject
|
||||
}
|
||||
|
||||
func (e CreateResourceByTradeData) GetAmount() decimal.Decimal {
|
||||
return e.Amount
|
||||
}
|
||||
|
||||
func (e CreateResourceByTradeData) Serialize() (string, error) {
|
||||
bytes, err := json.Marshal(e)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
func (e *CreateResourceByTradeData) Deserialize(str string) error {
|
||||
return json.Unmarshal([]byte(str), e)
|
||||
}
|
||||
|
||||
func NewCreateResourceByTradeData(req *CreateResourceData) (*CreateResourceByTradeData, error) {
|
||||
sku, err := Resource.GetSku(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, amount, err := Resource.GetPrice(sku, req.Count(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &CreateResourceByTradeData{
|
||||
Subject: sku.Name,
|
||||
Amount: amount,
|
||||
Req: req,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 服务错误
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
wecahtpaycore "github.com/wechatpay-apiv3/wechatpay-go/core"
|
||||
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/h5"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -31,19 +32,13 @@ type tradeService struct {
|
||||
}
|
||||
|
||||
// 创建交易
|
||||
func (s *tradeService) CreateTrade(uid int32, now time.Time, data *CreateTradeData) (*CreateTradeResult, error) {
|
||||
platform := data.Platform
|
||||
method := data.Method
|
||||
tType := data.Product.GetType()
|
||||
func (s *tradeService) CreateTrade(uid int32, now time.Time, payment *CreateTradeData, product ProductInfo) (*CreateTradeResult, error) {
|
||||
platform := payment.Platform
|
||||
method := payment.Method
|
||||
tType := product.GetType()
|
||||
expire := time.Now().Add(30 * time.Minute)
|
||||
subject, err := data.Product.GetSubject()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
amount, err := data.Product.GetAmount()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
subject := product.GetSubject()
|
||||
amount := product.GetAmount()
|
||||
|
||||
// 实际支付金额,只在创建真实订单时使用
|
||||
amountReal := amount
|
||||
@@ -52,10 +47,10 @@ func (s *tradeService) CreateTrade(uid int32, now time.Time, data *CreateTradeDa
|
||||
}
|
||||
|
||||
// 附加优惠券
|
||||
if data.CouponCode != nil {
|
||||
if payment.CouponCode != nil {
|
||||
coupon, err := q.Coupon.
|
||||
Where(
|
||||
q.Coupon.Code.Eq(*data.CouponCode),
|
||||
q.Coupon.Code.Eq(*payment.CouponCode),
|
||||
q.Coupon.Status.Eq(int(m.CouponStatusUnused)),
|
||||
).
|
||||
Take()
|
||||
@@ -150,6 +145,24 @@ func (s *tradeService) CreateTrade(uid int32, now time.Time, data *CreateTradeDa
|
||||
}
|
||||
paymentUrl = *resp.CodeUrl
|
||||
|
||||
// 微信 + 手机网站
|
||||
case method == m.TradeMethodWechat && platform == m.TradePlatformMobile:
|
||||
resp, _, err := g.WechatPay.H5.Prepay(context.Background(), h5.PrepayRequest{
|
||||
SpAppid: &env.WechatPayAppId,
|
||||
SpMchid: &env.WechatPayMchId,
|
||||
OutTradeNo: &tradeNo,
|
||||
Description: &subject,
|
||||
TimeExpire: &expire,
|
||||
NotifyUrl: &env.WechatPayCallbackUrl,
|
||||
Amount: &h5.Amount{
|
||||
Total: u.P(amountReal.Mul(decimal.NewFromInt(100)).Round(0).IntPart()),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paymentUrl = *resp.H5Url
|
||||
|
||||
// 商福通 + 电脑网站
|
||||
case
|
||||
method == m.TradeMethodSftAlipay && platform == m.TradePlatformPC,
|
||||
@@ -229,7 +242,7 @@ func (s *tradeService) CreateTrade(uid int32, now time.Time, data *CreateTradeDa
|
||||
}
|
||||
|
||||
// 缓存产品数据
|
||||
serialized, err := data.Product.Serialize()
|
||||
serialized, err := product.Serialize()
|
||||
if err != nil {
|
||||
return nil, core.NewServErr("序列化产品信息失败", err)
|
||||
}
|
||||
@@ -665,7 +678,6 @@ type CreateTradeData struct {
|
||||
Platform m.TradePlatform `json:"platform" validate:"required"`
|
||||
Method m.TradeMethod `json:"method" validate:"required"`
|
||||
CouponCode *string `json:"coupon_code"`
|
||||
Product ProductInfo
|
||||
}
|
||||
|
||||
type CreateTradeResult struct {
|
||||
@@ -698,8 +710,8 @@ type OnTradeCompletedData struct {
|
||||
|
||||
type ProductInfo interface {
|
||||
GetType() m.TradeType
|
||||
GetSubject() (string, error)
|
||||
GetAmount() (decimal.Decimal, error)
|
||||
GetSubject() string
|
||||
GetAmount() decimal.Decimal
|
||||
Serialize() (string, error)
|
||||
Deserialize(str string) error
|
||||
}
|
||||
|
||||
@@ -25,14 +25,8 @@ func (s *userService) UpdateBalanceByTrade(uid int32, info *RechargeProductInfo,
|
||||
}
|
||||
|
||||
// 生成账单
|
||||
subject, err := info.GetSubject()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amount, err := info.GetAmount()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subject := info.GetSubject()
|
||||
amount := info.GetAmount()
|
||||
err = q.Bill.Create(newForRecharge(uid, Bill.GenNo(), subject, amount, trade))
|
||||
if err != nil {
|
||||
return core.NewServErr("生成账单失败", err)
|
||||
@@ -54,10 +48,7 @@ func updateBalance(q *q.Query, uid int32, info *RechargeProductInfo) error {
|
||||
return core.NewServErr("查询用户失败", err)
|
||||
}
|
||||
|
||||
amount, err := info.GetAmount()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amount := info.GetAmount()
|
||||
balance := user.Balance.Add(amount)
|
||||
if balance.IsNegative() {
|
||||
return core.NewServErr("用户余额不足")
|
||||
@@ -85,13 +76,12 @@ func (r *RechargeProductInfo) GetType() m.TradeType {
|
||||
return m.TradeTypeRecharge
|
||||
}
|
||||
|
||||
func (r *RechargeProductInfo) GetSubject() (string, error) {
|
||||
amount, _ := r.GetAmount()
|
||||
return fmt.Sprintf("账户充值 - %s元", amount.StringFixed(2)), nil
|
||||
func (r *RechargeProductInfo) GetSubject() string {
|
||||
return fmt.Sprintf("账户充值 - %s元", r.GetAmount().StringFixed(2))
|
||||
}
|
||||
|
||||
func (r *RechargeProductInfo) GetAmount() (decimal.Decimal, error) {
|
||||
return decimal.NewFromInt(int64(r.Amount)).Div(decimal.NewFromInt(100)), nil
|
||||
func (r *RechargeProductInfo) GetAmount() decimal.Decimal {
|
||||
return decimal.NewFromInt(int64(r.Amount)).Div(decimal.NewFromInt(100))
|
||||
}
|
||||
|
||||
func (r *RechargeProductInfo) Serialize() (string, error) {
|
||||
|
||||
102
web/views/iden-result.html
Normal file
102
web/views/iden-result.html
Normal file
@@ -0,0 +1,102 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>认证结果</title>
|
||||
<style>
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||
background: #f5f5f5;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
|
||||
padding: 48px 40px;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.icon {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 auto 24px;
|
||||
font-size: 36px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.icon--success {
|
||||
background: #e6f9f0;
|
||||
}
|
||||
|
||||
.icon--fail {
|
||||
background: #fff1f0;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.title--success {
|
||||
color: #0a6640;
|
||||
}
|
||||
|
||||
.title--fail {
|
||||
color: #a8071a;
|
||||
}
|
||||
|
||||
.message {
|
||||
font-size: 15px;
|
||||
color: #666;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.divider {
|
||||
border: none;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
margin: 28px 0;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 13px;
|
||||
color: #aaa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
{{if .Success}}
|
||||
<div class="icon icon--success">✅</div>
|
||||
<h1 class="title title--success">认证成功</h1>
|
||||
{{else}}
|
||||
<div class="icon icon--fail">❌</div>
|
||||
<h1 class="title title--fail">认证失败</h1>
|
||||
{{end}}
|
||||
|
||||
<p class="message">{{.Message}}</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -2,8 +2,10 @@ package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"platform/web/events"
|
||||
deps "platform/web/globals"
|
||||
@@ -11,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/template/html/v2"
|
||||
"github.com/hibiken/asynq"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
@@ -42,11 +45,15 @@ func RunApp(pCtx context.Context) error {
|
||||
return g.Wait()
|
||||
}
|
||||
|
||||
//go:embed views/*.html
|
||||
var fs embed.FS
|
||||
|
||||
func RunWeb(ctx context.Context) error {
|
||||
|
||||
fiber := fiber.New(fiber.Config{
|
||||
ProxyHeader: fiber.HeaderXForwardedFor,
|
||||
ErrorHandler: ErrorHandler,
|
||||
Views: html.NewFileSystem(http.FS(fs), ".html"),
|
||||
})
|
||||
|
||||
ApplyMiddlewares(fiber)
|
||||
|
||||
Reference in New Issue
Block a user