Compare commits
4 Commits
v1.2.3
...
9d996acf5f
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d996acf5f | |||
| 99853b8514 | |||
| efce18e6f5 | |||
| 3dc9bc5b1d |
16
README.md
16
README.md
@@ -1,5 +1,7 @@
|
||||
## TODO
|
||||
|
||||
后端默认用户名不能是完整手机号
|
||||
|
||||
前端需要 token 化改造,以避免每次 basic 认证流程中 bcrypt 对比导致的性能对比
|
||||
|
||||
优化中间件,配置通用限速
|
||||
@@ -47,6 +49,20 @@ jsonb 类型转换问题,考虑一个高效的 any 到 struct 转换工具
|
||||
|
||||
冷数据迁移方案
|
||||
|
||||
## 开发环境
|
||||
|
||||
### 更新表结构的流程
|
||||
|
||||
1. 编辑 `scripts/sql/init.sql` 文件,参照原有格式,需要注意:
|
||||
- 先写 drop table if exists 语句,确保脚本可以幂等执行
|
||||
- 编写 create table 语句,按需添加审计字段和软删除字段 (created_at, updated_at, deleted_at)
|
||||
- 为有必要的字段添加索引
|
||||
- 为数据表及其字段添加注释
|
||||
- 在文件末尾创建数据表流程全部结束后,为字段添加外键
|
||||
2. 建议用数据库工具检查差异并增量更新,或者手动增量更新
|
||||
3. 创建 model 文件,并将其添加到 gen 代码中
|
||||
4. 生成查询文件
|
||||
|
||||
## 业务逻辑
|
||||
|
||||
### 订单关闭的几种方式
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -55,6 +55,19 @@ func PageResourceShort(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).
|
||||
@@ -95,6 +108,7 @@ type PageResourceShortReq 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 - 过期
|
||||
}
|
||||
|
||||
// PageResourceLong 分页查询当前用户长效套餐
|
||||
@@ -137,6 +151,19 @@ func PageResourceLong(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).
|
||||
@@ -177,6 +204,7 @@ type PageResourceLongReq 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 分页查询全部短效套餐
|
||||
@@ -488,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),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -60,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": "创建交易失败"})
|
||||
|
||||
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
|
||||
}
|
||||
@@ -22,6 +22,7 @@ func ApplyRouters(app *fiber.App) {
|
||||
debug := app.Group("/debug")
|
||||
debug.Get("/sms/:phone", handlers.DebugGetSmsCode)
|
||||
debug.Get("/proxy/register", handlers.DebugRegisterProxyBaiYin)
|
||||
debug.Get("/iden/clear/:phone", handlers.DebugIdentifyClear)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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