refactor: 重构项目结构,迁移后端至 mengyastore-backend-go,新增 Java 后端、前端功能更新及部署文档

This commit is contained in:
2026-03-27 15:10:53 +08:00
parent 84874707f5
commit 63781358b2
71 changed files with 2123 additions and 250 deletions

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"kiroAgent.configureMCP": "Disabled"
}

399
DEPLOY.md Normal file
View File

@@ -0,0 +1,399 @@
# 萌芽小店 · 生产环境部署指南
> 本指南覆盖从零开始将萌芽小店完整部署到生产服务器的全部步骤,包括后端 Docker 部署与前端静态文件托管。
---
## 目录
1. [环境要求](#1-环境要求)
2. [准备 MySQL 数据库](#2-准备-mysql-数据库)
3. [部署后端Docker](#3-部署后端docker)
4. [构建并部署前端](#4-构建并部署前端)
5. [Nginx 反向代理配置](#5-nginx-反向代理配置)
6. [验证部署](#6-验证部署)
7. [常见问题排查](#7-常见问题排查)
8. [升级与回滚](#8-升级与回滚)
---
## 1. 环境要求
| 组件 | 最低版本 | 说明 |
|------|----------|------|
| 服务器 OS | Linux (Ubuntu 22.04 / Debian 12 推荐) | 也支持 CentOS / AlmaLinux |
| Docker | 24.x | `docker --version` 确认 |
| Docker Compose | v2.x | `docker compose version` 确认 |
| MySQL | 8.x | 可使用内网 MySQL 实例 |
| Nginx | 1.20+ | 用于前端静态托管 + API 反向代理 |
| Node.js构建时 | 18+ | 仅前端打包时需要 |
---
## 2. 准备 MySQL 数据库
> **表结构无需手动创建**,后端启动时 GORM 会自动执行 `AutoMigrate` 建表。
### 2.1 创建数据库和用户
在 MySQL 服务器上执行:
```sql
CREATE DATABASE IF NOT EXISTS `mengyastore`
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'mengyastore'@'%'
IDENTIFIED BY 'your_strong_password';
GRANT ALL PRIVILEGES ON `mengyastore`.* TO 'mengyastore'@'%';
FLUSH PRIVILEGES;
```
或者使用项目提供的初始化脚本:
```bash
mysql -u root -p < mengyastore-backend/init.sql
```
### 2.2 验证连接
```bash
mysql -h 192.168.1.100 -P 3306 -u mengyastore -p mengyastore
# 出现 mysql> 提示符即表示连接成功
```
---
## 3. 部署后端Docker
### 3.1 将代码上传到服务器
```bash
# 方式一git clone推荐
git clone https://your-repo-url/mengyastore.git
cd mengyastore/mengyastore-backend
# 方式二scp 上传
scp -r mengyastore-backend/ user@your-server:/opt/mengyastore/
```
### 3.2 创建 `config.json`
`mengyastore-backend/` 目录下创建配置文件(**此文件不会被提交到 Git需手动创建**
```bash
cat > /opt/mengyastore/mengyastore-backend/config.json << 'EOF'
{
"adminToken": "your_strong_admin_token",
"databaseDsn": "mengyastore:your_password@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
}
EOF
```
> ⚠️ `adminToken` 请设置为足够强的随机字符串(建议 16 位以上),这是进入管理后台的唯一凭证。
### 3.3 检查 `docker-compose.yml`
确认 `mengyastore-backend/docker-compose.yml` 中的 `DATABASE_DSN` 与你的生产数据库匹配:
```yaml
services:
backend:
build:
context: .
container_name: mengyastore-backend
ports:
- "28081:8080" # 宿主机端口:容器端口,可按需修改
environment:
GIN_MODE: release
TZ: Asia/Shanghai
DATABASE_DSN: "mengyastore:your_password@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
volumes:
- ./config.json:/app/config.json:ro # 挂载配置文件(只读)
restart: unless-stopped
```
> `DATABASE_DSN` 环境变量优先级高于 `config.json`,两者保持一致即可。
### 3.4 构建并启动容器
```bash
cd /opt/mengyastore/mengyastore-backend
# 首次部署
docker compose up -d --build
# 查看启动日志
docker compose logs -f
# 预期看到:
# [DB] 数据库连接成功,表结构已同步
# 萌芽小店后端启动于 http://localhost:8080
```
### 3.5 验证后端
```bash
curl http://localhost:28081/api/health
# 应返回:{"status":"ok"}
curl http://localhost:28081/api/products
# 应返回:{"data":[...]}(空数组或商品列表)
```
---
## 4. 构建并部署前端
### 4.1 本地构建(推荐在本地完成后上传 dist
```bash
cd mengyastore-frontend
# 安装依赖
npm install
# 生产构建
npm run build
# 输出目录dist/
```
### 4.2 配置 API 地址
前端通过 Vite 的 `VITE_API_BASE_URL` 环境变量指定后端地址。如果前端与后端同域(通过 Nginx 代理),也可以不配置,默认会使用当前站点域名。
如果前后端跨域,在 `mengyastore-frontend/` 目录创建 `.env.production`
```ini
VITE_API_BASE_URL=https://store.api.shumengya.top
```
然后重新 `npm run build`
### 4.3 上传 dist 到服务器
```bash
# 假设静态文件托管在 /var/www/mengyastore/
scp -r dist/* user@your-server:/var/www/mengyastore/
# 或使用 rsync增量同步更快
rsync -avz --delete dist/ user@your-server:/var/www/mengyastore/
```
---
## 5. Nginx 反向代理配置
### 5.1 安装 Nginx
```bash
# Ubuntu / Debian
sudo apt update && sudo apt install -y nginx
# CentOS / AlmaLinux
sudo yum install -y nginx
```
### 5.2 创建站点配置
```bash
sudo nano /etc/nginx/sites-available/mengyastore
```
写入以下内容(替换 `your-domain.com` 为你的实际域名):
```nginx
server {
listen 80;
server_name your-domain.com;
# 前端静态文件
root /var/www/mengyastore;
index index.html;
# Vue Router History 模式:所有路由回退到 index.html
location / {
try_files $uri $uri/ /index.html;
}
# 反向代理后端 API
location /api/ {
proxy_pass http://127.0.0.1:28081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 30s;
proxy_read_timeout 60s;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2|webmanifest)$ {
expires 7d;
add_header Cache-Control "public, immutable";
}
}
```
### 5.3 启用配置并重启
```bash
sudo ln -s /etc/nginx/sites-available/mengyastore /etc/nginx/sites-enabled/
sudo nginx -t # 测试配置语法
sudo systemctl reload nginx
```
### 5.4 (可选)配置 HTTPSLet's Encrypt
```bash
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
# 按提示操作certbot 会自动修改 Nginx 配置并续签证书
```
---
## 6. 验证部署
### 6.1 检查列表
- [ ] `https://your-domain.com` 能正常打开首页
- [ ] 商品列表加载正常(若为空请先登录后台添加商品)
- [ ] 登录 SproutGate 账号后,收藏夹/聊天等功能正常
- [ ] **Logo 点击 5 次**弹出管理员登录框,输入 `adminToken` 能进入后台
- [ ] 后台可以新建/编辑/删除商品
- [ ] 下单流程(自动发货)能正常获取卡密
- [ ] PWA在 Chrome 地址栏点击安装图标,可添加到桌面
### 6.2 后端日志查看
```bash
docker compose -f /opt/mengyastore/mengyastore-backend/docker-compose.yml logs -f
```
---
## 7. 常见问题排查
### 问题:前端白屏 / 控制台报 CORS 错误
**原因**Nginx 未正确代理 `/api/` 请求,或后端未启动。
**排查**
```bash
curl http://127.0.0.1:28081/api/health
docker compose ps # 确认容器正在运行
```
---
### 问题:管理员登录失败("验证失败,无法连接服务器"
**原因**:后端容器未运行,或 Nginx `/api/` 代理配置有误。
**排查**
```bash
docker compose ps
curl http://127.0.0.1:28081/api/health
```
---
### 问题:管理员登录失败("令牌错误,请重试"
**原因**:输入的令牌与 `config.json` 中的 `adminToken` 不一致。
**排查**:检查服务器上的 `config.json`
```bash
cat /opt/mengyastore/mengyastore-backend/config.json
```
---
### 问题:商品列表为空
**原因**:数据库为空,需要通过管理后台添加商品。
**步骤**
1. 登录管理后台
2. 点击"商品管理" → "新增商品"
3. 填写商品名称、价格、卡密(自动发货)或选择手动发货模式
---
### 问题:数据库连接失败(启动时报错)
**原因**`DATABASE_DSN` 配置错误,或 MySQL 服务不可达。
**排查**
```bash
# 在宿主机上测试数据库连接
mysql -h 192.168.1.100 -P 3306 -u mengyastore -p
# 查看后端详细日志
docker compose logs backend | head -50
```
---
### 问题:`record not found` 日志警告
**说明**:这是 GORM 的正常行为,表示某些站点设置(如维护模式)在数据库中尚未有记录。**不影响功能**,首次设置后会自动写入。
---
## 8. 升级与回滚
### 升级
```bash
cd /opt/mengyastore/mengyastore-backend
# 拉取最新代码(如果使用 git
git pull
# 重新构建并重启
docker compose up -d --build
# 查看新版本日志
docker compose logs -f
```
### 回滚
```bash
# 查看历史镜像
docker images | grep mengyastore
# 停止当前容器,启动旧版本
docker compose down
docker tag mengyastore-backend-backend:previous mengyastore-backend-backend:latest
docker compose up -d
```
---
## 附:目录结构参考
```
/opt/mengyastore/
mengyastore-backend/
config.json ← 生产配置(不要提交到 Git
docker-compose.yml
Dockerfile
...Go 源码)
/var/www/mengyastore/ ← 前端 dist 文件
index.html
assets/
...
```
---
> 如遇到本指南未覆盖的问题,请查看后端实时日志:
> `docker compose -f /opt/mengyastore/mengyastore-backend/docker-compose.yml logs -f`
**部署完成 🎉** 访问 `https://your-domain.com` 即可看到萌芽小店正式上线。

262
README.md
View File

@@ -1,61 +1,263 @@
# mengyastore # 萌芽小店 · Mengyastore
萌芽小店,一个前后端分离的商城项目 一个前后端分离的轻量级商城,支持自动/手动发货、邮件通知、聊天客服、收藏夹与 PWA 安装
## 项目结构 ---
- `mengyastore-frontend/`Vue 3 + Vite 前端 ## 技术栈
- `mengyastore-backend/`Go + Gin 后端
- `mengyastore-backend/data/json/`:商品、订单、站点配置等本地数据
## 功能 ### 前端 `mengyastore-frontend/`
- 商品浏览、详情查看、下单 | 分类 | 技术 | 版本 | 说明 |
- 登录回调与用户订单页 |------|------|------|------|
- 后台商品管理 | 框架 | Vue 3 | ^3.4 | Composition API + `<script setup>` |
- 访问统计、商品浏览统计 | 构建工具 | Vite 5 | ^5.2 | 开发服务器 / 生产打包 |
| 路由 | Vue Router 4 | ^4.3 | Hash / History 模式 |
| 状态管理 | Pinia 2 | ^2.1 | 全局 auth 状态 |
| HTTP 客户端 | Axios | ^1.6 | API 请求封装 |
| Markdown 渲染 | markdown-it | ^14.1 | 商品描述富文本 |
| PWA | vite-plugin-pwa | ^1.2 | Service Worker + Web Manifest |
| PWA 图标生成 | @vite-pwa/assets-generator | ^1.0 | 从 logo 自动生成各尺寸 PNG |
| 认证 | SproutGate OAuth | — | 第三方账号系统redirect 回调 |
| 样式 | 原生 CSS + Scoped | — | CSS 变量、Flexbox、Grid、媒体查询 |
## 本地运行 **主要模块**
### 前端 ```
src/
modules/
admin/ # 管理员后台(商品/订单/聊天/站点设置)
auth/ # OAuth 回调处理
chat/ # 用户端悬浮聊天窗口
maintenance/ # 维护模式页面
shared/ # api.js / auth.js / SplashScreen.vue / useWishlist.js
store/ # 商品列表、详情、结账
user/ # 我的订单
wishlist/ # 收藏夹
assets/styles.css # 全局样式变量
router/index.js # 路由定义 + 全局导航守卫
main.js # 应用入口
```
**PWA 特性**
- `display: standalone` 独立窗口模式,可添加到主屏
- Service Worker静态资源 `CacheFirst`API 请求 `NetworkFirst`5 分钟缓存)
- 自动检测新版本,底部 toast 提示更新
- 启动画面SplashScreen.vue渐变背景 + Logo 浮动 + 扩散环 + 绿色圆点加载动画
---
### 后端 `mengyastore-backend/`
| 分类 | 技术 | 版本 | 说明 |
|------|------|------|------|
| 语言 | Go | 1.21+ | 静态编译,单二进制部署 |
| Web 框架 | Gin | ^1.9 | HTTP 路由、中间件、JSON 绑定 |
| ORM | GORM | ^1.25 | MySQL 数据库操作 |
| MySQL 驱动 | go-sql-driver/mysql | ^1.9 | GORM MySQL 方言 |
| CORS | gin-contrib/cors | — | 跨域请求支持 |
| UUID | google/uuid | — | 订单 ID 生成 |
| 邮件 | net/smtp + crypto/tls | 标准库 | SMTP 邮件通知,支持 SSL/TLS端口 465 |
| 认证 | SproutGate OAuth | — | `/api/auth/verify` Token 验证 |
| 数据库 | MySQL 8.x | — | 生产192.168.1.100:3306测试10.1.1.100:3306 |
| 容器化 | Docker + docker-compose | — | 镜像构建与部署 |
**主要模块**
```
internal/
auth/ # SproutGate OAuth 客户端
config/ # config.json 读写adminToken、DSN 等)
database/ # GORM 初始化 (db.go) + 表结构定义 (models.go)
email/ # SMTP 邮件发送服务
handlers/ # HTTP 处理器(按功能拆分文件)
admin.go # 通用管理员接口
admin_chat.go # 聊天管理
admin_orders.go # 订单管理(查看/确认/删除/分页)
admin_product.go # 商品 CRUD
admin_site.go # 站点设置维护模式、SMTP 配置)
chat.go # 用户聊天消息读写
order.go # 下单 / 自动发货 / 邮件通知
stats.go # 访问统计
wishlist.go # 收藏夹
models/ # 业务模型Product、Order、Chat 等)
storage/ # 数据库 CRUD 封装(每类资源一个文件)
cmd/
migrate/main.go # 数据库 Schema 初始化 / 迁移脚本
main.go # 路由注册 + 依赖注入入口
```
**数据库表**
| 表名 | 主要字段 |
|------|---------|
| `products` | id, name, description, price, discount_price, cover_url, screenshot_urls, tags, codes卡密, delivery_mode, require_login, max_per_account, total_sold, view_count, active, created_at |
| `product_codes` | id, product_id, code卡密条目 |
| `orders` | id, product_id, product_name, user_account, user_name, quantity, status, delivery_mode, delivered_codes, note, contact_phone, contact_email, notify_email, created_at |
| `chat_messages` | id, account_id, account_name, content, sent_at, from_admin |
| `wishlists` | id, account, product_id |
| `site_settings` | key, valueKV 存储maintenance、SMTP 配置等) |
---
## 功能列表
| 功能 | 前端 | 后端 |
|------|------|------|
| 商品浏览(分页:桌面 4×5 / 手机 5×2 | ✅ | ✅ |
| 商品详情 + Markdown 描述 | ✅ | ✅ |
| 下单(自动/手动发货) | ✅ | ✅ |
| 订单邮件通知SMTP 可配置) | ✅ | ✅ |
| 用户收藏夹 | ✅ | ✅ |
| 我的订单 | ✅ | ✅ |
| SproutGate 账号登录 | ✅ | ✅ |
| 用户聊天客服HTTP 轮询) | ✅ | ✅ |
| 维护模式 | ✅ | ✅ |
| 管理后台 - 商品 CRUD | ✅ | ✅ |
| 管理后台 - 订单查看/确认/删除/分页 | ✅ | ✅ |
| 管理后台 - 聊天消息管理 | ✅ | ✅ |
| 管理后台 - SMTP 邮件配置(含启用/关闭开关) | ✅ | ✅ |
| 管理后台 - 站点设置(维护模式) | ✅ | ✅ |
| 访问统计 & 订单统计 | ✅ | ✅ |
| PWA 安装 + 离线缓存 | ✅ | — |
| 移动端响应式 | ✅ | — |
---
## 快速开始(从零部署)
### 1. 准备 MySQL 数据库
> **表结构无需手动创建**,后端启动时 GORM 会自动 `AutoMigrate`。
> 只需创建数据库和用户:
```bash
mysql -u root -p < mengyastore-backend/init.sql
```
或手动执行:
```sql
CREATE DATABASE IF NOT EXISTS `mengyastore` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'mengyastore'@'%' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON `mengyastore`.* TO 'mengyastore'@'%';
FLUSH PRIVILEGES;
```
### 2. 配置后端
`mengyastore-backend/` 目录创建 `config.json`
```json
{
"adminToken": "your_admin_token_here",
"databaseDsn": "mengyastore:your_password@tcp(127.0.0.1:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
}
```
也可以用环境变量覆盖(优先级更高):
```bash
export DATABASE_DSN="mengyastore:your_password@tcp(127.0.0.1:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
```
### 3. 启动后端
```bash
cd mengyastore-backend
go run . # http://localhost:8080
# 首次启动会自动创建全部表结构
```
### 4. 启动前端
```bash ```bash
cd mengyastore-frontend cd mengyastore-frontend
npm install npm install
npm run dev npm run dev # http://localhost:5173
``` ```
默认会连接 `http://localhost:8080`,如需修改后端地址可设置: ### 5. 访问管理后台
在网站 Logo 上快速点击 **5 次**,输入 `config.json` 中的 `adminToken` 进入管理后台。
> **安全说明**:后端采用 `POST /api/admin/verify` 接口验证令牌,只返回 `{"valid": true/false}`,不会将令牌明文传输到前端。
---
## 生产部署Docker
```bash ```bash
VITE_API_BASE_URL=http://localhost:8080 cd mengyastore-backend
# 1. 创建 config.json同上
# 2. 修改 docker-compose.yml 中的 DATABASE_DSN 指向生产数据库
# 3. 启动
docker-compose up -d
``` ```
### 后端 `docker-compose.yml` 配置说明:
| 配置项 | 说明 |
|--------|------|
| `DATABASE_DSN` | 生产 MySQL 连接串(覆盖 config.json |
| `./config.json:/app/config.json:ro` | 只读挂载配置文件 |
---
## 本地开发
```bash ```bash
# 前端热重载
cd mengyastore-frontend
npm install
npm run dev # http://localhost:5173
# 后端热重载(需安装 air
cd mengyastore-backend cd mengyastore-backend
go run . go run .
``` ```
后端默认监听 `http://localhost:8080` **构建前端**
### 后端配置 ```bash
cd mengyastore-frontend
npm run build # 输出到 dist/
```
后端配置文件在 `mengyastore-backend/data/json/settings.json`,当前主要是: **构建后端二进制**
- `adminToken`:后台管理口令
## Docker
后端目录下已提供 `Dockerfile``docker-compose.yml`
```bash ```bash
cd mengyastore-backend cd mengyastore-backend
docker compose up -d --build go build -o mengyastore-backend .
./mengyastore-backend
``` ```
## 说明 ---
- 仓库不提交依赖目录和构建产物 ## 项目结构
- 本地数据文件都保存在 `mengyastore-backend/data/json/`
```
mengyastore/
mengyastore-frontend/ # Vue 3 + Vite 前端
mengyastore-backend/ # Go + Gin 后端
API_DOCS.md # API 接口文档
README.md # 本文件
```
---
---
## 工程亮点
- **安全**:管理员令牌通过 `POST /api/admin/verify` 服务端验证,令牌不在网络中明文传输
- **防刷**:购买数量限制同时统计 `pending``completed` 状态,防止并发绕过
- **兼容**:管理员鉴权支持 `X-Admin-Token` 请求头Spring Security 标准)/ `Authorization` / `?token` 三种方式
- **PWA**Service Worker 离线缓存 + 启动动画 + 自动更新提示
- **可移植**API 设计对齐 Spring Boot 风格,便于后端语言迁移
---
© 2025 2026 萌芽小店 · Powered by Vue 3 + Go + MySQL

View File

@@ -21,7 +21,7 @@ import (
) )
func main() { func main() {
cfg, err := config.Load("data/json/settings.json") cfg, err := config.Load("../../config.json")
if err != nil { if err != nil {
log.Fatalf("load config: %v", err) log.Fatalf("load config: %v", err)
} }

View File

@@ -8,8 +8,9 @@ services:
environment: environment:
GIN_MODE: release GIN_MODE: release
TZ: Asia/Shanghai TZ: Asia/Shanghai
# Production MySQL DSN — uses internal network address. # 生产环境 MySQL DSN使用内网地址。
# Change to TestDSN or override via .env file for local testing. # 本地开发请修改为测试库地址,或通过 .env 文件覆盖。
#mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local
DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local" DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
volumes: volumes:
- ./config.json:/app/config.json:ro - ./config.json:/app/config.json:ro

View File

@@ -0,0 +1,28 @@
-- ============================================================
-- 萌芽小店 · 数据库初始化脚本
--
-- 用途:创建数据库与用户,表结构由后端 GORM AutoMigrate 自动创建。
-- 使用 root 或有 GRANT 权限的账号执行本脚本:
-- mysql -u root -p < init.sql
-- ============================================================
-- 创建数据库utf8mb4 支持 emoji
CREATE DATABASE IF NOT EXISTS `mengyastore`
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
-- 创建专用用户并授权(按需修改密码)
CREATE USER IF NOT EXISTS 'mengyastore'@'%' IDENTIFIED BY 'mengyastore';
GRANT ALL PRIVILEGES ON `mengyastore`.* TO 'mengyastore'@'%';
FLUSH PRIVILEGES;
-- ============================================================
-- 说明:
-- 后端首次启动时会自动通过 GORM AutoMigrate 创建以下表:
-- products - 商品信息
-- product_codes - 商品发货码
-- orders - 订单记录
-- site_settings - 站点 KV 配置adminToken、SMTP 等)
-- wishlists - 用户收藏夹
-- chat_messages - 聊天消息
-- ============================================================

View File

@@ -44,23 +44,23 @@ func (c *SproutGateClient) VerifyToken(token string) (*VerifyResult, error) {
body, _ := json.Marshal(map[string]string{"token": token}) body, _ := json.Marshal(map[string]string{"token": token})
resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body)) resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body))
if err != nil { if err != nil {
log.Printf("[SproutGate] verify request failed: %v", err) log.Printf("[SproutGate] 验证请求失败: %v", err)
return nil, fmt.Errorf("verify request failed: %w", err) return nil, fmt.Errorf("验证请求失败: %w", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
rawBody, err := io.ReadAll(resp.Body) rawBody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
log.Printf("[SproutGate] read response body failed: %v", err) log.Printf("[SproutGate] 读取响应体失败: %v", err)
return nil, fmt.Errorf("read verify response: %w", err) return nil, fmt.Errorf("读取验证响应失败: %w", err)
} }
log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody)) log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody))
var result VerifyResult var result VerifyResult
if err := json.Unmarshal(rawBody, &result); err != nil { if err := json.Unmarshal(rawBody, &result); err != nil {
log.Printf("[SproutGate] decode response failed: %v", err) log.Printf("[SproutGate] 解析响应失败: %v", err)
return nil, fmt.Errorf("decode verify response: %w", err) return nil, fmt.Errorf("解析验证响应失败: %w", err)
} }
return &result, nil return &result, nil
} }

View File

@@ -10,30 +10,31 @@ type Config struct {
AdminToken string `json:"adminToken"` AdminToken string `json:"adminToken"`
AuthAPIURL string `json:"authApiUrl"` AuthAPIURL string `json:"authApiUrl"`
// Database DSN. If empty, falls back to the test DB DSN. // 数据库 DSN为空时回退到测试数据库。
// Format: "user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local" // 格式:user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local
DatabaseDSN string `json:"databaseDsn"` DatabaseDSN string `json:"databaseDsn"`
} }
// Default DSNs for each environment. // 各环境默认 DSN。
const ( const (
TestDSN = "mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local" 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" ProdDSN = "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
) )
func Load(path string) (*Config, error) { func Load(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
var cfg Config var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil { data, err := os.ReadFile(path)
return nil, fmt.Errorf("parse config: %w", err) if err == nil {
if jsonErr := json.Unmarshal(data, &cfg); jsonErr != nil {
return nil, fmt.Errorf("解析配置文件 %s 失败: %w", path, jsonErr)
}
} }
// 文件不存在时使用默认值,环境变量在下方仍优先生效。
if cfg.AdminToken == "" { if cfg.AdminToken == "" {
cfg.AdminToken = "shumengya520" cfg.AdminToken = "changeme"
} }
// Default to test DB if not configured; environment variable overrides config file. // DATABASE_DSN 环境变量优先于配置文件。
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" { if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
cfg.DatabaseDSN = dsn cfg.DatabaseDSN = dsn
} }

View File

@@ -9,7 +9,7 @@ import (
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
) )
// Open initialises a GORM DB connection and runs AutoMigrate for all models. // Open 初始化 GORM 数据库连接并自动同步所有表结构。
func Open(dsn string) (*gorm.DB, error) { func Open(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Warn), Logger: logger.Default.LogMode(logger.Warn),

View File

@@ -8,33 +8,33 @@ import (
"time" "time"
) )
// Config holds SMTP sender configuration. // Config 存储 SMTP 发件配置。
type Config struct { type Config struct {
SMTPHost string // e.g. smtp.qq.com SMTPHost string // 例:smtp.qq.com
SMTPPort string // e.g. 465 (SSL) or 587 (STARTTLS) SMTPPort string // 例:465SSL)或 587STARTTLS
From string // sender email address From string // 发件人邮箱地址
Password string // SMTP auth password / app password Password string // SMTP 密码或授权码
FromName string // display name, e.g. "萌芽小店" FromName string // 显示名称,例:"萌芽小店"
} }
// IsConfigured returns true if enough config is present to send mail. // IsConfigured 判断配置是否充足,可以尝试发送邮件。
func (c *Config) IsConfigured() bool { func (c *Config) IsConfigured() bool {
return c.From != "" && c.Password != "" && c.SMTPHost != "" return c.From != "" && c.Password != "" && c.SMTPHost != ""
} }
// OrderNotifyData contains the data for an order notification email. // OrderNotifyData 包含发送订单通知邮件所需的数据。
type OrderNotifyData struct { type OrderNotifyData struct {
ToEmail string ToEmail string
ToName string ToName string
ProductName string ProductName string
OrderID string OrderID string
Quantity int Quantity int
Codes []string // empty for manual delivery Codes []string // 手动发货时为空
IsManual bool IsManual bool
} }
// SendOrderNotify sends an order delivery notification email. // SendOrderNotify 发送订单发货通知邮件。
// Returns nil if config is not ready or ToEmail is empty (silently skip). // 若配置不完整或收件人为空,则静默跳过,返回 nil。
func SendOrderNotify(cfg Config, data OrderNotifyData) error { func SendOrderNotify(cfg Config, data OrderNotifyData) error {
if !cfg.IsConfigured() || data.ToEmail == "" { if !cfg.IsConfigured() || data.ToEmail == "" {
return nil return nil
@@ -57,13 +57,12 @@ func SendOrderNotify(cfg Config, data OrderNotifyData) error {
} }
body := buildBody(data) body := buildBody(data)
msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body) msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body)
addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort) addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)
auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost) auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost)
// QQ mail uses SSL on port 465; use TLS dial directly. // QQ 邮箱使用 SSL端口 465需直接 TLS 拨号。
if cfg.SMTPPort == "465" { if cfg.SMTPPort == "465" {
return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg) return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg)
} }
@@ -115,6 +114,7 @@ func buildBody(data OrderNotifyData) string {
return sb.String() return sb.String()
} }
// buildMIMEMessage 构建符合 MIME 规范的邮件报文,支持 UTF-8 中文。
func buildMIMEMessage(from, fromName, to, subject, body string) string { func buildMIMEMessage(from, fromName, to, subject, body string) string {
encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName)) encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName))
encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject)) encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject))
@@ -155,6 +155,7 @@ func encodeBase64(s string) string {
return buf.String() return buf.String()
} }
// sendSSL 通过 TLS 直接拨号发送邮件(适用于 465 端口 SSL 连接,如 QQ 邮箱)。
func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error { func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error {
tlsConfig := &tls.Config{ tlsConfig := &tls.Config{
ServerName: host, ServerName: host,
@@ -162,31 +163,31 @@ func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) err
} }
conn, err := tls.Dial("tcp", addr, tlsConfig) conn, err := tls.Dial("tcp", addr, tlsConfig)
if err != nil { if err != nil {
return fmt.Errorf("tls dial: %w", err) return fmt.Errorf("tls 拨号失败: %w", err)
} }
defer conn.Close() defer conn.Close()
client, err := smtp.NewClient(conn, host) client, err := smtp.NewClient(conn, host)
if err != nil { if err != nil {
return fmt.Errorf("smtp new client: %w", err) return fmt.Errorf("创建 SMTP 客户端失败: %w", err)
} }
defer client.Quit() //nolint:errcheck defer client.Quit() //nolint:errcheck
if err = client.Auth(auth); err != nil { if err = client.Auth(auth); err != nil {
return fmt.Errorf("smtp auth: %w", err) return fmt.Errorf("SMTP 认证失败: %w", err)
} }
if err = client.Mail(from); err != nil { if err = client.Mail(from); err != nil {
return fmt.Errorf("smtp MAIL FROM: %w", err) return fmt.Errorf("SMTP MAIL FROM 失败: %w", err)
} }
if err = client.Rcpt(to); err != nil { if err = client.Rcpt(to); err != nil {
return fmt.Errorf("smtp RCPT TO: %w", err) return fmt.Errorf("SMTP RCPT TO 失败: %w", err)
} }
w, err := client.Data() w, err := client.Data()
if err != nil { if err != nil {
return fmt.Errorf("smtp DATA: %w", err) return fmt.Errorf("SMTP DATA 失败: %w", err)
} }
if _, err = fmt.Fprint(w, msg); err != nil { if _, err = fmt.Fprint(w, msg); err != nil {
return fmt.Errorf("smtp write body: %w", err) return fmt.Errorf("写入邮件内容失败: %w", err)
} }
return w.Close() return w.Close()
} }

View File

@@ -1,32 +1,39 @@
package handlers package handlers
import ( import (
"github.com/gin-gonic/gin"
"net/http" "net/http"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/config" "mengyastore-backend/internal/config"
"mengyastore-backend/internal/storage" "mengyastore-backend/internal/storage"
) )
// AdminHandler holds dependencies for all admin-related routes. // AdminHandler 持有所有管理员路由所需的依赖。
type AdminHandler struct { type AdminHandler struct {
store *storage.JSONStore store *storage.ProductStore
cfg *config.Config cfg *config.Config
siteStore *storage.SiteStore siteStore *storage.SiteStore
orderStore *storage.OrderStore orderStore *storage.OrderStore
chatStore *storage.ChatStore chatStore *storage.ChatStore
} }
func NewAdminHandler(store *storage.JSONStore, cfg *config.Config, siteStore *storage.SiteStore, orderStore *storage.OrderStore, chatStore *storage.ChatStore) *AdminHandler { func NewAdminHandler(store *storage.ProductStore, cfg *config.Config, siteStore *storage.SiteStore, orderStore *storage.OrderStore, chatStore *storage.ChatStore) *AdminHandler {
return &AdminHandler{store: store, cfg: cfg, siteStore: siteStore, orderStore: orderStore, chatStore: chatStore} return &AdminHandler{store: store, cfg: cfg, siteStore: siteStore, orderStore: orderStore, chatStore: chatStore}
} }
// requireAdmin 校验管理员令牌。
// 优先级X-Admin-Token 请求头 > Authorization 请求头 > ?token 查询参数(旧版兼容)。
func (h *AdminHandler) requireAdmin(c *gin.Context) bool { func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
token := c.Query("token") token := c.GetHeader("X-Admin-Token")
if token == "" { if token == "" {
token = c.GetHeader("Authorization") token = c.GetHeader("Authorization")
} }
if token == h.cfg.AdminToken { if token == "" {
// 兼容旧版客户端的 URL 查询参数回退
token = c.Query("token")
}
if token != "" && token == h.cfg.AdminToken {
return true return true
} }
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})

View File

@@ -7,7 +7,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// GetAllConversations returns all conversations (map of accountID -> messages). // GetAllConversations 返回所有用户会话列表。
func (h *AdminHandler) GetAllConversations(c *gin.Context) { func (h *AdminHandler) GetAllConversations(c *gin.Context) {
if !h.requireAdmin(c) { if !h.requireAdmin(c) {
return return
@@ -20,14 +20,14 @@ func (h *AdminHandler) GetAllConversations(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}}) c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
} }
// GetConversation returns all messages for a specific account. // GetConversation 返回指定账号的全部消息记录。
func (h *AdminHandler) GetConversation(c *gin.Context) { func (h *AdminHandler) GetConversation(c *gin.Context) {
if !h.requireAdmin(c) { if !h.requireAdmin(c) {
return return
} }
accountID := c.Param("account") accountID := c.Param("account")
if accountID == "" { if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing account"}) c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
return return
} }
msgs, err := h.chatStore.GetMessages(accountID) msgs, err := h.chatStore.GetMessages(accountID)
@@ -42,19 +42,19 @@ type adminChatPayload struct {
Content string `json:"content"` Content string `json:"content"`
} }
// AdminReply sends a reply from admin to a specific user. // AdminReply 向指定用户发送管理员回复。
func (h *AdminHandler) AdminReply(c *gin.Context) { func (h *AdminHandler) AdminReply(c *gin.Context) {
if !h.requireAdmin(c) { if !h.requireAdmin(c) {
return return
} }
accountID := c.Param("account") accountID := c.Param("account")
if accountID == "" { if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing account"}) c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
return return
} }
var payload adminChatPayload var payload adminChatPayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
content := strings.TrimSpace(payload.Content) content := strings.TrimSpace(payload.Content)
@@ -70,14 +70,14 @@ func (h *AdminHandler) AdminReply(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}}) c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
} }
// ClearConversation deletes all messages with a specific user. // ClearConversation 清除与指定用户的全部消息记录。
func (h *AdminHandler) ClearConversation(c *gin.Context) { func (h *AdminHandler) ClearConversation(c *gin.Context) {
if !h.requireAdmin(c) { if !h.requireAdmin(c) {
return return
} }
accountID := c.Param("account") accountID := c.Param("account")
if accountID == "" { if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing account"}) c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
return return
} }
if err := h.chatStore.ClearConversation(accountID); err != nil { if err := h.chatStore.ClearConversation(accountID); err != nil {

View File

@@ -24,7 +24,7 @@ func (h *AdminHandler) DeleteOrder(c *gin.Context) {
} }
orderID := c.Param("id") orderID := c.Param("id")
if orderID == "" { if orderID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing order id"}) c.JSON(http.StatusBadRequest, gin.H{"error": "缺少订单 ID"})
return return
} }
if err := h.orderStore.Delete(orderID); err != nil { if err := h.orderStore.Delete(orderID); err != nil {

View File

@@ -30,8 +30,16 @@ type togglePayload struct {
Active bool `json:"active"` Active bool `json:"active"`
} }
func (h *AdminHandler) GetAdminToken(c *gin.Context) { // VerifyAdminToken 验证管理员令牌是否正确,返回 {"valid": true/false},不暴露实际令牌值。
c.JSON(http.StatusOK, gin.H{"token": h.cfg.AdminToken}) func (h *AdminHandler) VerifyAdminToken(c *gin.Context) {
var payload struct {
Token string `json:"token"`
}
if err := c.ShouldBindJSON(&payload); err != nil || payload.Token == "" {
c.JSON(http.StatusOK, gin.H{"valid": false})
return
}
c.JSON(http.StatusOK, gin.H{"valid": payload.Token == h.cfg.AdminToken})
} }
func (h *AdminHandler) ListAllProducts(c *gin.Context) { func (h *AdminHandler) ListAllProducts(c *gin.Context) {
@@ -52,12 +60,12 @@ func (h *AdminHandler) CreateProduct(c *gin.Context) {
} }
var payload productPayload var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs) screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid { if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"}) c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
return return
} }
active := true active := true
@@ -95,12 +103,12 @@ func (h *AdminHandler) UpdateProduct(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
var payload productPayload var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs) screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid { if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"}) c.JSON(http.StatusBadRequest, gin.H{"error": "截图链接最多 5 条"})
return return
} }
active := false active := false
@@ -138,7 +146,7 @@ func (h *AdminHandler) ToggleProduct(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
var payload togglePayload var payload togglePayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
updated, err := h.store.Toggle(id, payload.Active) updated, err := h.store.Toggle(id, payload.Active)
@@ -158,7 +166,7 @@ func (h *AdminHandler) DeleteProduct(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
c.JSON(http.StatusOK, gin.H{"status": "deleted"}) c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
} }
func normalizeScreenshotURLs(urls []string) ([]string, bool) { func normalizeScreenshotURLs(urls []string) ([]string, bool) {

View File

@@ -19,7 +19,7 @@ func (h *AdminHandler) SetMaintenance(c *gin.Context) {
} }
var payload maintenancePayload var payload maintenancePayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil { if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
@@ -43,7 +43,7 @@ func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
// Mask password in response // 响应中对密码脱敏处理
masked := cfg masked := cfg
if masked.Password != "" { if masked.Password != "" {
masked.Password = "••••••••" masked.Password = "••••••••"
@@ -57,10 +57,10 @@ func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
} }
var payload storage.SMTPConfig var payload storage.SMTPConfig
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
// If password is the masked sentinel, preserve the existing one // 若密码为脱敏占位符,则保留数据库中原有的密码
if payload.Password == "••••••••" { if payload.Password == "••••••••" {
existing, _ := h.siteStore.GetSMTPConfig() existing, _ := h.siteStore.GetSMTPConfig()
payload.Password = existing.Password payload.Password = existing.Password

View File

@@ -34,7 +34,7 @@ func (h *ChatHandler) requireChatUser(c *gin.Context) (account, name string, ok
return result.User.Account, result.User.Username, true return result.User.Account, result.User.Username, true
} }
// GetMyMessages returns all chat messages for the currently logged-in user. // GetMyMessages 返回当前登录用户的全部聊天消息。
func (h *ChatHandler) GetMyMessages(c *gin.Context) { func (h *ChatHandler) GetMyMessages(c *gin.Context) {
account, _, ok := h.requireChatUser(c) account, _, ok := h.requireChatUser(c)
if !ok { if !ok {
@@ -52,7 +52,7 @@ type chatMessagePayload struct {
Content string `json:"content"` Content string `json:"content"`
} }
// SendMyMessage sends a message from the current user to admin. // SendMyMessage 向管理员发送一条用户消息。
func (h *ChatHandler) SendMyMessage(c *gin.Context) { func (h *ChatHandler) SendMyMessage(c *gin.Context) {
account, name, ok := h.requireChatUser(c) account, name, ok := h.requireChatUser(c)
if !ok { if !ok {
@@ -60,7 +60,7 @@ func (h *ChatHandler) SendMyMessage(c *gin.Context) {
} }
var payload chatMessagePayload var payload chatMessagePayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
content := strings.TrimSpace(payload.Content) content := strings.TrimSpace(payload.Content)

View File

@@ -18,7 +18,7 @@ import (
const qrSize = "320x320" const qrSize = "320x320"
type OrderHandler struct { type OrderHandler struct {
productStore *storage.JSONStore productStore *storage.ProductStore
orderStore *storage.OrderStore orderStore *storage.OrderStore
siteStore *storage.SiteStore siteStore *storage.SiteStore
authClient *auth.SproutGateClient authClient *auth.SproutGateClient
@@ -33,7 +33,7 @@ type checkoutPayload struct {
NotifyEmail string `json:"notifyEmail"` NotifyEmail string `json:"notifyEmail"`
} }
func NewOrderHandler(productStore *storage.JSONStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler { func NewOrderHandler(productStore *storage.ProductStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient} return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
} }
@@ -87,13 +87,13 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
var payload checkoutPayload var payload checkoutPayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
payload.ProductID = strings.TrimSpace(payload.ProductID) payload.ProductID = strings.TrimSpace(payload.ProductID)
if payload.ProductID == "" { if payload.ProductID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing required fields"}) c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必填字段"})
return return
} }
if payload.Quantity <= 0 { if payload.Quantity <= 0 {
@@ -106,7 +106,7 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
return return
} }
if !product.Active { if !product.Active {
c.JSON(http.StatusBadRequest, gin.H{"error": "product is not available"}) c.JSON(http.StatusBadRequest, gin.H{"error": "商品暂时无法购买"})
return return
} }
@@ -164,11 +164,11 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
deliveryMode = "auto" deliveryMode = "auto"
} }
// Notification email priority: // 通知邮箱优先级:
// 1. SproutGate account email (logged-in user, most reliable) // 1. SproutGate 账号邮箱(已登录用户,最可靠)
// 2. notifyEmail passed by frontend (also comes from authState.email) // 2. 前端传入的 notifyEmail(来自 authState.email
// 3. contactEmail explicitly filled by user in checkout form // 3. 用户在结账表单填写的联系邮箱
// 4. empty → skip sending // 4. 均为空则不发送
notifyEmail := strings.TrimSpace(userEmail) notifyEmail := strings.TrimSpace(userEmail)
if notifyEmail == "" { if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.NotifyEmail) notifyEmail = strings.TrimSpace(payload.NotifyEmail)
@@ -177,6 +177,12 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
notifyEmail = strings.TrimSpace(payload.ContactEmail) notifyEmail = strings.TrimSpace(payload.ContactEmail)
} }
// 自动发货订单立即设为已完成(卡密已提取);手动发货订单初始状态为待处理,由管理员确认。
orderStatus := "pending"
if !isManual {
orderStatus = "completed"
}
order := models.Order{ order := models.Order{
ProductID: updatedProduct.ID, ProductID: updatedProduct.ID,
ProductName: updatedProduct.Name, ProductName: updatedProduct.Name,
@@ -184,7 +190,7 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
UserName: userName, UserName: userName,
Quantity: payload.Quantity, Quantity: payload.Quantity,
DeliveredCodes: deliveredCodes, DeliveredCodes: deliveredCodes,
Status: "pending", Status: orderStatus,
DeliveryMode: deliveryMode, DeliveryMode: deliveryMode,
Note: strings.TrimSpace(payload.Note), Note: strings.TrimSpace(payload.Note),
ContactPhone: strings.TrimSpace(payload.ContactPhone), ContactPhone: strings.TrimSpace(payload.ContactPhone),
@@ -201,10 +207,10 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil { if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
log.Printf("[Order] 更新销量失败 (非致命): %v", err) 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) h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
} else { } else {
// For manual delivery, notify user that order is received and pending // 手动发货:告知用户订单已收到,等待发货
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true) h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true)
} }
@@ -233,7 +239,7 @@ func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
isManual := order.DeliveryMode == "manual" isManual := order.DeliveryMode == "manual"
// For manual delivery, send a "delivered" notification when admin confirms // 手动发货确认后,发送"已发货"通知邮件
if isManual { if isManual {
confirmNotifyEmail := order.NotifyEmail confirmNotifyEmail := order.NotifyEmail
if confirmNotifyEmail == "" { if confirmNotifyEmail == "" {
@@ -286,3 +292,4 @@ func extractCodes(product *models.Product, count int) ([]string, bool) {
product.Codes = product.Codes[count:] product.Codes = product.Codes[count:]
return delivered, true return delivered, true
} }

View File

@@ -11,10 +11,10 @@ import (
) )
type PublicHandler struct { type PublicHandler struct {
store *storage.JSONStore store *storage.ProductStore
} }
func NewPublicHandler(store *storage.JSONStore) *PublicHandler { func NewPublicHandler(store *storage.ProductStore) *PublicHandler {
return &PublicHandler{store: store} return &PublicHandler{store: store}
} }
@@ -59,3 +59,4 @@ func sanitizeForPublic(items []models.Product) []models.Product {
} }
return out return out
} }

View File

@@ -58,7 +58,7 @@ func (h *WishlistHandler) AddToWishlist(c *gin.Context) {
} }
var payload wishlistItemPayload var payload wishlistItemPayload
if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" { if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return return
} }
if err := h.wishlistStore.Add(account, payload.ProductID); err != nil { if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
@@ -76,7 +76,7 @@ func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
} }
productID := c.Param("id") productID := c.Param("id")
if productID == "" { if productID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing product id"}) c.JSON(http.StatusBadRequest, gin.H{"error": "缺少商品 ID"})
return return
} }
if err := h.wishlistStore.Remove(account, productID); err != nil { if err := h.wishlistStore.Remove(account, productID); err != nil {

View File

@@ -112,13 +112,14 @@ func (s *OrderStore) ListAll() ([]models.Order, error) {
func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) { func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) {
var total int64 var total int64
// 统计 pending手动待发货和 completed 两种状态,防止用户快速下单绕过购买数量限制。
err := s.db.Model(&database.OrderRow{}). err := s.db.Model(&database.OrderRow{}).
Where("user_account = ? AND product_id = ? AND status = ?", account, productID, "completed"). Where("user_account = ? AND product_id = ? AND status IN ?", account, productID, []string{"pending", "completed"}).
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
return int(total), err return int(total), err
} }
// Count returns the total number of orders. // Count 返回所有订单的总数量。
func (s *OrderStore) Count() (int, error) { func (s *OrderStore) Count() (int, error) {
var count int64 var count int64
if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil { if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil {
@@ -127,12 +128,12 @@ func (s *OrderStore) Count() (int, error) {
return int(count), nil return int(count), nil
} }
// Delete removes a single order by ID. // Delete 根据 ID 删除单条订单。
func (s *OrderStore) Delete(id string) error { func (s *OrderStore) Delete(id string) error {
return s.db.Delete(&database.OrderRow{}, "id = ?", id).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). // UpdateCodes 更新订单的已发货卡密列表。
func (s *OrderStore) UpdateCodes(id string, codes []string) error { func (s *OrderStore) UpdateCodes(id string, codes []string) error {
return s.db.Model(&database.OrderRow{}).Where("id = ?", id). return s.db.Model(&database.OrderRow{}).Where("id = ?", id).
Update("delivered_codes", database.StringSlice(codes)).Error Update("delivered_codes", database.StringSlice(codes)).Error

View File

@@ -18,20 +18,20 @@ const defaultCoverURL = "https://img.shumengya.top/i/2026/01/04/695a55058c37f.pn
const viewCooldown = 6 * time.Hour const viewCooldown = 6 * time.Hour
const maxScreenshotURLs = 5 const maxScreenshotURLs = 5
type JSONStore struct { type ProductStore struct {
db *gorm.DB db *gorm.DB
mu sync.Mutex mu sync.Mutex
recentViews map[string]time.Time recentViews map[string]time.Time
} }
func NewJSONStore(db *gorm.DB) (*JSONStore, error) { func NewProductStore(db *gorm.DB) (*ProductStore, error) {
return &JSONStore{ return &ProductStore{
db: db, db: db,
recentViews: make(map[string]time.Time), recentViews: make(map[string]time.Time),
}, nil }, nil
} }
// rowToModel converts a ProductRow (+ codes) to a models.Product. // rowToModel 将数据库行(含卡密)转换为业务模型。
func rowToModel(row database.ProductRow, codes []string) models.Product { func rowToModel(row database.ProductRow, codes []string) models.Product {
return models.Product{ return models.Product{
ID: row.ID, ID: row.ID,
@@ -57,7 +57,7 @@ func rowToModel(row database.ProductRow, codes []string) models.Product {
} }
} }
func (s *JSONStore) loadCodes(productID string) ([]string, error) { func (s *ProductStore) loadCodes(productID string) ([]string, error) {
var rows []database.ProductCodeRow var rows []database.ProductCodeRow
if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil { if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil {
return nil, err return nil, err
@@ -69,7 +69,7 @@ func (s *JSONStore) loadCodes(productID string) ([]string, error) {
return codes, nil return codes, nil
} }
func (s *JSONStore) replaceCodes(productID string, codes []string) error { func (s *ProductStore) replaceCodes(productID string, codes []string) error {
if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil { if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil {
return err return err
} }
@@ -83,7 +83,7 @@ func (s *JSONStore) replaceCodes(productID string, codes []string) error {
return s.db.CreateInBatches(rows, 100).Error return s.db.CreateInBatches(rows, 100).Error
} }
func (s *JSONStore) ListAll() ([]models.Product, error) { func (s *ProductStore) ListAll() ([]models.Product, error) {
var rows []database.ProductRow var rows []database.ProductRow
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil { if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err return nil, err
@@ -96,14 +96,14 @@ func (s *JSONStore) ListAll() ([]models.Product, error) {
return products, nil return products, nil
} }
func (s *JSONStore) ListActive() ([]models.Product, error) { func (s *ProductStore) ListActive() ([]models.Product, error) {
var rows []database.ProductRow var rows []database.ProductRow
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil { if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err return nil, err
} }
products := make([]models.Product, 0, len(rows)) products := make([]models.Product, 0, len(rows))
for _, row := range rows { for _, row := range rows {
// For public listing we don't expose codes, but we still need Quantity // 公开接口不暴露卡密,但需要统计剩余库存数量
var count int64 var count int64
s.db.Model(&database.ProductCodeRow{}).Where("product_id = ?", row.ID).Count(&count) s.db.Model(&database.ProductCodeRow{}).Where("product_id = ?", row.ID).Count(&count)
row.Active = true row.Active = true
@@ -115,7 +115,7 @@ func (s *JSONStore) ListActive() ([]models.Product, error) {
return products, nil return products, nil
} }
func (s *JSONStore) GetByID(id string) (models.Product, error) { func (s *ProductStore) GetByID(id string) (models.Product, error) {
var row database.ProductRow var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil { 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")
@@ -124,7 +124,7 @@ func (s *JSONStore) GetByID(id string) (models.Product, error) {
return rowToModel(row, codes), nil return rowToModel(row, codes), nil
} }
func (s *JSONStore) Create(p models.Product) (models.Product, error) { func (s *ProductStore) Create(p models.Product) (models.Product, error) {
p = normalizeProduct(p) p = normalizeProduct(p)
p.ID = uuid.NewString() p.ID = uuid.NewString()
now := time.Now() now := time.Now()
@@ -160,7 +160,7 @@ func (s *JSONStore) Create(p models.Product) (models.Product, error) {
return p, nil return p, nil
} }
func (s *JSONStore) Update(id string, patch models.Product) (models.Product, error) { func (s *ProductStore) Update(id string, patch models.Product) (models.Product, error) {
var row database.ProductRow var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil { 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")
@@ -195,7 +195,7 @@ func (s *JSONStore) Update(id string, patch models.Product) (models.Product, err
return rowToModel(updated, codes), nil return rowToModel(updated, codes), nil
} }
func (s *JSONStore) Toggle(id string, active bool) (models.Product, error) { func (s *ProductStore) Toggle(id string, active bool) (models.Product, error) {
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil { if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
return models.Product{}, err return models.Product{}, err
} }
@@ -207,12 +207,12 @@ func (s *JSONStore) Toggle(id string, active bool) (models.Product, error) {
return rowToModel(row, codes), nil return rowToModel(row, codes), nil
} }
func (s *JSONStore) IncrementSold(id string, count int) error { func (s *ProductStore) IncrementSold(id string, count int) error {
return s.db.Model(&database.ProductRow{}).Where("id = ?", id). return s.db.Model(&database.ProductRow{}).Where("id = ?", id).
UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error
} }
func (s *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool, error) { func (s *ProductStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@@ -240,14 +240,14 @@ func (s *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool,
return rowToModel(row, nil), true, nil return rowToModel(row, nil), true, nil
} }
func (s *JSONStore) Delete(id string) error { func (s *ProductStore) Delete(id string) error {
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil { if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
return err return err
} }
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
} }
// normalizeProduct cleans up product fields (same logic as before, no file I/O). // normalizeProduct 对商品字段进行规范化处理(清理空白、设默认值等)。
func normalizeProduct(item models.Product) models.Product { func normalizeProduct(item models.Product) models.Product {
item.CoverURL = strings.TrimSpace(item.CoverURL) item.CoverURL = strings.TrimSpace(item.CoverURL)
if item.CoverURL == "" { if item.CoverURL == "" {
@@ -318,10 +318,11 @@ func buildViewKey(id, fingerprint string) string {
return fmt.Sprintf("%x", sum) return fmt.Sprintf("%x", sum)
} }
func (s *JSONStore) cleanupRecentViews(now time.Time) { func (s *ProductStore) cleanupRecentViews(now time.Time) {
for key, lastViewedAt := range s.recentViews { for key, lastViewedAt := range s.recentViews {
if now.Sub(lastViewedAt) >= viewCooldown { if now.Sub(lastViewedAt) >= viewCooldown {
delete(s.recentViews, key) delete(s.recentViews, key)
} }
} }
} }

View File

@@ -19,8 +19,9 @@ func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
func (s *SiteStore) get(key string) (string, error) { func (s *SiteStore) get(key string) (string, error) {
var row database.SiteSettingRow var row database.SiteSettingRow
if err := s.db.First(&row, "key = ?", key).Error; err != nil { // `key` 是 MySQL 保留字,需用反引号转义以避免 SQL 语法错误。
return "", nil // key not found → return zero value if err := s.db.Where("`key` = ?", key).First(&row).Error; err != nil {
return "", nil // 键不存在时返回零值
} }
return row.Value, nil return row.Value, nil
} }
@@ -74,15 +75,16 @@ func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
return s.set("maintenanceReason", reason) return s.set("maintenanceReason", reason)
} }
// RecordVisit increments the visit counter. Returns (totalVisits, counted, error). // RecordVisit 递增访问计数,返回 (总访问量, 是否计入, 错误)。
// For simplicity, every call increments (fingerprint dedup is handled in-memory by the handler layer). // 去重逻辑由上层 handler 的内存指纹完成,此处无条件累加。
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) { func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
total, err := s.IncrementVisits() total, err := s.IncrementVisits()
return total, true, err return total, true, err
} }
// SMTPConfig holds the mail sender configuration stored in the DB. // SMTPConfig 存储数据库中的发件 SMTP 配置。
type SMTPConfig struct { type SMTPConfig struct {
Enabled bool `json:"enabled"`
Email string `json:"email"` Email string `json:"email"`
Password string `json:"password"` Password string `json:"password"`
FromName string `json:"fromName"` FromName string `json:"fromName"`
@@ -90,15 +92,19 @@ type SMTPConfig struct {
Port string `json:"port"` Port string `json:"port"`
} }
// IsConfiguredEmail returns true if the SMTP config is ready to send mail. // IsConfiguredEmail 判断邮件通知是否已启用且 SMTP 配置完整。
func (c SMTPConfig) IsConfiguredEmail() bool { func (c SMTPConfig) IsConfiguredEmail() bool {
return c.Email != "" && c.Password != "" && c.Host != "" return c.Enabled && c.Email != "" && c.Password != "" && c.Host != ""
} }
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) { func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
cfg := SMTPConfig{ cfg := SMTPConfig{
Host: "smtp.qq.com", Enabled: true, // 默认启用
Port: "465", Host: "smtp.qq.com",
Port: "465",
}
if v, _ := s.get("smtpEnabled"); v == "false" {
cfg.Enabled = false
} }
if v, _ := s.get("smtpEmail"); v != "" { if v, _ := s.get("smtpEmail"); v != "" {
cfg.Email = v cfg.Email = v
@@ -119,7 +125,12 @@ func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
} }
func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error { func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error {
enabledVal := "true"
if !cfg.Enabled {
enabledVal = "false"
}
pairs := [][2]string{ pairs := [][2]string{
{"smtpEnabled", enabledVal},
{"smtpEmail", cfg.Email}, {"smtpEmail", cfg.Email},
{"smtpPassword", cfg.Password}, {"smtpPassword", cfg.Password},
{"smtpFromName", cfg.FromName}, {"smtpFromName", cfg.FromName},

View File

@@ -16,43 +16,43 @@ import (
) )
func main() { func main() {
cfg, err := config.Load("data/json/settings.json") cfg, err := config.Load("config.json")
if err != nil { if err != nil {
log.Fatalf("load config failed: %v", err) log.Fatalf("加载配置失败: %v", err)
} }
// Initialise database // 初始化数据库连接
db, err := database.Open(cfg.DatabaseDSN) db, err := database.Open(cfg.DatabaseDSN)
if err != nil { if err != nil {
log.Fatalf("init database failed: %v", err) log.Fatalf("初始化数据库失败: %v", err)
} }
store, err := storage.NewJSONStore(db) store, err := storage.NewProductStore(db)
if err != nil { if err != nil {
log.Fatalf("init store failed: %v", err) log.Fatalf("初始化商品存储失败: %v", err)
} }
orderStore, err := storage.NewOrderStore(db) orderStore, err := storage.NewOrderStore(db)
if err != nil { if err != nil {
log.Fatalf("init order store failed: %v", err) log.Fatalf("初始化订单存储失败: %v", err)
} }
siteStore, err := storage.NewSiteStore(db) siteStore, err := storage.NewSiteStore(db)
if err != nil { if err != nil {
log.Fatalf("init site store failed: %v", err) log.Fatalf("初始化站点存储失败: %v", err)
} }
wishlistStore, err := storage.NewWishlistStore(db) wishlistStore, err := storage.NewWishlistStore(db)
if err != nil { if err != nil {
log.Fatalf("init wishlist store failed: %v", err) log.Fatalf("初始化收藏夹存储失败: %v", err)
} }
chatStore, err := storage.NewChatStore(db) chatStore, err := storage.NewChatStore(db)
if err != nil { if err != nil {
log.Fatalf("init chat store failed: %v", err) log.Fatalf("初始化聊天存储失败: %v", err)
} }
r := gin.Default() r := gin.Default()
r.Use(cors.New(cors.Config{ r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"}, AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Admin-Token"},
ExposeHeaders: []string{"Content-Length"}, ExposeHeaders: []string{"Content-Length"},
AllowCredentials: false, AllowCredentials: false,
MaxAge: 12 * time.Hour, MaxAge: 12 * time.Hour,
@@ -80,7 +80,7 @@ func main() {
r.GET("/api/orders", orderHandler.ListMyOrders) r.GET("/api/orders", orderHandler.ListMyOrders)
r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder) r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)
r.GET("/api/admin/token", adminHandler.GetAdminToken) r.POST("/api/admin/verify", adminHandler.VerifyAdminToken)
r.GET("/api/admin/products", adminHandler.ListAllProducts) r.GET("/api/admin/products", adminHandler.ListAllProducts)
r.POST("/api/admin/products", adminHandler.CreateProduct) r.POST("/api/admin/products", adminHandler.CreateProduct)
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct) r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
@@ -96,11 +96,11 @@ func main() {
r.POST("/api/wishlist", wishlistHandler.AddToWishlist) r.POST("/api/wishlist", wishlistHandler.AddToWishlist)
r.DELETE("/api/wishlist/:id", wishlistHandler.RemoveFromWishlist) r.DELETE("/api/wishlist/:id", wishlistHandler.RemoveFromWishlist)
// Chat routes (user) // 用户聊天路由
r.GET("/api/chat/messages", chatHandler.GetMyMessages) r.GET("/api/chat/messages", chatHandler.GetMyMessages)
r.POST("/api/chat/messages", chatHandler.SendMyMessage) r.POST("/api/chat/messages", chatHandler.SendMyMessage)
// Chat routes (admin) // 管理员聊天路由
r.GET("/api/admin/chat", adminHandler.GetAllConversations) r.GET("/api/admin/chat", adminHandler.GetAllConversations)
r.GET("/api/admin/chat/:account", adminHandler.GetConversation) r.GET("/api/admin/chat/:account", adminHandler.GetConversation)
r.POST("/api/admin/chat/:account", adminHandler.AdminReply) r.POST("/api/admin/chat/:account", adminHandler.AdminReply)
@@ -108,6 +108,7 @@ func main() {
log.Println("萌芽小店后端启动于 http://localhost:8080") log.Println("萌芽小店后端启动于 http://localhost:8080")
if err := r.Run(":8080"); err != nil { if err := r.Run(":8080"); err != nil {
log.Fatalf("server run failed: %v", err) log.Fatalf("服务器启动失败: %v", err)
} }
} }

View File

@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

View File

@@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,39 @@
plugins {
id 'java'
id 'org.springframework.boot' version '4.0.4'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.smyhub.store'
version = '0.0.1-SNAPSHOT'
description = 'mengyastore-backend-java'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
developmentOnly 'org.springframework.boot:spring-boot-docker-compose'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}

View File

@@ -0,0 +1 @@
services: { }

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = 'mengyastore-backend-java'

View File

@@ -0,0 +1,13 @@
package com.smyhub.store.mengyastorebackendjava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MengyastoreBackendJavaApplication {
public static void main(String[] args) {
SpringApplication.run(MengyastoreBackendJavaApplication.class, args);
}
}

View File

@@ -0,0 +1,3 @@
spring:
application:
name: mengyastore-backend-java

View File

@@ -0,0 +1,13 @@
package com.smyhub.store.mengyastorebackendjava;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MengyastoreBackendJavaApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
mengyastore-backend-java/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip

View File

@@ -0,0 +1 @@
services: { }

295
mengyastore-backend-java/mvnw vendored Normal file
View File

@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
mengyastore-backend-java/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

View File

@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.12</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.smyhub.store</groupId>
<artifactId>mengyastore-backend-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mengyastore-backend-java</name>
<description>mengyastore-backend-java</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-docker-compose</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,13 @@
package com.smyhub.store.mengyastorebackendjava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MengyastoreBackendJavaApplication {
public static void main(String[] args) {
SpringApplication.run(MengyastoreBackendJavaApplication.class, args);
}
}

View File

@@ -0,0 +1,3 @@
spring:
application:
name: mengyastore-backend-java

View File

@@ -0,0 +1,13 @@
package com.smyhub.store.mengyastorebackendjava;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MengyastoreBackendJavaApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -1,3 +0,0 @@
{
"adminToken": "shumengya520"
}

View File

@@ -2106,9 +2106,6 @@
"arm" "arm"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2126,9 +2123,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2146,9 +2140,6 @@
"s390x" "s390x"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2166,9 +2157,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2186,9 +2174,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2206,9 +2191,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2226,9 +2208,6 @@
"arm" "arm"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2252,9 +2231,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2278,9 +2254,6 @@
"s390x" "s390x"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2304,9 +2277,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2330,9 +2300,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2356,9 +2323,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [

View File

@@ -120,7 +120,7 @@
<script setup> <script setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue' import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { fetchAdminToken, fetchStats, recordSiteVisit } from './modules/shared/api' import { verifyAdminToken, fetchStats, recordSiteVisit } from './modules/shared/api'
import { authState, isLoggedIn, clearAuth, getLoginUrl } from './modules/shared/auth' import { authState, isLoggedIn, clearAuth, getLoginUrl } from './modules/shared/auth'
import { wishlistCount, loadWishlist } from './modules/shared/useWishlist' import { wishlistCount, loadWishlist } from './modules/shared/useWishlist'
import ChatWidget from './modules/chat/ChatWidget.vue' import ChatWidget from './modules/chat/ChatWidget.vue'
@@ -171,10 +171,10 @@ const submitAdminToken = async () => {
if (!input) return if (!input) return
tokenError.value = '' tokenError.value = ''
try { try {
const correctToken = await fetchAdminToken() const valid = await verifyAdminToken(input)
if (input === correctToken) { if (valid) {
showAdminModal.value = false showAdminModal.value = false
router.push(`/admin?token=${encodeURIComponent(correctToken)}`) router.push(`/admin?token=${encodeURIComponent(input)}`)
} else { } else {
tokenError.value = '令牌错误,请重试' tokenError.value = '令牌错误,请重试'
} }

View File

@@ -42,7 +42,6 @@
v-model:token="token" v-model:token="token"
:message="!token || message ? message : ''" :message="!token || message ? message : ''"
:inline-message="token && message ? message : ''" :inline-message="token && message ? message : ''"
@auto-get="autoGetToken"
/> />
<!-- Section: Products --> <!-- Section: Products -->
@@ -96,7 +95,6 @@ import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { import {
fetchAdminProducts, fetchAdminProducts,
fetchAdminToken,
createProduct, createProduct,
updateProduct, updateProduct,
toggleProduct, toggleProduct,
@@ -183,12 +181,6 @@ const refresh = async () => {
} }
} }
const autoGetToken = async () => {
const fetched = await fetchAdminToken()
token.value = fetched
syncQuery()
await refresh()
}
const loadMaintenance = async () => { const loadMaintenance = async () => {
try { try {

View File

@@ -135,7 +135,7 @@ const load = async () => {
loading.value = true loading.value = true
try { try {
conversations.value = await fetchAdminAllConversations(props.adminToken) conversations.value = await fetchAdminAllConversations(props.adminToken)
// Refresh current conversation messages if one is selected // 若当前已选中某个会话,则刷新其消息列表
if (selectedAccount.value) { if (selectedAccount.value) {
currentMessages.value = conversations.value[selectedAccount.value] || [] currentMessages.value = conversations.value[selectedAccount.value] || []
await scrollThreadBottom() await scrollThreadBottom()

View File

@@ -98,7 +98,7 @@ const pagedOrders = computed(() => {
return props.orders.slice(start, start + PAGE_SIZE) return props.orders.slice(start, start + PAGE_SIZE)
}) })
// Reset to page 1 when orders list changes // 订单列表变化时重置到第一页
watch(() => props.orders.length, () => { currentPage.value = 1 }) watch(() => props.orders.length, () => { currentPage.value = 1 })
const remove = (id) => { const remove = (id) => {

View File

@@ -5,26 +5,35 @@
<span class="smtp-desc tag">下单/发货时自动给用户发送通知邮件支持 QQ / 163 / Gmail / 自定义域名邮箱</span> <span class="smtp-desc tag">下单/发货时自动给用户发送通知邮件支持 QQ / 163 / Gmail / 自定义域名邮箱</span>
<span v-if="message" class="msg-tag" :class="{ error: message.includes('失败') }">{{ message }}</span> <span v-if="message" class="msg-tag" :class="{ error: message.includes('失败') }">{{ message }}</span>
</div> </div>
<div class="smtp-fields"> <div class="smtp-enable-row">
<label class="smtp-toggle">
<input type="checkbox" v-model="form.enabled" />
<span>启用邮件通知</span>
</label>
<span class="smtp-status-tag" :class="form.enabled ? 'tag-on' : 'tag-off'">
{{ form.enabled ? '已启用' : '已关闭' }}
</span>
</div>
<div class="smtp-fields" :class="{ 'smtp-fields-disabled': !form.enabled }">
<label class="smtp-field"> <label class="smtp-field">
<span>发件邮箱</span> <span>发件邮箱</span>
<input v-model="form.email" type="email" placeholder="noreply@yourdomain.com" /> <input v-model="form.email" type="email" placeholder="noreply@yourdomain.com" :disabled="!form.enabled" />
</label> </label>
<label class="smtp-field"> <label class="smtp-field">
<span>SMTP 密码 / 授权码</span> <span>SMTP 密码 / 授权码</span>
<input v-model="form.password" type="password" placeholder="QQ/163 填授权码;其他填密码" autocomplete="new-password" /> <input v-model="form.password" type="password" placeholder="QQ/163 填授权码;其他填密码" autocomplete="new-password" :disabled="!form.enabled" />
</label> </label>
<label class="smtp-field"> <label class="smtp-field">
<span>发件人名称</span> <span>发件人名称</span>
<input v-model="form.fromName" type="text" placeholder="萌芽小店" /> <input v-model="form.fromName" type="text" placeholder="萌芽小店" :disabled="!form.enabled" />
</label> </label>
<label class="smtp-field"> <label class="smtp-field">
<span>SMTP 主机</span> <span>SMTP 主机</span>
<input v-model="form.host" type="text" placeholder="smtp.qq.com" /> <input v-model="form.host" type="text" placeholder="smtp.qq.com" :disabled="!form.enabled" />
</label> </label>
<label class="smtp-field smtp-field-port"> <label class="smtp-field smtp-field-port">
<span>端口</span> <span>端口</span>
<input v-model="form.port" type="text" placeholder="465" /> <input v-model="form.port" type="text" placeholder="465" :disabled="!form.enabled" />
</label> </label>
<button class="primary smtp-save-btn" type="button" :disabled="saving" @click="save"> <button class="primary smtp-save-btn" type="button" :disabled="saving" @click="save">
{{ saving ? '保存中...' : '保存配置' }} {{ saving ? '保存中...' : '保存配置' }}
@@ -46,6 +55,7 @@ const emit = defineEmits(['save'])
const saving = ref(false) const saving = ref(false)
const form = reactive({ const form = reactive({
enabled: true,
email: '', email: '',
password: '', password: '',
fromName: '', fromName: '',
@@ -55,6 +65,7 @@ const form = reactive({
watch(() => props.config, (cfg) => { watch(() => props.config, (cfg) => {
if (!cfg) return if (!cfg) return
form.enabled = cfg.enabled !== false
form.email = cfg.email || '' form.email = cfg.email || ''
form.password = cfg.password || '' form.password = cfg.password || ''
form.fromName = cfg.fromName || '' form.fromName = cfg.fromName || ''
@@ -101,6 +112,47 @@ const save = async () => {
color: var(--muted); color: var(--muted);
} }
.smtp-enable-row {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.smtp-toggle {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 14px;
color: var(--text);
font-weight: 500;
}
.smtp-toggle input[type="checkbox"] {
width: 16px;
height: 16px;
accent-color: var(--accent);
cursor: pointer;
}
.smtp-status-tag {
font-size: 12px;
font-weight: 600;
padding: 2px 8px;
border-radius: 999px;
}
.tag-on {
background: rgba(74, 222, 128, 0.15);
color: #2d8a4e;
}
.tag-off {
background: rgba(0,0,0,0.06);
color: #888;
}
.smtp-fields { .smtp-fields {
display: flex; display: flex;
gap: 10px; gap: 10px;
@@ -108,6 +160,11 @@ const save = async () => {
align-items: flex-end; align-items: flex-end;
} }
.smtp-fields-disabled {
opacity: 0.45;
pointer-events: none;
}
.smtp-field { .smtp-field {
display: flex; display: flex;
flex-direction: column; flex-direction: column;

View File

@@ -3,8 +3,7 @@
<div class="form-field token-field"> <div class="form-field token-field">
<label>管理 Token</label> <label>管理 Token</label>
<div class="token-input-wrap"> <div class="token-input-wrap">
<input :value="token" @input="$emit('update:token', $event.target.value)" placeholder="粘贴 token 后自动加载…" /> <input :value="token" @input="$emit('update:token', $event.target.value)" placeholder="粘贴管理员令牌后自动加载…" />
<button class="ghost small" type="button" @click="$emit('auto-get')">自动获取</button>
</div> </div>
</div> </div>
<p <p
@@ -28,7 +27,7 @@ defineProps({
inlineMessage: { type: String, default: '' } inlineMessage: { type: String, default: '' }
}) })
defineEmits(['update:token', 'auto-get']) defineEmits(['update:token'])
</script> </script>
<style scoped> <style scoped>

View File

@@ -52,7 +52,7 @@ onMounted(async () => {
} }
try { try {
// Verify token and get up-to-date user info from SproutGate // 验证 token 并从 SproutGate 获取最新用户信息
const verifyData = await verifySproutGateToken(token) const verifyData = await verifySproutGateToken(token)
if (!verifyData.valid) { if (!verifyData.valid) {
status.value = 'error' status.value = 'error'
@@ -71,7 +71,7 @@ onMounted(async () => {
status.value = 'success' status.value = 'success'
setTimeout(() => router.push('/'), 1000) setTimeout(() => router.push('/'), 1000)
} catch { } catch {
// If verify fails (network issue), fall back to fragment data // 验证失败(如网络异常)时,回退使用 URL fragment 中的数据
setAuth({ token, account, username, avatarUrl: fragmentAvatar }) setAuth({ token, account, username, avatarUrl: fragmentAvatar })
displayName.value = username || account displayName.value = username || account
status.value = 'success' status.value = 'success'

View File

@@ -121,7 +121,7 @@ const loadMessages = async () => {
messages.value = await fetchMyChatMessages(props.userToken) messages.value = await fetchMyChatMessages(props.userToken)
await scrollBottom() await scrollBottom()
} catch { } catch {
// silently ignore polling errors // 静默忽略轮询错误,避免频繁弹出错误提示
} }
} }

View File

@@ -1,11 +1,18 @@
import axios from 'axios' import axios from 'axios'
const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080' const apiBaseURL =
import.meta.env.VITE_API_BASE_URL ||
import.meta.env.VITE_API_BASE ||
(typeof window !== 'undefined' ? window.location.origin : 'http://localhost:8080')
const api = axios.create({ const api = axios.create({
baseURL: apiBaseURL baseURL: apiBaseURL
}) })
// 管理员请求头构建辅助函数,使用 X-Admin-Token 请求头。
// 后端保留 ?token= 查询参数作为旧版兼容,新请求统一使用请求头以兼容 Spring Security。
const adminHeaders = (token) => ({ 'X-Admin-Token': token })
const authApi = axios.create({ const authApi = axios.create({
baseURL: 'https://auth.api.shumengya.top' baseURL: 'https://auth.api.shumengya.top'
}) })
@@ -60,40 +67,40 @@ export const fetchMyOrders = async (authToken) => {
return data.data || [] return data.data || []
} }
export const fetchAdminToken = async () => { export const verifyAdminToken = async (token) => {
const { data } = await api.get('/api/admin/token') const { data } = await api.post('/api/admin/verify', { token })
return data.token || '' return data.valid === true
} }
export const fetchAdminProducts = async (token) => { export const fetchAdminProducts = async (token) => {
const { data } = await api.get('/api/admin/products', { params: { token } }) const { data } = await api.get('/api/admin/products', { headers: adminHeaders(token) })
return data.data || [] return data.data || []
} }
export const createProduct = async (token, payload) => { export const createProduct = async (token, payload) => {
const { data } = await api.post('/api/admin/products', payload, { const { data } = await api.post('/api/admin/products', payload, {
params: { token } headers: adminHeaders(token)
}) })
return data.data return data.data
} }
export const updateProduct = async (token, id, payload) => { export const updateProduct = async (token, id, payload) => {
const { data } = await api.put(`/api/admin/products/${id}`, payload, { const { data } = await api.put(`/api/admin/products/${id}`, payload, {
params: { token } headers: adminHeaders(token)
}) })
return data.data return data.data
} }
export const toggleProduct = async (token, id, active) => { export const toggleProduct = async (token, id, active) => {
const { data } = await api.patch(`/api/admin/products/${id}/status`, { active }, { const { data } = await api.patch(`/api/admin/products/${id}/status`, { active }, {
params: { token } headers: adminHeaders(token)
}) })
return data.data return data.data
} }
export const deleteProduct = async (token, id) => { export const deleteProduct = async (token, id) => {
const { data } = await api.delete(`/api/admin/products/${id}`, { const { data } = await api.delete(`/api/admin/products/${id}`, {
params: { token } headers: adminHeaders(token)
}) })
return data return data
} }
@@ -120,12 +127,12 @@ export const removeFromWishlist = async (token, productId) => {
} }
export const fetchAdminOrders = async (token) => { export const fetchAdminOrders = async (token) => {
const { data } = await api.get('/api/admin/orders', { params: { token } }) const { data } = await api.get('/api/admin/orders', { headers: adminHeaders(token) })
return data.data || [] return data.data || []
} }
export const deleteAdminOrder = async (token, orderId) => { export const deleteAdminOrder = async (token, orderId) => {
await api.delete(`/api/admin/orders/${orderId}`, { params: { token } }) await api.delete(`/api/admin/orders/${orderId}`, { headers: adminHeaders(token) })
} }
export const fetchSiteMaintenance = async () => { export const fetchSiteMaintenance = async () => {
@@ -135,19 +142,19 @@ export const fetchSiteMaintenance = async () => {
export const setSiteMaintenance = async (token, maintenance, reason) => { export const setSiteMaintenance = async (token, maintenance, reason) => {
const { data } = await api.post('/api/admin/site/maintenance', { maintenance, reason }, { const { data } = await api.post('/api/admin/site/maintenance', { maintenance, reason }, {
params: { token } headers: adminHeaders(token)
}) })
return data.data || {} return data.data || {}
} }
// ---- SMTP Config ---- // ---- SMTP Config ----
export const fetchSMTPConfig = async (token) => { export const fetchSMTPConfig = async (token) => {
const { data } = await api.get('/api/admin/site/smtp', { params: { token } }) const { data } = await api.get('/api/admin/site/smtp', { headers: adminHeaders(token) })
return data.data || {} return data.data || {}
} }
export const setSMTPConfig = async (token, cfg) => { export const setSMTPConfig = async (token, cfg) => {
const { data } = await api.post('/api/admin/site/smtp', cfg, { params: { token } }) const { data } = await api.post('/api/admin/site/smtp', cfg, { headers: adminHeaders(token) })
return data.data return data.data
} }
@@ -168,13 +175,13 @@ export const sendChatMessage = async (userToken, content) => {
// ---- Chat (admin) ---- // ---- Chat (admin) ----
export const fetchAdminAllConversations = async (adminToken) => { export const fetchAdminAllConversations = async (adminToken) => {
const { data } = await api.get('/api/admin/chat', { params: { token: adminToken } }) const { data } = await api.get('/api/admin/chat', { headers: adminHeaders(adminToken) })
return data.data?.conversations || {} return data.data?.conversations || {}
} }
export const fetchAdminConversation = async (adminToken, account) => { export const fetchAdminConversation = async (adminToken, account) => {
const { data } = await api.get(`/api/admin/chat/${encodeURIComponent(account)}`, { const { data } = await api.get(`/api/admin/chat/${encodeURIComponent(account)}`, {
params: { token: adminToken } headers: adminHeaders(adminToken)
}) })
return data.data?.messages || [] return data.data?.messages || []
} }
@@ -183,13 +190,13 @@ export const adminSendChatReply = async (adminToken, account, content) => {
const { data } = await api.post( const { data } = await api.post(
`/api/admin/chat/${encodeURIComponent(account)}`, `/api/admin/chat/${encodeURIComponent(account)}`,
{ content }, { content },
{ params: { token: adminToken } } { headers: adminHeaders(adminToken) }
) )
return data.data?.message || null return data.data?.message || null
} }
export const adminClearConversation = async (adminToken, account) => { export const adminClearConversation = async (adminToken, account) => {
await api.delete(`/api/admin/chat/${encodeURIComponent(account)}`, { await api.delete(`/api/admin/chat/${encodeURIComponent(account)}`, {
params: { token: adminToken } headers: adminHeaders(adminToken)
}) })
} }

View File

@@ -29,7 +29,7 @@ const addToWishlist = async (productId) => {
try { try {
wishlistIds.value = await apiAddToWishlist(authState.token, productId) wishlistIds.value = await apiAddToWishlist(authState.token, productId)
} catch { } catch {
// ignore // 忽略错误
} }
} }
@@ -38,7 +38,7 @@ const removeFromWishlist = async (productId) => {
try { try {
wishlistIds.value = await apiRemoveFromWishlist(authState.token, productId) wishlistIds.value = await apiRemoveFromWishlist(authState.token, productId)
} catch { } catch {
// ignore // 忽略错误
} }
} }

View File

@@ -0,0 +1,12 @@
项目名称:萌芽小店项目-支持网关登录商品售卖平台
时间2026.1 - 2026.03
技术栈Golang,Gin,MySQL,Redis,Vue
描述:前后端分离的轻量级商城平台,支持登录、商品展示与下单、自动/手动发货、邮件通知、收藏夹、客服聊天、维护模式与 PWA 离线缓存。
商品与订单管理、发货与订单状态联动、SMTP 邮件通知、后台运维(商品/订单/对话/站点设置)、用户聊天客服与维护模式能力。
通过限购与订单状态约束降低并发超卖风险;通过公开/用户/管理员分层实现权限边界隔离;通过分层架构与可运维配置提升可维护性。
后端采用分层解耦与 ORM 自动建表,支持多环境配置与容器化部署;前端路由守卫与接口封装增强可用性与一致性。
上线地址https://store.shumengya.top
开源地址https://github.com/shumengya/mengyastore

View File

@@ -0,0 +1,72 @@
# 萌芽小店Mengyastore面试经历要点
## 1. 项目一句话
一个前后端分离的轻量级商城系统,支持商品浏览、下单与发货(自动/手动)、邮件通知、聊天客服、收藏夹,以及 PWA 安装与离线缓存。
## 2. 技术栈(可直接复述)
- 前端Vue 3Composition API、Vite、Vue Router 4、Pinia、Axios、`markdown-it`商品描述渲染、PWA`vite-plugin-pwa`
- 后端Go 1.21+、Gin、GORM、MySQL、SMTP 邮件发送net/smtp + TLS
- 部署Docker / docker-compose后端二进制容器化 + 挂载只读配置)
- 认证SproutGate OAuth用户侧 Bearer token 校验);管理员使用 `adminToken``/api/admin/verify` + 请求头/查询参数校验)
## 3. 整体架构
- 前端:按功能拆分模块(`admin/` 管理后台、`store/` 商品/结账、`chat/` 客服、`wishlist/` 收藏、`maintenance/` 维护页),并在路由层做维护模式守卫。
- 后端:使用 `internal/handlers` 按业务拆路由与处理逻辑;使用 `internal/storage` 把数据访问封装成独立存储层;通过 `cmd/migrate` 做旧数据到 MySQL 的迁移/初始化。
- 数据库:以 `products / product_codes / orders / chat_messages / wishlists / site_settings` 等核心表承载业务状态与统计。
## 4. 关键业务链路(面试重点)
### 4.1 商品浏览与下单
- 商品列表:`GET /api/products`
- 记录浏览量:`POST /api/products/:id/view`
- 下单(创建订单与支付流程):`POST /api/checkout`
- 确认付款/触发发货:`POST /api/orders/:id/confirm`
### 4.2 自动发货 vs 手动发货
- 自动发货(`deliveryMode = "auto"`):在下单/确认流程中从 `product_codes` 取出卡密,写入订单 `delivered_codes`,订单完成后返回卡密内容,并更新销量统计。
- 手动发货(`deliveryMode = "manual"`):下单不提取卡密,确认后订单状态变为完成但不返回卡密;管理员在后台查看订单信息后进行发货相关操作。
### 4.3 邮件通知SMTP 可配置)
- 由管理员在后台配置 SMTP`GET/POST /api/admin/site/smtp`
- 下单或状态变更时触发邮件通知(例如订单确认/发货相关通知)。
### 4.4 聊天客服HTTP 轮询)
- 用户端拉取消息:`GET /api/chat/messages`
- 用户端发送消息(有频率限制):`POST /api/chat/messages`
- 管理员端会话管理:
- 获取全部会话:`GET /api/admin/chat`
- 获取指定用户会话:`GET /api/admin/chat/:account`
- 管理员回复:`POST /api/admin/chat/:account`
- 清除对话:`DELETE /api/admin/chat/:account`
### 4.5 维护模式与管理后台鉴权
- 维护模式:前端在路由守卫里调用 `GET /api/site/maintenance`,站点维护时重定向到 `/maintenance`(管理员可豁免)。
- 管理后台鉴权:`POST /api/admin/verify` 校验 token后续管理员接口通过 `X-Admin-Token` 头部携带。
## 5. PWA 体验亮点(可讲“工程化”)
- 支持 `display: standalone` 的安装到桌面体验
- Service Worker静态资源 `CacheFirst`API 请求 `NetworkFirst`API 有短时缓存策略)
- 自动检测新版本并提示更新
- 启动动画与引导SplashScreen 过渡体验)
## 6. 数据治理/防刷点(面试可用)
- 针对购买并发/绕过:通过统计 `pending``completed` 等订单状态来限制每账户购买数量,减少并发下的超额风险。
- 对外接口与管理员接口分离:公开接口与需要登录/需要管理员 token 的接口分层,降低权限误用概率。
## 7. 部署与环境配置(可讲“落地”)
- 后端容器通过 `DATABASE_DSN` 环境变量覆盖配置文件里的 DSN
- `config.json` 作为只读挂载到容器内,减少运行时误写配置的风险
- 端口映射示例:`28081:8080`
## 8. 面试常问我怎么回答(可直接拿来用)
1. 为什么不使用 WebSocket
- 该项目选择 HTTP 轮询实现客服,降低复杂度;在并发不极端的场景下更易落地、便于维护,并且配合频率限制即可控制滥用。
2. 自动发货如何保证数据一致?
- 关键状态更新与卡密提取/写入集中在后端的“创建订单/确认订单”链路内,确保业务流程按接口语义串联执行(如订单完成状态与卡密归属同步)。
3. PWA 离线策略怎么选?
- 静态资源走 `CacheFirst` 提升加载速度与离线能力API 走 `NetworkFirst` 保持业务数据的新鲜度,必要时做短时缓存降抖。
## 9. 你可以按自己的贡献再补一句(占位)
- 个人在项目中主要负责:前端模块/接口封装/后端某模块实现(按实际替换)
- 自己解决过的一个难点:例如“接口鉴权边界/订单发货逻辑/SMTP 配置联调/PWA 缓存策略”等(按实际替换)