feat: major update - MySQL, chat, wishlist, PWA, admin overhaul
This commit is contained in:
256
mengyastore-backend/README.md
Normal file
256
mengyastore-backend/README.md
Normal file
@@ -0,0 +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` 比对。
|
||||
304
mengyastore-backend/cmd/migrate/main.go
Normal file
304
mengyastore-backend/cmd/migrate/main.go
Normal file
@@ -0,0 +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("data/json/settings.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,119 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": "0bea9606-51aa-4fe2-a932-ab0e36ee33ca",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"LINUX-INVITE-001"
|
||||
],
|
||||
"status": "pending",
|
||||
"createdAt": "2026-03-19T17:23:46.1743551+08:00"
|
||||
},
|
||||
{
|
||||
"id": "5be3ecbd-873b-4ea2-9209-e96f6eb528cd",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"LINUX-INVITE-002"
|
||||
],
|
||||
"status": "pending",
|
||||
"createdAt": "2026-03-19T17:24:07.6045189+08:00"
|
||||
},
|
||||
{
|
||||
"id": "c0cbb6c7-76be-49ef-9e67-8d2ae890e555",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"啊伟大伟大伟大我"
|
||||
],
|
||||
"status": "pending",
|
||||
"createdAt": "2026-03-19T22:28:28.5393405+08:00"
|
||||
},
|
||||
{
|
||||
"id": "f299bbb4-0de4-4824-84ab-d1ccfb3b35dd",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"啊伟大伟大伟大伟大"
|
||||
],
|
||||
"status": "pending",
|
||||
"createdAt": "2026-03-20T10:32:38.352837+08:00"
|
||||
},
|
||||
{
|
||||
"id": "413931af-2867-4855-89af-515747d4b5e5",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"你是傻逼哈哈哈被骗了吧"
|
||||
],
|
||||
"status": "pending",
|
||||
"createdAt": "2026-03-20T10:32:55.2785291+08:00"
|
||||
},
|
||||
{
|
||||
"id": "59ab54e0-8b98-48d3-bf63-a843ef2c95a4",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"唐"
|
||||
],
|
||||
"status": "pending",
|
||||
"createdAt": "2026-03-20T10:39:37.9977301+08:00"
|
||||
},
|
||||
{
|
||||
"id": "94e82c71-8237-429f-b593-2530314b72af",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "",
|
||||
"userName": "",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"原神牛逼"
|
||||
],
|
||||
"status": "completed",
|
||||
"createdAt": "2026-03-20T10:40:45.3820749+08:00"
|
||||
},
|
||||
{
|
||||
"id": "058cad17-608c-4108-b012-af42f688a047",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "shumengya",
|
||||
"userName": "树萌芽",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"123123123131"
|
||||
],
|
||||
"status": "completed",
|
||||
"createdAt": "2026-03-20T10:44:21.375082+08:00"
|
||||
},
|
||||
{
|
||||
"id": "e95f30ab-da4f-4dec-872c-3c9047cd8193",
|
||||
"productId": "seed-1",
|
||||
"productName": "Linux Do 邀请码",
|
||||
"userAccount": "shumengya",
|
||||
"userName": "树萌芽",
|
||||
"quantity": 1,
|
||||
"deliveredCodes": [
|
||||
"131231231231231"
|
||||
],
|
||||
"status": "completed",
|
||||
"createdAt": "2026-03-20T10:57:13.3436565+08:00"
|
||||
}
|
||||
]
|
||||
@@ -1,181 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": "seed-1",
|
||||
"name": "Linux Do 邀请码",
|
||||
"price": 7,
|
||||
"discountPrice": 4,
|
||||
"tags": [
|
||||
"邀请码",
|
||||
"LinuxDo"
|
||||
],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 10,
|
||||
"description": "Linux.do论坛邀请码 默认每天可以生成一个,先到先得.",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-15T10:00:00+08:00",
|
||||
"updatedAt": "2026-03-20T11:37:16.2219815+08:00"
|
||||
},
|
||||
{
|
||||
"id": "seed-2",
|
||||
"name": "ChatGPT普号",
|
||||
"price": 1,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 2,
|
||||
"description": "ChatGPT 普号 纯手工注册 数量不多",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-15T10:05:00+08:00",
|
||||
"updatedAt": "2026-03-20T11:34:54.3522714+08:00"
|
||||
},
|
||||
{
|
||||
"id": "2b6b6051-bca7-42da-b127-c7b721c50c06",
|
||||
"name": "谷歌账号",
|
||||
"price": 20,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 1,
|
||||
"description": "谷歌账号 现货 可绑定F2A验证",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-15T20:52:52.0381722+08:00",
|
||||
"updatedAt": "2026-03-19T19:33:05.6844325+08:00"
|
||||
},
|
||||
{
|
||||
"id": "b9922892-c197-44be-be87-637ccb6bebeb",
|
||||
"name": "萌芽币",
|
||||
"price": 999999,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 1,
|
||||
"description": "非买品 仅展示",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-15T21:03:00.0164528+08:00",
|
||||
"updatedAt": "2026-03-19T19:33:07.508758+08:00"
|
||||
},
|
||||
{
|
||||
"id": "ee8e0140-221c-4bfa-b10a-13b1f98ea4e5",
|
||||
"name": "Keep校园跑 代刷4公里",
|
||||
"price": 1,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 1,
|
||||
"description": "keep校园跑带刷 每天4-5公里 下单后直接联系我发账号",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-15T21:06:11.9820102+08:00",
|
||||
"updatedAt": "2026-03-19T19:33:09.1800225+08:00"
|
||||
},
|
||||
{
|
||||
"id": "00bbf5db-b99e-4e88-a8ee-e7747b5969fe",
|
||||
"name": "学习通/慕课挂课脚本",
|
||||
"price": 25,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 1,
|
||||
"description": "学习通,慕课挂科脚本 手机 电脑都可以挂 不会弄可联系教你",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-15T21:06:45.3807471+08:00",
|
||||
"updatedAt": "2026-03-19T19:33:02.9673884+08:00"
|
||||
},
|
||||
{
|
||||
"id": "6c7bf494-ef2c-4221-9bf7-ec3c94070d25",
|
||||
"name": "smyhub.com后缀域名邮箱",
|
||||
"price": 5,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 0,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [],
|
||||
"viewCount": 1,
|
||||
"description": "纪念意义,比如我自己的mail@smyhub.com 目前已经续费了5年到2031年",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-18T22:17:41.3034538+08:00",
|
||||
"updatedAt": "2026-03-19T19:32:26.7674929+08:00"
|
||||
},
|
||||
{
|
||||
"id": "a30a2275-1c9c-49e4-a402-3e446e3e0f5c",
|
||||
"name": "萌芽账号邀请码",
|
||||
"price": 10,
|
||||
"discountPrice": 8,
|
||||
"tags": [],
|
||||
"quantity": 1,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [
|
||||
"原神牛逼"
|
||||
],
|
||||
"viewCount": 0,
|
||||
"description": "萌芽统一账号登录平台邀请码",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-20T11:04:05.5787516+08:00",
|
||||
"updatedAt": "2026-03-20T11:04:05.5787516+08:00"
|
||||
},
|
||||
{
|
||||
"id": "bcd5d73b-6ad9-4ed9-8e18-42ea0482ceb3",
|
||||
"name": "Keep 代跑脚本",
|
||||
"price": 50,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 1,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [
|
||||
"傻逼"
|
||||
],
|
||||
"viewCount": 0,
|
||||
"description": "Keep 校园跑脚本",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-20T11:17:36.1915376+08:00",
|
||||
"updatedAt": "2026-03-20T11:17:36.1915376+08:00"
|
||||
},
|
||||
{
|
||||
"id": "7ab90d55-92c1-49d3-9d0a-01e5b1c08340",
|
||||
"name": "原神牛逼",
|
||||
"price": 0,
|
||||
"discountPrice": 0,
|
||||
"tags": [],
|
||||
"quantity": 1,
|
||||
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
|
||||
"screenshotUrls": [],
|
||||
"verificationUrl": "",
|
||||
"codes": [
|
||||
"原神牛逼"
|
||||
],
|
||||
"viewCount": 0,
|
||||
"description": "购买后直接发送一句原神牛逼",
|
||||
"active": true,
|
||||
"createdAt": "2026-03-20T11:36:36.6726035+08:00",
|
||||
"updatedAt": "2026-03-20T11:42:05.3303102+08:00"
|
||||
}
|
||||
]
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"totalVisits": 3
|
||||
}
|
||||
@@ -8,6 +8,9 @@ services:
|
||||
environment:
|
||||
GIN_MODE: release
|
||||
TZ: Asia/Shanghai
|
||||
# Production MySQL DSN — uses internal network address.
|
||||
# Change to TestDSN or override via .env file for local testing.
|
||||
DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./config.json:/app/config.json:ro
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module mengyastore-backend
|
||||
|
||||
go 1.21
|
||||
go 1.21.0
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/cors v1.7.2
|
||||
@@ -9,6 +9,7 @@ require (
|
||||
)
|
||||
|
||||
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
|
||||
@@ -18,7 +19,10 @@ require (
|
||||
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
|
||||
@@ -33,7 +37,9 @@ require (
|
||||
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.14.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,3 +1,5 @@
|
||||
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=
|
||||
@@ -26,6 +28,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
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=
|
||||
@@ -33,6 +37,10 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
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=
|
||||
@@ -87,6 +95,8 @@ 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=
|
||||
@@ -97,5 +107,9 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
|
||||
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=
|
||||
|
||||
@@ -26,6 +26,8 @@ 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 {
|
||||
|
||||
@@ -9,8 +9,18 @@ import (
|
||||
type Config struct {
|
||||
AdminToken string `json:"adminToken"`
|
||||
AuthAPIURL string `json:"authApiUrl"`
|
||||
|
||||
// Database DSN. If empty, falls back to the test DB DSN.
|
||||
// Format: "user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
DatabaseDSN string `json:"databaseDsn"`
|
||||
}
|
||||
|
||||
// Default DSNs for each environment.
|
||||
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) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -23,5 +33,12 @@ func Load(path string) (*Config, error) {
|
||||
if cfg.AdminToken == "" {
|
||||
cfg.AdminToken = "shumengya520"
|
||||
}
|
||||
// Default to test DB if not configured; environment variable overrides config file.
|
||||
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
|
||||
cfg.DatabaseDSN = dsn
|
||||
}
|
||||
if cfg.DatabaseDSN == "" {
|
||||
cfg.DatabaseDSN = TestDSN
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
45
mengyastore-backend/internal/database/db.go
Normal file
45
mengyastore-backend/internal/database/db.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Open initialises a GORM DB connection and runs AutoMigrate for all models.
|
||||
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{},
|
||||
)
|
||||
}
|
||||
121
mengyastore-backend/internal/database/models.go
Normal file
121
mengyastore-backend/internal/database/models.go
Normal file
@@ -0,0 +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" }
|
||||
192
mengyastore-backend/internal/email/email.go
Normal file
192
mengyastore-backend/internal/email/email.go
Normal file
@@ -0,0 +1,192 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config holds SMTP sender configuration.
|
||||
type Config struct {
|
||||
SMTPHost string // e.g. smtp.qq.com
|
||||
SMTPPort string // e.g. 465 (SSL) or 587 (STARTTLS)
|
||||
From string // sender email address
|
||||
Password string // SMTP auth password / app password
|
||||
FromName string // display name, e.g. "萌芽小店"
|
||||
}
|
||||
|
||||
// IsConfigured returns true if enough config is present to send mail.
|
||||
func (c *Config) IsConfigured() bool {
|
||||
return c.From != "" && c.Password != "" && c.SMTPHost != ""
|
||||
}
|
||||
|
||||
// OrderNotifyData contains the data for an order notification email.
|
||||
type OrderNotifyData struct {
|
||||
ToEmail string
|
||||
ToName string
|
||||
ProductName string
|
||||
OrderID string
|
||||
Quantity int
|
||||
Codes []string // empty for manual delivery
|
||||
IsManual bool
|
||||
}
|
||||
|
||||
// SendOrderNotify sends an order delivery notification email.
|
||||
// Returns nil if config is not ready or ToEmail is empty (silently skip).
|
||||
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 mail uses SSL on port 465; use TLS dial directly.
|
||||
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()
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
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 dial: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("smtp new client: %w", err)
|
||||
}
|
||||
defer client.Quit() //nolint:errcheck
|
||||
|
||||
if err = client.Auth(auth); err != nil {
|
||||
return fmt.Errorf("smtp auth: %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("smtp write body: %w", err)
|
||||
}
|
||||
return w.Close()
|
||||
}
|
||||
@@ -1,160 +1,24 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/models"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
|
||||
// AdminHandler holds dependencies for all admin-related routes.
|
||||
type AdminHandler struct {
|
||||
store *storage.JSONStore
|
||||
cfg *config.Config
|
||||
store *storage.JSONStore
|
||||
cfg *config.Config
|
||||
siteStore *storage.SiteStore
|
||||
orderStore *storage.OrderStore
|
||||
chatStore *storage.ChatStore
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type togglePayload struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
func NewAdminHandler(store *storage.JSONStore, cfg *config.Config) *AdminHandler {
|
||||
return &AdminHandler{store: store, cfg: cfg}
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"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": "invalid payload"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
|
||||
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,
|
||||
}
|
||||
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": "invalid payload"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
|
||||
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,
|
||||
}
|
||||
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": "invalid payload"})
|
||||
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{"status": "deleted"})
|
||||
func NewAdminHandler(store *storage.JSONStore, 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}
|
||||
}
|
||||
|
||||
func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
|
||||
@@ -168,43 +32,3 @@ func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
88
mengyastore-backend/internal/handlers/admin_chat.go
Normal file
88
mengyastore-backend/internal/handlers/admin_chat.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetAllConversations returns all conversations (map of accountID -> messages).
|
||||
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 returns all messages for a specific account.
|
||||
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": "missing account"})
|
||||
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 sends a reply from admin to a specific user.
|
||||
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": "missing account"})
|
||||
return
|
||||
}
|
||||
var payload adminChatPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
||||
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 deletes all messages with a specific user.
|
||||
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": "missing account"})
|
||||
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}})
|
||||
}
|
||||
35
mengyastore-backend/internal/handlers/admin_orders.go
Normal file
35
mengyastore-backend/internal/handlers/admin_orders.go
Normal file
@@ -0,0 +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": "missing order 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}})
|
||||
}
|
||||
202
mengyastore-backend/internal/handlers/admin_product.go
Normal file
202
mengyastore-backend/internal/handlers/admin_product.go
Normal file
@@ -0,0 +1,202 @@
|
||||
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"`
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"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": "invalid payload"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
|
||||
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": "invalid payload"})
|
||||
return
|
||||
}
|
||||
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
|
||||
if !valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
|
||||
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": "invalid payload"})
|
||||
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{"status": "deleted"})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
73
mengyastore-backend/internal/handlers/admin_site.go
Normal file
73
mengyastore-backend/internal/handlers/admin_site.go
Normal file
@@ -0,0 +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": "invalid payload"})
|
||||
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
|
||||
}
|
||||
// Mask password in response
|
||||
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": "invalid payload"})
|
||||
return
|
||||
}
|
||||
// If password is the masked sentinel, preserve the existing one
|
||||
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"})
|
||||
}
|
||||
82
mengyastore-backend/internal/handlers/chat.go
Normal file
82
mengyastore-backend/internal/handlers/chat.go
Normal file
@@ -0,0 +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 returns all chat messages for the currently logged-in user.
|
||||
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 sends a message from the current user to admin.
|
||||
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": "invalid payload"})
|
||||
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}})
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/email"
|
||||
"mengyastore-backend/internal/models"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
@@ -19,47 +20,70 @@ const qrSize = "320x320"
|
||||
type OrderHandler struct {
|
||||
productStore *storage.JSONStore
|
||||
orderStore *storage.OrderStore
|
||||
siteStore *storage.SiteStore
|
||||
authClient *auth.SproutGateClient
|
||||
}
|
||||
|
||||
type checkoutPayload struct {
|
||||
ProductID string `json:"productId"`
|
||||
Quantity int `json:"quantity"`
|
||||
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.JSONStore, orderStore *storage.OrderStore, authClient *auth.SproutGateClient) *OrderHandler {
|
||||
return &OrderHandler{productStore: productStore, orderStore: orderStore, authClient: authClient}
|
||||
func NewOrderHandler(productStore *storage.JSONStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
|
||||
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
|
||||
}
|
||||
|
||||
func (h *OrderHandler) tryExtractUser(c *gin.Context) (string, string) {
|
||||
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 ") {
|
||||
log.Println("[Order] 无 Authorization header,匿名下单")
|
||||
return "", ""
|
||||
return "", "", ""
|
||||
}
|
||||
userToken := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
log.Printf("[Order] 检测到用户 token,正在验证 (长度=%d)", len(userToken))
|
||||
|
||||
result, err := h.authClient.VerifyToken(userToken)
|
||||
if err != nil {
|
||||
log.Printf("[Order] 验证 token 失败: %v", err)
|
||||
return "", ""
|
||||
if err != nil || !result.Valid || result.User == nil {
|
||||
return "", "", ""
|
||||
}
|
||||
if !result.Valid {
|
||||
log.Println("[Order] token 验证返回 valid=false")
|
||||
return "", ""
|
||||
}
|
||||
if result.User == nil {
|
||||
log.Println("[Order] token 验证成功但 user 为空")
|
||||
return "", ""
|
||||
}
|
||||
|
||||
log.Printf("[Order] 用户身份验证成功: account=%s username=%s", result.User.Account, result.User.Username)
|
||||
return result.User.Account, result.User.Username
|
||||
return result.User.Account, result.User.Username, result.User.Email
|
||||
}
|
||||
|
||||
func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
userAccount, userName := h.tryExtractUser(c)
|
||||
userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
|
||||
|
||||
var payload checkoutPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
@@ -85,21 +109,72 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "product is not available"})
|
||||
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
|
||||
}
|
||||
|
||||
deliveredCodes, ok := extractCodes(&product, payload.Quantity)
|
||||
if !ok {
|
||||
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
|
||||
}
|
||||
}
|
||||
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"
|
||||
}
|
||||
|
||||
// Notification email priority:
|
||||
// 1. SproutGate account email (logged-in user, most reliable)
|
||||
// 2. notifyEmail passed by frontend (also comes from authState.email)
|
||||
// 3. contactEmail explicitly filled by user in checkout form
|
||||
// 4. empty → skip sending
|
||||
notifyEmail := strings.TrimSpace(userEmail)
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
|
||||
}
|
||||
if notifyEmail == "" {
|
||||
notifyEmail = strings.TrimSpace(payload.ContactEmail)
|
||||
}
|
||||
|
||||
order := models.Order{
|
||||
@@ -110,6 +185,11 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
Quantity: payload.Quantity,
|
||||
DeliveredCodes: deliveredCodes,
|
||||
Status: "pending",
|
||||
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 {
|
||||
@@ -117,6 +197,17 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !isManual {
|
||||
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
|
||||
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
|
||||
}
|
||||
// Send delivery notification for auto-delivery orders immediately
|
||||
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
|
||||
} else {
|
||||
// For manual delivery, notify user that order is received and pending
|
||||
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))
|
||||
|
||||
@@ -139,11 +230,25 @@ func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
isManual := order.DeliveryMode == "manual"
|
||||
|
||||
// For manual delivery, send a "delivered" notification when admin confirms
|
||||
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,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -50,3 +50,17 @@ func (h *StatsHandler) RecordVisit(c *gin.Context) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
88
mengyastore-backend/internal/handlers/wishlist.go
Normal file
88
mengyastore-backend/internal/handlers/wishlist.go
Normal file
@@ -0,0 +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": "invalid payload"})
|
||||
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": "missing product 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}})
|
||||
}
|
||||
12
mengyastore-backend/internal/models/chat.go
Normal file
12
mengyastore-backend/internal/models/chat.go
Normal file
@@ -0,0 +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"`
|
||||
}
|
||||
@@ -11,5 +11,10 @@ type Order struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ type Product struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
99
mengyastore-backend/internal/storage/chatstore.go
Normal file
99
mengyastore-backend/internal/storage/chatstore.go
Normal file
@@ -0,0 +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
|
||||
}
|
||||
@@ -2,16 +2,15 @@ package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
@@ -20,238 +19,235 @@ const viewCooldown = 6 * time.Hour
|
||||
const maxScreenshotURLs = 5
|
||||
|
||||
type JSONStore struct {
|
||||
path string
|
||||
db *gorm.DB
|
||||
mu sync.Mutex
|
||||
recentViews map[string]time.Time
|
||||
}
|
||||
|
||||
func NewJSONStore(path string) (*JSONStore, error) {
|
||||
if err := ensureProductsFile(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
func NewJSONStore(db *gorm.DB) (*JSONStore, error) {
|
||||
return &JSONStore{
|
||||
path: path,
|
||||
db: db,
|
||||
recentViews: make(map[string]time.Time),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ensureProductsFile(path string) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("mkdir data dir: %w", err)
|
||||
}
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return nil
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("stat data file: %w", err)
|
||||
// rowToModel converts a ProductRow (+ codes) to a models.Product.
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
initial := []models.Product{}
|
||||
bytes, err := json.MarshalIndent(initial, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("init json: %w", err)
|
||||
func (s *JSONStore) 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
|
||||
}
|
||||
if err := os.WriteFile(path, bytes, 0o644); err != nil {
|
||||
return fmt.Errorf("write init json: %w", err)
|
||||
codes := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
codes[i] = r.Code
|
||||
}
|
||||
return nil
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) 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 *JSONStore) ListAll() ([]models.Product, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.readAll()
|
||||
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 *JSONStore) ListActive() ([]models.Product, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
var rows []database.ProductRow
|
||||
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
active := make([]models.Product, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item.Active {
|
||||
active = append(active, item)
|
||||
}
|
||||
products := make([]models.Product, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
// For public listing we don't expose codes, but we still need Quantity
|
||||
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 active, nil
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) GetByID(id string) (models.Product, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
items, err := s.readAll()
|
||||
if 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")
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.ID == id {
|
||||
return item, nil
|
||||
}
|
||||
}
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) Create(p models.Product) (models.Product, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
p = normalizeProduct(p)
|
||||
p.ID = uuid.NewString()
|
||||
now := time.Now()
|
||||
p.CreatedAt = now
|
||||
p.UpdatedAt = now
|
||||
items = append(items, p)
|
||||
if err := s.writeAll(items); err != nil {
|
||||
|
||||
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 *JSONStore) Update(id string, patch models.Product) (models.Product, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
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
|
||||
}
|
||||
for i, item := range items {
|
||||
if item.ID == id {
|
||||
normalized := normalizeProduct(patch)
|
||||
item.Name = normalized.Name
|
||||
item.Price = normalized.Price
|
||||
item.DiscountPrice = normalized.DiscountPrice
|
||||
item.Tags = normalized.Tags
|
||||
item.CoverURL = normalized.CoverURL
|
||||
item.ScreenshotURLs = normalized.ScreenshotURLs
|
||||
item.VerificationURL = normalized.VerificationURL
|
||||
item.Codes = normalized.Codes
|
||||
item.Quantity = normalized.Quantity
|
||||
item.Description = normalized.Description
|
||||
item.Active = normalized.Active
|
||||
item.UpdatedAt = time.Now()
|
||||
items[i] = item
|
||||
if err := s.writeAll(items); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
if err := s.replaceCodes(id, normalized.Codes); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
|
||||
var updated database.ProductRow
|
||||
s.db.First(&updated, "id = ?", id)
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(updated, codes), nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) Toggle(id string, active bool) (models.Product, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
for i, item := range items {
|
||||
if item.ID == id {
|
||||
item.Active = active
|
||||
item.UpdatedAt = time.Now()
|
||||
items[i] = item
|
||||
if err := s.writeAll(items); err != nil {
|
||||
return models.Product{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
var row database.ProductRow
|
||||
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
}
|
||||
return models.Product{}, fmt.Errorf("product not found")
|
||||
codes, _ := s.loadCodes(id)
|
||||
return rowToModel(row, codes), nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) 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 *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
return models.Product{}, false, err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
s.cleanupRecentViews(now)
|
||||
key := buildViewKey(id, fingerprint)
|
||||
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
|
||||
for _, item := range items {
|
||||
if item.ID == id {
|
||||
return item, false, nil
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
for i, item := range items {
|
||||
if item.ID == id {
|
||||
item.ViewCount++
|
||||
item.UpdatedAt = now
|
||||
items[i] = item
|
||||
s.recentViews[key] = now
|
||||
if err := s.writeAll(items); err != nil {
|
||||
return models.Product{}, false, err
|
||||
}
|
||||
return item, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return models.Product{}, false, fmt.Errorf("product not found")
|
||||
return rowToModel(row, nil), true, nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) Delete(id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
filtered := make([]models.Product, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item.ID != id {
|
||||
filtered = append(filtered, item)
|
||||
}
|
||||
}
|
||||
if err := s.writeAll(filtered); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) readAll() ([]models.Product, error) {
|
||||
bytes, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read products: %w", err)
|
||||
}
|
||||
var items []models.Product
|
||||
if err := json.Unmarshal(bytes, &items); err != nil {
|
||||
return nil, fmt.Errorf("parse products: %w", err)
|
||||
}
|
||||
for i, item := range items {
|
||||
items[i] = normalizeProduct(item)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (s *JSONStore) writeAll(items []models.Product) error {
|
||||
for i, item := range items {
|
||||
items[i] = normalizeProduct(item)
|
||||
}
|
||||
bytes, err := json.MarshalIndent(items, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode products: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
|
||||
return fmt.Errorf("write products: %w", err)
|
||||
}
|
||||
return nil
|
||||
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// normalizeProduct cleans up product fields (same logic as before, no file I/O).
|
||||
func normalizeProduct(item models.Product) models.Product {
|
||||
item.CoverURL = strings.TrimSpace(item.CoverURL)
|
||||
if item.CoverURL == "" {
|
||||
@@ -276,6 +272,9 @@ func normalizeProduct(item models.Product) models.Product {
|
||||
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
|
||||
item.Codes = sanitizeCodes(item.Codes)
|
||||
item.Quantity = len(item.Codes)
|
||||
if item.DeliveryMode == "" {
|
||||
item.DeliveryMode = "auto"
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
@@ -284,10 +283,7 @@ func sanitizeCodes(codes []string) []string {
|
||||
seen := map[string]bool{}
|
||||
for _, code := range codes {
|
||||
trimmed := strings.TrimSpace(code)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
if seen[trimmed] {
|
||||
if trimmed == "" || seen[trimmed] {
|
||||
continue
|
||||
}
|
||||
seen[trimmed] = true
|
||||
|
||||
@@ -1,140 +1,139 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/models"
|
||||
)
|
||||
|
||||
type OrderStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewOrderStore(path string) (*OrderStore, error) {
|
||||
if err := ensureOrdersFile(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &OrderStore{path: path}, nil
|
||||
func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
|
||||
return &OrderStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) Count() (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
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,
|
||||
}
|
||||
return len(items), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
matched := make([]models.Order, 0)
|
||||
for i := len(items) - 1; i >= 0; i-- {
|
||||
if items[i].UserAccount == account {
|
||||
matched = append(matched, items[i])
|
||||
}
|
||||
}
|
||||
return matched, nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) Confirm(id string) (models.Order, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
for i, item := range items {
|
||||
if item.ID == id {
|
||||
if item.Status == "completed" {
|
||||
return item, nil
|
||||
}
|
||||
items[i].Status = "completed"
|
||||
if err := s.writeAll(items); err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
return items[i], nil
|
||||
}
|
||||
}
|
||||
return models.Order{}, fmt.Errorf("order not found")
|
||||
}
|
||||
|
||||
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
items, err := s.readAll()
|
||||
if err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
|
||||
order.ID = uuid.NewString()
|
||||
order.CreatedAt = time.Now()
|
||||
items = append(items, order)
|
||||
if err := s.writeAll(items); err != nil {
|
||||
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) readAll() ([]models.Order, error) {
|
||||
bytes, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read orders: %w", err)
|
||||
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")
|
||||
}
|
||||
var items []models.Order
|
||||
if err := json.Unmarshal(bytes, &items); err != nil {
|
||||
return nil, fmt.Errorf("parse orders: %w", err)
|
||||
}
|
||||
return items, nil
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func (s *OrderStore) writeAll(items []models.Order) error {
|
||||
bytes, err := json.MarshalIndent(items, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode orders: %w", err)
|
||||
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 := os.WriteFile(s.path, bytes, 0o644); err != nil {
|
||||
return fmt.Errorf("write orders: %w", err)
|
||||
if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
|
||||
return models.Order{}, err
|
||||
}
|
||||
return nil
|
||||
row.Status = "completed"
|
||||
return orderRowToModel(row), nil
|
||||
}
|
||||
|
||||
func ensureOrdersFile(path string) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("mkdir data dir: %w", err)
|
||||
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
|
||||
}
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return nil
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("stat data file: %w", err)
|
||||
orders := make([]models.Order, len(rows))
|
||||
for i, r := range rows {
|
||||
orders[i] = orderRowToModel(r)
|
||||
}
|
||||
|
||||
initial := []models.Order{}
|
||||
bytes, err := json.MarshalIndent(initial, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("init json: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(path, bytes, 0o644); err != nil {
|
||||
return fmt.Errorf("write init json: %w", err)
|
||||
}
|
||||
return nil
|
||||
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
|
||||
err := s.db.Model(&database.OrderRow{}).
|
||||
Where("user_account = ? AND product_id = ? AND status = ?", account, productID, "completed").
|
||||
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
|
||||
return int(total), err
|
||||
}
|
||||
|
||||
// Count returns the total number of orders.
|
||||
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 removes a single order by ID.
|
||||
func (s *OrderStore) Delete(id string) error {
|
||||
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// UpdateCodes replaces the delivered codes for an order (used by auto-delivery to set codes after extracting).
|
||||
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,128 +1,135 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"mengyastore-backend/internal/database"
|
||||
)
|
||||
|
||||
const visitCooldown = 6 * time.Hour
|
||||
|
||||
type siteData struct {
|
||||
TotalVisits int `json:"totalVisits"`
|
||||
}
|
||||
|
||||
type SiteStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
recentVisits map[string]time.Time
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSiteStore(path string) (*SiteStore, error) {
|
||||
if err := ensureSiteFile(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &SiteStore{
|
||||
path: path,
|
||||
recentVisits: make(map[string]time.Time),
|
||||
}, nil
|
||||
func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
|
||||
return &SiteStore{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) RecordVisit(fingerprint string) (int, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
s.cleanupRecentVisits(now)
|
||||
|
||||
key := buildSiteVisitKey(fingerprint)
|
||||
if last, ok := s.recentVisits[key]; ok && now.Sub(last) < visitCooldown {
|
||||
data, err := s.read()
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
return data.TotalVisits, false, nil
|
||||
func (s *SiteStore) get(key string) (string, error) {
|
||||
var row database.SiteSettingRow
|
||||
if err := s.db.First(&row, "key = ?", key).Error; err != nil {
|
||||
return "", nil // key not found → return zero value
|
||||
}
|
||||
return row.Value, nil
|
||||
}
|
||||
|
||||
data, err := s.read()
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
data.TotalVisits++
|
||||
s.recentVisits[key] = now
|
||||
if err := s.write(data); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
return data.TotalVisits, true, 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) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
data, err := s.read()
|
||||
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
|
||||
}
|
||||
return data.TotalVisits, nil
|
||||
current++
|
||||
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (s *SiteStore) read() (siteData, error) {
|
||||
bytes, err := os.ReadFile(s.path)
|
||||
func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
|
||||
v, err := s.get("maintenance")
|
||||
if err != nil {
|
||||
return siteData{}, fmt.Errorf("read site data: %w", err)
|
||||
return false, "", err
|
||||
}
|
||||
var data siteData
|
||||
if err := json.Unmarshal(bytes, &data); err != nil {
|
||||
return siteData{}, fmt.Errorf("parse site data: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
enabled = v == "true"
|
||||
reason, err = s.get("maintenanceReason")
|
||||
return enabled, reason, err
|
||||
}
|
||||
|
||||
func (s *SiteStore) write(data siteData) error {
|
||||
bytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode site data: %w", err)
|
||||
func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
|
||||
v := "false"
|
||||
if enabled {
|
||||
v = "true"
|
||||
}
|
||||
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
|
||||
return fmt.Errorf("write site data: %w", err)
|
||||
if err := s.set("maintenance", v); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return s.set("maintenanceReason", reason)
|
||||
}
|
||||
|
||||
func (s *SiteStore) cleanupRecentVisits(now time.Time) {
|
||||
for key, last := range s.recentVisits {
|
||||
if now.Sub(last) >= visitCooldown {
|
||||
delete(s.recentVisits, key)
|
||||
// RecordVisit increments the visit counter. Returns (totalVisits, counted, error).
|
||||
// For simplicity, every call increments (fingerprint dedup is handled in-memory by the handler layer).
|
||||
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
|
||||
total, err := s.IncrementVisits()
|
||||
return total, true, err
|
||||
}
|
||||
|
||||
// SMTPConfig holds the mail sender configuration stored in the DB.
|
||||
type SMTPConfig struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
FromName string `json:"fromName"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
}
|
||||
|
||||
// IsConfiguredEmail returns true if the SMTP config is ready to send mail.
|
||||
func (c SMTPConfig) IsConfiguredEmail() bool {
|
||||
return c.Email != "" && c.Password != "" && c.Host != ""
|
||||
}
|
||||
|
||||
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
|
||||
cfg := SMTPConfig{
|
||||
Host: "smtp.qq.com",
|
||||
Port: "465",
|
||||
}
|
||||
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 {
|
||||
pairs := [][2]string{
|
||||
{"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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func buildSiteVisitKey(fingerprint string) string {
|
||||
sum := sha256.Sum256([]byte("site|" + fingerprint))
|
||||
return fmt.Sprintf("%x", sum)
|
||||
}
|
||||
|
||||
func ensureSiteFile(path string) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("mkdir data dir: %w", err)
|
||||
}
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return nil
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("stat site file: %w", err)
|
||||
}
|
||||
initial := siteData{TotalVisits: 0}
|
||||
bytes, err := json.MarshalIndent(initial, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("init site json: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(path, bytes, 0o644); err != nil {
|
||||
return fmt.Errorf("write site json: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
38
mengyastore-backend/internal/storage/wishliststore.go
Normal file
38
mengyastore-backend/internal/storage/wishliststore.go
Normal file
@@ -0,0 +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
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"mengyastore-backend/internal/auth"
|
||||
"mengyastore-backend/internal/config"
|
||||
"mengyastore-backend/internal/database"
|
||||
"mengyastore-backend/internal/handlers"
|
||||
"mengyastore-backend/internal/storage"
|
||||
)
|
||||
@@ -20,18 +21,32 @@ func main() {
|
||||
log.Fatalf("load config failed: %v", err)
|
||||
}
|
||||
|
||||
store, err := storage.NewJSONStore("data/json/products.json")
|
||||
// Initialise database
|
||||
db, err := database.Open(cfg.DatabaseDSN)
|
||||
if err != nil {
|
||||
log.Fatalf("init database failed: %v", err)
|
||||
}
|
||||
|
||||
store, err := storage.NewJSONStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("init store failed: %v", err)
|
||||
}
|
||||
orderStore, err := storage.NewOrderStore("data/json/orders.json")
|
||||
orderStore, err := storage.NewOrderStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("init order store failed: %v", err)
|
||||
}
|
||||
siteStore, err := storage.NewSiteStore("data/json/site.json")
|
||||
siteStore, err := storage.NewSiteStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("init site store failed: %v", err)
|
||||
}
|
||||
wishlistStore, err := storage.NewWishlistStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("init wishlist store failed: %v", err)
|
||||
}
|
||||
chatStore, err := storage.NewChatStore(db)
|
||||
if err != nil {
|
||||
log.Fatalf("init chat store failed: %v", err)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
r.Use(cors.New(cors.Config{
|
||||
@@ -50,15 +65,18 @@ func main() {
|
||||
authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)
|
||||
|
||||
publicHandler := handlers.NewPublicHandler(store)
|
||||
adminHandler := handlers.NewAdminHandler(store, cfg)
|
||||
orderHandler := handlers.NewOrderHandler(store, orderStore, authClient)
|
||||
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)
|
||||
|
||||
@@ -68,6 +86,25 @@ func main() {
|
||||
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)
|
||||
|
||||
// Chat routes (user)
|
||||
r.GET("/api/chat/messages", chatHandler.GetMyMessages)
|
||||
r.POST("/api/chat/messages", chatHandler.SendMyMessage)
|
||||
|
||||
// Chat routes (admin)
|
||||
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 {
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user