update: 2026-03-28 21:00
This commit is contained in:
@@ -1,256 +1,256 @@
|
||||
# 萌芽小店 · 后端
|
||||
|
||||
基于 **Go + Gin + GORM** 构建的 RESTful API 服务,负责商品管理、订单处理、用户认证、聊天消息等核心业务。
|
||||
|
||||
## 技术依赖
|
||||
|
||||
| 包 | 版本 | 用途 |
|
||||
|----|------|------|
|
||||
| gin | v1.9 | HTTP 路由框架 |
|
||||
| gorm | v1.31 | ORM |
|
||||
| gorm/driver/mysql | v1.6 | MySQL 驱动 |
|
||||
| go-sql-driver/mysql | v1.9 | 底层 MySQL 连接 |
|
||||
| gin-contrib/cors | latest | CORS 中间件 |
|
||||
| google/uuid | latest | UUID 生成 |
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
mengyastore-backend/
|
||||
├── main.go # 程序入口,路由注册
|
||||
├── cmd/
|
||||
│ └── migrate/
|
||||
│ └── main.go # 一次性 JSON→MySQL 数据迁移脚本
|
||||
├── data/
|
||||
│ └── json/
|
||||
│ └── settings.json # 服务配置(adminToken、DSN 等)
|
||||
├── internal/
|
||||
│ ├── config/
|
||||
│ │ └── config.go # 配置加载
|
||||
│ ├── database/
|
||||
│ │ ├── db.go # GORM 初始化 + AutoMigrate
|
||||
│ │ └── models.go # 数据库行结构体(GORM 模型)
|
||||
│ ├── models/
|
||||
│ │ ├── product.go # 业务模型 Product
|
||||
│ │ ├── order.go # 业务模型 Order
|
||||
│ │ └── chat.go # 业务模型 ChatMessage
|
||||
│ ├── storage/
|
||||
│ │ ├── jsonstore.go # 商品存储(GORM 实现)
|
||||
│ │ ├── orderstore.go # 订单存储
|
||||
│ │ ├── sitestore.go # 站点设置存储
|
||||
│ │ ├── wishliststore.go # 收藏夹存储
|
||||
│ │ └── chatstore.go # 聊天消息存储(含内存级频率限制)
|
||||
│ ├── handlers/
|
||||
│ │ ├── admin.go # AdminHandler 结构体 + requireAdmin
|
||||
│ │ ├── admin_product.go # 商品 CRUD 接口
|
||||
│ │ ├── admin_site.go # 维护模式接口
|
||||
│ │ ├── admin_orders.go # 订单管理接口
|
||||
│ │ ├── admin_chat.go # 管理员聊天接口
|
||||
│ │ ├── public.go # 公开接口(商品列表、浏览量)
|
||||
│ │ ├── order.go # 下单、确认订单接口
|
||||
│ │ ├── stats.go # 统计信息接口
|
||||
│ │ ├── wishlist.go # 收藏夹接口(用户)
|
||||
│ │ └── chat.go # 聊天接口(用户)
|
||||
│ └── auth/
|
||||
│ └── sproutgate.go # SproutGate OAuth 客户端
|
||||
```
|
||||
|
||||
## API 路由一览
|
||||
|
||||
### 公开接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/health` | 健康检查 |
|
||||
| GET | `/api/products` | 获取商品列表(仅 active) |
|
||||
| POST | `/api/products/:id/view` | 记录商品浏览量 |
|
||||
| GET | `/api/stats` | 获取总订单数和总访问量 |
|
||||
| POST | `/api/site/visit` | 记录站点访问 |
|
||||
| GET | `/api/site/maintenance` | 获取维护状态 |
|
||||
| POST | `/api/checkout` | 创建订单(生成支付二维码) |
|
||||
| GET | `/api/orders` | 获取当前用户订单(需 Bearer token) |
|
||||
| POST | `/api/orders/:id/confirm` | 确认付款(触发发货) |
|
||||
|
||||
### 收藏夹(需登录)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/wishlist` | 获取收藏商品 ID 列表 |
|
||||
| POST | `/api/wishlist` | 添加收藏 |
|
||||
| DELETE | `/api/wishlist/:id` | 取消收藏 |
|
||||
|
||||
### 聊天(需登录)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/chat/messages` | 获取自己的聊天记录 |
|
||||
| POST | `/api/chat/messages` | 发送消息(1 秒频率限制) |
|
||||
|
||||
### 管理员接口(需 `?token=xxx` 或 `Authorization: <token>`)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/admin/token` | 获取令牌(用于验证) |
|
||||
| GET | `/api/admin/products` | 获取全部商品(含卡密) |
|
||||
| POST | `/api/admin/products` | 创建商品 |
|
||||
| PUT | `/api/admin/products/:id` | 编辑商品 |
|
||||
| PATCH | `/api/admin/products/:id/status` | 切换上下架 |
|
||||
| DELETE | `/api/admin/products/:id` | 删除商品 |
|
||||
| POST | `/api/admin/site/maintenance` | 设置维护模式 |
|
||||
| GET | `/api/admin/orders` | 获取全部订单 |
|
||||
| DELETE | `/api/admin/orders/:id` | 删除订单 |
|
||||
| GET | `/api/admin/chat` | 获取全部用户对话 |
|
||||
| GET | `/api/admin/chat/:account` | 获取指定用户对话 |
|
||||
| POST | `/api/admin/chat/:account` | 管理员回复 |
|
||||
| DELETE | `/api/admin/chat/:account` | 清除对话 |
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
### products
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | varchar(36) | UUID 主键 |
|
||||
| name | varchar(255) | 商品名称 |
|
||||
| price | double | 原价 |
|
||||
| discount_price | double | 折扣价(0 = 无折扣)|
|
||||
| tags | json | 标签数组 |
|
||||
| cover_url | varchar(500) | 封面图 URL |
|
||||
| screenshot_urls | json | 截图 URL 数组(最多 5 张)|
|
||||
| verification_url | varchar(500) | 验证链接 |
|
||||
| description | text | Markdown 描述 |
|
||||
| active | tinyint(1) | 是否上架 |
|
||||
| require_login | tinyint(1) | 是否必须登录购买 |
|
||||
| max_per_account | bigint | 每账户最大购买数(0=不限)|
|
||||
| total_sold | bigint | 累计销量 |
|
||||
| view_count | bigint | 累计浏览量 |
|
||||
| delivery_mode | varchar(20) | 发货模式:`auto` / `manual` |
|
||||
| show_note | tinyint(1) | 下单时显示备注输入框 |
|
||||
| show_contact | tinyint(1) | 下单时显示联系方式输入框 |
|
||||
| created_at | datetime(3) | 创建时间 |
|
||||
|
||||
### product_codes
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | bigint unsigned | 自增主键 |
|
||||
| product_id | varchar(36) | 关联商品 ID(索引)|
|
||||
| code | text | 卡密内容 |
|
||||
|
||||
### orders
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | varchar(36) | UUID 主键 |
|
||||
| product_id | varchar(36) | 商品 ID(索引)|
|
||||
| product_name | varchar(255) | 商品名称快照 |
|
||||
| user_account | varchar(255) | 用户账号(可空,匿名)|
|
||||
| user_name | varchar(255) | 用户昵称 |
|
||||
| quantity | bigint | 购买数量 |
|
||||
| delivered_codes | json | 已发放卡密 |
|
||||
| status | varchar(20) | `pending` / `completed` |
|
||||
| delivery_mode | varchar(20) | `auto` / `manual` |
|
||||
| note | text | 用户备注 |
|
||||
| contact_phone | varchar(50) | 联系手机号 |
|
||||
| contact_email | varchar(255) | 联系邮箱 |
|
||||
| created_at | datetime(3) | 下单时间 |
|
||||
|
||||
### site_settings
|
||||
|
||||
键值对存储,当前使用的键:
|
||||
|
||||
| Key | 说明 |
|
||||
|-----|------|
|
||||
| `totalVisits` | 总访问量 |
|
||||
| `maintenance` | 维护模式(`true` / `false`)|
|
||||
| `maintenanceReason` | 维护原因文本 |
|
||||
|
||||
### wishlists
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | bigint unsigned | 自增主键 |
|
||||
| account_id | varchar(255) | 用户账号(唯一索引)|
|
||||
| product_id | varchar(36) | 商品 ID(联合唯一)|
|
||||
|
||||
### chat_messages
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | varchar(36) | UUID 主键 |
|
||||
| account_id | varchar(255) | 用户账号(索引)|
|
||||
| account_name | varchar(255) | 用户昵称 |
|
||||
| content | text | 消息内容 |
|
||||
| sent_at | datetime(3) | 发送时间 |
|
||||
| from_admin | tinyint(1) | 是否来自管理员 |
|
||||
|
||||
## 配置文件
|
||||
|
||||
`data/json/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"adminToken": "你的管理员令牌",
|
||||
"authApiUrl": "https://auth.api.shumengya.top",
|
||||
"databaseDsn": ""
|
||||
}
|
||||
```
|
||||
|
||||
`databaseDsn` 为空时自动使用测试数据库。也可以通过环境变量 `DATABASE_DSN` 覆盖。
|
||||
|
||||
## 发货逻辑
|
||||
|
||||
### 自动发货(`deliveryMode = "auto"`)
|
||||
|
||||
1. `POST /api/checkout` → 从 `product_codes` 提取指定数量的卡密
|
||||
2. 商品 `quantity` 减少,卡密从数据库删除
|
||||
3. 卡密保存到订单 `delivered_codes`
|
||||
4. 用户 `POST /api/orders/:id/confirm` 确认付款后,订单状态变为 `completed`,响应中返回卡密内容
|
||||
5. 同时调用 `IncrementSold` 增加销量统计
|
||||
|
||||
### 手动发货(`deliveryMode = "manual"`)
|
||||
|
||||
1. `POST /api/checkout` → 创建订单,不提取卡密
|
||||
2. 用户 `POST /api/orders/:id/confirm` 后,订单变为 `completed`,但 `delivered_codes` 为空
|
||||
3. 管理员在后台查看订单的备注、手机号、邮箱后手动发货
|
||||
|
||||
## 本地开发
|
||||
|
||||
```bash
|
||||
go run . # 启动服务(默认 :8080)
|
||||
go build -o mengyastore-backend.exe . # 构建可执行文件
|
||||
go run ./cmd/migrate/main.go # 迁移旧 JSON 数据到数据库
|
||||
```
|
||||
|
||||
### 切换数据库
|
||||
|
||||
```bash
|
||||
# 测试库(默认)
|
||||
# host: 10.1.1.100:3306 / db: mengyastore-test
|
||||
|
||||
# 生产库
|
||||
set DATABASE_DSN=mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local
|
||||
./mengyastore-backend.exe
|
||||
```
|
||||
|
||||
## 认证说明
|
||||
|
||||
### 用户认证
|
||||
|
||||
通过 SproutGate OAuth 服务验证 Bearer Token:
|
||||
|
||||
```go
|
||||
result, err := authClient.VerifyToken(token)
|
||||
// result.Valid, result.User.Account, result.User.Username
|
||||
```
|
||||
|
||||
### 管理员认证
|
||||
|
||||
管理员令牌通过查询参数或 Authorization 头传入:
|
||||
|
||||
```
|
||||
GET /api/admin/products?token=xxx
|
||||
Authorization: xxx
|
||||
```
|
||||
|
||||
令牌与 `settings.json` 中的 `adminToken` 比对。
|
||||
# 萌芽小店 · 后端
|
||||
|
||||
基于 **Go + Gin + GORM** 构建的 RESTful API 服务,负责商品管理、订单处理、用户认证、聊天消息等核心业务。
|
||||
|
||||
## 技术依赖
|
||||
|
||||
| 包 | 版本 | 用途 |
|
||||
|----|------|------|
|
||||
| gin | v1.9 | HTTP 路由框架 |
|
||||
| gorm | v1.31 | ORM |
|
||||
| gorm/driver/mysql | v1.6 | MySQL 驱动 |
|
||||
| go-sql-driver/mysql | v1.9 | 底层 MySQL 连接 |
|
||||
| gin-contrib/cors | latest | CORS 中间件 |
|
||||
| google/uuid | latest | UUID 生成 |
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
mengyastore-backend/
|
||||
├── main.go # 程序入口,路由注册
|
||||
├── cmd/
|
||||
│ └── migrate/
|
||||
│ └── main.go # 一次性 JSON→MySQL 数据迁移脚本
|
||||
├── data/
|
||||
│ └── json/
|
||||
│ └── settings.json # 服务配置(adminToken、DSN 等)
|
||||
├── internal/
|
||||
│ ├── config/
|
||||
│ │ └── config.go # 配置加载
|
||||
│ ├── database/
|
||||
│ │ ├── db.go # GORM 初始化 + AutoMigrate
|
||||
│ │ └── models.go # 数据库行结构体(GORM 模型)
|
||||
│ ├── models/
|
||||
│ │ ├── product.go # 业务模型 Product
|
||||
│ │ ├── order.go # 业务模型 Order
|
||||
│ │ └── chat.go # 业务模型 ChatMessage
|
||||
│ ├── storage/
|
||||
│ │ ├── jsonstore.go # 商品存储(GORM 实现)
|
||||
│ │ ├── orderstore.go # 订单存储
|
||||
│ │ ├── sitestore.go # 站点设置存储
|
||||
│ │ ├── wishliststore.go # 收藏夹存储
|
||||
│ │ └── chatstore.go # 聊天消息存储(含内存级频率限制)
|
||||
│ ├── handlers/
|
||||
│ │ ├── admin.go # AdminHandler 结构体 + requireAdmin
|
||||
│ │ ├── admin_product.go # 商品 CRUD 接口
|
||||
│ │ ├── admin_site.go # 维护模式接口
|
||||
│ │ ├── admin_orders.go # 订单管理接口
|
||||
│ │ ├── admin_chat.go # 管理员聊天接口
|
||||
│ │ ├── public.go # 公开接口(商品列表、浏览量)
|
||||
│ │ ├── order.go # 下单、确认订单接口
|
||||
│ │ ├── stats.go # 统计信息接口
|
||||
│ │ ├── wishlist.go # 收藏夹接口(用户)
|
||||
│ │ └── chat.go # 聊天接口(用户)
|
||||
│ └── auth/
|
||||
│ └── sproutgate.go # SproutGate OAuth 客户端
|
||||
```
|
||||
|
||||
## API 路由一览
|
||||
|
||||
### 公开接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/health` | 健康检查 |
|
||||
| GET | `/api/products` | 获取商品列表(仅 active) |
|
||||
| POST | `/api/products/:id/view` | 记录商品浏览量 |
|
||||
| GET | `/api/stats` | 获取总订单数和总访问量 |
|
||||
| POST | `/api/site/visit` | 记录站点访问 |
|
||||
| GET | `/api/site/maintenance` | 获取维护状态 |
|
||||
| POST | `/api/checkout` | 创建订单(生成支付二维码) |
|
||||
| GET | `/api/orders` | 获取当前用户订单(需 Bearer token) |
|
||||
| POST | `/api/orders/:id/confirm` | 确认付款(触发发货) |
|
||||
|
||||
### 收藏夹(需登录)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/wishlist` | 获取收藏商品 ID 列表 |
|
||||
| POST | `/api/wishlist` | 添加收藏 |
|
||||
| DELETE | `/api/wishlist/:id` | 取消收藏 |
|
||||
|
||||
### 聊天(需登录)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/chat/messages` | 获取自己的聊天记录 |
|
||||
| POST | `/api/chat/messages` | 发送消息(1 秒频率限制) |
|
||||
|
||||
### 管理员接口(需 `?token=xxx` 或 `Authorization: <token>`)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/admin/token` | 获取令牌(用于验证) |
|
||||
| GET | `/api/admin/products` | 获取全部商品(含卡密) |
|
||||
| POST | `/api/admin/products` | 创建商品 |
|
||||
| PUT | `/api/admin/products/:id` | 编辑商品 |
|
||||
| PATCH | `/api/admin/products/:id/status` | 切换上下架 |
|
||||
| DELETE | `/api/admin/products/:id` | 删除商品 |
|
||||
| POST | `/api/admin/site/maintenance` | 设置维护模式 |
|
||||
| GET | `/api/admin/orders` | 获取全部订单 |
|
||||
| DELETE | `/api/admin/orders/:id` | 删除订单 |
|
||||
| GET | `/api/admin/chat` | 获取全部用户对话 |
|
||||
| GET | `/api/admin/chat/:account` | 获取指定用户对话 |
|
||||
| POST | `/api/admin/chat/:account` | 管理员回复 |
|
||||
| DELETE | `/api/admin/chat/:account` | 清除对话 |
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
### products
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | varchar(36) | UUID 主键 |
|
||||
| name | varchar(255) | 商品名称 |
|
||||
| price | double | 原价 |
|
||||
| discount_price | double | 折扣价(0 = 无折扣)|
|
||||
| tags | json | 标签数组 |
|
||||
| cover_url | varchar(500) | 封面图 URL |
|
||||
| screenshot_urls | json | 截图 URL 数组(最多 5 张)|
|
||||
| verification_url | varchar(500) | 验证链接 |
|
||||
| description | text | Markdown 描述 |
|
||||
| active | tinyint(1) | 是否上架 |
|
||||
| require_login | tinyint(1) | 是否必须登录购买 |
|
||||
| max_per_account | bigint | 每账户最大购买数(0=不限)|
|
||||
| total_sold | bigint | 累计销量 |
|
||||
| view_count | bigint | 累计浏览量 |
|
||||
| delivery_mode | varchar(20) | 发货模式:`auto` / `manual` |
|
||||
| show_note | tinyint(1) | 下单时显示备注输入框 |
|
||||
| show_contact | tinyint(1) | 下单时显示联系方式输入框 |
|
||||
| created_at | datetime(3) | 创建时间 |
|
||||
|
||||
### product_codes
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | bigint unsigned | 自增主键 |
|
||||
| product_id | varchar(36) | 关联商品 ID(索引)|
|
||||
| code | text | 卡密内容 |
|
||||
|
||||
### orders
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | varchar(36) | UUID 主键 |
|
||||
| product_id | varchar(36) | 商品 ID(索引)|
|
||||
| product_name | varchar(255) | 商品名称快照 |
|
||||
| user_account | varchar(255) | 用户账号(可空,匿名)|
|
||||
| user_name | varchar(255) | 用户昵称 |
|
||||
| quantity | bigint | 购买数量 |
|
||||
| delivered_codes | json | 已发放卡密 |
|
||||
| status | varchar(20) | `pending` / `completed` |
|
||||
| delivery_mode | varchar(20) | `auto` / `manual` |
|
||||
| note | text | 用户备注 |
|
||||
| contact_phone | varchar(50) | 联系手机号 |
|
||||
| contact_email | varchar(255) | 联系邮箱 |
|
||||
| created_at | datetime(3) | 下单时间 |
|
||||
|
||||
### site_settings
|
||||
|
||||
键值对存储,当前使用的键:
|
||||
|
||||
| Key | 说明 |
|
||||
|-----|------|
|
||||
| `totalVisits` | 总访问量 |
|
||||
| `maintenance` | 维护模式(`true` / `false`)|
|
||||
| `maintenanceReason` | 维护原因文本 |
|
||||
|
||||
### wishlists
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | bigint unsigned | 自增主键 |
|
||||
| account_id | varchar(255) | 用户账号(唯一索引)|
|
||||
| product_id | varchar(36) | 商品 ID(联合唯一)|
|
||||
|
||||
### chat_messages
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | varchar(36) | UUID 主键 |
|
||||
| account_id | varchar(255) | 用户账号(索引)|
|
||||
| account_name | varchar(255) | 用户昵称 |
|
||||
| content | text | 消息内容 |
|
||||
| sent_at | datetime(3) | 发送时间 |
|
||||
| from_admin | tinyint(1) | 是否来自管理员 |
|
||||
|
||||
## 配置文件
|
||||
|
||||
`data/json/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"adminToken": "你的管理员令牌",
|
||||
"authApiUrl": "https://auth.api.shumengya.top",
|
||||
"databaseDsn": ""
|
||||
}
|
||||
```
|
||||
|
||||
`databaseDsn` 为空时自动使用测试数据库。也可以通过环境变量 `DATABASE_DSN` 覆盖。
|
||||
|
||||
## 发货逻辑
|
||||
|
||||
### 自动发货(`deliveryMode = "auto"`)
|
||||
|
||||
1. `POST /api/checkout` → 从 `product_codes` 提取指定数量的卡密
|
||||
2. 商品 `quantity` 减少,卡密从数据库删除
|
||||
3. 卡密保存到订单 `delivered_codes`
|
||||
4. 用户 `POST /api/orders/:id/confirm` 确认付款后,订单状态变为 `completed`,响应中返回卡密内容
|
||||
5. 同时调用 `IncrementSold` 增加销量统计
|
||||
|
||||
### 手动发货(`deliveryMode = "manual"`)
|
||||
|
||||
1. `POST /api/checkout` → 创建订单,不提取卡密
|
||||
2. 用户 `POST /api/orders/:id/confirm` 后,订单变为 `completed`,但 `delivered_codes` 为空
|
||||
3. 管理员在后台查看订单的备注、手机号、邮箱后手动发货
|
||||
|
||||
## 本地开发
|
||||
|
||||
```bash
|
||||
go run . # 启动服务(默认 :8080)
|
||||
go build -o mengyastore-backend.exe . # 构建可执行文件
|
||||
go run ./cmd/migrate/main.go # 迁移旧 JSON 数据到数据库
|
||||
```
|
||||
|
||||
### 切换数据库
|
||||
|
||||
```bash
|
||||
# 测试库(默认)
|
||||
# host: 10.1.1.100:3306 / db: mengyastore-test
|
||||
|
||||
# 生产库
|
||||
set DATABASE_DSN=mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local
|
||||
./mengyastore-backend.exe
|
||||
```
|
||||
|
||||
## 认证说明
|
||||
|
||||
### 用户认证
|
||||
|
||||
通过 SproutGate OAuth 服务验证 Bearer Token:
|
||||
|
||||
```go
|
||||
result, err := authClient.VerifyToken(token)
|
||||
// result.Valid, result.User.Account, result.User.Username
|
||||
```
|
||||
|
||||
### 管理员认证
|
||||
|
||||
管理员令牌通过查询参数或 Authorization 头传入:
|
||||
|
||||
```
|
||||
GET /api/admin/products?token=xxx
|
||||
Authorization: xxx
|
||||
```
|
||||
|
||||
令牌与 `settings.json` 中的 `adminToken` 比对。
|
||||
|
||||
@@ -1,304 +1,304 @@
|
||||
// migrate imports existing JSON data files into the MySQL database.
|
||||
// Run once after switching to DB storage:
|
||||
//
|
||||
// go run ./cmd/migrate/main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load("../../config.json")
|
||||
if err != nil {
|
||||
log.Fatalf("load config: %v", err)
|
||||
}
|
||||
|
||||
db, err := gorm.Open(mysql.Open(cfg.DatabaseDSN), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Info),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("open db: %v", err)
|
||||
}
|
||||
|
||||
// Ensure tables exist
|
||||
if err := db.AutoMigrate(
|
||||
&database.ProductRow{},
|
||||
&database.ProductCodeRow{},
|
||||
&database.OrderRow{},
|
||||
&database.SiteSettingRow{},
|
||||
&database.WishlistRow{},
|
||||
&database.ChatMessageRow{},
|
||||
); err != nil {
|
||||
log.Fatalf("auto migrate: %v", err)
|
||||
}
|
||||
|
||||
log.Println("数据库连接成功,开始导入...")
|
||||
migrateProducts(db)
|
||||
migrateOrders(db)
|
||||
migrateWishlists(db)
|
||||
migrateChats(db)
|
||||
migrateSite(db)
|
||||
log.Println("✅ 数据导入完成!")
|
||||
}
|
||||
|
||||
// ─── Products ─────────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonProduct struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags []string `json:"tags"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
Description string `json:"description"`
|
||||
Active bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
TotalSold int `json:"totalSold"`
|
||||
ViewCount int `json:"viewCount"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
Codes []string `json:"codes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func migrateProducts(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/products.json")
|
||||
if err != nil {
|
||||
log.Printf("[products] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var products []jsonProduct
|
||||
if err := json.Unmarshal(data, &products); err != nil {
|
||||
log.Printf("[products] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
for _, p := range products {
|
||||
if p.ID == "" {
|
||||
continue
|
||||
}
|
||||
if p.DeliveryMode == "" {
|
||||
p.DeliveryMode = "auto"
|
||||
}
|
||||
row := database.ProductRow{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Price: p.Price,
|
||||
DiscountPrice: p.DiscountPrice,
|
||||
Tags: database.StringSlice(p.Tags),
|
||||
CoverURL: p.CoverURL,
|
||||
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
|
||||
Description: p.Description,
|
||||
Active: p.Active,
|
||||
RequireLogin: p.RequireLogin,
|
||||
MaxPerAccount: p.MaxPerAccount,
|
||||
TotalSold: p.TotalSold,
|
||||
ViewCount: p.ViewCount,
|
||||
DeliveryMode: p.DeliveryMode,
|
||||
ShowNote: p.ShowNote,
|
||||
ShowContact: p.ShowContact,
|
||||
CreatedAt: p.CreatedAt,
|
||||
}
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = time.Now()
|
||||
}
|
||||
result := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row)
|
||||
if result.Error != nil {
|
||||
log.Printf("[products] 导入 %s 失败: %v", p.ID, result.Error)
|
||||
continue
|
||||
}
|
||||
// Codes → product_codes
|
||||
for _, code := range p.Codes {
|
||||
if code == "" {
|
||||
continue
|
||||
}
|
||||
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.ProductCodeRow{
|
||||
ProductID: p.ID,
|
||||
Code: code,
|
||||
})
|
||||
}
|
||||
}
|
||||
log.Printf("[products] 导入 %d 条商品", len(products))
|
||||
}
|
||||
|
||||
// ─── Orders ───────────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonOrder struct {
|
||||
ID string `json:"id"`
|
||||
ProductID string `json:"productId"`
|
||||
ProductName string `json:"productName"`
|
||||
UserAccount string `json:"userAccount"`
|
||||
UserName string `json:"userName"`
|
||||
Quantity int `json:"quantity"`
|
||||
DeliveredCodes []string `json:"deliveredCodes"`
|
||||
Status string `json:"status"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func migrateOrders(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/orders.json")
|
||||
if err != nil {
|
||||
log.Printf("[orders] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var orders []jsonOrder
|
||||
if err := json.Unmarshal(data, &orders); err != nil {
|
||||
log.Printf("[orders] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
for _, o := range orders {
|
||||
if o.ID == "" {
|
||||
continue
|
||||
}
|
||||
if o.DeliveryMode == "" {
|
||||
o.DeliveryMode = "auto"
|
||||
}
|
||||
if o.DeliveredCodes == nil {
|
||||
o.DeliveredCodes = []string{}
|
||||
}
|
||||
row := database.OrderRow{
|
||||
ID: o.ID,
|
||||
ProductID: o.ProductID,
|
||||
ProductName: o.ProductName,
|
||||
UserAccount: o.UserAccount,
|
||||
UserName: o.UserName,
|
||||
Quantity: o.Quantity,
|
||||
DeliveredCodes: database.StringSlice(o.DeliveredCodes),
|
||||
Status: o.Status,
|
||||
DeliveryMode: o.DeliveryMode,
|
||||
Note: o.Note,
|
||||
ContactPhone: o.ContactPhone,
|
||||
ContactEmail: o.ContactEmail,
|
||||
CreatedAt: o.CreatedAt,
|
||||
}
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = time.Now()
|
||||
}
|
||||
if result := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row); result.Error != nil {
|
||||
log.Printf("[orders] 导入 %s 失败: %v", o.ID, result.Error)
|
||||
}
|
||||
}
|
||||
log.Printf("[orders] 导入 %d 条订单", len(orders))
|
||||
}
|
||||
|
||||
// ─── Wishlists ────────────────────────────────────────────────────────────────
|
||||
|
||||
func migrateWishlists(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/wishlists.json")
|
||||
if err != nil {
|
||||
log.Printf("[wishlists] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var wl map[string][]string
|
||||
if err := json.Unmarshal(data, &wl); err != nil {
|
||||
log.Printf("[wishlists] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for account, productIDs := range wl {
|
||||
for _, pid := range productIDs {
|
||||
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.WishlistRow{
|
||||
AccountID: account,
|
||||
ProductID: pid,
|
||||
})
|
||||
count++
|
||||
}
|
||||
}
|
||||
log.Printf("[wishlists] 导入 %d 条收藏记录", count)
|
||||
}
|
||||
|
||||
// ─── Chats ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonChatMsg struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountId"`
|
||||
AccountName string `json:"accountName"`
|
||||
Content string `json:"content"`
|
||||
SentAt time.Time `json:"sentAt"`
|
||||
FromAdmin bool `json:"fromAdmin"`
|
||||
}
|
||||
|
||||
func migrateChats(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/chats.json")
|
||||
if err != nil {
|
||||
log.Printf("[chats] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var convs map[string][]jsonChatMsg
|
||||
if err := json.Unmarshal(data, &convs); err != nil {
|
||||
log.Printf("[chats] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for _, msgs := range convs {
|
||||
for _, m := range msgs {
|
||||
if m.ID == "" {
|
||||
continue
|
||||
}
|
||||
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.ChatMessageRow{
|
||||
ID: m.ID,
|
||||
AccountID: m.AccountID,
|
||||
AccountName: m.AccountName,
|
||||
Content: m.Content,
|
||||
SentAt: m.SentAt,
|
||||
FromAdmin: m.FromAdmin,
|
||||
})
|
||||
count++
|
||||
}
|
||||
}
|
||||
log.Printf("[chats] 导入 %d 条聊天消息", count)
|
||||
}
|
||||
|
||||
// ─── Site settings ────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonSite struct {
|
||||
TotalVisits int `json:"totalVisits"`
|
||||
Maintenance bool `json:"maintenance"`
|
||||
MaintenanceReason string `json:"maintenanceReason"`
|
||||
}
|
||||
|
||||
func migrateSite(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/site.json")
|
||||
if err != nil {
|
||||
log.Printf("[site] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var site jsonSite
|
||||
if err := json.Unmarshal(data, &site); err != nil {
|
||||
log.Printf("[site] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
upsert := func(key, value string) {
|
||||
db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
||||
}).Create(&database.SiteSettingRow{Key: key, Value: value})
|
||||
}
|
||||
upsert("totalVisits", strconv.Itoa(site.TotalVisits))
|
||||
maintenance := "false"
|
||||
if site.Maintenance {
|
||||
maintenance = "true"
|
||||
}
|
||||
upsert("maintenance", maintenance)
|
||||
upsert("maintenanceReason", site.MaintenanceReason)
|
||||
log.Printf("[site] 站点设置导入完成(访问量: %d)", site.TotalVisits)
|
||||
}
|
||||
// migrate imports existing JSON data files into the MySQL database.
|
||||
// Run once after switching to DB storage:
|
||||
//
|
||||
// go run ./cmd/migrate/main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load("../../config.json")
|
||||
if err != nil {
|
||||
log.Fatalf("load config: %v", err)
|
||||
}
|
||||
|
||||
db, err := gorm.Open(mysql.Open(cfg.DatabaseDSN), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Info),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("open db: %v", err)
|
||||
}
|
||||
|
||||
// Ensure tables exist
|
||||
if err := db.AutoMigrate(
|
||||
&database.ProductRow{},
|
||||
&database.ProductCodeRow{},
|
||||
&database.OrderRow{},
|
||||
&database.SiteSettingRow{},
|
||||
&database.WishlistRow{},
|
||||
&database.ChatMessageRow{},
|
||||
); err != nil {
|
||||
log.Fatalf("auto migrate: %v", err)
|
||||
}
|
||||
|
||||
log.Println("数据库连接成功,开始导入...")
|
||||
migrateProducts(db)
|
||||
migrateOrders(db)
|
||||
migrateWishlists(db)
|
||||
migrateChats(db)
|
||||
migrateSite(db)
|
||||
log.Println("✅ 数据导入完成!")
|
||||
}
|
||||
|
||||
// ─── Products ─────────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonProduct struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags []string `json:"tags"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
Description string `json:"description"`
|
||||
Active bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
TotalSold int `json:"totalSold"`
|
||||
ViewCount int `json:"viewCount"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
Codes []string `json:"codes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func migrateProducts(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/products.json")
|
||||
if err != nil {
|
||||
log.Printf("[products] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var products []jsonProduct
|
||||
if err := json.Unmarshal(data, &products); err != nil {
|
||||
log.Printf("[products] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
for _, p := range products {
|
||||
if p.ID == "" {
|
||||
continue
|
||||
}
|
||||
if p.DeliveryMode == "" {
|
||||
p.DeliveryMode = "auto"
|
||||
}
|
||||
row := database.ProductRow{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Price: p.Price,
|
||||
DiscountPrice: p.DiscountPrice,
|
||||
Tags: database.StringSlice(p.Tags),
|
||||
CoverURL: p.CoverURL,
|
||||
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
|
||||
Description: p.Description,
|
||||
Active: p.Active,
|
||||
RequireLogin: p.RequireLogin,
|
||||
MaxPerAccount: p.MaxPerAccount,
|
||||
TotalSold: p.TotalSold,
|
||||
ViewCount: p.ViewCount,
|
||||
DeliveryMode: p.DeliveryMode,
|
||||
ShowNote: p.ShowNote,
|
||||
ShowContact: p.ShowContact,
|
||||
CreatedAt: p.CreatedAt,
|
||||
}
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = time.Now()
|
||||
}
|
||||
result := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row)
|
||||
if result.Error != nil {
|
||||
log.Printf("[products] 导入 %s 失败: %v", p.ID, result.Error)
|
||||
continue
|
||||
}
|
||||
// Codes → product_codes
|
||||
for _, code := range p.Codes {
|
||||
if code == "" {
|
||||
continue
|
||||
}
|
||||
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.ProductCodeRow{
|
||||
ProductID: p.ID,
|
||||
Code: code,
|
||||
})
|
||||
}
|
||||
}
|
||||
log.Printf("[products] 导入 %d 条商品", len(products))
|
||||
}
|
||||
|
||||
// ─── Orders ───────────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonOrder struct {
|
||||
ID string `json:"id"`
|
||||
ProductID string `json:"productId"`
|
||||
ProductName string `json:"productName"`
|
||||
UserAccount string `json:"userAccount"`
|
||||
UserName string `json:"userName"`
|
||||
Quantity int `json:"quantity"`
|
||||
DeliveredCodes []string `json:"deliveredCodes"`
|
||||
Status string `json:"status"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func migrateOrders(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/orders.json")
|
||||
if err != nil {
|
||||
log.Printf("[orders] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var orders []jsonOrder
|
||||
if err := json.Unmarshal(data, &orders); err != nil {
|
||||
log.Printf("[orders] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
for _, o := range orders {
|
||||
if o.ID == "" {
|
||||
continue
|
||||
}
|
||||
if o.DeliveryMode == "" {
|
||||
o.DeliveryMode = "auto"
|
||||
}
|
||||
if o.DeliveredCodes == nil {
|
||||
o.DeliveredCodes = []string{}
|
||||
}
|
||||
row := database.OrderRow{
|
||||
ID: o.ID,
|
||||
ProductID: o.ProductID,
|
||||
ProductName: o.ProductName,
|
||||
UserAccount: o.UserAccount,
|
||||
UserName: o.UserName,
|
||||
Quantity: o.Quantity,
|
||||
DeliveredCodes: database.StringSlice(o.DeliveredCodes),
|
||||
Status: o.Status,
|
||||
DeliveryMode: o.DeliveryMode,
|
||||
Note: o.Note,
|
||||
ContactPhone: o.ContactPhone,
|
||||
ContactEmail: o.ContactEmail,
|
||||
CreatedAt: o.CreatedAt,
|
||||
}
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = time.Now()
|
||||
}
|
||||
if result := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row); result.Error != nil {
|
||||
log.Printf("[orders] 导入 %s 失败: %v", o.ID, result.Error)
|
||||
}
|
||||
}
|
||||
log.Printf("[orders] 导入 %d 条订单", len(orders))
|
||||
}
|
||||
|
||||
// ─── Wishlists ────────────────────────────────────────────────────────────────
|
||||
|
||||
func migrateWishlists(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/wishlists.json")
|
||||
if err != nil {
|
||||
log.Printf("[wishlists] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var wl map[string][]string
|
||||
if err := json.Unmarshal(data, &wl); err != nil {
|
||||
log.Printf("[wishlists] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for account, productIDs := range wl {
|
||||
for _, pid := range productIDs {
|
||||
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.WishlistRow{
|
||||
AccountID: account,
|
||||
ProductID: pid,
|
||||
})
|
||||
count++
|
||||
}
|
||||
}
|
||||
log.Printf("[wishlists] 导入 %d 条收藏记录", count)
|
||||
}
|
||||
|
||||
// ─── Chats ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonChatMsg struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountId"`
|
||||
AccountName string `json:"accountName"`
|
||||
Content string `json:"content"`
|
||||
SentAt time.Time `json:"sentAt"`
|
||||
FromAdmin bool `json:"fromAdmin"`
|
||||
}
|
||||
|
||||
func migrateChats(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/chats.json")
|
||||
if err != nil {
|
||||
log.Printf("[chats] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var convs map[string][]jsonChatMsg
|
||||
if err := json.Unmarshal(data, &convs); err != nil {
|
||||
log.Printf("[chats] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for _, msgs := range convs {
|
||||
for _, m := range msgs {
|
||||
if m.ID == "" {
|
||||
continue
|
||||
}
|
||||
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.ChatMessageRow{
|
||||
ID: m.ID,
|
||||
AccountID: m.AccountID,
|
||||
AccountName: m.AccountName,
|
||||
Content: m.Content,
|
||||
SentAt: m.SentAt,
|
||||
FromAdmin: m.FromAdmin,
|
||||
})
|
||||
count++
|
||||
}
|
||||
}
|
||||
log.Printf("[chats] 导入 %d 条聊天消息", count)
|
||||
}
|
||||
|
||||
// ─── Site settings ────────────────────────────────────────────────────────────
|
||||
|
||||
type jsonSite struct {
|
||||
TotalVisits int `json:"totalVisits"`
|
||||
Maintenance bool `json:"maintenance"`
|
||||
MaintenanceReason string `json:"maintenanceReason"`
|
||||
}
|
||||
|
||||
func migrateSite(db *gorm.DB) {
|
||||
data, err := os.ReadFile("data/json/site.json")
|
||||
if err != nil {
|
||||
log.Printf("[site] 文件不存在,跳过: %v", err)
|
||||
return
|
||||
}
|
||||
var site jsonSite
|
||||
if err := json.Unmarshal(data, &site); err != nil {
|
||||
log.Printf("[site] JSON 解析失败: %v", err)
|
||||
return
|
||||
}
|
||||
upsert := func(key, value string) {
|
||||
db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
||||
}).Create(&database.SiteSettingRow{Key: key, Value: value})
|
||||
}
|
||||
upsert("totalVisits", strconv.Itoa(site.TotalVisits))
|
||||
maintenance := "false"
|
||||
if site.Maintenance {
|
||||
maintenance = "true"
|
||||
}
|
||||
upsert("maintenance", maintenance)
|
||||
upsert("maintenanceReason", site.MaintenanceReason)
|
||||
log.Printf("[site] 站点设置导入完成(访问量: %d)", site.TotalVisits)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
container_name: mengyastore-backend
|
||||
ports:
|
||||
- "28081:8080"
|
||||
environment:
|
||||
GIN_MODE: release
|
||||
TZ: Asia/Shanghai
|
||||
# 生产环境 MySQL DSN,使用内网地址。
|
||||
# 本地开发请修改为测试库地址,或通过 .env 文件覆盖。
|
||||
#mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local
|
||||
DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
volumes:
|
||||
- ./config.json:/app/config.json:ro
|
||||
restart: unless-stopped
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
container_name: mengyastore-backend
|
||||
ports:
|
||||
- "28081:8080"
|
||||
environment:
|
||||
GIN_MODE: release
|
||||
TZ: Asia/Shanghai
|
||||
# 生产环境 MySQL DSN,使用内网地址。
|
||||
# 本地开发请修改为测试库地址,或通过 .env 文件覆盖。
|
||||
#mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local
|
||||
DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
volumes:
|
||||
- ./config.json:/app/config.json:ro
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
module mengyastore-backend
|
||||
|
||||
go 1.21.0
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/cors v1.7.2
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/google/uuid v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.9.3 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.7.0 // indirect
|
||||
golang.org/x/crypto v0.22.0 // indirect
|
||||
golang.org/x/net v0.24.0 // indirect
|
||||
golang.org/x/sys v0.19.0 // indirect
|
||||
golang.org/x/text v0.20.0 // indirect
|
||||
google.golang.org/protobuf v1.34.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gorm.io/driver/mysql v1.6.0 // indirect
|
||||
gorm.io/gorm v1.31.1 // indirect
|
||||
)
|
||||
module mengyastore-backend
|
||||
|
||||
go 1.21.0
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/cors v1.7.2
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/google/uuid v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.9.3 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.7.0 // indirect
|
||||
golang.org/x/crypto v0.22.0 // indirect
|
||||
golang.org/x/net v0.24.0 // indirect
|
||||
golang.org/x/sys v0.19.0 // indirect
|
||||
golang.org/x/text v0.20.0 // indirect
|
||||
google.golang.org/protobuf v1.34.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gorm.io/driver/mysql v1.6.0 // indirect
|
||||
gorm.io/gorm v1.31.1 // indirect
|
||||
)
|
||||
|
||||
@@ -1,115 +1,115 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
|
||||
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
||||
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg=
|
||||
github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
|
||||
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
|
||||
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
||||
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
|
||||
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4=
|
||||
google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
|
||||
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
||||
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg=
|
||||
github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
|
||||
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
|
||||
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
||||
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
|
||||
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4=
|
||||
google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
|
||||
@@ -1,66 +1,66 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultAuthAPIURL = "https://auth.api.shumengya.top"
|
||||
|
||||
type SproutGateClient struct {
|
||||
apiURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type VerifyResult struct {
|
||||
Valid bool `json:"valid"`
|
||||
User *SproutGateUser `json:"user"`
|
||||
}
|
||||
|
||||
type SproutGateUser struct {
|
||||
Account string `json:"account"`
|
||||
Username string `json:"username"`
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
Level int `json:"level"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func NewSproutGateClient(apiURL string) *SproutGateClient {
|
||||
if apiURL == "" {
|
||||
apiURL = defaultAuthAPIURL
|
||||
}
|
||||
return &SproutGateClient{
|
||||
apiURL: apiURL,
|
||||
httpClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SproutGateClient) VerifyToken(token string) (*VerifyResult, error) {
|
||||
body, _ := json.Marshal(map[string]string{"token": token})
|
||||
resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] 验证请求失败: %v", err)
|
||||
return nil, fmt.Errorf("验证请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
rawBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] 读取响应体失败: %v", err)
|
||||
return nil, fmt.Errorf("读取验证响应失败: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody))
|
||||
|
||||
var result VerifyResult
|
||||
if err := json.Unmarshal(rawBody, &result); err != nil {
|
||||
log.Printf("[SproutGate] 解析响应失败: %v", err)
|
||||
return nil, fmt.Errorf("解析验证响应失败: %w", err)
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultAuthAPIURL = "https://auth.api.shumengya.top"
|
||||
|
||||
type SproutGateClient struct {
|
||||
apiURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type VerifyResult struct {
|
||||
Valid bool `json:"valid"`
|
||||
User *SproutGateUser `json:"user"`
|
||||
}
|
||||
|
||||
type SproutGateUser struct {
|
||||
Account string `json:"account"`
|
||||
Username string `json:"username"`
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
Level int `json:"level"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func NewSproutGateClient(apiURL string) *SproutGateClient {
|
||||
if apiURL == "" {
|
||||
apiURL = defaultAuthAPIURL
|
||||
}
|
||||
return &SproutGateClient{
|
||||
apiURL: apiURL,
|
||||
httpClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SproutGateClient) VerifyToken(token string) (*VerifyResult, error) {
|
||||
body, _ := json.Marshal(map[string]string{"token": token})
|
||||
resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] 验证请求失败: %v", err)
|
||||
return nil, fmt.Errorf("验证请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
rawBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] 读取响应体失败: %v", err)
|
||||
return nil, fmt.Errorf("读取验证响应失败: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody))
|
||||
|
||||
var result VerifyResult
|
||||
if err := json.Unmarshal(rawBody, &result); err != nil {
|
||||
log.Printf("[SproutGate] 解析响应失败: %v", err)
|
||||
return nil, fmt.Errorf("解析验证响应失败: %w", err)
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AdminToken string `json:"adminToken"`
|
||||
AuthAPIURL string `json:"authApiUrl"`
|
||||
|
||||
// 数据库 DSN,为空时回退到测试数据库。
|
||||
// 格式:user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local
|
||||
DatabaseDSN string `json:"databaseDsn"`
|
||||
}
|
||||
|
||||
// 各环境默认 DSN。
|
||||
const (
|
||||
TestDSN = "mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
ProdDSN = "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
)
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
var cfg Config
|
||||
data, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
if jsonErr := json.Unmarshal(data, &cfg); jsonErr != nil {
|
||||
return nil, fmt.Errorf("解析配置文件 %s 失败: %w", path, jsonErr)
|
||||
}
|
||||
}
|
||||
// 文件不存在时使用默认值,环境变量在下方仍优先生效。
|
||||
|
||||
if cfg.AdminToken == "" {
|
||||
cfg.AdminToken = "changeme"
|
||||
}
|
||||
// DATABASE_DSN 环境变量优先于配置文件。
|
||||
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
|
||||
cfg.DatabaseDSN = dsn
|
||||
}
|
||||
if cfg.DatabaseDSN == "" {
|
||||
cfg.DatabaseDSN = TestDSN
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AdminToken string `json:"adminToken"`
|
||||
AuthAPIURL string `json:"authApiUrl"`
|
||||
|
||||
// 数据库 DSN,为空时回退到测试数据库。
|
||||
// 格式:user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local
|
||||
DatabaseDSN string `json:"databaseDsn"`
|
||||
}
|
||||
|
||||
// 各环境默认 DSN。
|
||||
const (
|
||||
TestDSN = "mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
ProdDSN = "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
)
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
var cfg Config
|
||||
data, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
if jsonErr := json.Unmarshal(data, &cfg); jsonErr != nil {
|
||||
return nil, fmt.Errorf("解析配置文件 %s 失败: %w", path, jsonErr)
|
||||
}
|
||||
}
|
||||
// 文件不存在时使用默认值,环境变量在下方仍优先生效。
|
||||
|
||||
if cfg.AdminToken == "" {
|
||||
cfg.AdminToken = "changeme"
|
||||
}
|
||||
// DATABASE_DSN 环境变量优先于配置文件。
|
||||
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
|
||||
cfg.DatabaseDSN = dsn
|
||||
}
|
||||
if cfg.DatabaseDSN == "" {
|
||||
cfg.DatabaseDSN = TestDSN
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Open 初始化 GORM 数据库连接并自动同步所有表结构。
|
||||
func Open(dsn string) (*gorm.DB, error) {
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Warn),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlDB.SetMaxIdleConns(5)
|
||||
sqlDB.SetMaxOpenConns(20)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
if err := autoMigrate(db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Println("[DB] 数据库连接成功,表结构已同步")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func autoMigrate(db *gorm.DB) error {
|
||||
return db.AutoMigrate(
|
||||
&ProductRow{},
|
||||
&ProductCodeRow{},
|
||||
&OrderRow{},
|
||||
&SiteSettingRow{},
|
||||
&WishlistRow{},
|
||||
&ChatMessageRow{},
|
||||
)
|
||||
}
|
||||
package database
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Open 初始化 GORM 数据库连接并自动同步所有表结构。
|
||||
func Open(dsn string) (*gorm.DB, error) {
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Warn),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlDB.SetMaxIdleConns(5)
|
||||
sqlDB.SetMaxOpenConns(20)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
if err := autoMigrate(db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Println("[DB] 数据库连接成功,表结构已同步")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func autoMigrate(db *gorm.DB) error {
|
||||
return db.AutoMigrate(
|
||||
&ProductRow{},
|
||||
&ProductCodeRow{},
|
||||
&OrderRow{},
|
||||
&SiteSettingRow{},
|
||||
&WishlistRow{},
|
||||
&ChatMessageRow{},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,121 +1,121 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StringSlice is a JSON-serialized string slice stored as a MySQL TEXT/JSON column.
|
||||
type StringSlice []string
|
||||
|
||||
func (s StringSlice) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
return "[]", nil
|
||||
}
|
||||
b, err := json.Marshal(s)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func (s *StringSlice) Scan(src any) error {
|
||||
var raw []byte
|
||||
switch v := src.(type) {
|
||||
case string:
|
||||
raw = []byte(v)
|
||||
case []byte:
|
||||
raw = v
|
||||
default:
|
||||
return fmt.Errorf("StringSlice: unsupported type %T", src)
|
||||
}
|
||||
return json.Unmarshal(raw, s)
|
||||
}
|
||||
|
||||
// ─── Products ────────────────────────────────────────────────────────────────
|
||||
|
||||
// ProductRow is the GORM model for the `products` table.
|
||||
type ProductRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
Name string `gorm:"size:255;not null"`
|
||||
Price float64 `gorm:"not null;default:0"`
|
||||
DiscountPrice float64 `gorm:"default:0"`
|
||||
Tags StringSlice `gorm:"type:json"`
|
||||
CoverURL string `gorm:"size:500"`
|
||||
ScreenshotURLs StringSlice `gorm:"type:json"`
|
||||
VerificationURL string `gorm:"size:500;default:''"`
|
||||
Description string `gorm:"type:text"`
|
||||
Active bool `gorm:"default:true;index"`
|
||||
RequireLogin bool `gorm:"default:false"`
|
||||
MaxPerAccount int `gorm:"default:0"`
|
||||
TotalSold int `gorm:"default:0"`
|
||||
ViewCount int `gorm:"default:0"`
|
||||
DeliveryMode string `gorm:"size:20;default:'auto'"`
|
||||
ShowNote bool `gorm:"default:false"`
|
||||
ShowContact bool `gorm:"default:false"`
|
||||
CreatedAt time.Time `gorm:"index"`
|
||||
}
|
||||
|
||||
func (ProductRow) TableName() string { return "products" }
|
||||
|
||||
// ProductCodeRow stores individual codes for a product (one row per code).
|
||||
type ProductCodeRow struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
ProductID string `gorm:"size:36;not null;index"`
|
||||
Code string `gorm:"type:text;not null"`
|
||||
}
|
||||
|
||||
func (ProductCodeRow) TableName() string { return "product_codes" }
|
||||
|
||||
// ─── Orders ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type OrderRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
ProductID string `gorm:"size:36;not null;index"`
|
||||
ProductName string `gorm:"size:255;not null"`
|
||||
UserAccount string `gorm:"size:255;index"`
|
||||
UserName string `gorm:"size:255"`
|
||||
Quantity int `gorm:"not null;default:1"`
|
||||
DeliveredCodes StringSlice `gorm:"type:json"`
|
||||
Status string `gorm:"size:20;not null;default:'pending';index"`
|
||||
DeliveryMode string `gorm:"size:20;default:'auto'"`
|
||||
Note string `gorm:"type:text"`
|
||||
ContactPhone string `gorm:"size:50"`
|
||||
ContactEmail string `gorm:"size:255"`
|
||||
NotifyEmail string `gorm:"size:255"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (OrderRow) TableName() string { return "orders" }
|
||||
|
||||
// ─── Site settings ───────────────────────────────────────────────────────────
|
||||
|
||||
// SiteSettingRow stores arbitrary key-value pairs for site-wide settings.
|
||||
type SiteSettingRow struct {
|
||||
Key string `gorm:"primaryKey;size:64"`
|
||||
Value string `gorm:"type:text"`
|
||||
}
|
||||
|
||||
func (SiteSettingRow) TableName() string { return "site_settings" }
|
||||
|
||||
// ─── Wishlists ───────────────────────────────────────────────────────────────
|
||||
|
||||
type WishlistRow struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
AccountID string `gorm:"size:255;not null;index:idx_wishlist,unique"`
|
||||
ProductID string `gorm:"size:36;not null;index:idx_wishlist,unique"`
|
||||
}
|
||||
|
||||
func (WishlistRow) TableName() string { return "wishlists" }
|
||||
|
||||
// ─── Chat messages ───────────────────────────────────────────────────────────
|
||||
|
||||
type ChatMessageRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
AccountID string `gorm:"size:255;not null;index"`
|
||||
AccountName string `gorm:"size:255"`
|
||||
Content string `gorm:"type:text;not null"`
|
||||
SentAt time.Time `gorm:"not null"`
|
||||
FromAdmin bool `gorm:"default:false"`
|
||||
}
|
||||
|
||||
func (ChatMessageRow) TableName() string { return "chat_messages" }
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StringSlice is a JSON-serialized string slice stored as a MySQL TEXT/JSON column.
|
||||
type StringSlice []string
|
||||
|
||||
func (s StringSlice) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
return "[]", nil
|
||||
}
|
||||
b, err := json.Marshal(s)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func (s *StringSlice) Scan(src any) error {
|
||||
var raw []byte
|
||||
switch v := src.(type) {
|
||||
case string:
|
||||
raw = []byte(v)
|
||||
case []byte:
|
||||
raw = v
|
||||
default:
|
||||
return fmt.Errorf("StringSlice: unsupported type %T", src)
|
||||
}
|
||||
return json.Unmarshal(raw, s)
|
||||
}
|
||||
|
||||
// ─── Products ────────────────────────────────────────────────────────────────
|
||||
|
||||
// ProductRow is the GORM model for the `products` table.
|
||||
type ProductRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
Name string `gorm:"size:255;not null"`
|
||||
Price float64 `gorm:"not null;default:0"`
|
||||
DiscountPrice float64 `gorm:"default:0"`
|
||||
Tags StringSlice `gorm:"type:json"`
|
||||
CoverURL string `gorm:"size:500"`
|
||||
ScreenshotURLs StringSlice `gorm:"type:json"`
|
||||
VerificationURL string `gorm:"size:500;default:''"`
|
||||
Description string `gorm:"type:text"`
|
||||
Active bool `gorm:"default:true;index"`
|
||||
RequireLogin bool `gorm:"default:false"`
|
||||
MaxPerAccount int `gorm:"default:0"`
|
||||
TotalSold int `gorm:"default:0"`
|
||||
ViewCount int `gorm:"default:0"`
|
||||
DeliveryMode string `gorm:"size:20;default:'auto'"`
|
||||
ShowNote bool `gorm:"default:false"`
|
||||
ShowContact bool `gorm:"default:false"`
|
||||
CreatedAt time.Time `gorm:"index"`
|
||||
}
|
||||
|
||||
func (ProductRow) TableName() string { return "products" }
|
||||
|
||||
// ProductCodeRow stores individual codes for a product (one row per code).
|
||||
type ProductCodeRow struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
ProductID string `gorm:"size:36;not null;index"`
|
||||
Code string `gorm:"type:text;not null"`
|
||||
}
|
||||
|
||||
func (ProductCodeRow) TableName() string { return "product_codes" }
|
||||
|
||||
// ─── Orders ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type OrderRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
ProductID string `gorm:"size:36;not null;index"`
|
||||
ProductName string `gorm:"size:255;not null"`
|
||||
UserAccount string `gorm:"size:255;index"`
|
||||
UserName string `gorm:"size:255"`
|
||||
Quantity int `gorm:"not null;default:1"`
|
||||
DeliveredCodes StringSlice `gorm:"type:json"`
|
||||
Status string `gorm:"size:20;not null;default:'pending';index"`
|
||||
DeliveryMode string `gorm:"size:20;default:'auto'"`
|
||||
Note string `gorm:"type:text"`
|
||||
ContactPhone string `gorm:"size:50"`
|
||||
ContactEmail string `gorm:"size:255"`
|
||||
NotifyEmail string `gorm:"size:255"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (OrderRow) TableName() string { return "orders" }
|
||||
|
||||
// ─── Site settings ───────────────────────────────────────────────────────────
|
||||
|
||||
// SiteSettingRow stores arbitrary key-value pairs for site-wide settings.
|
||||
type SiteSettingRow struct {
|
||||
Key string `gorm:"primaryKey;size:64"`
|
||||
Value string `gorm:"type:text"`
|
||||
}
|
||||
|
||||
func (SiteSettingRow) TableName() string { return "site_settings" }
|
||||
|
||||
// ─── Wishlists ───────────────────────────────────────────────────────────────
|
||||
|
||||
type WishlistRow struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
AccountID string `gorm:"size:255;not null;index:idx_wishlist,unique"`
|
||||
ProductID string `gorm:"size:36;not null;index:idx_wishlist,unique"`
|
||||
}
|
||||
|
||||
func (WishlistRow) TableName() string { return "wishlists" }
|
||||
|
||||
// ─── Chat messages ───────────────────────────────────────────────────────────
|
||||
|
||||
type ChatMessageRow struct {
|
||||
ID string `gorm:"primaryKey;size:36"`
|
||||
AccountID string `gorm:"size:255;not null;index"`
|
||||
AccountName string `gorm:"size:255"`
|
||||
Content string `gorm:"type:text;not null"`
|
||||
SentAt time.Time `gorm:"not null"`
|
||||
FromAdmin bool `gorm:"default:false"`
|
||||
}
|
||||
|
||||
func (ChatMessageRow) TableName() string { return "chat_messages" }
|
||||
|
||||
@@ -1,193 +1,193 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config 存储 SMTP 发件配置。
|
||||
type Config struct {
|
||||
SMTPHost string // 例:smtp.qq.com
|
||||
SMTPPort string // 例:465(SSL)或 587(STARTTLS)
|
||||
From string // 发件人邮箱地址
|
||||
Password string // SMTP 密码或授权码
|
||||
FromName string // 显示名称,例:"萌芽小店"
|
||||
}
|
||||
|
||||
// IsConfigured 判断配置是否充足,可以尝试发送邮件。
|
||||
func (c *Config) IsConfigured() bool {
|
||||
return c.From != "" && c.Password != "" && c.SMTPHost != ""
|
||||
}
|
||||
|
||||
// OrderNotifyData 包含发送订单通知邮件所需的数据。
|
||||
type OrderNotifyData struct {
|
||||
ToEmail string
|
||||
ToName string
|
||||
ProductName string
|
||||
OrderID string
|
||||
Quantity int
|
||||
Codes []string // 手动发货时为空
|
||||
IsManual bool
|
||||
}
|
||||
|
||||
// SendOrderNotify 发送订单发货通知邮件。
|
||||
// 若配置不完整或收件人为空,则静默跳过,返回 nil。
|
||||
func SendOrderNotify(cfg Config, data OrderNotifyData) error {
|
||||
if !cfg.IsConfigured() || data.ToEmail == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if cfg.SMTPPort == "" {
|
||||
cfg.SMTPPort = "465"
|
||||
}
|
||||
if cfg.SMTPHost == "" {
|
||||
cfg.SMTPHost = "smtp.qq.com"
|
||||
}
|
||||
fromName := cfg.FromName
|
||||
if fromName == "" {
|
||||
fromName = "萌芽小店"
|
||||
}
|
||||
|
||||
subject := "【萌芽小店】您的订单已发货"
|
||||
if data.IsManual {
|
||||
subject = "【萌芽小店】您的订单正在处理中"
|
||||
}
|
||||
|
||||
body := buildBody(data)
|
||||
msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body)
|
||||
|
||||
addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)
|
||||
auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost)
|
||||
|
||||
// QQ 邮箱使用 SSL(端口 465),需直接 TLS 拨号。
|
||||
if cfg.SMTPPort == "465" {
|
||||
return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg)
|
||||
}
|
||||
return smtp.SendMail(addr, auth, cfg.From, []string{data.ToEmail}, []byte(msg))
|
||||
}
|
||||
|
||||
func buildBody(data OrderNotifyData) string {
|
||||
var sb strings.Builder
|
||||
now := time.Now().Format("2006 年 01 月 02 日 15:04:05")
|
||||
|
||||
recipient := data.ToName
|
||||
if recipient == "" {
|
||||
recipient = "用户"
|
||||
}
|
||||
|
||||
sb.WriteString("尊敬的 ")
|
||||
sb.WriteString(recipient)
|
||||
sb.WriteString(",\n\n")
|
||||
sb.WriteString(" 您好!感谢您在萌芽小店的支持与购买。\n\n")
|
||||
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(" 订单信息\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(fmt.Sprintf(" 商品名称:%s\n", data.ProductName))
|
||||
sb.WriteString(fmt.Sprintf(" 订单编号:%s\n", data.OrderID))
|
||||
sb.WriteString(fmt.Sprintf(" 购买数量:%d 件\n", data.Quantity))
|
||||
sb.WriteString(fmt.Sprintf(" 通知时间:%s\n", now))
|
||||
sb.WriteString("────────────────────────────────\n\n")
|
||||
|
||||
if data.IsManual {
|
||||
sb.WriteString(" 您的订单已成功提交,目前正在等待人工审核与处理。\n")
|
||||
sb.WriteString(" 工作人员将尽快为您安排发货,请耐心等候。\n")
|
||||
sb.WriteString(" 发货完成后,我们将另行发送邮件通知。\n\n")
|
||||
} else {
|
||||
sb.WriteString(" 您的订单已完成自动发货,发货内容如下:\n\n")
|
||||
if len(data.Codes) > 0 {
|
||||
for i, code := range data.Codes {
|
||||
sb.WriteString(fmt.Sprintf(" [%d] %s\n", i+1, code))
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
sb.WriteString(" 请妥善保管以上发货内容,切勿泄露给他人。\n\n")
|
||||
}
|
||||
|
||||
sb.WriteString(" 如有任何疑问,请联系在线客服,我们将竭诚为您服务。\n\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(" 此邮件由系统自动发送,请勿直接回复。\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// buildMIMEMessage 构建符合 MIME 规范的邮件报文,支持 UTF-8 中文。
|
||||
func buildMIMEMessage(from, fromName, to, subject, body string) string {
|
||||
encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName))
|
||||
encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject))
|
||||
return fmt.Sprintf(
|
||||
"From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s",
|
||||
encodedFromName, from, to, encodedSubject, encodeBase64(body),
|
||||
)
|
||||
}
|
||||
|
||||
func encodeBase64(s string) string {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
b := []byte(s)
|
||||
var buf strings.Builder
|
||||
for i := 0; i < len(b); i += 3 {
|
||||
remaining := len(b) - i
|
||||
b0 := b[i]
|
||||
b1 := byte(0)
|
||||
b2 := byte(0)
|
||||
if remaining > 1 {
|
||||
b1 = b[i+1]
|
||||
}
|
||||
if remaining > 2 {
|
||||
b2 = b[i+2]
|
||||
}
|
||||
buf.WriteByte(chars[b0>>2])
|
||||
buf.WriteByte(chars[((b0&0x03)<<4)|(b1>>4)])
|
||||
if remaining > 1 {
|
||||
buf.WriteByte(chars[((b1&0x0f)<<2)|(b2>>6)])
|
||||
} else {
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
if remaining > 2 {
|
||||
buf.WriteByte(chars[b2&0x3f])
|
||||
} else {
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// sendSSL 通过 TLS 直接拨号发送邮件(适用于 465 端口 SSL 连接,如 QQ 邮箱)。
|
||||
func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error {
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: host,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
conn, err := tls.Dial("tcp", addr, tlsConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tls 拨号失败: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 SMTP 客户端失败: %w", err)
|
||||
}
|
||||
defer client.Quit() //nolint:errcheck
|
||||
|
||||
if err = client.Auth(auth); err != nil {
|
||||
return fmt.Errorf("SMTP 认证失败: %w", err)
|
||||
}
|
||||
if err = client.Mail(from); err != nil {
|
||||
return fmt.Errorf("SMTP MAIL FROM 失败: %w", err)
|
||||
}
|
||||
if err = client.Rcpt(to); err != nil {
|
||||
return fmt.Errorf("SMTP RCPT TO 失败: %w", err)
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP DATA 失败: %w", err)
|
||||
}
|
||||
if _, err = fmt.Fprint(w, msg); err != nil {
|
||||
return fmt.Errorf("写入邮件内容失败: %w", err)
|
||||
}
|
||||
return w.Close()
|
||||
}
|
||||
package email
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config 存储 SMTP 发件配置。
|
||||
type Config struct {
|
||||
SMTPHost string // 例:smtp.qq.com
|
||||
SMTPPort string // 例:465(SSL)或 587(STARTTLS)
|
||||
From string // 发件人邮箱地址
|
||||
Password string // SMTP 密码或授权码
|
||||
FromName string // 显示名称,例:"萌芽小店"
|
||||
}
|
||||
|
||||
// IsConfigured 判断配置是否充足,可以尝试发送邮件。
|
||||
func (c *Config) IsConfigured() bool {
|
||||
return c.From != "" && c.Password != "" && c.SMTPHost != ""
|
||||
}
|
||||
|
||||
// OrderNotifyData 包含发送订单通知邮件所需的数据。
|
||||
type OrderNotifyData struct {
|
||||
ToEmail string
|
||||
ToName string
|
||||
ProductName string
|
||||
OrderID string
|
||||
Quantity int
|
||||
Codes []string // 手动发货时为空
|
||||
IsManual bool
|
||||
}
|
||||
|
||||
// SendOrderNotify 发送订单发货通知邮件。
|
||||
// 若配置不完整或收件人为空,则静默跳过,返回 nil。
|
||||
func SendOrderNotify(cfg Config, data OrderNotifyData) error {
|
||||
if !cfg.IsConfigured() || data.ToEmail == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if cfg.SMTPPort == "" {
|
||||
cfg.SMTPPort = "465"
|
||||
}
|
||||
if cfg.SMTPHost == "" {
|
||||
cfg.SMTPHost = "smtp.qq.com"
|
||||
}
|
||||
fromName := cfg.FromName
|
||||
if fromName == "" {
|
||||
fromName = "萌芽小店"
|
||||
}
|
||||
|
||||
subject := "【萌芽小店】您的订单已发货"
|
||||
if data.IsManual {
|
||||
subject = "【萌芽小店】您的订单正在处理中"
|
||||
}
|
||||
|
||||
body := buildBody(data)
|
||||
msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body)
|
||||
|
||||
addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)
|
||||
auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost)
|
||||
|
||||
// QQ 邮箱使用 SSL(端口 465),需直接 TLS 拨号。
|
||||
if cfg.SMTPPort == "465" {
|
||||
return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg)
|
||||
}
|
||||
return smtp.SendMail(addr, auth, cfg.From, []string{data.ToEmail}, []byte(msg))
|
||||
}
|
||||
|
||||
func buildBody(data OrderNotifyData) string {
|
||||
var sb strings.Builder
|
||||
now := time.Now().Format("2006 年 01 月 02 日 15:04:05")
|
||||
|
||||
recipient := data.ToName
|
||||
if recipient == "" {
|
||||
recipient = "用户"
|
||||
}
|
||||
|
||||
sb.WriteString("尊敬的 ")
|
||||
sb.WriteString(recipient)
|
||||
sb.WriteString(",\n\n")
|
||||
sb.WriteString(" 您好!感谢您在萌芽小店的支持与购买。\n\n")
|
||||
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(" 订单信息\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(fmt.Sprintf(" 商品名称:%s\n", data.ProductName))
|
||||
sb.WriteString(fmt.Sprintf(" 订单编号:%s\n", data.OrderID))
|
||||
sb.WriteString(fmt.Sprintf(" 购买数量:%d 件\n", data.Quantity))
|
||||
sb.WriteString(fmt.Sprintf(" 通知时间:%s\n", now))
|
||||
sb.WriteString("────────────────────────────────\n\n")
|
||||
|
||||
if data.IsManual {
|
||||
sb.WriteString(" 您的订单已成功提交,目前正在等待人工审核与处理。\n")
|
||||
sb.WriteString(" 工作人员将尽快为您安排发货,请耐心等候。\n")
|
||||
sb.WriteString(" 发货完成后,我们将另行发送邮件通知。\n\n")
|
||||
} else {
|
||||
sb.WriteString(" 您的订单已完成自动发货,发货内容如下:\n\n")
|
||||
if len(data.Codes) > 0 {
|
||||
for i, code := range data.Codes {
|
||||
sb.WriteString(fmt.Sprintf(" [%d] %s\n", i+1, code))
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
sb.WriteString(" 请妥善保管以上发货内容,切勿泄露给他人。\n\n")
|
||||
}
|
||||
|
||||
sb.WriteString(" 如有任何疑问,请联系在线客服,我们将竭诚为您服务。\n\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
sb.WriteString(" 此邮件由系统自动发送,请勿直接回复。\n")
|
||||
sb.WriteString("────────────────────────────────\n")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// buildMIMEMessage 构建符合 MIME 规范的邮件报文,支持 UTF-8 中文。
|
||||
func buildMIMEMessage(from, fromName, to, subject, body string) string {
|
||||
encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName))
|
||||
encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject))
|
||||
return fmt.Sprintf(
|
||||
"From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s",
|
||||
encodedFromName, from, to, encodedSubject, encodeBase64(body),
|
||||
)
|
||||
}
|
||||
|
||||
func encodeBase64(s string) string {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
b := []byte(s)
|
||||
var buf strings.Builder
|
||||
for i := 0; i < len(b); i += 3 {
|
||||
remaining := len(b) - i
|
||||
b0 := b[i]
|
||||
b1 := byte(0)
|
||||
b2 := byte(0)
|
||||
if remaining > 1 {
|
||||
b1 = b[i+1]
|
||||
}
|
||||
if remaining > 2 {
|
||||
b2 = b[i+2]
|
||||
}
|
||||
buf.WriteByte(chars[b0>>2])
|
||||
buf.WriteByte(chars[((b0&0x03)<<4)|(b1>>4)])
|
||||
if remaining > 1 {
|
||||
buf.WriteByte(chars[((b1&0x0f)<<2)|(b2>>6)])
|
||||
} else {
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
if remaining > 2 {
|
||||
buf.WriteByte(chars[b2&0x3f])
|
||||
} else {
|
||||
buf.WriteByte('=')
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// sendSSL 通过 TLS 直接拨号发送邮件(适用于 465 端口 SSL 连接,如 QQ 邮箱)。
|
||||
func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error {
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: host,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
conn, err := tls.Dial("tcp", addr, tlsConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tls 拨号失败: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 SMTP 客户端失败: %w", err)
|
||||
}
|
||||
defer client.Quit() //nolint:errcheck
|
||||
|
||||
if err = client.Auth(auth); err != nil {
|
||||
return fmt.Errorf("SMTP 认证失败: %w", err)
|
||||
}
|
||||
if err = client.Mail(from); err != nil {
|
||||
return fmt.Errorf("SMTP MAIL FROM 失败: %w", err)
|
||||
}
|
||||
if err = client.Rcpt(to); err != nil {
|
||||
return fmt.Errorf("SMTP RCPT TO 失败: %w", err)
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP DATA 失败: %w", err)
|
||||
}
|
||||
if _, err = fmt.Fprint(w, msg); err != nil {
|
||||
return fmt.Errorf("写入邮件内容失败: %w", err)
|
||||
}
|
||||
return w.Close()
|
||||
}
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
// AdminHandler 持有所有管理员路由所需的依赖。
|
||||
type AdminHandler struct {
|
||||
store *storage.ProductStore
|
||||
cfg *config.Config
|
||||
siteStore *storage.SiteStore
|
||||
orderStore *storage.OrderStore
|
||||
chatStore *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewAdminHandler(store *storage.ProductStore, cfg *config.Config, siteStore *storage.SiteStore, orderStore *storage.OrderStore, chatStore *storage.ChatStore) *AdminHandler {
|
||||
return &AdminHandler{store: store, cfg: cfg, siteStore: siteStore, orderStore: orderStore, chatStore: chatStore}
|
||||
}
|
||||
|
||||
// requireAdmin 校验管理员令牌。
|
||||
// 优先级:X-Admin-Token 请求头 > Authorization 请求头 > ?token 查询参数(旧版兼容)。
|
||||
func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
|
||||
token := c.GetHeader("X-Admin-Token")
|
||||
if token == "" {
|
||||
token = c.GetHeader("Authorization")
|
||||
}
|
||||
if token == "" {
|
||||
// 兼容旧版客户端的 URL 查询参数回退
|
||||
token = c.Query("token")
|
||||
}
|
||||
if token != "" && token == h.cfg.AdminToken {
|
||||
return true
|
||||
}
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
// AdminHandler 持有所有管理员路由所需的依赖。
|
||||
type AdminHandler struct {
|
||||
store *storage.ProductStore
|
||||
cfg *config.Config
|
||||
siteStore *storage.SiteStore
|
||||
orderStore *storage.OrderStore
|
||||
chatStore *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewAdminHandler(store *storage.ProductStore, cfg *config.Config, siteStore *storage.SiteStore, orderStore *storage.OrderStore, chatStore *storage.ChatStore) *AdminHandler {
|
||||
return &AdminHandler{store: store, cfg: cfg, siteStore: siteStore, orderStore: orderStore, chatStore: chatStore}
|
||||
}
|
||||
|
||||
// requireAdmin 校验管理员令牌。
|
||||
// 优先级:X-Admin-Token 请求头 > Authorization 请求头 > ?token 查询参数(旧版兼容)。
|
||||
func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
|
||||
token := c.GetHeader("X-Admin-Token")
|
||||
if token == "" {
|
||||
token = c.GetHeader("Authorization")
|
||||
}
|
||||
if token == "" {
|
||||
// 兼容旧版客户端的 URL 查询参数回退
|
||||
token = c.Query("token")
|
||||
}
|
||||
if token != "" && token == h.cfg.AdminToken {
|
||||
return true
|
||||
}
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -1,88 +1,88 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetAllConversations 返回所有用户会话列表。
|
||||
func (h *AdminHandler) GetAllConversations(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
convs, err := h.chatStore.ListConversations()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
|
||||
}
|
||||
|
||||
// GetConversation 返回指定账号的全部消息记录。
|
||||
func (h *AdminHandler) GetConversation(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
msgs, err := h.chatStore.GetMessages(accountID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
|
||||
}
|
||||
|
||||
type adminChatPayload struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// AdminReply 向指定用户发送管理员回复。
|
||||
func (h *AdminHandler) AdminReply(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
var payload adminChatPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(payload.Content)
|
||||
if content == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
|
||||
return
|
||||
}
|
||||
msg, err := h.chatStore.SendAdminMessage(accountID, content)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
|
||||
}
|
||||
|
||||
// ClearConversation 清除与指定用户的全部消息记录。
|
||||
func (h *AdminHandler) ClearConversation(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
if err := h.chatStore.ClearConversation(accountID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetAllConversations 返回所有用户会话列表。
|
||||
func (h *AdminHandler) GetAllConversations(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
convs, err := h.chatStore.ListConversations()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
|
||||
}
|
||||
|
||||
// GetConversation 返回指定账号的全部消息记录。
|
||||
func (h *AdminHandler) GetConversation(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
msgs, err := h.chatStore.GetMessages(accountID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
|
||||
}
|
||||
|
||||
type adminChatPayload struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// AdminReply 向指定用户发送管理员回复。
|
||||
func (h *AdminHandler) AdminReply(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
var payload adminChatPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(payload.Content)
|
||||
if content == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
|
||||
return
|
||||
}
|
||||
msg, err := h.chatStore.SendAdminMessage(accountID, content)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
|
||||
}
|
||||
|
||||
// ClearConversation 清除与指定用户的全部消息记录。
|
||||
func (h *AdminHandler) ClearConversation(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
accountID := c.Param("account")
|
||||
if accountID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
|
||||
return
|
||||
}
|
||||
if err := h.chatStore.ClearConversation(accountID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (h *AdminHandler) ListAllOrders(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
orders, err := h.orderStore.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": orders})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteOrder(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
orderID := c.Param("id")
|
||||
if orderID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少订单 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.orderStore.Delete(orderID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (h *AdminHandler) ListAllOrders(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
orders, err := h.orderStore.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": orders})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteOrder(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
orderID := c.Param("id")
|
||||
if orderID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少订单 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.orderStore.Delete(orderID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
|
||||
@@ -1,210 +1,210 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type productPayload struct {
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags string `json:"tags"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
Codes []string `json:"codes"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
Description string `json:"description"`
|
||||
Active *bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
}
|
||||
|
||||
type togglePayload struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// VerifyAdminToken 验证管理员令牌是否正确,返回 {"valid": true/false},不暴露实际令牌值。
|
||||
func (h *AdminHandler) VerifyAdminToken(c *gin.Context) {
|
||||
var payload struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&payload); err != nil || payload.Token == "" {
|
||||
c.JSON(http.StatusOK, gin.H{"valid": false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"valid": payload.Token == h.cfg.AdminToken})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListAllProducts(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
items, err := h.store.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": items})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload productPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
|
||||
return
|
||||
}
|
||||
active := true
|
||||
if payload.Active != nil {
|
||||
active = *payload.Active
|
||||
}
|
||||
product := models.Product{
|
||||
Name: payload.Name,
|
||||
Price: payload.Price,
|
||||
DiscountPrice: payload.DiscountPrice,
|
||||
Tags: normalizeTags(payload.Tags),
|
||||
CoverURL: strings.TrimSpace(payload.CoverURL),
|
||||
Codes: payload.Codes,
|
||||
ScreenshotURLs: screenshotURLs,
|
||||
Description: payload.Description,
|
||||
Active: active,
|
||||
RequireLogin: payload.RequireLogin,
|
||||
MaxPerAccount: payload.MaxPerAccount,
|
||||
DeliveryMode: payload.DeliveryMode,
|
||||
ShowNote: payload.ShowNote,
|
||||
ShowContact: payload.ShowContact,
|
||||
}
|
||||
created, err := h.store.Create(product)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": created})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
var payload productPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
|
||||
return
|
||||
}
|
||||
active := false
|
||||
if payload.Active != nil {
|
||||
active = *payload.Active
|
||||
}
|
||||
patch := models.Product{
|
||||
Name: payload.Name,
|
||||
Price: payload.Price,
|
||||
DiscountPrice: payload.DiscountPrice,
|
||||
Tags: normalizeTags(payload.Tags),
|
||||
CoverURL: strings.TrimSpace(payload.CoverURL),
|
||||
Codes: payload.Codes,
|
||||
ScreenshotURLs: screenshotURLs,
|
||||
Description: payload.Description,
|
||||
Active: active,
|
||||
RequireLogin: payload.RequireLogin,
|
||||
MaxPerAccount: payload.MaxPerAccount,
|
||||
DeliveryMode: payload.DeliveryMode,
|
||||
ShowNote: payload.ShowNote,
|
||||
ShowContact: payload.ShowContact,
|
||||
}
|
||||
updated, err := h.store.Update(id, patch)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updated})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ToggleProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
var payload togglePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
updated, err := h.store.Toggle(id, payload.Active)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updated})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
if err := h.store.Delete(id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
|
||||
func normalizeScreenshotURLs(urls []string) ([]string, bool) {
|
||||
cleaned := make([]string, 0, len(urls))
|
||||
for _, url := range urls {
|
||||
trimmed := strings.TrimSpace(url)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, trimmed)
|
||||
if len(cleaned) > 5 {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return cleaned, true
|
||||
}
|
||||
|
||||
func normalizeTags(tagsCSV string) []string {
|
||||
if tagsCSV == "" {
|
||||
return []string{}
|
||||
}
|
||||
parts := strings.Split(tagsCSV, ",")
|
||||
clean := make([]string, 0, len(parts))
|
||||
seen := map[string]bool{}
|
||||
for _, p := range parts {
|
||||
t := strings.TrimSpace(p)
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(t)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
clean = append(clean, t)
|
||||
if len(clean) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type productPayload struct {
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags string `json:"tags"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
Codes []string `json:"codes"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
Description string `json:"description"`
|
||||
Active *bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
}
|
||||
|
||||
type togglePayload struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// VerifyAdminToken 验证管理员令牌是否正确,返回 {"valid": true/false},不暴露实际令牌值。
|
||||
func (h *AdminHandler) VerifyAdminToken(c *gin.Context) {
|
||||
var payload struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&payload); err != nil || payload.Token == "" {
|
||||
c.JSON(http.StatusOK, gin.H{"valid": false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"valid": payload.Token == h.cfg.AdminToken})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListAllProducts(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
items, err := h.store.ListAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": items})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload productPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
|
||||
return
|
||||
}
|
||||
active := true
|
||||
if payload.Active != nil {
|
||||
active = *payload.Active
|
||||
}
|
||||
product := models.Product{
|
||||
Name: payload.Name,
|
||||
Price: payload.Price,
|
||||
DiscountPrice: payload.DiscountPrice,
|
||||
Tags: normalizeTags(payload.Tags),
|
||||
CoverURL: strings.TrimSpace(payload.CoverURL),
|
||||
Codes: payload.Codes,
|
||||
ScreenshotURLs: screenshotURLs,
|
||||
Description: payload.Description,
|
||||
Active: active,
|
||||
RequireLogin: payload.RequireLogin,
|
||||
MaxPerAccount: payload.MaxPerAccount,
|
||||
DeliveryMode: payload.DeliveryMode,
|
||||
ShowNote: payload.ShowNote,
|
||||
ShowContact: payload.ShowContact,
|
||||
}
|
||||
created, err := h.store.Create(product)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": created})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
var payload productPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
|
||||
return
|
||||
}
|
||||
active := false
|
||||
if payload.Active != nil {
|
||||
active = *payload.Active
|
||||
}
|
||||
patch := models.Product{
|
||||
Name: payload.Name,
|
||||
Price: payload.Price,
|
||||
DiscountPrice: payload.DiscountPrice,
|
||||
Tags: normalizeTags(payload.Tags),
|
||||
CoverURL: strings.TrimSpace(payload.CoverURL),
|
||||
Codes: payload.Codes,
|
||||
ScreenshotURLs: screenshotURLs,
|
||||
Description: payload.Description,
|
||||
Active: active,
|
||||
RequireLogin: payload.RequireLogin,
|
||||
MaxPerAccount: payload.MaxPerAccount,
|
||||
DeliveryMode: payload.DeliveryMode,
|
||||
ShowNote: payload.ShowNote,
|
||||
ShowContact: payload.ShowContact,
|
||||
}
|
||||
updated, err := h.store.Update(id, patch)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updated})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ToggleProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
var payload togglePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
updated, err := h.store.Toggle(id, payload.Active)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updated})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) DeleteProduct(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
id := c.Param("id")
|
||||
if err := h.store.Delete(id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
|
||||
}
|
||||
|
||||
func normalizeScreenshotURLs(urls []string) ([]string, bool) {
|
||||
cleaned := make([]string, 0, len(urls))
|
||||
for _, url := range urls {
|
||||
trimmed := strings.TrimSpace(url)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, trimmed)
|
||||
if len(cleaned) > 5 {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return cleaned, true
|
||||
}
|
||||
|
||||
func normalizeTags(tagsCSV string) []string {
|
||||
if tagsCSV == "" {
|
||||
return []string{}
|
||||
}
|
||||
parts := strings.Split(tagsCSV, ",")
|
||||
clean := make([]string, 0, len(parts))
|
||||
seen := map[string]bool{}
|
||||
for _, p := range parts {
|
||||
t := strings.TrimSpace(p)
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(t)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
clean = append(clean, t)
|
||||
if len(clean) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
@@ -1,73 +1,73 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type maintenancePayload struct {
|
||||
Maintenance bool `json:"maintenance"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SetMaintenance(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload maintenancePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"maintenance": payload.Maintenance,
|
||||
"reason": payload.Reason,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
cfg, err := h.siteStore.GetSMTPConfig()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 响应中对密码脱敏处理
|
||||
masked := cfg
|
||||
if masked.Password != "" {
|
||||
masked.Password = "••••••••"
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": masked})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload storage.SMTPConfig
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
// 若密码为脱敏占位符,则保留数据库中原有的密码
|
||||
if payload.Password == "••••••••" {
|
||||
existing, _ := h.siteStore.GetSMTPConfig()
|
||||
payload.Password = existing.Password
|
||||
}
|
||||
if err := h.siteStore.SetSMTPConfig(payload); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": "ok"})
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type maintenancePayload struct {
|
||||
Maintenance bool `json:"maintenance"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SetMaintenance(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload maintenancePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"maintenance": payload.Maintenance,
|
||||
"reason": payload.Reason,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
cfg, err := h.siteStore.GetSMTPConfig()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 响应中对密码脱敏处理
|
||||
masked := cfg
|
||||
if masked.Password != "" {
|
||||
masked.Password = "••••••••"
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": masked})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
|
||||
if !h.requireAdmin(c) {
|
||||
return
|
||||
}
|
||||
var payload storage.SMTPConfig
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
// 若密码为脱敏占位符,则保留数据库中原有的密码
|
||||
if payload.Password == "••••••••" {
|
||||
existing, _ := h.siteStore.GetSMTPConfig()
|
||||
payload.Password = existing.Password
|
||||
}
|
||||
if err := h.siteStore.SetSMTPConfig(payload); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": "ok"})
|
||||
}
|
||||
|
||||
@@ -1,82 +1,82 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chatStore *storage.ChatStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
func NewChatHandler(chatStore *storage.ChatStore, authClient *auth.SproutGateClient) *ChatHandler {
|
||||
return &ChatHandler{chatStore: chatStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) requireChatUser(c *gin.Context) (account, name string, ok bool) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return "", "", false
|
||||
}
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(token)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return "", "", false
|
||||
}
|
||||
return result.User.Account, result.User.Username, true
|
||||
}
|
||||
|
||||
// GetMyMessages 返回当前登录用户的全部聊天消息。
|
||||
func (h *ChatHandler) GetMyMessages(c *gin.Context) {
|
||||
account, _, ok := h.requireChatUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
msgs, err := h.chatStore.GetMessages(account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
|
||||
}
|
||||
|
||||
type chatMessagePayload struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// SendMyMessage 向管理员发送一条用户消息。
|
||||
func (h *ChatHandler) SendMyMessage(c *gin.Context) {
|
||||
account, name, ok := h.requireChatUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload chatMessagePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(payload.Content)
|
||||
if content == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
msg, rateLimited, err := h.chatStore.SendUserMessage(account, name, content)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if rateLimited {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "发送太频繁,请稍候"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chatStore *storage.ChatStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
func NewChatHandler(chatStore *storage.ChatStore, authClient *auth.SproutGateClient) *ChatHandler {
|
||||
return &ChatHandler{chatStore: chatStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) requireChatUser(c *gin.Context) (account, name string, ok bool) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return "", "", false
|
||||
}
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(token)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return "", "", false
|
||||
}
|
||||
return result.User.Account, result.User.Username, true
|
||||
}
|
||||
|
||||
// GetMyMessages 返回当前登录用户的全部聊天消息。
|
||||
func (h *ChatHandler) GetMyMessages(c *gin.Context) {
|
||||
account, _, ok := h.requireChatUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
msgs, err := h.chatStore.GetMessages(account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
|
||||
}
|
||||
|
||||
type chatMessagePayload struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// SendMyMessage 向管理员发送一条用户消息。
|
||||
func (h *ChatHandler) SendMyMessage(c *gin.Context) {
|
||||
account, name, ok := h.requireChatUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload chatMessagePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(payload.Content)
|
||||
if content == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
msg, rateLimited, err := h.chatStore.SendUserMessage(account, name, content)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if rateLimited {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "发送太频繁,请稍候"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
|
||||
}
|
||||
|
||||
@@ -1,295 +1,295 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/email"
|
||||
"mengyastore-backend/internal/models"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
const qrSize = "320x320"
|
||||
|
||||
type OrderHandler struct {
|
||||
productStore *storage.ProductStore
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
type checkoutPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
Quantity int `json:"quantity"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
NotifyEmail string `json:"notifyEmail"`
|
||||
}
|
||||
|
||||
func NewOrderHandler(productStore *storage.ProductStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
|
||||
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *OrderHandler) sendOrderNotify(toEmail, toName, productName, orderID string, qty int, codes []string, isManual bool) {
|
||||
if toEmail == "" {
|
||||
return
|
||||
}
|
||||
cfg, err := h.siteStore.GetSMTPConfig()
|
||||
if err != nil || !cfg.IsConfiguredEmail() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
emailCfg := email.Config{
|
||||
SMTPHost: cfg.Host,
|
||||
SMTPPort: cfg.Port,
|
||||
From: cfg.Email,
|
||||
Password: cfg.Password,
|
||||
FromName: cfg.FromName,
|
||||
}
|
||||
if err := email.SendOrderNotify(emailCfg, email.OrderNotifyData{
|
||||
ToEmail: toEmail,
|
||||
ToName: toName,
|
||||
ProductName: productName,
|
||||
OrderID: orderID,
|
||||
Quantity: qty,
|
||||
Codes: codes,
|
||||
IsManual: isManual,
|
||||
}); err != nil {
|
||||
log.Printf("[Email] 发送通知失败 order=%s to=%s: %v", orderID, toEmail, err)
|
||||
} else {
|
||||
log.Printf("[Email] 发送通知成功 order=%s to=%s", orderID, toEmail)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (h *OrderHandler) tryExtractUserWithEmail(c *gin.Context) (account, username, userEmail string) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
return "", "", ""
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
return "", "", ""
|
||||
}
|
||||
return result.User.Account, result.User.Username, result.User.Email
|
||||
}
|
||||
|
||||
func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
|
||||
|
||||
var payload checkoutPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
|
||||
payload.ProductID = strings.TrimSpace(payload.ProductID)
|
||||
if payload.ProductID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必填字段"})
|
||||
return
|
||||
}
|
||||
if payload.Quantity <= 0 {
|
||||
payload.Quantity = 1
|
||||
}
|
||||
|
||||
product, err := h.productStore.GetByID(payload.ProductID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !product.Active {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "商品暂时无法购买"})
|
||||
return
|
||||
}
|
||||
|
||||
if product.RequireLogin && userAccount == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "该商品需要登录后才能购买"})
|
||||
return
|
||||
}
|
||||
|
||||
if product.MaxPerAccount > 0 && userAccount != "" {
|
||||
purchased, err := h.orderStore.CountPurchasedByAccount(userAccount, product.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if purchased+payload.Quantity > product.MaxPerAccount {
|
||||
remain := product.MaxPerAccount - purchased
|
||||
if remain <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您已达上限", product.MaxPerAccount)})
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您还可购买 %d 个", product.MaxPerAccount, remain)})
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if product.Quantity < payload.Quantity {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := product.DeliveryMode == "manual"
|
||||
|
||||
var deliveredCodes []string
|
||||
var updatedProduct models.Product
|
||||
|
||||
if isManual {
|
||||
updatedProduct = product
|
||||
} else {
|
||||
var ok bool
|
||||
deliveredCodes, ok = extractCodes(&product, payload.Quantity)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"})
|
||||
return
|
||||
}
|
||||
product.Quantity = len(product.Codes)
|
||||
updatedProduct, err = h.productStore.Update(product.ID, product)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
deliveryMode := product.DeliveryMode
|
||||
if deliveryMode == "" {
|
||||
deliveryMode = "auto"
|
||||
}
|
||||
|
||||
// 通知邮箱优先级:
|
||||
// 1. SproutGate 账号邮箱(已登录用户,最可靠)
|
||||
// 2. 前端传入的 notifyEmail(来自 authState.email)
|
||||
// 3. 用户在结账表单填写的联系邮箱
|
||||
// 4. 均为空则不发送
|
||||
notifyEmail := strings.TrimSpace(userEmail)
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
|
||||
}
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.ContactEmail)
|
||||
}
|
||||
|
||||
// 自动发货订单立即设为已完成(卡密已提取);手动发货订单初始状态为待处理,由管理员确认。
|
||||
orderStatus := "pending"
|
||||
if !isManual {
|
||||
orderStatus = "completed"
|
||||
}
|
||||
|
||||
order := models.Order{
|
||||
ProductID: updatedProduct.ID,
|
||||
ProductName: updatedProduct.Name,
|
||||
UserAccount: userAccount,
|
||||
UserName: userName,
|
||||
Quantity: payload.Quantity,
|
||||
DeliveredCodes: deliveredCodes,
|
||||
Status: orderStatus,
|
||||
DeliveryMode: deliveryMode,
|
||||
Note: strings.TrimSpace(payload.Note),
|
||||
ContactPhone: strings.TrimSpace(payload.ContactPhone),
|
||||
ContactEmail: strings.TrimSpace(payload.ContactEmail),
|
||||
NotifyEmail: notifyEmail,
|
||||
}
|
||||
created, err := h.orderStore.Create(order)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if !isManual {
|
||||
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
|
||||
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
|
||||
}
|
||||
// 自动发货:立即发送卡密通知邮件
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
|
||||
} else {
|
||||
// 手动发货:告知用户订单已收到,等待发货
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true)
|
||||
}
|
||||
|
||||
qrPayload := fmt.Sprintf("order:%s:%s", created.ID, created.ProductID)
|
||||
qrURL := fmt.Sprintf("https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s", qrSize, url.QueryEscape(qrPayload))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"orderId": created.ID,
|
||||
"qrCodeUrl": qrURL,
|
||||
"productId": created.ProductID,
|
||||
"productQty": created.Quantity,
|
||||
"viewCount": updatedProduct.ViewCount,
|
||||
"status": created.Status,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
|
||||
orderID := c.Param("id")
|
||||
order, err := h.orderStore.Confirm(orderID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := order.DeliveryMode == "manual"
|
||||
|
||||
// 手动发货确认后,发送"已发货"通知邮件
|
||||
if isManual {
|
||||
confirmNotifyEmail := order.NotifyEmail
|
||||
if confirmNotifyEmail == "" {
|
||||
confirmNotifyEmail = order.ContactEmail
|
||||
}
|
||||
h.sendOrderNotify(confirmNotifyEmail, order.UserName, order.ProductName, order.ID, order.Quantity, order.DeliveredCodes, false)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"orderId": order.ID,
|
||||
"status": order.Status,
|
||||
"deliveryMode": order.DeliveryMode,
|
||||
"deliveredCodes": order.DeliveredCodes,
|
||||
"isManual": isManual,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *OrderHandler) ListMyOrders(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return
|
||||
}
|
||||
|
||||
orders, err := h.orderStore.ListByAccount(result.User.Account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": orders})
|
||||
}
|
||||
|
||||
func extractCodes(product *models.Product, count int) ([]string, bool) {
|
||||
if count <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
if len(product.Codes) < count {
|
||||
return nil, false
|
||||
}
|
||||
delivered := make([]string, count)
|
||||
copy(delivered, product.Codes[:count])
|
||||
product.Codes = product.Codes[count:]
|
||||
return delivered, true
|
||||
}
|
||||
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/email"
|
||||
"mengyastore-backend/internal/models"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
const qrSize = "320x320"
|
||||
|
||||
type OrderHandler struct {
|
||||
productStore *storage.ProductStore
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
type checkoutPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
Quantity int `json:"quantity"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
NotifyEmail string `json:"notifyEmail"`
|
||||
}
|
||||
|
||||
func NewOrderHandler(productStore *storage.ProductStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
|
||||
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *OrderHandler) sendOrderNotify(toEmail, toName, productName, orderID string, qty int, codes []string, isManual bool) {
|
||||
if toEmail == "" {
|
||||
return
|
||||
}
|
||||
cfg, err := h.siteStore.GetSMTPConfig()
|
||||
if err != nil || !cfg.IsConfiguredEmail() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
emailCfg := email.Config{
|
||||
SMTPHost: cfg.Host,
|
||||
SMTPPort: cfg.Port,
|
||||
From: cfg.Email,
|
||||
Password: cfg.Password,
|
||||
FromName: cfg.FromName,
|
||||
}
|
||||
if err := email.SendOrderNotify(emailCfg, email.OrderNotifyData{
|
||||
ToEmail: toEmail,
|
||||
ToName: toName,
|
||||
ProductName: productName,
|
||||
OrderID: orderID,
|
||||
Quantity: qty,
|
||||
Codes: codes,
|
||||
IsManual: isManual,
|
||||
}); err != nil {
|
||||
log.Printf("[Email] 发送通知失败 order=%s to=%s: %v", orderID, toEmail, err)
|
||||
} else {
|
||||
log.Printf("[Email] 发送通知成功 order=%s to=%s", orderID, toEmail)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (h *OrderHandler) tryExtractUserWithEmail(c *gin.Context) (account, username, userEmail string) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
return "", "", ""
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
return "", "", ""
|
||||
}
|
||||
return result.User.Account, result.User.Username, result.User.Email
|
||||
}
|
||||
|
||||
func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
|
||||
|
||||
var payload checkoutPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
|
||||
payload.ProductID = strings.TrimSpace(payload.ProductID)
|
||||
if payload.ProductID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必填字段"})
|
||||
return
|
||||
}
|
||||
if payload.Quantity <= 0 {
|
||||
payload.Quantity = 1
|
||||
}
|
||||
|
||||
product, err := h.productStore.GetByID(payload.ProductID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !product.Active {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "商品暂时无法购买"})
|
||||
return
|
||||
}
|
||||
|
||||
if product.RequireLogin && userAccount == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "该商品需要登录后才能购买"})
|
||||
return
|
||||
}
|
||||
|
||||
if product.MaxPerAccount > 0 && userAccount != "" {
|
||||
purchased, err := h.orderStore.CountPurchasedByAccount(userAccount, product.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if purchased+payload.Quantity > product.MaxPerAccount {
|
||||
remain := product.MaxPerAccount - purchased
|
||||
if remain <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您已达上限", product.MaxPerAccount)})
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您还可购买 %d 个", product.MaxPerAccount, remain)})
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if product.Quantity < payload.Quantity {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := product.DeliveryMode == "manual"
|
||||
|
||||
var deliveredCodes []string
|
||||
var updatedProduct models.Product
|
||||
|
||||
if isManual {
|
||||
updatedProduct = product
|
||||
} else {
|
||||
var ok bool
|
||||
deliveredCodes, ok = extractCodes(&product, payload.Quantity)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"})
|
||||
return
|
||||
}
|
||||
product.Quantity = len(product.Codes)
|
||||
updatedProduct, err = h.productStore.Update(product.ID, product)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
deliveryMode := product.DeliveryMode
|
||||
if deliveryMode == "" {
|
||||
deliveryMode = "auto"
|
||||
}
|
||||
|
||||
// 通知邮箱优先级:
|
||||
// 1. SproutGate 账号邮箱(已登录用户,最可靠)
|
||||
// 2. 前端传入的 notifyEmail(来自 authState.email)
|
||||
// 3. 用户在结账表单填写的联系邮箱
|
||||
// 4. 均为空则不发送
|
||||
notifyEmail := strings.TrimSpace(userEmail)
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
|
||||
}
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.ContactEmail)
|
||||
}
|
||||
|
||||
// 自动发货订单立即设为已完成(卡密已提取);手动发货订单初始状态为待处理,由管理员确认。
|
||||
orderStatus := "pending"
|
||||
if !isManual {
|
||||
orderStatus = "completed"
|
||||
}
|
||||
|
||||
order := models.Order{
|
||||
ProductID: updatedProduct.ID,
|
||||
ProductName: updatedProduct.Name,
|
||||
UserAccount: userAccount,
|
||||
UserName: userName,
|
||||
Quantity: payload.Quantity,
|
||||
DeliveredCodes: deliveredCodes,
|
||||
Status: orderStatus,
|
||||
DeliveryMode: deliveryMode,
|
||||
Note: strings.TrimSpace(payload.Note),
|
||||
ContactPhone: strings.TrimSpace(payload.ContactPhone),
|
||||
ContactEmail: strings.TrimSpace(payload.ContactEmail),
|
||||
NotifyEmail: notifyEmail,
|
||||
}
|
||||
created, err := h.orderStore.Create(order)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if !isManual {
|
||||
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
|
||||
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
|
||||
}
|
||||
// 自动发货:立即发送卡密通知邮件
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
|
||||
} else {
|
||||
// 手动发货:告知用户订单已收到,等待发货
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true)
|
||||
}
|
||||
|
||||
qrPayload := fmt.Sprintf("order:%s:%s", created.ID, created.ProductID)
|
||||
qrURL := fmt.Sprintf("https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s", qrSize, url.QueryEscape(qrPayload))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"orderId": created.ID,
|
||||
"qrCodeUrl": qrURL,
|
||||
"productId": created.ProductID,
|
||||
"productQty": created.Quantity,
|
||||
"viewCount": updatedProduct.ViewCount,
|
||||
"status": created.Status,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
|
||||
orderID := c.Param("id")
|
||||
order, err := h.orderStore.Confirm(orderID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := order.DeliveryMode == "manual"
|
||||
|
||||
// 手动发货确认后,发送"已发货"通知邮件
|
||||
if isManual {
|
||||
confirmNotifyEmail := order.NotifyEmail
|
||||
if confirmNotifyEmail == "" {
|
||||
confirmNotifyEmail = order.ContactEmail
|
||||
}
|
||||
h.sendOrderNotify(confirmNotifyEmail, order.UserName, order.ProductName, order.ID, order.Quantity, order.DeliveredCodes, false)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"orderId": order.ID,
|
||||
"status": order.Status,
|
||||
"deliveryMode": order.DeliveryMode,
|
||||
"deliveredCodes": order.DeliveredCodes,
|
||||
"isManual": isManual,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *OrderHandler) ListMyOrders(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return
|
||||
}
|
||||
|
||||
orders, err := h.orderStore.ListByAccount(result.User.Account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": orders})
|
||||
}
|
||||
|
||||
func extractCodes(product *models.Product, count int) ([]string, bool) {
|
||||
if count <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
if len(product.Codes) < count {
|
||||
return nil, false
|
||||
}
|
||||
delivered := make([]string, count)
|
||||
copy(delivered, product.Codes[:count])
|
||||
product.Codes = product.Codes[count:]
|
||||
return delivered, true
|
||||
}
|
||||
|
||||
|
||||
@@ -59,4 +59,4 @@ func sanitizeForPublic(items []models.Product) []models.Product {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,66 +1,66 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type StatsHandler struct {
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
}
|
||||
|
||||
func NewStatsHandler(orderStore *storage.OrderStore, siteStore *storage.SiteStore) *StatsHandler {
|
||||
return &StatsHandler{orderStore: orderStore, siteStore: siteStore}
|
||||
}
|
||||
|
||||
func (h *StatsHandler) GetStats(c *gin.Context) {
|
||||
totalOrders, err := h.orderStore.Count()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
totalVisits, err := h.siteStore.GetTotalVisits()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"totalOrders": totalOrders,
|
||||
"totalVisits": totalVisits,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatsHandler) RecordVisit(c *gin.Context) {
|
||||
fingerprint := buildViewerFingerprint(c)
|
||||
totalVisits, counted, err := h.siteStore.RecordVisit(fingerprint)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"totalVisits": totalVisits,
|
||||
"counted": counted,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatsHandler) GetMaintenance(c *gin.Context) {
|
||||
enabled, reason, err := h.siteStore.GetMaintenance()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"maintenance": enabled,
|
||||
"reason": reason,
|
||||
},
|
||||
})
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type StatsHandler struct {
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
}
|
||||
|
||||
func NewStatsHandler(orderStore *storage.OrderStore, siteStore *storage.SiteStore) *StatsHandler {
|
||||
return &StatsHandler{orderStore: orderStore, siteStore: siteStore}
|
||||
}
|
||||
|
||||
func (h *StatsHandler) GetStats(c *gin.Context) {
|
||||
totalOrders, err := h.orderStore.Count()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
totalVisits, err := h.siteStore.GetTotalVisits()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"totalOrders": totalOrders,
|
||||
"totalVisits": totalVisits,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatsHandler) RecordVisit(c *gin.Context) {
|
||||
fingerprint := buildViewerFingerprint(c)
|
||||
totalVisits, counted, err := h.siteStore.RecordVisit(fingerprint)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"totalVisits": totalVisits,
|
||||
"counted": counted,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *StatsHandler) GetMaintenance(c *gin.Context) {
|
||||
enabled, reason, err := h.siteStore.GetMaintenance()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"maintenance": enabled,
|
||||
"reason": reason,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,88 +1,88 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type WishlistHandler struct {
|
||||
wishlistStore *storage.WishlistStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
func NewWishlistHandler(wishlistStore *storage.WishlistStore, authClient *auth.SproutGateClient) *WishlistHandler {
|
||||
return &WishlistHandler{wishlistStore: wishlistStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) requireUser(c *gin.Context) (string, bool) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(token)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return "", false
|
||||
}
|
||||
return result.User.Account, true
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) GetWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ids, err := h.wishlistStore.Get(account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
type wishlistItemPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) AddToWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload wishlistItemPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ids, _ := h.wishlistStore.Get(account)
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
productID := c.Param("id")
|
||||
if productID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少商品 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.wishlistStore.Remove(account, productID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ids, _ := h.wishlistStore.Get(account)
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
type WishlistHandler struct {
|
||||
wishlistStore *storage.WishlistStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
func NewWishlistHandler(wishlistStore *storage.WishlistStore, authClient *auth.SproutGateClient) *WishlistHandler {
|
||||
return &WishlistHandler{wishlistStore: wishlistStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) requireUser(c *gin.Context) (string, bool) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
result, err := h.authClient.VerifyToken(token)
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
|
||||
return "", false
|
||||
}
|
||||
return result.User.Account, true
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) GetWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ids, err := h.wishlistStore.Get(account)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
type wishlistItemPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) AddToWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var payload wishlistItemPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
|
||||
return
|
||||
}
|
||||
if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ids, _ := h.wishlistStore.Get(account)
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
|
||||
account, ok := h.requireUser(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
productID := c.Param("id")
|
||||
if productID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少商品 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.wishlistStore.Remove(account, productID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
ids, _ := h.wishlistStore.Get(account)
|
||||
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type ChatMessage struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountId"`
|
||||
AccountName string `json:"accountName"`
|
||||
Content string `json:"content"`
|
||||
SentAt time.Time `json:"sentAt"`
|
||||
FromAdmin bool `json:"fromAdmin"`
|
||||
}
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type ChatMessage struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountId"`
|
||||
AccountName string `json:"accountName"`
|
||||
Content string `json:"content"`
|
||||
SentAt time.Time `json:"sentAt"`
|
||||
FromAdmin bool `json:"fromAdmin"`
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Order struct {
|
||||
ID string `json:"id"`
|
||||
ProductID string `json:"productId"`
|
||||
ProductName string `json:"productName"`
|
||||
UserAccount string `json:"userAccount"`
|
||||
UserName string `json:"userName"`
|
||||
Quantity int `json:"quantity"`
|
||||
DeliveredCodes []string `json:"deliveredCodes"`
|
||||
Status string `json:"status"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
NotifyEmail string `json:"notifyEmail"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Order struct {
|
||||
ID string `json:"id"`
|
||||
ProductID string `json:"productId"`
|
||||
ProductName string `json:"productName"`
|
||||
UserAccount string `json:"userAccount"`
|
||||
UserName string `json:"userName"`
|
||||
Quantity int `json:"quantity"`
|
||||
DeliveredCodes []string `json:"deliveredCodes"`
|
||||
Status string `json:"status"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
Note string `json:"note"`
|
||||
ContactPhone string `json:"contactPhone"`
|
||||
ContactEmail string `json:"contactEmail"`
|
||||
NotifyEmail string `json:"notifyEmail"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Product struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags []string `json:"tags"`
|
||||
Quantity int `json:"quantity"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
VerificationURL string `json:"verificationUrl"`
|
||||
Codes []string `json:"codes"`
|
||||
ViewCount int `json:"viewCount"`
|
||||
Description string `json:"description"`
|
||||
Active bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
TotalSold int `json:"totalSold"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Product struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
DiscountPrice float64 `json:"discountPrice"`
|
||||
Tags []string `json:"tags"`
|
||||
Quantity int `json:"quantity"`
|
||||
CoverURL string `json:"coverUrl"`
|
||||
ScreenshotURLs []string `json:"screenshotUrls"`
|
||||
VerificationURL string `json:"verificationUrl"`
|
||||
Codes []string `json:"codes"`
|
||||
ViewCount int `json:"viewCount"`
|
||||
Description string `json:"description"`
|
||||
Active bool `json:"active"`
|
||||
RequireLogin bool `json:"requireLogin"`
|
||||
MaxPerAccount int `json:"maxPerAccount"`
|
||||
TotalSold int `json:"totalSold"`
|
||||
DeliveryMode string `json:"deliveryMode"`
|
||||
ShowNote bool `json:"showNote"`
|
||||
ShowContact bool `json:"showContact"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
@@ -1,99 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type ChatStore struct {
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
lastSent map[string]time.Time
|
||||
}
|
||||
|
||||
func NewChatStore(db *gorm.DB) (*ChatStore, error) {
|
||||
return &ChatStore{db: db, lastSent: make(map[string]time.Time)}, nil
|
||||
}
|
||||
|
||||
func chatRowToModel(row database.ChatMessageRow) models.ChatMessage {
|
||||
return models.ChatMessage{
|
||||
ID: row.ID,
|
||||
AccountID: row.AccountID,
|
||||
AccountName: row.AccountName,
|
||||
Content: row.Content,
|
||||
SentAt: row.SentAt,
|
||||
FromAdmin: row.FromAdmin,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatStore) GetMessages(accountID string) ([]models.ChatMessage, error) {
|
||||
var rows []database.ChatMessageRow
|
||||
if err := s.db.Where("account_id = ?", accountID).Order("sent_at ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgs := make([]models.ChatMessage, len(rows))
|
||||
for i, r := range rows {
|
||||
msgs[i] = chatRowToModel(r)
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListConversations() (map[string][]models.ChatMessage, error) {
|
||||
var rows []database.ChatMessageRow
|
||||
if err := s.db.Order("account_id, sent_at ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(map[string][]models.ChatMessage)
|
||||
for _, r := range rows {
|
||||
result[r.AccountID] = append(result[r.AccountID], chatRowToModel(r))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) SendUserMessage(accountID, accountName, content string) (models.ChatMessage, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if last, ok := s.lastSent[accountID]; ok && time.Since(last) < time.Second {
|
||||
return models.ChatMessage{}, true, nil
|
||||
}
|
||||
s.lastSent[accountID] = time.Now()
|
||||
|
||||
row := database.ChatMessageRow{
|
||||
ID: uuid.New().String(),
|
||||
AccountID: accountID,
|
||||
AccountName: accountName,
|
||||
Content: content,
|
||||
SentAt: time.Now(),
|
||||
FromAdmin: false,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.ChatMessage{}, false, err
|
||||
}
|
||||
return chatRowToModel(row), false, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) SendAdminMessage(accountID, content string) (models.ChatMessage, error) {
|
||||
row := database.ChatMessageRow{
|
||||
ID: uuid.New().String(),
|
||||
AccountID: accountID,
|
||||
AccountName: "管理员",
|
||||
Content: content,
|
||||
SentAt: time.Now(),
|
||||
FromAdmin: true,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.ChatMessage{}, err
|
||||
}
|
||||
return chatRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ClearConversation(accountID string) error {
|
||||
return s.db.Where("account_id = ?", accountID).Delete(&database.ChatMessageRow{}).Error
|
||||
}
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type ChatStore struct {
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
lastSent map[string]time.Time
|
||||
}
|
||||
|
||||
func NewChatStore(db *gorm.DB) (*ChatStore, error) {
|
||||
return &ChatStore{db: db, lastSent: make(map[string]time.Time)}, nil
|
||||
}
|
||||
|
||||
func chatRowToModel(row database.ChatMessageRow) models.ChatMessage {
|
||||
return models.ChatMessage{
|
||||
ID: row.ID,
|
||||
AccountID: row.AccountID,
|
||||
AccountName: row.AccountName,
|
||||
Content: row.Content,
|
||||
SentAt: row.SentAt,
|
||||
FromAdmin: row.FromAdmin,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatStore) GetMessages(accountID string) ([]models.ChatMessage, error) {
|
||||
var rows []database.ChatMessageRow
|
||||
if err := s.db.Where("account_id = ?", accountID).Order("sent_at ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgs := make([]models.ChatMessage, len(rows))
|
||||
for i, r := range rows {
|
||||
msgs[i] = chatRowToModel(r)
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListConversations() (map[string][]models.ChatMessage, error) {
|
||||
var rows []database.ChatMessageRow
|
||||
if err := s.db.Order("account_id, sent_at ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(map[string][]models.ChatMessage)
|
||||
for _, r := range rows {
|
||||
result[r.AccountID] = append(result[r.AccountID], chatRowToModel(r))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) SendUserMessage(accountID, accountName, content string) (models.ChatMessage, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if last, ok := s.lastSent[accountID]; ok && time.Since(last) < time.Second {
|
||||
return models.ChatMessage{}, true, nil
|
||||
}
|
||||
s.lastSent[accountID] = time.Now()
|
||||
|
||||
row := database.ChatMessageRow{
|
||||
ID: uuid.New().String(),
|
||||
AccountID: accountID,
|
||||
AccountName: accountName,
|
||||
Content: content,
|
||||
SentAt: time.Now(),
|
||||
FromAdmin: false,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.ChatMessage{}, false, err
|
||||
}
|
||||
return chatRowToModel(row), false, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) SendAdminMessage(accountID, content string) (models.ChatMessage, error) {
|
||||
row := database.ChatMessageRow{
|
||||
ID: uuid.New().String(),
|
||||
AccountID: accountID,
|
||||
AccountName: "管理员",
|
||||
Content: content,
|
||||
SentAt: time.Now(),
|
||||
FromAdmin: true,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.ChatMessage{}, err
|
||||
}
|
||||
return chatRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ClearConversation(accountID string) error {
|
||||
return s.db.Where("account_id = ?", accountID).Delete(&database.ChatMessageRow{}).Error
|
||||
}
|
||||
|
||||
@@ -1,140 +1,140 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type OrderStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
|
||||
return &OrderStore{db: db}, nil
|
||||
}
|
||||
|
||||
func orderRowToModel(row database.OrderRow) models.Order {
|
||||
return models.Order{
|
||||
ID: row.ID,
|
||||
ProductID: row.ProductID,
|
||||
ProductName: row.ProductName,
|
||||
UserAccount: row.UserAccount,
|
||||
UserName: row.UserName,
|
||||
Quantity: row.Quantity,
|
||||
DeliveredCodes: row.DeliveredCodes,
|
||||
Status: row.Status,
|
||||
DeliveryMode: row.DeliveryMode,
|
||||
Note: row.Note,
|
||||
ContactPhone: row.ContactPhone,
|
||||
ContactEmail: row.ContactEmail,
|
||||
NotifyEmail: row.NotifyEmail,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
|
||||
if order.ID == "" {
|
||||
order.ID = uuid.NewString()
|
||||
}
|
||||
if len(order.DeliveredCodes) == 0 {
|
||||
order.DeliveredCodes = []string{}
|
||||
}
|
||||
row := database.OrderRow{
|
||||
ID: order.ID,
|
||||
ProductID: order.ProductID,
|
||||
ProductName: order.ProductName,
|
||||
UserAccount: order.UserAccount,
|
||||
UserName: order.UserName,
|
||||
Quantity: order.Quantity,
|
||||
DeliveredCodes: database.StringSlice(order.DeliveredCodes),
|
||||
Status: order.Status,
|
||||
DeliveryMode: order.DeliveryMode,
|
||||
Note: order.Note,
|
||||
ContactPhone: order.ContactPhone,
|
||||
ContactEmail: order.ContactEmail,
|
||||
NotifyEmail: order.NotifyEmail,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
order.CreatedAt = row.CreatedAt
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) GetByID(id string) (models.Order, error) {
|
||||
var row database.OrderRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) Confirm(id string) (models.Order, error) {
|
||||
var row database.OrderRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
row.Status = "completed"
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
|
||||
var rows []database.OrderRow
|
||||
if err := s.db.Where("user_account = ?", account).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListAll() ([]models.Order, error) {
|
||||
var rows []database.OrderRow
|
||||
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) {
|
||||
var total int64
|
||||
// 统计 pending(手动待发货)和 completed 两种状态,防止用户快速下单绕过购买数量限制。
|
||||
err := s.db.Model(&database.OrderRow{}).
|
||||
Where("user_account = ? AND product_id = ? AND status IN ?", account, productID, []string{"pending", "completed"}).
|
||||
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
|
||||
return int(total), err
|
||||
}
|
||||
|
||||
// Count 返回所有订单的总数量。
|
||||
func (s *OrderStore) Count() (int, error) {
|
||||
var count int64
|
||||
if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
// Delete 根据 ID 删除单条订单。
|
||||
func (s *OrderStore) Delete(id string) error {
|
||||
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// UpdateCodes 更新订单的已发货卡密列表。
|
||||
func (s *OrderStore) UpdateCodes(id string, codes []string) error {
|
||||
return s.db.Model(&database.OrderRow{}).Where("id = ?", id).
|
||||
Update("delivered_codes", database.StringSlice(codes)).Error
|
||||
}
|
||||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type OrderStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
|
||||
return &OrderStore{db: db}, nil
|
||||
}
|
||||
|
||||
func orderRowToModel(row database.OrderRow) models.Order {
|
||||
return models.Order{
|
||||
ID: row.ID,
|
||||
ProductID: row.ProductID,
|
||||
ProductName: row.ProductName,
|
||||
UserAccount: row.UserAccount,
|
||||
UserName: row.UserName,
|
||||
Quantity: row.Quantity,
|
||||
DeliveredCodes: row.DeliveredCodes,
|
||||
Status: row.Status,
|
||||
DeliveryMode: row.DeliveryMode,
|
||||
Note: row.Note,
|
||||
ContactPhone: row.ContactPhone,
|
||||
ContactEmail: row.ContactEmail,
|
||||
NotifyEmail: row.NotifyEmail,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
|
||||
if order.ID == "" {
|
||||
order.ID = uuid.NewString()
|
||||
}
|
||||
if len(order.DeliveredCodes) == 0 {
|
||||
order.DeliveredCodes = []string{}
|
||||
}
|
||||
row := database.OrderRow{
|
||||
ID: order.ID,
|
||||
ProductID: order.ProductID,
|
||||
ProductName: order.ProductName,
|
||||
UserAccount: order.UserAccount,
|
||||
UserName: order.UserName,
|
||||
Quantity: order.Quantity,
|
||||
DeliveredCodes: database.StringSlice(order.DeliveredCodes),
|
||||
Status: order.Status,
|
||||
DeliveryMode: order.DeliveryMode,
|
||||
Note: order.Note,
|
||||
ContactPhone: order.ContactPhone,
|
||||
ContactEmail: order.ContactEmail,
|
||||
NotifyEmail: order.NotifyEmail,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
order.CreatedAt = row.CreatedAt
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) GetByID(id string) (models.Order, error) {
|
||||
var row database.OrderRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) Confirm(id string) (models.Order, error) {
|
||||
var row database.OrderRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
row.Status = "completed"
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
|
||||
var rows []database.OrderRow
|
||||
if err := s.db.Where("user_account = ?", account).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListAll() ([]models.Order, error) {
|
||||
var rows []database.OrderRow
|
||||
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) {
|
||||
var total int64
|
||||
// 统计 pending(手动待发货)和 completed 两种状态,防止用户快速下单绕过购买数量限制。
|
||||
err := s.db.Model(&database.OrderRow{}).
|
||||
Where("user_account = ? AND product_id = ? AND status IN ?", account, productID, []string{"pending", "completed"}).
|
||||
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
|
||||
return int(total), err
|
||||
}
|
||||
|
||||
// Count 返回所有订单的总数量。
|
||||
func (s *OrderStore) Count() (int, error) {
|
||||
var count int64
|
||||
if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
// Delete 根据 ID 删除单条订单。
|
||||
func (s *OrderStore) Delete(id string) error {
|
||||
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// UpdateCodes 更新订单的已发货卡密列表。
|
||||
func (s *OrderStore) UpdateCodes(id string, codes []string) error {
|
||||
return s.db.Model(&database.OrderRow{}).Where("id = ?", id).
|
||||
Update("delivered_codes", database.StringSlice(codes)).Error
|
||||
}
|
||||
|
||||
@@ -1,328 +1,328 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
const defaultCoverURL = "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png"
|
||||
const viewCooldown = 6 * time.Hour
|
||||
const maxScreenshotURLs = 5
|
||||
|
||||
type ProductStore struct {
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
recentViews map[string]time.Time
|
||||
}
|
||||
|
||||
func NewProductStore(db *gorm.DB) (*ProductStore, error) {
|
||||
return &ProductStore{
|
||||
db: db,
|
||||
recentViews: make(map[string]time.Time),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// rowToModel 将数据库行(含卡密)转换为业务模型。
|
||||
func rowToModel(row database.ProductRow, codes []string) models.Product {
|
||||
return models.Product{
|
||||
ID: row.ID,
|
||||
Name: row.Name,
|
||||
Price: row.Price,
|
||||
DiscountPrice: row.DiscountPrice,
|
||||
Tags: row.Tags,
|
||||
CoverURL: row.CoverURL,
|
||||
ScreenshotURLs: row.ScreenshotURLs,
|
||||
VerificationURL: row.VerificationURL,
|
||||
Description: row.Description,
|
||||
Active: row.Active,
|
||||
RequireLogin: row.RequireLogin,
|
||||
MaxPerAccount: row.MaxPerAccount,
|
||||
TotalSold: row.TotalSold,
|
||||
ViewCount: row.ViewCount,
|
||||
DeliveryMode: row.DeliveryMode,
|
||||
ShowNote: row.ShowNote,
|
||||
ShowContact: row.ShowContact,
|
||||
Codes: codes,
|
||||
Quantity: len(codes),
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProductStore) loadCodes(productID string) ([]string, error) {
|
||||
var rows []database.ProductCodeRow
|
||||
if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
codes := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
codes[i] = r.Code
|
||||
}
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) replaceCodes(productID string, codes []string) error {
|
||||
if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows := make([]database.ProductCodeRow, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
rows = append(rows, database.ProductCodeRow{ProductID: productID, Code: code})
|
||||
}
|
||||
return s.db.CreateInBatches(rows, 100).Error
|
||||
}
|
||||
|
||||
func (s *ProductStore) ListAll() ([]models.Product, error) {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
codes, _ := s.loadCodes(row.ID)
|
||||
products = append(products, rowToModel(row, codes))
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) ListActive() ([]models.Product, error) {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
// 公开接口不暴露卡密,但需要统计剩余库存数量
|
||||
var count int64
|
||||
s.db.Model(&database.ProductCodeRow{}).Where("product_id = ?", row.ID).Count(&count)
|
||||
row.Active = true
|
||||
p := rowToModel(row, nil)
|
||||
p.Quantity = int(count)
|
||||
p.Codes = nil
|
||||
products = append(products, p)
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) GetByID(id string) (models.Product, error) {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Create(p models.Product) (models.Product, error) {
|
||||
p = normalizeProduct(p)
|
||||
p.ID = uuid.NewString()
|
||||
now := time.Now()
|
||||
p.CreatedAt = now
|
||||
|
||||
row := database.ProductRow{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Price: p.Price,
|
||||
DiscountPrice: p.DiscountPrice,
|
||||
Tags: database.StringSlice(p.Tags),
|
||||
CoverURL: p.CoverURL,
|
||||
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
|
||||
VerificationURL: p.VerificationURL,
|
||||
Description: p.Description,
|
||||
Active: p.Active,
|
||||
RequireLogin: p.RequireLogin,
|
||||
MaxPerAccount: p.MaxPerAccount,
|
||||
TotalSold: p.TotalSold,
|
||||
ViewCount: p.ViewCount,
|
||||
DeliveryMode: p.DeliveryMode,
|
||||
ShowNote: p.ShowNote,
|
||||
ShowContact: p.ShowContact,
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
if err := s.replaceCodes(p.ID, p.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
p.Quantity = len(p.Codes)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Update(id string, patch models.Product) (models.Product, error) {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
normalized := normalizeProduct(patch)
|
||||
|
||||
if err := s.db.Model(&row).Updates(map[string]interface{}{
|
||||
"name": normalized.Name,
|
||||
"price": normalized.Price,
|
||||
"discount_price": normalized.DiscountPrice,
|
||||
"tags": database.StringSlice(normalized.Tags),
|
||||
"cover_url": normalized.CoverURL,
|
||||
"screenshot_urls": database.StringSlice(normalized.ScreenshotURLs),
|
||||
"verification_url": normalized.VerificationURL,
|
||||
"description": normalized.Description,
|
||||
"active": normalized.Active,
|
||||
"require_login": normalized.RequireLogin,
|
||||
"max_per_account": normalized.MaxPerAccount,
|
||||
"delivery_mode": normalized.DeliveryMode,
|
||||
"show_note": normalized.ShowNote,
|
||||
"show_contact": normalized.ShowContact,
|
||||
}).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
if err := s.replaceCodes(id, normalized.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
|
||||
var updated database.ProductRow
|
||||
s.db.First(&updated, "id = ?", id)
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(updated, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Toggle(id string, active bool) (models.Product, error) {
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) IncrementSold(id string, count int) error {
|
||||
return s.db.Model(&database.ProductRow{}).Where("id = ?", id).
|
||||
UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error
|
||||
}
|
||||
|
||||
func (s *ProductStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
s.cleanupRecentViews(now)
|
||||
key := buildViewKey(id, fingerprint)
|
||||
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
}
|
||||
return rowToModel(row, nil), false, nil
|
||||
}
|
||||
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).
|
||||
UpdateColumn("view_count", gorm.Expr("view_count + 1")).Error; err != nil {
|
||||
return models.Product{}, false, err
|
||||
}
|
||||
s.recentViews[key] = now
|
||||
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
}
|
||||
return rowToModel(row, nil), true, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Delete(id string) error {
|
||||
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// normalizeProduct 对商品字段进行规范化处理(清理空白、设默认值等)。
|
||||
func normalizeProduct(item models.Product) models.Product {
|
||||
item.CoverURL = strings.TrimSpace(item.CoverURL)
|
||||
if item.CoverURL == "" {
|
||||
item.CoverURL = defaultCoverURL
|
||||
}
|
||||
if item.Tags == nil {
|
||||
item.Tags = []string{}
|
||||
}
|
||||
item.Tags = sanitizeTags(item.Tags)
|
||||
if item.ScreenshotURLs == nil {
|
||||
item.ScreenshotURLs = []string{}
|
||||
}
|
||||
if len(item.ScreenshotURLs) > maxScreenshotURLs {
|
||||
item.ScreenshotURLs = item.ScreenshotURLs[:maxScreenshotURLs]
|
||||
}
|
||||
if item.Codes == nil {
|
||||
item.Codes = []string{}
|
||||
}
|
||||
if item.DiscountPrice <= 0 || item.DiscountPrice >= item.Price {
|
||||
item.DiscountPrice = 0
|
||||
}
|
||||
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
|
||||
item.Codes = sanitizeCodes(item.Codes)
|
||||
item.Quantity = len(item.Codes)
|
||||
if item.DeliveryMode == "" {
|
||||
item.DeliveryMode = "auto"
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func sanitizeCodes(codes []string) []string {
|
||||
clean := make([]string, 0, len(codes))
|
||||
seen := map[string]bool{}
|
||||
for _, code := range codes {
|
||||
trimmed := strings.TrimSpace(code)
|
||||
if trimmed == "" || seen[trimmed] {
|
||||
continue
|
||||
}
|
||||
seen[trimmed] = true
|
||||
clean = append(clean, trimmed)
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func sanitizeTags(tags []string) []string {
|
||||
clean := make([]string, 0, len(tags))
|
||||
seen := map[string]bool{}
|
||||
for _, tag := range tags {
|
||||
t := strings.TrimSpace(tag)
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(t)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
clean = append(clean, t)
|
||||
if len(clean) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func buildViewKey(id, fingerprint string) string {
|
||||
sum := sha256.Sum256([]byte(id + "|" + fingerprint))
|
||||
return fmt.Sprintf("%x", sum)
|
||||
}
|
||||
|
||||
func (s *ProductStore) cleanupRecentViews(now time.Time) {
|
||||
for key, lastViewedAt := range s.recentViews {
|
||||
if now.Sub(lastViewedAt) >= viewCooldown {
|
||||
delete(s.recentViews, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
const defaultCoverURL = "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png"
|
||||
const viewCooldown = 6 * time.Hour
|
||||
const maxScreenshotURLs = 5
|
||||
|
||||
type ProductStore struct {
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
recentViews map[string]time.Time
|
||||
}
|
||||
|
||||
func NewProductStore(db *gorm.DB) (*ProductStore, error) {
|
||||
return &ProductStore{
|
||||
db: db,
|
||||
recentViews: make(map[string]time.Time),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// rowToModel 将数据库行(含卡密)转换为业务模型。
|
||||
func rowToModel(row database.ProductRow, codes []string) models.Product {
|
||||
return models.Product{
|
||||
ID: row.ID,
|
||||
Name: row.Name,
|
||||
Price: row.Price,
|
||||
DiscountPrice: row.DiscountPrice,
|
||||
Tags: row.Tags,
|
||||
CoverURL: row.CoverURL,
|
||||
ScreenshotURLs: row.ScreenshotURLs,
|
||||
VerificationURL: row.VerificationURL,
|
||||
Description: row.Description,
|
||||
Active: row.Active,
|
||||
RequireLogin: row.RequireLogin,
|
||||
MaxPerAccount: row.MaxPerAccount,
|
||||
TotalSold: row.TotalSold,
|
||||
ViewCount: row.ViewCount,
|
||||
DeliveryMode: row.DeliveryMode,
|
||||
ShowNote: row.ShowNote,
|
||||
ShowContact: row.ShowContact,
|
||||
Codes: codes,
|
||||
Quantity: len(codes),
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProductStore) loadCodes(productID string) ([]string, error) {
|
||||
var rows []database.ProductCodeRow
|
||||
if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
codes := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
codes[i] = r.Code
|
||||
}
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) replaceCodes(productID string, codes []string) error {
|
||||
if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows := make([]database.ProductCodeRow, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
rows = append(rows, database.ProductCodeRow{ProductID: productID, Code: code})
|
||||
}
|
||||
return s.db.CreateInBatches(rows, 100).Error
|
||||
}
|
||||
|
||||
func (s *ProductStore) ListAll() ([]models.Product, error) {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
codes, _ := s.loadCodes(row.ID)
|
||||
products = append(products, rowToModel(row, codes))
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) ListActive() ([]models.Product, error) {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
// 公开接口不暴露卡密,但需要统计剩余库存数量
|
||||
var count int64
|
||||
s.db.Model(&database.ProductCodeRow{}).Where("product_id = ?", row.ID).Count(&count)
|
||||
row.Active = true
|
||||
p := rowToModel(row, nil)
|
||||
p.Quantity = int(count)
|
||||
p.Codes = nil
|
||||
products = append(products, p)
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) GetByID(id string) (models.Product, error) {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Create(p models.Product) (models.Product, error) {
|
||||
p = normalizeProduct(p)
|
||||
p.ID = uuid.NewString()
|
||||
now := time.Now()
|
||||
p.CreatedAt = now
|
||||
|
||||
row := database.ProductRow{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Price: p.Price,
|
||||
DiscountPrice: p.DiscountPrice,
|
||||
Tags: database.StringSlice(p.Tags),
|
||||
CoverURL: p.CoverURL,
|
||||
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
|
||||
VerificationURL: p.VerificationURL,
|
||||
Description: p.Description,
|
||||
Active: p.Active,
|
||||
RequireLogin: p.RequireLogin,
|
||||
MaxPerAccount: p.MaxPerAccount,
|
||||
TotalSold: p.TotalSold,
|
||||
ViewCount: p.ViewCount,
|
||||
DeliveryMode: p.DeliveryMode,
|
||||
ShowNote: p.ShowNote,
|
||||
ShowContact: p.ShowContact,
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.db.Create(&row).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
if err := s.replaceCodes(p.ID, p.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
p.Quantity = len(p.Codes)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Update(id string, patch models.Product) (models.Product, error) {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
normalized := normalizeProduct(patch)
|
||||
|
||||
if err := s.db.Model(&row).Updates(map[string]interface{}{
|
||||
"name": normalized.Name,
|
||||
"price": normalized.Price,
|
||||
"discount_price": normalized.DiscountPrice,
|
||||
"tags": database.StringSlice(normalized.Tags),
|
||||
"cover_url": normalized.CoverURL,
|
||||
"screenshot_urls": database.StringSlice(normalized.ScreenshotURLs),
|
||||
"verification_url": normalized.VerificationURL,
|
||||
"description": normalized.Description,
|
||||
"active": normalized.Active,
|
||||
"require_login": normalized.RequireLogin,
|
||||
"max_per_account": normalized.MaxPerAccount,
|
||||
"delivery_mode": normalized.DeliveryMode,
|
||||
"show_note": normalized.ShowNote,
|
||||
"show_contact": normalized.ShowContact,
|
||||
}).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
if err := s.replaceCodes(id, normalized.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
|
||||
var updated database.ProductRow
|
||||
s.db.First(&updated, "id = ?", id)
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(updated, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Toggle(id string, active bool) (models.Product, error) {
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) IncrementSold(id string, count int) error {
|
||||
return s.db.Model(&database.ProductRow{}).Where("id = ?", id).
|
||||
UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error
|
||||
}
|
||||
|
||||
func (s *ProductStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
s.cleanupRecentViews(now)
|
||||
key := buildViewKey(id, fingerprint)
|
||||
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
}
|
||||
return rowToModel(row, nil), false, nil
|
||||
}
|
||||
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).
|
||||
UpdateColumn("view_count", gorm.Expr("view_count + 1")).Error; err != nil {
|
||||
return models.Product{}, false, err
|
||||
}
|
||||
s.recentViews[key] = now
|
||||
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
}
|
||||
return rowToModel(row, nil), true, nil
|
||||
}
|
||||
|
||||
func (s *ProductStore) Delete(id string) error {
|
||||
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// normalizeProduct 对商品字段进行规范化处理(清理空白、设默认值等)。
|
||||
func normalizeProduct(item models.Product) models.Product {
|
||||
item.CoverURL = strings.TrimSpace(item.CoverURL)
|
||||
if item.CoverURL == "" {
|
||||
item.CoverURL = defaultCoverURL
|
||||
}
|
||||
if item.Tags == nil {
|
||||
item.Tags = []string{}
|
||||
}
|
||||
item.Tags = sanitizeTags(item.Tags)
|
||||
if item.ScreenshotURLs == nil {
|
||||
item.ScreenshotURLs = []string{}
|
||||
}
|
||||
if len(item.ScreenshotURLs) > maxScreenshotURLs {
|
||||
item.ScreenshotURLs = item.ScreenshotURLs[:maxScreenshotURLs]
|
||||
}
|
||||
if item.Codes == nil {
|
||||
item.Codes = []string{}
|
||||
}
|
||||
if item.DiscountPrice <= 0 || item.DiscountPrice >= item.Price {
|
||||
item.DiscountPrice = 0
|
||||
}
|
||||
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
|
||||
item.Codes = sanitizeCodes(item.Codes)
|
||||
item.Quantity = len(item.Codes)
|
||||
if item.DeliveryMode == "" {
|
||||
item.DeliveryMode = "auto"
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func sanitizeCodes(codes []string) []string {
|
||||
clean := make([]string, 0, len(codes))
|
||||
seen := map[string]bool{}
|
||||
for _, code := range codes {
|
||||
trimmed := strings.TrimSpace(code)
|
||||
if trimmed == "" || seen[trimmed] {
|
||||
continue
|
||||
}
|
||||
seen[trimmed] = true
|
||||
clean = append(clean, trimmed)
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func sanitizeTags(tags []string) []string {
|
||||
clean := make([]string, 0, len(tags))
|
||||
seen := map[string]bool{}
|
||||
for _, tag := range tags {
|
||||
t := strings.TrimSpace(tag)
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(t)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
clean = append(clean, t)
|
||||
if len(clean) >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func buildViewKey(id, fingerprint string) string {
|
||||
sum := sha256.Sum256([]byte(id + "|" + fingerprint))
|
||||
return fmt.Sprintf("%x", sum)
|
||||
}
|
||||
|
||||
func (s *ProductStore) cleanupRecentViews(now time.Time) {
|
||||
for key, lastViewedAt := range s.recentViews {
|
||||
if now.Sub(lastViewedAt) >= viewCooldown {
|
||||
delete(s.recentViews, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,146 +1,146 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
type SiteStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
|
||||
return &SiteStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) get(key string) (string, error) {
|
||||
var row database.SiteSettingRow
|
||||
// `key` 是 MySQL 保留字,需用反引号转义以避免 SQL 语法错误。
|
||||
if err := s.db.Where("`key` = ?", key).First(&row).Error; err != nil {
|
||||
return "", nil // 键不存在时返回零值
|
||||
}
|
||||
return row.Value, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) set(key, value string) error {
|
||||
return s.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
||||
}).Create(&database.SiteSettingRow{Key: key, Value: value}).Error
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetTotalVisits() (int, error) {
|
||||
v, err := s.get("totalVisits")
|
||||
if err != nil || v == "" {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := strconv.Atoi(v)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) IncrementVisits() (int, error) {
|
||||
current, err := s.GetTotalVisits()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
current++
|
||||
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
|
||||
v, err := s.get("maintenance")
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
enabled = v == "true"
|
||||
reason, err = s.get("maintenanceReason")
|
||||
return enabled, reason, err
|
||||
}
|
||||
|
||||
func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
|
||||
v := "false"
|
||||
if enabled {
|
||||
v = "true"
|
||||
}
|
||||
if err := s.set("maintenance", v); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.set("maintenanceReason", reason)
|
||||
}
|
||||
|
||||
// RecordVisit 递增访问计数,返回 (总访问量, 是否计入, 错误)。
|
||||
// 去重逻辑由上层 handler 的内存指纹完成,此处无条件累加。
|
||||
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
|
||||
total, err := s.IncrementVisits()
|
||||
return total, true, err
|
||||
}
|
||||
|
||||
// SMTPConfig 存储数据库中的发件 SMTP 配置。
|
||||
type SMTPConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
FromName string `json:"fromName"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
}
|
||||
|
||||
// IsConfiguredEmail 判断邮件通知是否已启用且 SMTP 配置完整。
|
||||
func (c SMTPConfig) IsConfiguredEmail() bool {
|
||||
return c.Enabled && c.Email != "" && c.Password != "" && c.Host != ""
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
|
||||
cfg := SMTPConfig{
|
||||
Enabled: true, // 默认启用
|
||||
Host: "smtp.qq.com",
|
||||
Port: "465",
|
||||
}
|
||||
if v, _ := s.get("smtpEnabled"); v == "false" {
|
||||
cfg.Enabled = false
|
||||
}
|
||||
if v, _ := s.get("smtpEmail"); v != "" {
|
||||
cfg.Email = v
|
||||
}
|
||||
if v, _ := s.get("smtpPassword"); v != "" {
|
||||
cfg.Password = v
|
||||
}
|
||||
if v, _ := s.get("smtpFromName"); v != "" {
|
||||
cfg.FromName = v
|
||||
}
|
||||
if v, _ := s.get("smtpHost"); v != "" {
|
||||
cfg.Host = v
|
||||
}
|
||||
if v, _ := s.get("smtpPort"); v != "" {
|
||||
cfg.Port = v
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error {
|
||||
enabledVal := "true"
|
||||
if !cfg.Enabled {
|
||||
enabledVal = "false"
|
||||
}
|
||||
pairs := [][2]string{
|
||||
{"smtpEnabled", enabledVal},
|
||||
{"smtpEmail", cfg.Email},
|
||||
{"smtpPassword", cfg.Password},
|
||||
{"smtpFromName", cfg.FromName},
|
||||
{"smtpHost", cfg.Host},
|
||||
{"smtpPort", cfg.Port},
|
||||
}
|
||||
for _, p := range pairs {
|
||||
if err := s.set(p[0], p[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
package storage
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
type SiteStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
|
||||
return &SiteStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) get(key string) (string, error) {
|
||||
var row database.SiteSettingRow
|
||||
// `key` 是 MySQL 保留字,需用反引号转义以避免 SQL 语法错误。
|
||||
if err := s.db.Where("`key` = ?", key).First(&row).Error; err != nil {
|
||||
return "", nil // 键不存在时返回零值
|
||||
}
|
||||
return row.Value, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) set(key, value string) error {
|
||||
return s.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
||||
}).Create(&database.SiteSettingRow{Key: key, Value: value}).Error
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetTotalVisits() (int, error) {
|
||||
v, err := s.get("totalVisits")
|
||||
if err != nil || v == "" {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := strconv.Atoi(v)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) IncrementVisits() (int, error) {
|
||||
current, err := s.GetTotalVisits()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
current++
|
||||
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
|
||||
v, err := s.get("maintenance")
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
enabled = v == "true"
|
||||
reason, err = s.get("maintenanceReason")
|
||||
return enabled, reason, err
|
||||
}
|
||||
|
||||
func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
|
||||
v := "false"
|
||||
if enabled {
|
||||
v = "true"
|
||||
}
|
||||
if err := s.set("maintenance", v); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.set("maintenanceReason", reason)
|
||||
}
|
||||
|
||||
// RecordVisit 递增访问计数,返回 (总访问量, 是否计入, 错误)。
|
||||
// 去重逻辑由上层 handler 的内存指纹完成,此处无条件累加。
|
||||
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
|
||||
total, err := s.IncrementVisits()
|
||||
return total, true, err
|
||||
}
|
||||
|
||||
// SMTPConfig 存储数据库中的发件 SMTP 配置。
|
||||
type SMTPConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
FromName string `json:"fromName"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
}
|
||||
|
||||
// IsConfiguredEmail 判断邮件通知是否已启用且 SMTP 配置完整。
|
||||
func (c SMTPConfig) IsConfiguredEmail() bool {
|
||||
return c.Enabled && c.Email != "" && c.Password != "" && c.Host != ""
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
|
||||
cfg := SMTPConfig{
|
||||
Enabled: true, // 默认启用
|
||||
Host: "smtp.qq.com",
|
||||
Port: "465",
|
||||
}
|
||||
if v, _ := s.get("smtpEnabled"); v == "false" {
|
||||
cfg.Enabled = false
|
||||
}
|
||||
if v, _ := s.get("smtpEmail"); v != "" {
|
||||
cfg.Email = v
|
||||
}
|
||||
if v, _ := s.get("smtpPassword"); v != "" {
|
||||
cfg.Password = v
|
||||
}
|
||||
if v, _ := s.get("smtpFromName"); v != "" {
|
||||
cfg.FromName = v
|
||||
}
|
||||
if v, _ := s.get("smtpHost"); v != "" {
|
||||
cfg.Host = v
|
||||
}
|
||||
if v, _ := s.get("smtpPort"); v != "" {
|
||||
cfg.Port = v
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error {
|
||||
enabledVal := "true"
|
||||
if !cfg.Enabled {
|
||||
enabledVal = "false"
|
||||
}
|
||||
pairs := [][2]string{
|
||||
{"smtpEnabled", enabledVal},
|
||||
{"smtpEmail", cfg.Email},
|
||||
{"smtpPassword", cfg.Password},
|
||||
{"smtpFromName", cfg.FromName},
|
||||
{"smtpHost", cfg.Host},
|
||||
{"smtpPort", cfg.Port},
|
||||
}
|
||||
for _, p := range pairs {
|
||||
if err := s.set(p[0], p[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
type WishlistStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewWishlistStore(db *gorm.DB) (*WishlistStore, error) {
|
||||
return &WishlistStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Get(accountID string) ([]string, error) {
|
||||
var rows []database.WishlistRow
|
||||
if err := s.db.Where("account_id = ?", accountID).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
ids[i] = r.ProductID
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Add(accountID, productID string) error {
|
||||
return s.db.Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&database.WishlistRow{AccountID: accountID, ProductID: productID}).Error
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Remove(accountID, productID string) error {
|
||||
return s.db.Where("account_id = ? AND product_id = ?", accountID, productID).
|
||||
Delete(&database.WishlistRow{}).Error
|
||||
}
|
||||
package storage
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
type WishlistStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewWishlistStore(db *gorm.DB) (*WishlistStore, error) {
|
||||
return &WishlistStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Get(accountID string) ([]string, error) {
|
||||
var rows []database.WishlistRow
|
||||
if err := s.db.Where("account_id = ?", accountID).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
ids[i] = r.ProductID
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Add(accountID, productID string) error {
|
||||
return s.db.Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&database.WishlistRow{AccountID: accountID, ProductID: productID}).Error
|
||||
}
|
||||
|
||||
func (s *WishlistStore) Remove(accountID, productID string) error {
|
||||
return s.db.Where("account_id = ? AND product_id = ?", accountID, productID).
|
||||
Delete(&database.WishlistRow{}).Error
|
||||
}
|
||||
|
||||
@@ -1,114 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/handlers"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load("config.json")
|
||||
if err != nil {
|
||||
log.Fatalf("加载配置失败: %v", err)
|
||||
}
|
||||
|
||||
// 初始化数据库连接
|
||||
db, err := database.Open(cfg.DatabaseDSN)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化数据库失败: %v", err)
|
||||
}
|
||||
|
||||
store, err := storage.NewProductStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化商品存储失败: %v", err)
|
||||
}
|
||||
orderStore, err := storage.NewOrderStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化订单存储失败: %v", err)
|
||||
}
|
||||
siteStore, err := storage.NewSiteStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化站点存储失败: %v", err)
|
||||
}
|
||||
wishlistStore, err := storage.NewWishlistStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化收藏夹存储失败: %v", err)
|
||||
}
|
||||
chatStore, err := storage.NewChatStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化聊天存储失败: %v", err)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Admin-Token"},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 12 * time.Hour,
|
||||
}))
|
||||
|
||||
r.GET("/api/health", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)
|
||||
|
||||
publicHandler := handlers.NewPublicHandler(store)
|
||||
adminHandler := handlers.NewAdminHandler(store, cfg, siteStore, orderStore, chatStore)
|
||||
orderHandler := handlers.NewOrderHandler(store, orderStore, siteStore, authClient)
|
||||
statsHandler := handlers.NewStatsHandler(orderStore, siteStore)
|
||||
wishlistHandler := handlers.NewWishlistHandler(wishlistStore, authClient)
|
||||
chatHandler := handlers.NewChatHandler(chatStore, authClient)
|
||||
|
||||
r.GET("/api/products", publicHandler.ListProducts)
|
||||
r.POST("/api/checkout", orderHandler.CreateOrder)
|
||||
r.POST("/api/products/:id/view", publicHandler.RecordProductView)
|
||||
r.GET("/api/stats", statsHandler.GetStats)
|
||||
r.POST("/api/site/visit", statsHandler.RecordVisit)
|
||||
r.GET("/api/site/maintenance", statsHandler.GetMaintenance)
|
||||
r.GET("/api/orders", orderHandler.ListMyOrders)
|
||||
r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)
|
||||
|
||||
r.POST("/api/admin/verify", adminHandler.VerifyAdminToken)
|
||||
r.GET("/api/admin/products", adminHandler.ListAllProducts)
|
||||
r.POST("/api/admin/products", adminHandler.CreateProduct)
|
||||
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
|
||||
r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
|
||||
r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)
|
||||
r.POST("/api/admin/site/maintenance", adminHandler.SetMaintenance)
|
||||
r.GET("/api/admin/site/smtp", adminHandler.GetSMTPConfig)
|
||||
r.POST("/api/admin/site/smtp", adminHandler.SetSMTPConfig)
|
||||
r.GET("/api/admin/orders", adminHandler.ListAllOrders)
|
||||
r.DELETE("/api/admin/orders/:id", adminHandler.DeleteOrder)
|
||||
|
||||
r.GET("/api/wishlist", wishlistHandler.GetWishlist)
|
||||
r.POST("/api/wishlist", wishlistHandler.AddToWishlist)
|
||||
r.DELETE("/api/wishlist/:id", wishlistHandler.RemoveFromWishlist)
|
||||
|
||||
// 用户聊天路由
|
||||
r.GET("/api/chat/messages", chatHandler.GetMyMessages)
|
||||
r.POST("/api/chat/messages", chatHandler.SendMyMessage)
|
||||
|
||||
// 管理员聊天路由
|
||||
r.GET("/api/admin/chat", adminHandler.GetAllConversations)
|
||||
r.GET("/api/admin/chat/:account", adminHandler.GetConversation)
|
||||
r.POST("/api/admin/chat/:account", adminHandler.AdminReply)
|
||||
r.DELETE("/api/admin/chat/:account", adminHandler.ClearConversation)
|
||||
|
||||
log.Println("萌芽小店后端启动于 http://localhost:8080")
|
||||
if err := r.Run(":8080"); err != nil {
|
||||
log.Fatalf("服务器启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/handlers"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load("config.json")
|
||||
if err != nil {
|
||||
log.Fatalf("加载配置失败: %v", err)
|
||||
}
|
||||
|
||||
// 初始化数据库连接
|
||||
db, err := database.Open(cfg.DatabaseDSN)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化数据库失败: %v", err)
|
||||
}
|
||||
|
||||
store, err := storage.NewProductStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化商品存储失败: %v", err)
|
||||
}
|
||||
orderStore, err := storage.NewOrderStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化订单存储失败: %v", err)
|
||||
}
|
||||
siteStore, err := storage.NewSiteStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化站点存储失败: %v", err)
|
||||
}
|
||||
wishlistStore, err := storage.NewWishlistStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化收藏夹存储失败: %v", err)
|
||||
}
|
||||
chatStore, err := storage.NewChatStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("初始化聊天存储失败: %v", err)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Admin-Token"},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 12 * time.Hour,
|
||||
}))
|
||||
|
||||
r.GET("/api/health", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)
|
||||
|
||||
publicHandler := handlers.NewPublicHandler(store)
|
||||
adminHandler := handlers.NewAdminHandler(store, cfg, siteStore, orderStore, chatStore)
|
||||
orderHandler := handlers.NewOrderHandler(store, orderStore, siteStore, authClient)
|
||||
statsHandler := handlers.NewStatsHandler(orderStore, siteStore)
|
||||
wishlistHandler := handlers.NewWishlistHandler(wishlistStore, authClient)
|
||||
chatHandler := handlers.NewChatHandler(chatStore, authClient)
|
||||
|
||||
r.GET("/api/products", publicHandler.ListProducts)
|
||||
r.POST("/api/checkout", orderHandler.CreateOrder)
|
||||
r.POST("/api/products/:id/view", publicHandler.RecordProductView)
|
||||
r.GET("/api/stats", statsHandler.GetStats)
|
||||
r.POST("/api/site/visit", statsHandler.RecordVisit)
|
||||
r.GET("/api/site/maintenance", statsHandler.GetMaintenance)
|
||||
r.GET("/api/orders", orderHandler.ListMyOrders)
|
||||
r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)
|
||||
|
||||
r.POST("/api/admin/verify", adminHandler.VerifyAdminToken)
|
||||
r.GET("/api/admin/products", adminHandler.ListAllProducts)
|
||||
r.POST("/api/admin/products", adminHandler.CreateProduct)
|
||||
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
|
||||
r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
|
||||
r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)
|
||||
r.POST("/api/admin/site/maintenance", adminHandler.SetMaintenance)
|
||||
r.GET("/api/admin/site/smtp", adminHandler.GetSMTPConfig)
|
||||
r.POST("/api/admin/site/smtp", adminHandler.SetSMTPConfig)
|
||||
r.GET("/api/admin/orders", adminHandler.ListAllOrders)
|
||||
r.DELETE("/api/admin/orders/:id", adminHandler.DeleteOrder)
|
||||
|
||||
r.GET("/api/wishlist", wishlistHandler.GetWishlist)
|
||||
r.POST("/api/wishlist", wishlistHandler.AddToWishlist)
|
||||
r.DELETE("/api/wishlist/:id", wishlistHandler.RemoveFromWishlist)
|
||||
|
||||
// 用户聊天路由
|
||||
r.GET("/api/chat/messages", chatHandler.GetMyMessages)
|
||||
r.POST("/api/chat/messages", chatHandler.SendMyMessage)
|
||||
|
||||
// 管理员聊天路由
|
||||
r.GET("/api/admin/chat", adminHandler.GetAllConversations)
|
||||
r.GET("/api/admin/chat/:account", adminHandler.GetConversation)
|
||||
r.POST("/api/admin/chat/:account", adminHandler.AdminReply)
|
||||
r.DELETE("/api/admin/chat/:account", adminHandler.ClearConversation)
|
||||
|
||||
log.Println("萌芽小店后端启动于 http://localhost:8080")
|
||||
if err := r.Run(":8080"); err != nil {
|
||||
log.Fatalf("服务器启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user