Compare commits

..

4 Commits

108 changed files with 15722 additions and 2423 deletions

4
.gitignore vendored
View File

@@ -10,3 +10,7 @@ coverage/
*.exe~
*~
.DS_Store
.cursor/
config.json
mengyastore-backend/data/
mengyastore-frontend/public/logo.png

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

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

543
API_DOCS.md Normal file
View File

@@ -0,0 +1,543 @@
# 萌芽账户认证中心 API 文档
访问 **`GET /`** 或 **`GET /api`**(无鉴权)可得到 JSON 格式的简要说明(服务名、版本、`/api/docs``/api/health` 入口、路由前缀摘要)。
接入地址:
- 统一登录前端:`https://auth.shumengya.top`
- 后端 API`https://auth.api.shumengya.top`
- 本地开发 API`http://<host>:8080`
对外接入建议:
1. 第三方应用按钮跳转到统一登录前端。
2. 登录成功后回跳到业务站点。
3. 业务站点使用回跳带回的 `token` 调用后端 API。
示例按钮:
```html
<a href="https://auth.shumengya.top/?redirect_uri=https%3A%2F%2Fapp.example.com%2Fauth%2Fcallback&state=abc123">
使用萌芽统一账户认证登录
</a>
```
回跳说明:
- 用户已登录时,统一登录前端会提示“继续授权”或“切换账号”。
- 登录成功后会回跳到 `redirect_uri`(或 `return_url`),并在 URL **`#fragment`**(哈希)中带上令牌与用户信息(见下表)。
- 第三方应用拿到 `token` 后,建议调用 **`POST /api/auth/verify`**(无副作用、适合网关鉴权)或 **`GET /api/auth/me`**(会更新访问记录,适合业务拉全量资料)校验并解析用户身份。
### 统一登录前端:查询参数
| 参数 | 必填 | 说明 |
|------|------|------|
| `redirect_uri` | 与 `return_url` 至少其一 | 登录成功后的回跳地址,须进行 URL 编码;可为绝对 URL 或相对路径(相对路径相对统一登录站点解析)。 |
| `return_url` | 同上 | 与 `redirect_uri` 同义,二者都传时优先 `redirect_uri`。 |
| `state` | 否 | OAuth 风格透传字符串;回跳时原样写入哈希参数,供业务防 CSRF 或关联会话。 |
| `prompt` | 否 | 预留;前端可读,当前可用于将来扩展交互策略。 |
| `client_id` | 否 | 第三方应用稳定标识(字母数字开头,可含 `_.:-`,最长 64。写入用户「应用接入记录」并随登录请求提交给后端。 |
| `client_name` | 否 | 展示用名称(最长 128`client_id` 配对;可选。 |
### 回跳 URL`#` 哈希参数
成功授权后,前端将使用 [`URLSearchParams`](https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams) 写入哈希,例如:`https://app.example.com/auth/callback#token=...&expiresAt=...&account=...&username=...&state=...`
| 参数 | 说明 |
|------|------|
| `token` | JWT调用受保护接口时放在请求头 `Authorization: Bearer <token>`。 |
| `expiresAt` | 过期时间RFC3339与签发侧一致当前默认为登录时起算 **7 天**)。 |
| `account` | 账户名(与 JWT `sub` 一致)。 |
| `username` | 展示用昵称,可能为空。 |
| `state` | 若登录请求携带了 `state`,则原样返回。 |
业务站点回调页应用脚本读取 `location.hash`,解析后**仅在 HTTPS 环境**将 `token` 存于内存或安全存储,并尽快用后端 **`POST /api/auth/verify`** 校验(勿仅信任哈希中的明文字段)。
### 第三方后端接入建议
1. **仅信服务端**:回调页将 `token` 交给自有后端,由后端请求 `POST https://<api-host>/api/auth/verify`JSON body`{"token":"..."}`),根据 `valid``user.account` 建立会话。
2. **CORS**:浏览器直连 API 时须后端已配置 CORS本服务默认允许任意 `Origin`);若从服务端发起请求则不受 CORS 限制。
3. **令牌过期**`verify` / `me` 返回 401 或 `verify``valid:false` 时,应引导用户重新走统一登录。
## 认证与统一登录
### 登录获取统一令牌
`POST /api/auth/login`
请求:
```json
{
"account": "demo",
"password": "demo123",
"clientId": "my-app",
"clientName": "我的应用"
}
```
`clientId` / `clientName` 可选;规则与请求头 `X-Auth-Client` / `X-Auth-Client-Name` 一致。传入且格式合法时,会在登录成功后写入该用户的 **应用接入记录**(见下文 `authClients`)。
响应:
```json
{
"token": "jwt-token",
"expiresAt": "2026-03-14T12:00:00Z",
"user": {
"account": "demo",
"username": "示例用户",
"email": "demo@example.com",
"level": 0,
"sproutCoins": 10,
"secondaryEmails": ["demo2@example.com"],
"phone": "13800000000",
"avatarUrl": "https://example.com/avatar.png",
"websiteUrl": "https://example.com",
"bio": "### 简介",
"createdAt": "2026-03-14T12:00:00Z",
"updatedAt": "2026-03-14T12:00:00Z"
}
}
```
若账户已被管理员封禁,返回 **403**,且**不会签发 JWT**,响应示例:
```json
{
"error": "account is banned",
"banReason": "违规内容"
}
```
`banReason` 可能为空字符串或省略。
**常见 HTTP 状态码(登录)**
| 状态码 | 含义 |
|--------|------|
| 200 | 成功,返回 `token``expiresAt``user`。 |
| 400 | 请求体非法或缺少 `account` / `password`。 |
| 401 | 账户不存在或密码错误(统一文案 `invalid credentials`)。 |
| 403 | 账户已封禁(见上文 JSON。 |
| 500 | 服务器内部错误(读库、签发 JWT 失败等)。 |
**JWT 概要**:算法 **HS256**;载荷含 `account`(与 `sub` 一致)、`iss`(见 `data/config/auth.json`)、`iat` / `exp`。客户端只需透传字符串,**勿在前端解析密钥**。
### 校验令牌
`POST /api/auth/verify`
请求:
```json
{
"token": "jwt-token"
}
```
响应:
```json
{
"valid": true,
"user": { "account": "demo", "...": "..." }
}
```
若账户已封禁,返回 **200**`valid`**false**(不返回 `user` 对象),示例:
```json
{
"valid": false,
"error": "account is banned",
"banReason": "违规内容"
}
```
令牌过期、签名错误、issuer 不匹配等解析失败时返回 **401**,示例:`{"valid": false, "error": "invalid token"}`
`verify``me` 的取舍:**仅校验身份、不改变用户数据**时用 `verify`;需要最新资料、签到状态或写入「最后访问」时用 `GET /api/auth/me`(需 Bearer
**应用接入记录(可选)**:第三方在 **`POST /api/auth/verify`** 或 **`GET /api/auth/me`** 上携带请求头:
- `X-Auth-Client`:应用 ID格式同登录 JSON 的 `clientId`
- `X-Auth-Client-Name`:可选展示名
校验成功且用户未封禁时,服务端会更新该用户 JSON 中的 `authClients` 数组(`clientId``displayName``firstSeenAt``lastSeenAt`)。**`POST /api/auth/verify` 的响应体 `user` 仍为 `Public()`,不含 `authClients`**,避免向调用方泄露用户在其他应用的接入情况;**`GET /api/auth/me`** 与管理员列表中的 `user``OwnerPublic`**包含** `authClients`,用户可在统一登录前端的个人中心查看。
### 获取当前用户信息
`GET /api/auth/me`
请求头:
`Authorization: Bearer <jwt-token>`
可选(由前端调用 `https://cf-ip-geo.smyhub.com/api` 等接口解析后传入,用于记录「最后访问 IP」与「最后显示位置」
- `X-Visit-Ip`:客户端公网 IP与地理接口返回的 `ip` 一致即可)
- `X-Visit-Location`:展示用位置文案(例如将 `geo.countryName``regionName``cityName` 拼接为 `中国 四川 成都`
**服务端回退(避免浏览器跨域导致头缺失)**:若未传 `X-Visit-Location`,后端会用 `X-Visit-Ip`;若也未传 `X-Visit-Ip`,则用连接的 `ClientIP()`(请在前置反向代理上正确传递 `X-Forwarded-For` 等,并在生产环境为 Gin 配置可信代理)。随后服务端请求 `GEO_LOOKUP_URL`(默认 `https://cf-ip-geo.smyhub.com/api?ip=<ip>`)解析展示位置并写入用户记录。
响应:
```json
{
"user": { "account": "demo", "...": "..." },
"checkIn": {
"rewardCoins": 1,
"checkedInToday": false,
"lastCheckInDate": "",
"lastCheckInAt": "",
"today": "2026-03-14"
}
}
```
> `user` 还会包含 `lastVisitAt`、`lastVisitDate`、`checkInDays`、`checkInStreak`、`visitDays`、`visitStreak` 等统计字段。
> 在登录用户本人、管理员列表等场景下,`user` 还可包含 `lastVisitIp`、`lastVisitDisplayLocation`(最近一次通过 `/api/auth/me` 上报的访问 IP 与位置文案)。**公开用户资料接口** `GET /api/public/users/:account` 与 **`POST /api/auth/verify` 的 `user` 中不包含这两项**(避免公开展示或第三方校验时令牌响应携带访问隐私)。
> 说明:密码不会返回。
若账户在登录后被封禁,持旧 JWT 调用 `GET /api/auth/me``PUT /api/auth/profile``POST /api/auth/check-in`、辅助邮箱等需登录接口时,返回 **403**,正文同登录封禁响应(`error` + 可选 `banReason`)。客户端应作废本地令牌。
### 每日签到
`POST /api/auth/check-in`
请求头:
`Authorization: Bearer <jwt-token>`
响应:
```json
{
"checkedIn": true,
"alreadyCheckedIn": false,
"rewardCoins": 1,
"awardedCoins": 1,
"message": "签到成功",
"user": { "account": "demo", "...": "..." }
}
```
### 更新当前用户资料
`PUT /api/auth/profile`
请求头:
`Authorization: Bearer <jwt-token>`
请求(字段可选):
```json
{
"password": "newpass",
"username": "新昵称",
"phone": "13800000000",
"avatarUrl": "https://example.com/avatar.png",
"websiteUrl": "https://example.com",
"bio": "### 新简介"
}
```
说明:`websiteUrl` 须为 `http`/`https` 地址;可传空字符串清除;未写协议时服务端会补全为 `https://`
响应:
```json
{
"user": { "account": "demo", "...": "..." }
}
```
## 用户广场
### 获取用户公开主页
`GET /api/public/users/{account}`
说明:
- 仅支持账户名 `account`,不支持昵称查询。
- 适合第三方应用展示用户公开资料。
- 若该账户已被封禁,返回 **404** `{"error":"user not found"}`(与不存在账户相同,避免公开资料泄露)。
- 响应中含该用户**最近一次被服务端记录的**访问 IP`lastVisitIp`)与展示用地理位置(`lastVisitDisplayLocation`,与本人中心一致);`POST /api/auth/verify` 返回的用户 JSON **不含**上述两项。
响应:
```json
{
"user": {
"account": "demo",
"username": "示例用户",
"level": 3,
"sproutCoins": 10,
"avatarUrl": "https://example.com/avatar.png",
"websiteUrl": "https://example.com",
"lastVisitIp": "203.0.113.1",
"lastVisitDisplayLocation": "中国 广东省 深圳市",
"bio": "### 简介"
}
}
```
### 公开注册策略
`GET /api/public/registration-policy`
无需鉴权。用于前端判断是否展示「邀请码」输入框。
响应:
```json
{
"requireInviteCode": false
}
```
`requireInviteCode`**true** 时,`POST /api/auth/register` 必须携带有效 `inviteCode`(见下节)。
### 注册账号(发送邮箱验证码)
`POST /api/auth/register`
请求:
```json
{
"account": "demo",
"password": "demo123",
"username": "示例用户",
"email": "demo@example.com",
"inviteCode": "ABCD1234"
}
```
- `inviteCode`:可选。若服务端开启「强制邀请码」,则必填且须为管理员发放的未过期、未用尽邀请码。邀请码**不区分大小写**;成功完成 `verify-email` 创建用户后才会扣减使用次数。
响应:
```json
{
"sent": true,
"expiresAt": "2026-03-14T12:10:00Z"
}
```
### 验证邮箱并完成注册
`POST /api/auth/verify-email`
请求:
```json
{
"account": "demo",
"code": "123456"
}
```
响应:
```json
{
"created": true,
"user": { "account": "demo", "...": "..." }
}
```
### 忘记密码(发送重置验证码)
`POST /api/auth/forgot-password`
请求:
```json
{
"account": "demo",
"email": "demo@example.com"
}
```
响应:
```json
{
"sent": true,
"expiresAt": "2026-03-14T12:10:00Z"
}
```
### 重置密码
`POST /api/auth/reset-password`
请求:
```json
{
"account": "demo",
"code": "123456",
"newPassword": "newpass"
}
```
响应:
```json
{ "reset": true }
```
### 申请添加辅助邮箱(发送验证码)
`POST /api/auth/secondary-email/request`
请求头:
`Authorization: Bearer <jwt-token>`
请求:
```json
{
"email": "demo2@example.com"
}
```
响应:
```json
{
"sent": true,
"expiresAt": "2026-03-14T12:10:00Z"
}
```
### 验证辅助邮箱
`POST /api/auth/secondary-email/verify`
请求头:
`Authorization: Bearer <jwt-token>`
请求:
```json
{
"email": "demo2@example.com",
"code": "123456"
}
```
响应:
```json
{
"verified": true,
"user": { "account": "demo", "...": "..." }
}
```
## 管理端接口(需要管理员 Token
管理员 Token 存放在 `data/config/admin.json` 中;如果文件不存在,后端启动时会自动生成并写入该文件。
请求时可使用以下任一方式携带:
- Query`?token=<admin-token>`
- Header`X-Admin-Token: <admin-token>`
### 签到奖励设置
`GET /api/admin/check-in/config`
`PUT /api/admin/check-in/config`
请求:
```json
{
"rewardCoins": 1
}
```
- Header`Authorization: Bearer <admin-token>`
### 注册策略与邀请码
`GET /api/admin/registration`
响应含 `requireInviteCode``invites` 数组(每项含 `code``note``maxUses``uses``expiresAt``createdAt`)。`maxUses` 为 0 表示不限次数。
`PUT /api/admin/registration`
请求:
```json
{ "requireInviteCode": true }
```
`POST /api/admin/registration/invites`
请求:
```json
{
"note": "内测批次",
"maxUses": 10,
"expiresAt": "2026-12-31T15:59:59Z"
}
```
`expiresAt` 可省略;须为 RFC3339。响应 `201``invite` 内含服务端生成的 8 位邀请码。
`DELETE /api/admin/registration/invites/{code}`
删除指定邀请码(`code` 与存储大小写可能不同,按不区分大小写匹配)。
### 获取用户列表
`GET /api/admin/users`
响应:
```json
{
"total": 1,
"users": [{ "account": "demo", "...": "..." }]
}
```
### 新建用户
`POST /api/admin/users`
请求:
```json
{
"account": "demo",
"password": "demo123",
"username": "示例用户",
"email": "demo@example.com",
"level": 0,
"sproutCoins": 10,
"secondaryEmails": ["demo2@example.com"],
"phone": "13800000000",
"avatarUrl": "https://example.com/avatar.png",
"websiteUrl": "https://example.com",
"bio": "### 简介"
}
```
### 更新用户
`PUT /api/admin/users/{account}`
请求(字段可选):
```json
{
"password": "newpass",
"username": "新昵称",
"level": 1,
"secondaryEmails": ["demo2@example.com"],
"sproutCoins": 99,
"websiteUrl": "https://example.com",
"banned": true,
"banReason": "违规说明(最多 500 字)"
}
```
- `banned`:是否封禁;解封时请传 `false`,并可将 `banReason` 置为空字符串。
- `banReason`:仅当用户处于封禁状态时允许设为非空;封禁时若首次写入会记录 `bannedAt`RFC3339存于用户 JSON
管理员列表 `GET /api/admin/users` 中每条 `user` 可含 `banned``banReason`(不含 `bannedAt` 亦可从存储文件中查看)。
### 删除用户
`DELETE /api/admin/users/{account}`
响应:
```json
{ "deleted": true }
```
## 数据存储说明
- 用户数据:`data/users/*.json`
- 注册待验证:`data/pending/*.json`
- 密码重置记录:`data/reset/*.json`
- 辅助邮箱验证:`data/secondary/*.json`
- 管理员 Token`data/config/admin.json`
- JWT 配置:`data/config/auth.json`
- 邮件配置:`data/config/email.json`
- 注册策略与邀请码:`data/config/registration.json`
## 快速联调用示例
```bash
# 服务根路径 JSON 说明
curl -s http://localhost:8080/ | jq .
# 登录
curl -X POST http://localhost:8080/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"account":"demo","password":"demo123"}'
# 校验令牌(推荐第三方网关先调此接口)
curl -X POST http://localhost:8080/api/auth/verify \
-H 'Content-Type: application/json' \
-d '{"token":"<jwt-token>"}'
# 使用令牌获取用户信息(会更新访问记录)
curl http://localhost:8080/api/auth/me \
-H 'Authorization: Bearer <jwt-token>'
```

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
cd mengyastore-frontend
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
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
# 前端热重载
cd mengyastore-frontend
npm install
npm run dev # http://localhost:5173
# 后端热重载(需安装 air
cd mengyastore-backend
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
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

@@ -0,0 +1,256 @@
# 萌芽小店 · 后端
基于 **Go + Gin + GORM** 构建的 RESTful API 服务,负责商品管理、订单处理、用户认证、聊天消息等核心业务。
## 技术依赖
| 包 | 版本 | 用途 |
|----|------|------|
| gin | v1.9 | HTTP 路由框架 |
| gorm | v1.31 | ORM |
| gorm/driver/mysql | v1.6 | MySQL 驱动 |
| go-sql-driver/mysql | v1.9 | 底层 MySQL 连接 |
| gin-contrib/cors | latest | CORS 中间件 |
| google/uuid | latest | UUID 生成 |
## 目录结构
```
mengyastore-backend/
├── main.go # 程序入口,路由注册
├── cmd/
│ └── migrate/
│ └── main.go # 一次性 JSON→MySQL 数据迁移脚本
├── data/
│ └── json/
│ └── settings.json # 服务配置adminToken、DSN 等)
├── internal/
│ ├── config/
│ │ └── config.go # 配置加载
│ ├── database/
│ │ ├── db.go # GORM 初始化 + AutoMigrate
│ │ └── models.go # 数据库行结构体GORM 模型)
│ ├── models/
│ │ ├── product.go # 业务模型 Product
│ │ ├── order.go # 业务模型 Order
│ │ └── chat.go # 业务模型 ChatMessage
│ ├── storage/
│ │ ├── jsonstore.go # 商品存储GORM 实现)
│ │ ├── orderstore.go # 订单存储
│ │ ├── sitestore.go # 站点设置存储
│ │ ├── wishliststore.go # 收藏夹存储
│ │ └── chatstore.go # 聊天消息存储(含内存级频率限制)
│ ├── handlers/
│ │ ├── admin.go # AdminHandler 结构体 + requireAdmin
│ │ ├── admin_product.go # 商品 CRUD 接口
│ │ ├── admin_site.go # 维护模式接口
│ │ ├── admin_orders.go # 订单管理接口
│ │ ├── admin_chat.go # 管理员聊天接口
│ │ ├── public.go # 公开接口(商品列表、浏览量)
│ │ ├── order.go # 下单、确认订单接口
│ │ ├── stats.go # 统计信息接口
│ │ ├── wishlist.go # 收藏夹接口(用户)
│ │ └── chat.go # 聊天接口(用户)
│ └── auth/
│ └── sproutgate.go # SproutGate OAuth 客户端
```
## API 路由一览
### 公开接口
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/api/health` | 健康检查 |
| GET | `/api/products` | 获取商品列表(仅 active |
| POST | `/api/products/:id/view` | 记录商品浏览量 |
| GET | `/api/stats` | 获取总订单数和总访问量 |
| POST | `/api/site/visit` | 记录站点访问 |
| GET | `/api/site/maintenance` | 获取维护状态 |
| POST | `/api/checkout` | 创建订单(生成支付二维码) |
| GET | `/api/orders` | 获取当前用户订单(需 Bearer token |
| POST | `/api/orders/:id/confirm` | 确认付款(触发发货) |
### 收藏夹(需登录)
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/api/wishlist` | 获取收藏商品 ID 列表 |
| POST | `/api/wishlist` | 添加收藏 |
| DELETE | `/api/wishlist/:id` | 取消收藏 |
### 聊天(需登录)
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/api/chat/messages` | 获取自己的聊天记录 |
| POST | `/api/chat/messages` | 发送消息1 秒频率限制) |
### 管理员接口(需 `?token=xxx` 或 `Authorization: <token>`
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/api/admin/token` | 获取令牌(用于验证) |
| GET | `/api/admin/products` | 获取全部商品(含卡密) |
| POST | `/api/admin/products` | 创建商品 |
| PUT | `/api/admin/products/:id` | 编辑商品 |
| PATCH | `/api/admin/products/:id/status` | 切换上下架 |
| DELETE | `/api/admin/products/:id` | 删除商品 |
| POST | `/api/admin/site/maintenance` | 设置维护模式 |
| GET | `/api/admin/orders` | 获取全部订单 |
| DELETE | `/api/admin/orders/:id` | 删除订单 |
| GET | `/api/admin/chat` | 获取全部用户对话 |
| GET | `/api/admin/chat/:account` | 获取指定用户对话 |
| POST | `/api/admin/chat/:account` | 管理员回复 |
| DELETE | `/api/admin/chat/:account` | 清除对话 |
## 数据库表结构
### products
| 字段 | 类型 | 说明 |
|------|------|------|
| id | varchar(36) | UUID 主键 |
| name | varchar(255) | 商品名称 |
| price | double | 原价 |
| discount_price | double | 折扣价0 = 无折扣)|
| tags | json | 标签数组 |
| cover_url | varchar(500) | 封面图 URL |
| screenshot_urls | json | 截图 URL 数组(最多 5 张)|
| verification_url | varchar(500) | 验证链接 |
| description | text | Markdown 描述 |
| active | tinyint(1) | 是否上架 |
| require_login | tinyint(1) | 是否必须登录购买 |
| max_per_account | bigint | 每账户最大购买数0=不限)|
| total_sold | bigint | 累计销量 |
| view_count | bigint | 累计浏览量 |
| delivery_mode | varchar(20) | 发货模式:`auto` / `manual` |
| show_note | tinyint(1) | 下单时显示备注输入框 |
| show_contact | tinyint(1) | 下单时显示联系方式输入框 |
| created_at | datetime(3) | 创建时间 |
### product_codes
| 字段 | 类型 | 说明 |
|------|------|------|
| id | bigint unsigned | 自增主键 |
| product_id | varchar(36) | 关联商品 ID索引|
| code | text | 卡密内容 |
### orders
| 字段 | 类型 | 说明 |
|------|------|------|
| id | varchar(36) | UUID 主键 |
| product_id | varchar(36) | 商品 ID索引|
| product_name | varchar(255) | 商品名称快照 |
| user_account | varchar(255) | 用户账号(可空,匿名)|
| user_name | varchar(255) | 用户昵称 |
| quantity | bigint | 购买数量 |
| delivered_codes | json | 已发放卡密 |
| status | varchar(20) | `pending` / `completed` |
| delivery_mode | varchar(20) | `auto` / `manual` |
| note | text | 用户备注 |
| contact_phone | varchar(50) | 联系手机号 |
| contact_email | varchar(255) | 联系邮箱 |
| created_at | datetime(3) | 下单时间 |
### site_settings
键值对存储,当前使用的键:
| Key | 说明 |
|-----|------|
| `totalVisits` | 总访问量 |
| `maintenance` | 维护模式(`true` / `false`|
| `maintenanceReason` | 维护原因文本 |
### wishlists
| 字段 | 类型 | 说明 |
|------|------|------|
| id | bigint unsigned | 自增主键 |
| account_id | varchar(255) | 用户账号(唯一索引)|
| product_id | varchar(36) | 商品 ID联合唯一|
### chat_messages
| 字段 | 类型 | 说明 |
|------|------|------|
| id | varchar(36) | UUID 主键 |
| account_id | varchar(255) | 用户账号(索引)|
| account_name | varchar(255) | 用户昵称 |
| content | text | 消息内容 |
| sent_at | datetime(3) | 发送时间 |
| from_admin | tinyint(1) | 是否来自管理员 |
## 配置文件
`data/json/settings.json`
```json
{
"adminToken": "你的管理员令牌",
"authApiUrl": "https://auth.api.shumengya.top",
"databaseDsn": ""
}
```
`databaseDsn` 为空时自动使用测试数据库。也可以通过环境变量 `DATABASE_DSN` 覆盖。
## 发货逻辑
### 自动发货(`deliveryMode = "auto"`
1. `POST /api/checkout` → 从 `product_codes` 提取指定数量的卡密
2. 商品 `quantity` 减少,卡密从数据库删除
3. 卡密保存到订单 `delivered_codes`
4. 用户 `POST /api/orders/:id/confirm` 确认付款后,订单状态变为 `completed`,响应中返回卡密内容
5. 同时调用 `IncrementSold` 增加销量统计
### 手动发货(`deliveryMode = "manual"`
1. `POST /api/checkout` → 创建订单,不提取卡密
2. 用户 `POST /api/orders/:id/confirm` 后,订单变为 `completed`,但 `delivered_codes` 为空
3. 管理员在后台查看订单的备注、手机号、邮箱后手动发货
## 本地开发
```bash
go run . # 启动服务(默认 :8080
go build -o mengyastore-backend.exe . # 构建可执行文件
go run ./cmd/migrate/main.go # 迁移旧 JSON 数据到数据库
```
### 切换数据库
```bash
# 测试库(默认)
# host: 10.1.1.100:3306 / db: mengyastore-test
# 生产库
set DATABASE_DSN=mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local
./mengyastore-backend.exe
```
## 认证说明
### 用户认证
通过 SproutGate OAuth 服务验证 Bearer Token
```go
result, err := authClient.VerifyToken(token)
// result.Valid, result.User.Account, result.User.Username
```
### 管理员认证
管理员令牌通过查询参数或 Authorization 头传入:
```
GET /api/admin/products?token=xxx
Authorization: xxx
```
令牌与 `settings.json` 中的 `adminToken` 比对。

View File

@@ -0,0 +1,304 @@
// migrate imports existing JSON data files into the MySQL database.
// Run once after switching to DB storage:
//
// go run ./cmd/migrate/main.go
package main
import (
"encoding/json"
"log"
"os"
"strconv"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"mengyastore-backend/internal/config"
"mengyastore-backend/internal/database"
)
func main() {
cfg, err := config.Load("../../config.json")
if err != nil {
log.Fatalf("load config: %v", err)
}
db, err := gorm.Open(mysql.Open(cfg.DatabaseDSN), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
log.Fatalf("open db: %v", err)
}
// Ensure tables exist
if err := db.AutoMigrate(
&database.ProductRow{},
&database.ProductCodeRow{},
&database.OrderRow{},
&database.SiteSettingRow{},
&database.WishlistRow{},
&database.ChatMessageRow{},
); err != nil {
log.Fatalf("auto migrate: %v", err)
}
log.Println("数据库连接成功,开始导入...")
migrateProducts(db)
migrateOrders(db)
migrateWishlists(db)
migrateChats(db)
migrateSite(db)
log.Println("✅ 数据导入完成!")
}
// ─── Products ─────────────────────────────────────────────────────────────────
type jsonProduct struct {
ID string `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
DiscountPrice float64 `json:"discountPrice"`
Tags []string `json:"tags"`
CoverURL string `json:"coverUrl"`
ScreenshotURLs []string `json:"screenshotUrls"`
Description string `json:"description"`
Active bool `json:"active"`
RequireLogin bool `json:"requireLogin"`
MaxPerAccount int `json:"maxPerAccount"`
TotalSold int `json:"totalSold"`
ViewCount int `json:"viewCount"`
DeliveryMode string `json:"deliveryMode"`
ShowNote bool `json:"showNote"`
ShowContact bool `json:"showContact"`
Codes []string `json:"codes"`
CreatedAt time.Time `json:"createdAt"`
}
func migrateProducts(db *gorm.DB) {
data, err := os.ReadFile("data/json/products.json")
if err != nil {
log.Printf("[products] 文件不存在,跳过: %v", err)
return
}
var products []jsonProduct
if err := json.Unmarshal(data, &products); err != nil {
log.Printf("[products] JSON 解析失败: %v", err)
return
}
for _, p := range products {
if p.ID == "" {
continue
}
if p.DeliveryMode == "" {
p.DeliveryMode = "auto"
}
row := database.ProductRow{
ID: p.ID,
Name: p.Name,
Price: p.Price,
DiscountPrice: p.DiscountPrice,
Tags: database.StringSlice(p.Tags),
CoverURL: p.CoverURL,
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
Description: p.Description,
Active: p.Active,
RequireLogin: p.RequireLogin,
MaxPerAccount: p.MaxPerAccount,
TotalSold: p.TotalSold,
ViewCount: p.ViewCount,
DeliveryMode: p.DeliveryMode,
ShowNote: p.ShowNote,
ShowContact: p.ShowContact,
CreatedAt: p.CreatedAt,
}
if row.CreatedAt.IsZero() {
row.CreatedAt = time.Now()
}
result := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row)
if result.Error != nil {
log.Printf("[products] 导入 %s 失败: %v", p.ID, result.Error)
continue
}
// Codes → product_codes
for _, code := range p.Codes {
if code == "" {
continue
}
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.ProductCodeRow{
ProductID: p.ID,
Code: code,
})
}
}
log.Printf("[products] 导入 %d 条商品", len(products))
}
// ─── Orders ───────────────────────────────────────────────────────────────────
type jsonOrder struct {
ID string `json:"id"`
ProductID string `json:"productId"`
ProductName string `json:"productName"`
UserAccount string `json:"userAccount"`
UserName string `json:"userName"`
Quantity int `json:"quantity"`
DeliveredCodes []string `json:"deliveredCodes"`
Status string `json:"status"`
DeliveryMode string `json:"deliveryMode"`
Note string `json:"note"`
ContactPhone string `json:"contactPhone"`
ContactEmail string `json:"contactEmail"`
CreatedAt time.Time `json:"createdAt"`
}
func migrateOrders(db *gorm.DB) {
data, err := os.ReadFile("data/json/orders.json")
if err != nil {
log.Printf("[orders] 文件不存在,跳过: %v", err)
return
}
var orders []jsonOrder
if err := json.Unmarshal(data, &orders); err != nil {
log.Printf("[orders] JSON 解析失败: %v", err)
return
}
for _, o := range orders {
if o.ID == "" {
continue
}
if o.DeliveryMode == "" {
o.DeliveryMode = "auto"
}
if o.DeliveredCodes == nil {
o.DeliveredCodes = []string{}
}
row := database.OrderRow{
ID: o.ID,
ProductID: o.ProductID,
ProductName: o.ProductName,
UserAccount: o.UserAccount,
UserName: o.UserName,
Quantity: o.Quantity,
DeliveredCodes: database.StringSlice(o.DeliveredCodes),
Status: o.Status,
DeliveryMode: o.DeliveryMode,
Note: o.Note,
ContactPhone: o.ContactPhone,
ContactEmail: o.ContactEmail,
CreatedAt: o.CreatedAt,
}
if row.CreatedAt.IsZero() {
row.CreatedAt = time.Now()
}
if result := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row); result.Error != nil {
log.Printf("[orders] 导入 %s 失败: %v", o.ID, result.Error)
}
}
log.Printf("[orders] 导入 %d 条订单", len(orders))
}
// ─── Wishlists ────────────────────────────────────────────────────────────────
func migrateWishlists(db *gorm.DB) {
data, err := os.ReadFile("data/json/wishlists.json")
if err != nil {
log.Printf("[wishlists] 文件不存在,跳过: %v", err)
return
}
var wl map[string][]string
if err := json.Unmarshal(data, &wl); err != nil {
log.Printf("[wishlists] JSON 解析失败: %v", err)
return
}
count := 0
for account, productIDs := range wl {
for _, pid := range productIDs {
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.WishlistRow{
AccountID: account,
ProductID: pid,
})
count++
}
}
log.Printf("[wishlists] 导入 %d 条收藏记录", count)
}
// ─── Chats ────────────────────────────────────────────────────────────────────
type jsonChatMsg struct {
ID string `json:"id"`
AccountID string `json:"accountId"`
AccountName string `json:"accountName"`
Content string `json:"content"`
SentAt time.Time `json:"sentAt"`
FromAdmin bool `json:"fromAdmin"`
}
func migrateChats(db *gorm.DB) {
data, err := os.ReadFile("data/json/chats.json")
if err != nil {
log.Printf("[chats] 文件不存在,跳过: %v", err)
return
}
var convs map[string][]jsonChatMsg
if err := json.Unmarshal(data, &convs); err != nil {
log.Printf("[chats] JSON 解析失败: %v", err)
return
}
count := 0
for _, msgs := range convs {
for _, m := range msgs {
if m.ID == "" {
continue
}
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&database.ChatMessageRow{
ID: m.ID,
AccountID: m.AccountID,
AccountName: m.AccountName,
Content: m.Content,
SentAt: m.SentAt,
FromAdmin: m.FromAdmin,
})
count++
}
}
log.Printf("[chats] 导入 %d 条聊天消息", count)
}
// ─── Site settings ────────────────────────────────────────────────────────────
type jsonSite struct {
TotalVisits int `json:"totalVisits"`
Maintenance bool `json:"maintenance"`
MaintenanceReason string `json:"maintenanceReason"`
}
func migrateSite(db *gorm.DB) {
data, err := os.ReadFile("data/json/site.json")
if err != nil {
log.Printf("[site] 文件不存在,跳过: %v", err)
return
}
var site jsonSite
if err := json.Unmarshal(data, &site); err != nil {
log.Printf("[site] JSON 解析失败: %v", err)
return
}
upsert := func(key, value string) {
db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "key"}},
DoUpdates: clause.AssignmentColumns([]string{"value"}),
}).Create(&database.SiteSettingRow{Key: key, Value: value})
}
upsert("totalVisits", strconv.Itoa(site.TotalVisits))
maintenance := "false"
if site.Maintenance {
maintenance = "true"
}
upsert("maintenance", maintenance)
upsert("maintenanceReason", site.MaintenanceReason)
log.Printf("[site] 站点设置导入完成(访问量: %d", site.TotalVisits)
}

View File

@@ -0,0 +1,17 @@
services:
backend:
build:
context: .
container_name: mengyastore-backend
ports:
- "28081:8080"
environment:
GIN_MODE: release
TZ: Asia/Shanghai
# 生产环境 MySQL DSN使用内网地址。
# 本地开发请修改为测试库地址,或通过 .env 文件覆盖。
#mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local
DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
volumes:
- ./config.json:/app/config.json:ro
restart: unless-stopped

View File

@@ -1,6 +1,6 @@
module mengyastore-backend
go 1.21
go 1.21.0
require (
github.com/gin-contrib/cors v1.7.2
@@ -9,6 +9,7 @@ require (
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
@@ -18,7 +19,10 @@ require (
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/kr/text v0.2.0 // indirect
@@ -33,7 +37,9 @@ require (
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/text v0.20.0 // indirect
google.golang.org/protobuf v1.34.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/mysql v1.6.0 // indirect
gorm.io/gorm v1.31.1 // indirect
)

View File

@@ -1,3 +1,5 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
@@ -26,6 +28,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
@@ -33,6 +37,10 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@@ -87,6 +95,8 @@ golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4=
@@ -97,5 +107,9 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

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

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

View File

@@ -0,0 +1,45 @@
package config
import (
"encoding/json"
"fmt"
"os"
)
type Config struct {
AdminToken string `json:"adminToken"`
AuthAPIURL string `json:"authApiUrl"`
// 数据库 DSN为空时回退到测试数据库。
// 格式user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local
DatabaseDSN string `json:"databaseDsn"`
}
// 各环境默认 DSN。
const (
TestDSN = "mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local"
ProdDSN = "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
)
func Load(path string) (*Config, error) {
var cfg Config
data, err := os.ReadFile(path)
if err == nil {
if jsonErr := json.Unmarshal(data, &cfg); jsonErr != nil {
return nil, fmt.Errorf("解析配置文件 %s 失败: %w", path, jsonErr)
}
}
// 文件不存在时使用默认值,环境变量在下方仍优先生效。
if cfg.AdminToken == "" {
cfg.AdminToken = "changeme"
}
// DATABASE_DSN 环境变量优先于配置文件。
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
cfg.DatabaseDSN = dsn
}
if cfg.DatabaseDSN == "" {
cfg.DatabaseDSN = TestDSN
}
return &cfg, nil
}

View File

@@ -0,0 +1,45 @@
package database
import (
"log"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Open 初始化 GORM 数据库连接并自动同步所有表结构。
func Open(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Warn),
})
if err != nil {
return nil, err
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
sqlDB.SetMaxIdleConns(5)
sqlDB.SetMaxOpenConns(20)
sqlDB.SetConnMaxLifetime(time.Hour)
if err := autoMigrate(db); err != nil {
return nil, err
}
log.Println("[DB] 数据库连接成功,表结构已同步")
return db, nil
}
func autoMigrate(db *gorm.DB) error {
return db.AutoMigrate(
&ProductRow{},
&ProductCodeRow{},
&OrderRow{},
&SiteSettingRow{},
&WishlistRow{},
&ChatMessageRow{},
)
}

View File

@@ -0,0 +1,121 @@
package database
import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
)
// StringSlice is a JSON-serialized string slice stored as a MySQL TEXT/JSON column.
type StringSlice []string
func (s StringSlice) Value() (driver.Value, error) {
if s == nil {
return "[]", nil
}
b, err := json.Marshal(s)
return string(b), err
}
func (s *StringSlice) Scan(src any) error {
var raw []byte
switch v := src.(type) {
case string:
raw = []byte(v)
case []byte:
raw = v
default:
return fmt.Errorf("StringSlice: unsupported type %T", src)
}
return json.Unmarshal(raw, s)
}
// ─── Products ────────────────────────────────────────────────────────────────
// ProductRow is the GORM model for the `products` table.
type ProductRow struct {
ID string `gorm:"primaryKey;size:36"`
Name string `gorm:"size:255;not null"`
Price float64 `gorm:"not null;default:0"`
DiscountPrice float64 `gorm:"default:0"`
Tags StringSlice `gorm:"type:json"`
CoverURL string `gorm:"size:500"`
ScreenshotURLs StringSlice `gorm:"type:json"`
VerificationURL string `gorm:"size:500;default:''"`
Description string `gorm:"type:text"`
Active bool `gorm:"default:true;index"`
RequireLogin bool `gorm:"default:false"`
MaxPerAccount int `gorm:"default:0"`
TotalSold int `gorm:"default:0"`
ViewCount int `gorm:"default:0"`
DeliveryMode string `gorm:"size:20;default:'auto'"`
ShowNote bool `gorm:"default:false"`
ShowContact bool `gorm:"default:false"`
CreatedAt time.Time `gorm:"index"`
}
func (ProductRow) TableName() string { return "products" }
// ProductCodeRow stores individual codes for a product (one row per code).
type ProductCodeRow struct {
ID uint `gorm:"primaryKey;autoIncrement"`
ProductID string `gorm:"size:36;not null;index"`
Code string `gorm:"type:text;not null"`
}
func (ProductCodeRow) TableName() string { return "product_codes" }
// ─── Orders ──────────────────────────────────────────────────────────────────
type OrderRow struct {
ID string `gorm:"primaryKey;size:36"`
ProductID string `gorm:"size:36;not null;index"`
ProductName string `gorm:"size:255;not null"`
UserAccount string `gorm:"size:255;index"`
UserName string `gorm:"size:255"`
Quantity int `gorm:"not null;default:1"`
DeliveredCodes StringSlice `gorm:"type:json"`
Status string `gorm:"size:20;not null;default:'pending';index"`
DeliveryMode string `gorm:"size:20;default:'auto'"`
Note string `gorm:"type:text"`
ContactPhone string `gorm:"size:50"`
ContactEmail string `gorm:"size:255"`
NotifyEmail string `gorm:"size:255"`
CreatedAt time.Time
}
func (OrderRow) TableName() string { return "orders" }
// ─── Site settings ───────────────────────────────────────────────────────────
// SiteSettingRow stores arbitrary key-value pairs for site-wide settings.
type SiteSettingRow struct {
Key string `gorm:"primaryKey;size:64"`
Value string `gorm:"type:text"`
}
func (SiteSettingRow) TableName() string { return "site_settings" }
// ─── Wishlists ───────────────────────────────────────────────────────────────
type WishlistRow struct {
ID uint `gorm:"primaryKey;autoIncrement"`
AccountID string `gorm:"size:255;not null;index:idx_wishlist,unique"`
ProductID string `gorm:"size:36;not null;index:idx_wishlist,unique"`
}
func (WishlistRow) TableName() string { return "wishlists" }
// ─── Chat messages ───────────────────────────────────────────────────────────
type ChatMessageRow struct {
ID string `gorm:"primaryKey;size:36"`
AccountID string `gorm:"size:255;not null;index"`
AccountName string `gorm:"size:255"`
Content string `gorm:"type:text;not null"`
SentAt time.Time `gorm:"not null"`
FromAdmin bool `gorm:"default:false"`
}
func (ChatMessageRow) TableName() string { return "chat_messages" }

View File

@@ -0,0 +1,193 @@
package email
import (
"crypto/tls"
"fmt"
"net/smtp"
"strings"
"time"
)
// Config 存储 SMTP 发件配置。
type Config struct {
SMTPHost string // 例smtp.qq.com
SMTPPort string // 例465SSL或 587STARTTLS
From string // 发件人邮箱地址
Password string // SMTP 密码或授权码
FromName string // 显示名称,例:"萌芽小店"
}
// IsConfigured 判断配置是否充足,可以尝试发送邮件。
func (c *Config) IsConfigured() bool {
return c.From != "" && c.Password != "" && c.SMTPHost != ""
}
// OrderNotifyData 包含发送订单通知邮件所需的数据。
type OrderNotifyData struct {
ToEmail string
ToName string
ProductName string
OrderID string
Quantity int
Codes []string // 手动发货时为空
IsManual bool
}
// SendOrderNotify 发送订单发货通知邮件。
// 若配置不完整或收件人为空,则静默跳过,返回 nil。
func SendOrderNotify(cfg Config, data OrderNotifyData) error {
if !cfg.IsConfigured() || data.ToEmail == "" {
return nil
}
if cfg.SMTPPort == "" {
cfg.SMTPPort = "465"
}
if cfg.SMTPHost == "" {
cfg.SMTPHost = "smtp.qq.com"
}
fromName := cfg.FromName
if fromName == "" {
fromName = "萌芽小店"
}
subject := "【萌芽小店】您的订单已发货"
if data.IsManual {
subject = "【萌芽小店】您的订单正在处理中"
}
body := buildBody(data)
msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body)
addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)
auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost)
// QQ 邮箱使用 SSL端口 465需直接 TLS 拨号。
if cfg.SMTPPort == "465" {
return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg)
}
return smtp.SendMail(addr, auth, cfg.From, []string{data.ToEmail}, []byte(msg))
}
func buildBody(data OrderNotifyData) string {
var sb strings.Builder
now := time.Now().Format("2006 年 01 月 02 日 15:04:05")
recipient := data.ToName
if recipient == "" {
recipient = "用户"
}
sb.WriteString("尊敬的 ")
sb.WriteString(recipient)
sb.WriteString("\n\n")
sb.WriteString(" 您好!感谢您在萌芽小店的支持与购买。\n\n")
sb.WriteString("────────────────────────────────\n")
sb.WriteString(" 订单信息\n")
sb.WriteString("────────────────────────────────\n")
sb.WriteString(fmt.Sprintf(" 商品名称:%s\n", data.ProductName))
sb.WriteString(fmt.Sprintf(" 订单编号:%s\n", data.OrderID))
sb.WriteString(fmt.Sprintf(" 购买数量:%d 件\n", data.Quantity))
sb.WriteString(fmt.Sprintf(" 通知时间:%s\n", now))
sb.WriteString("────────────────────────────────\n\n")
if data.IsManual {
sb.WriteString(" 您的订单已成功提交,目前正在等待人工审核与处理。\n")
sb.WriteString(" 工作人员将尽快为您安排发货,请耐心等候。\n")
sb.WriteString(" 发货完成后,我们将另行发送邮件通知。\n\n")
} else {
sb.WriteString(" 您的订单已完成自动发货,发货内容如下:\n\n")
if len(data.Codes) > 0 {
for i, code := range data.Codes {
sb.WriteString(fmt.Sprintf(" [%d] %s\n", i+1, code))
}
sb.WriteString("\n")
}
sb.WriteString(" 请妥善保管以上发货内容,切勿泄露给他人。\n\n")
}
sb.WriteString(" 如有任何疑问,请联系在线客服,我们将竭诚为您服务。\n\n")
sb.WriteString("────────────────────────────────\n")
sb.WriteString(" 此邮件由系统自动发送,请勿直接回复。\n")
sb.WriteString("────────────────────────────────\n")
return sb.String()
}
// buildMIMEMessage 构建符合 MIME 规范的邮件报文,支持 UTF-8 中文。
func buildMIMEMessage(from, fromName, to, subject, body string) string {
encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName))
encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject))
return fmt.Sprintf(
"From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s",
encodedFromName, from, to, encodedSubject, encodeBase64(body),
)
}
func encodeBase64(s string) string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
b := []byte(s)
var buf strings.Builder
for i := 0; i < len(b); i += 3 {
remaining := len(b) - i
b0 := b[i]
b1 := byte(0)
b2 := byte(0)
if remaining > 1 {
b1 = b[i+1]
}
if remaining > 2 {
b2 = b[i+2]
}
buf.WriteByte(chars[b0>>2])
buf.WriteByte(chars[((b0&0x03)<<4)|(b1>>4)])
if remaining > 1 {
buf.WriteByte(chars[((b1&0x0f)<<2)|(b2>>6)])
} else {
buf.WriteByte('=')
}
if remaining > 2 {
buf.WriteByte(chars[b2&0x3f])
} else {
buf.WriteByte('=')
}
}
return buf.String()
}
// sendSSL 通过 TLS 直接拨号发送邮件(适用于 465 端口 SSL 连接,如 QQ 邮箱)。
func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error {
tlsConfig := &tls.Config{
ServerName: host,
MinVersion: tls.VersionTLS12,
}
conn, err := tls.Dial("tcp", addr, tlsConfig)
if err != nil {
return fmt.Errorf("tls 拨号失败: %w", err)
}
defer conn.Close()
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("创建 SMTP 客户端失败: %w", err)
}
defer client.Quit() //nolint:errcheck
if err = client.Auth(auth); err != nil {
return fmt.Errorf("SMTP 认证失败: %w", err)
}
if err = client.Mail(from); err != nil {
return fmt.Errorf("SMTP MAIL FROM 失败: %w", err)
}
if err = client.Rcpt(to); err != nil {
return fmt.Errorf("SMTP RCPT TO 失败: %w", err)
}
w, err := client.Data()
if err != nil {
return fmt.Errorf("SMTP DATA 失败: %w", err)
}
if _, err = fmt.Fprint(w, msg); err != nil {
return fmt.Errorf("写入邮件内容失败: %w", err)
}
return w.Close()
}

View File

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

View File

@@ -0,0 +1,88 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// GetAllConversations 返回所有用户会话列表。
func (h *AdminHandler) GetAllConversations(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
convs, err := h.chatStore.ListConversations()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
}
// GetConversation 返回指定账号的全部消息记录。
func (h *AdminHandler) GetConversation(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
accountID := c.Param("account")
if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
return
}
msgs, err := h.chatStore.GetMessages(accountID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
}
type adminChatPayload struct {
Content string `json:"content"`
}
// AdminReply 向指定用户发送管理员回复。
func (h *AdminHandler) AdminReply(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
accountID := c.Param("account")
if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
return
}
var payload adminChatPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
content := strings.TrimSpace(payload.Content)
if content == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
return
}
msg, err := h.chatStore.SendAdminMessage(accountID, content)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
}
// ClearConversation 清除与指定用户的全部消息记录。
func (h *AdminHandler) ClearConversation(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
accountID := c.Param("account")
if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少账号参数"})
return
}
if err := h.chatStore.ClearConversation(accountID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
}

View File

@@ -0,0 +1,35 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func (h *AdminHandler) ListAllOrders(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
orders, err := h.orderStore.ListAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": orders})
}
func (h *AdminHandler) DeleteOrder(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
orderID := c.Param("id")
if orderID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少订单 ID"})
return
}
if err := h.orderStore.Delete(orderID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
}

View File

@@ -6,16 +6,9 @@ import (
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/config"
"mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage"
)
type AdminHandler struct {
store *storage.JSONStore
cfg *config.Config
}
type productPayload struct {
Name string `json:"name"`
Price float64 `json:"price"`
@@ -26,18 +19,27 @@ type productPayload struct {
ScreenshotURLs []string `json:"screenshotUrls"`
Description string `json:"description"`
Active *bool `json:"active"`
RequireLogin bool `json:"requireLogin"`
MaxPerAccount int `json:"maxPerAccount"`
DeliveryMode string `json:"deliveryMode"`
ShowNote bool `json:"showNote"`
ShowContact bool `json:"showContact"`
}
type togglePayload struct {
Active bool `json:"active"`
}
func NewAdminHandler(store *storage.JSONStore, cfg *config.Config) *AdminHandler {
return &AdminHandler{store: store, cfg: cfg}
}
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"token": h.cfg.AdminToken})
// VerifyAdminToken 验证管理员令牌是否正确,返回 {"valid": true/false},不暴露实际令牌值。
func (h *AdminHandler) VerifyAdminToken(c *gin.Context) {
var payload struct {
Token string `json:"token"`
}
if err := c.ShouldBindJSON(&payload); err != nil || payload.Token == "" {
c.JSON(http.StatusOK, gin.H{"valid": false})
return
}
c.JSON(http.StatusOK, gin.H{"valid": payload.Token == h.cfg.AdminToken})
}
func (h *AdminHandler) ListAllProducts(c *gin.Context) {
@@ -58,12 +60,12 @@ func (h *AdminHandler) CreateProduct(c *gin.Context) {
}
var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
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
}
active := true
@@ -80,6 +82,11 @@ func (h *AdminHandler) CreateProduct(c *gin.Context) {
ScreenshotURLs: screenshotURLs,
Description: payload.Description,
Active: active,
RequireLogin: payload.RequireLogin,
MaxPerAccount: payload.MaxPerAccount,
DeliveryMode: payload.DeliveryMode,
ShowNote: payload.ShowNote,
ShowContact: payload.ShowContact,
}
created, err := h.store.Create(product)
if err != nil {
@@ -96,12 +103,12 @@ func (h *AdminHandler) UpdateProduct(c *gin.Context) {
id := c.Param("id")
var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
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
}
active := false
@@ -118,6 +125,11 @@ func (h *AdminHandler) UpdateProduct(c *gin.Context) {
ScreenshotURLs: screenshotURLs,
Description: payload.Description,
Active: active,
RequireLogin: payload.RequireLogin,
MaxPerAccount: payload.MaxPerAccount,
DeliveryMode: payload.DeliveryMode,
ShowNote: payload.ShowNote,
ShowContact: payload.ShowContact,
}
updated, err := h.store.Update(id, patch)
if err != nil {
@@ -134,7 +146,7 @@ func (h *AdminHandler) ToggleProduct(c *gin.Context) {
id := c.Param("id")
var payload togglePayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
updated, err := h.store.Toggle(id, payload.Active)
@@ -154,19 +166,7 @@ func (h *AdminHandler) DeleteProduct(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
token := c.Query("token")
if token == "" {
token = c.GetHeader("Authorization")
}
if token == h.cfg.AdminToken {
return true
}
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return false
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
}
func normalizeScreenshotURLs(urls []string) ([]string, bool) {

View File

@@ -0,0 +1,73 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/storage"
)
type maintenancePayload struct {
Maintenance bool `json:"maintenance"`
Reason string `json:"reason"`
}
func (h *AdminHandler) SetMaintenance(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
var payload maintenancePayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"maintenance": payload.Maintenance,
"reason": payload.Reason,
},
})
}
func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
cfg, err := h.siteStore.GetSMTPConfig()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// 响应中对密码脱敏处理
masked := cfg
if masked.Password != "" {
masked.Password = "••••••••"
}
c.JSON(http.StatusOK, gin.H{"data": masked})
}
func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
var payload storage.SMTPConfig
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
// 若密码为脱敏占位符,则保留数据库中原有的密码
if payload.Password == "••••••••" {
existing, _ := h.siteStore.GetSMTPConfig()
payload.Password = existing.Password
}
if err := h.siteStore.SetSMTPConfig(payload); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": "ok"})
}

View File

@@ -0,0 +1,82 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/storage"
)
type ChatHandler struct {
chatStore *storage.ChatStore
authClient *auth.SproutGateClient
}
func NewChatHandler(chatStore *storage.ChatStore, authClient *auth.SproutGateClient) *ChatHandler {
return &ChatHandler{chatStore: chatStore, authClient: authClient}
}
func (h *ChatHandler) requireChatUser(c *gin.Context) (account, name string, ok bool) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return "", "", false
}
token := strings.TrimPrefix(authHeader, "Bearer ")
result, err := h.authClient.VerifyToken(token)
if err != nil || !result.Valid || result.User == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
return "", "", false
}
return result.User.Account, result.User.Username, true
}
// GetMyMessages 返回当前登录用户的全部聊天消息。
func (h *ChatHandler) GetMyMessages(c *gin.Context) {
account, _, ok := h.requireChatUser(c)
if !ok {
return
}
msgs, err := h.chatStore.GetMessages(account)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
}
type chatMessagePayload struct {
Content string `json:"content"`
}
// SendMyMessage 向管理员发送一条用户消息。
func (h *ChatHandler) SendMyMessage(c *gin.Context) {
account, name, ok := h.requireChatUser(c)
if !ok {
return
}
var payload chatMessagePayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
content := strings.TrimSpace(payload.Content)
if content == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
return
}
msg, rateLimited, err := h.chatStore.SendUserMessage(account, name, content)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if rateLimited {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "发送太频繁,请稍候"})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
}

View File

@@ -0,0 +1,295 @@
package handlers
import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/email"
"mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage"
)
const qrSize = "320x320"
type OrderHandler struct {
productStore *storage.ProductStore
orderStore *storage.OrderStore
siteStore *storage.SiteStore
authClient *auth.SproutGateClient
}
type checkoutPayload struct {
ProductID string `json:"productId"`
Quantity int `json:"quantity"`
Note string `json:"note"`
ContactPhone string `json:"contactPhone"`
ContactEmail string `json:"contactEmail"`
NotifyEmail string `json:"notifyEmail"`
}
func NewOrderHandler(productStore *storage.ProductStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
}
func (h *OrderHandler) sendOrderNotify(toEmail, toName, productName, orderID string, qty int, codes []string, isManual bool) {
if toEmail == "" {
return
}
cfg, err := h.siteStore.GetSMTPConfig()
if err != nil || !cfg.IsConfiguredEmail() {
return
}
go func() {
emailCfg := email.Config{
SMTPHost: cfg.Host,
SMTPPort: cfg.Port,
From: cfg.Email,
Password: cfg.Password,
FromName: cfg.FromName,
}
if err := email.SendOrderNotify(emailCfg, email.OrderNotifyData{
ToEmail: toEmail,
ToName: toName,
ProductName: productName,
OrderID: orderID,
Quantity: qty,
Codes: codes,
IsManual: isManual,
}); err != nil {
log.Printf("[Email] 发送通知失败 order=%s to=%s: %v", orderID, toEmail, err)
} else {
log.Printf("[Email] 发送通知成功 order=%s to=%s", orderID, toEmail)
}
}()
}
func (h *OrderHandler) tryExtractUserWithEmail(c *gin.Context) (account, username, userEmail string) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
return "", "", ""
}
userToken := strings.TrimPrefix(authHeader, "Bearer ")
result, err := h.authClient.VerifyToken(userToken)
if err != nil || !result.Valid || result.User == nil {
return "", "", ""
}
return result.User.Account, result.User.Username, result.User.Email
}
func (h *OrderHandler) CreateOrder(c *gin.Context) {
userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
var payload checkoutPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
payload.ProductID = strings.TrimSpace(payload.ProductID)
if payload.ProductID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必填字段"})
return
}
if payload.Quantity <= 0 {
payload.Quantity = 1
}
product, err := h.productStore.GetByID(payload.ProductID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
if !product.Active {
c.JSON(http.StatusBadRequest, gin.H{"error": "商品暂时无法购买"})
return
}
if product.RequireLogin && userAccount == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "该商品需要登录后才能购买"})
return
}
if product.MaxPerAccount > 0 && userAccount != "" {
purchased, err := h.orderStore.CountPurchasedByAccount(userAccount, product.ID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if purchased+payload.Quantity > product.MaxPerAccount {
remain := product.MaxPerAccount - purchased
if remain <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您已达上限", product.MaxPerAccount)})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("每个账户最多购买 %d 个,您还可购买 %d 个", product.MaxPerAccount, remain)})
}
return
}
}
if product.Quantity < payload.Quantity {
c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"})
return
}
isManual := product.DeliveryMode == "manual"
var deliveredCodes []string
var updatedProduct models.Product
if isManual {
updatedProduct = product
} else {
var ok bool
deliveredCodes, ok = extractCodes(&product, payload.Quantity)
if !ok {
c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"})
return
}
product.Quantity = len(product.Codes)
updatedProduct, err = h.productStore.Update(product.ID, product)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
}
deliveryMode := product.DeliveryMode
if deliveryMode == "" {
deliveryMode = "auto"
}
// 通知邮箱优先级:
// 1. SproutGate 账号邮箱(已登录用户,最可靠)
// 2. 前端传入的 notifyEmail来自 authState.email
// 3. 用户在结账表单填写的联系邮箱
// 4. 均为空则不发送
notifyEmail := strings.TrimSpace(userEmail)
if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
}
if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.ContactEmail)
}
// 自动发货订单立即设为已完成(卡密已提取);手动发货订单初始状态为待处理,由管理员确认。
orderStatus := "pending"
if !isManual {
orderStatus = "completed"
}
order := models.Order{
ProductID: updatedProduct.ID,
ProductName: updatedProduct.Name,
UserAccount: userAccount,
UserName: userName,
Quantity: payload.Quantity,
DeliveredCodes: deliveredCodes,
Status: orderStatus,
DeliveryMode: deliveryMode,
Note: strings.TrimSpace(payload.Note),
ContactPhone: strings.TrimSpace(payload.ContactPhone),
ContactEmail: strings.TrimSpace(payload.ContactEmail),
NotifyEmail: notifyEmail,
}
created, err := h.orderStore.Create(order)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !isManual {
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
}
// 自动发货:立即发送卡密通知邮件
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
} else {
// 手动发货:告知用户订单已收到,等待发货
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true)
}
qrPayload := fmt.Sprintf("order:%s:%s", created.ID, created.ProductID)
qrURL := fmt.Sprintf("https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s", qrSize, url.QueryEscape(qrPayload))
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"orderId": created.ID,
"qrCodeUrl": qrURL,
"productId": created.ProductID,
"productQty": created.Quantity,
"viewCount": updatedProduct.ViewCount,
"status": created.Status,
},
})
}
func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
orderID := c.Param("id")
order, err := h.orderStore.Confirm(orderID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
isManual := order.DeliveryMode == "manual"
// 手动发货确认后,发送"已发货"通知邮件
if isManual {
confirmNotifyEmail := order.NotifyEmail
if confirmNotifyEmail == "" {
confirmNotifyEmail = order.ContactEmail
}
h.sendOrderNotify(confirmNotifyEmail, order.UserName, order.ProductName, order.ID, order.Quantity, order.DeliveredCodes, false)
}
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"orderId": order.ID,
"status": order.Status,
"deliveryMode": order.DeliveryMode,
"deliveredCodes": order.DeliveredCodes,
"isManual": isManual,
},
})
}
func (h *OrderHandler) ListMyOrders(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
userToken := strings.TrimPrefix(authHeader, "Bearer ")
result, err := h.authClient.VerifyToken(userToken)
if err != nil || !result.Valid || result.User == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
return
}
orders, err := h.orderStore.ListByAccount(result.User.Account)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": orders})
}
func extractCodes(product *models.Product, count int) ([]string, bool) {
if count <= 0 {
return nil, false
}
if len(product.Codes) < count {
return nil, false
}
delivered := make([]string, count)
copy(delivered, product.Codes[:count])
product.Codes = product.Codes[count:]
return delivered, true
}

View File

@@ -11,10 +11,10 @@ import (
)
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}
}
@@ -59,3 +59,4 @@ func sanitizeForPublic(items []models.Product) []models.Product {
}
return out
}

View File

@@ -50,3 +50,17 @@ func (h *StatsHandler) RecordVisit(c *gin.Context) {
},
})
}
func (h *StatsHandler) GetMaintenance(c *gin.Context) {
enabled, reason, err := h.siteStore.GetMaintenance()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"maintenance": enabled,
"reason": reason,
},
})
}

View File

@@ -0,0 +1,88 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/storage"
)
type WishlistHandler struct {
wishlistStore *storage.WishlistStore
authClient *auth.SproutGateClient
}
func NewWishlistHandler(wishlistStore *storage.WishlistStore, authClient *auth.SproutGateClient) *WishlistHandler {
return &WishlistHandler{wishlistStore: wishlistStore, authClient: authClient}
}
func (h *WishlistHandler) requireUser(c *gin.Context) (string, bool) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return "", false
}
token := strings.TrimPrefix(authHeader, "Bearer ")
result, err := h.authClient.VerifyToken(token)
if err != nil || !result.Valid || result.User == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
return "", false
}
return result.User.Account, true
}
func (h *WishlistHandler) GetWishlist(c *gin.Context) {
account, ok := h.requireUser(c)
if !ok {
return
}
ids, err := h.wishlistStore.Get(account)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}
type wishlistItemPayload struct {
ProductID string `json:"productId"`
}
func (h *WishlistHandler) AddToWishlist(c *gin.Context) {
account, ok := h.requireUser(c)
if !ok {
return
}
var payload wishlistItemPayload
if err := c.ShouldBindJSON(&payload); err != nil || payload.ProductID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
return
}
if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ids, _ := h.wishlistStore.Get(account)
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}
func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
account, ok := h.requireUser(c)
if !ok {
return
}
productID := c.Param("id")
if productID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少商品 ID"})
return
}
if err := h.wishlistStore.Remove(account, productID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ids, _ := h.wishlistStore.Get(account)
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}

View File

@@ -0,0 +1,12 @@
package models
import "time"
type ChatMessage struct {
ID string `json:"id"`
AccountID string `json:"accountId"`
AccountName string `json:"accountName"`
Content string `json:"content"`
SentAt time.Time `json:"sentAt"`
FromAdmin bool `json:"fromAdmin"`
}

View File

@@ -11,5 +11,10 @@ type Order struct {
Quantity int `json:"quantity"`
DeliveredCodes []string `json:"deliveredCodes"`
Status string `json:"status"`
DeliveryMode string `json:"deliveryMode"`
Note string `json:"note"`
ContactPhone string `json:"contactPhone"`
ContactEmail string `json:"contactEmail"`
NotifyEmail string `json:"notifyEmail"`
CreatedAt time.Time `json:"createdAt"`
}

View File

@@ -16,6 +16,12 @@ type Product struct {
ViewCount int `json:"viewCount"`
Description string `json:"description"`
Active bool `json:"active"`
RequireLogin bool `json:"requireLogin"`
MaxPerAccount int `json:"maxPerAccount"`
TotalSold int `json:"totalSold"`
DeliveryMode string `json:"deliveryMode"`
ShowNote bool `json:"showNote"`
ShowContact bool `json:"showContact"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}

View File

@@ -0,0 +1,99 @@
package storage
import (
"sync"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models"
)
type ChatStore struct {
db *gorm.DB
mu sync.Mutex
lastSent map[string]time.Time
}
func NewChatStore(db *gorm.DB) (*ChatStore, error) {
return &ChatStore{db: db, lastSent: make(map[string]time.Time)}, nil
}
func chatRowToModel(row database.ChatMessageRow) models.ChatMessage {
return models.ChatMessage{
ID: row.ID,
AccountID: row.AccountID,
AccountName: row.AccountName,
Content: row.Content,
SentAt: row.SentAt,
FromAdmin: row.FromAdmin,
}
}
func (s *ChatStore) GetMessages(accountID string) ([]models.ChatMessage, error) {
var rows []database.ChatMessageRow
if err := s.db.Where("account_id = ?", accountID).Order("sent_at ASC").Find(&rows).Error; err != nil {
return nil, err
}
msgs := make([]models.ChatMessage, len(rows))
for i, r := range rows {
msgs[i] = chatRowToModel(r)
}
return msgs, nil
}
func (s *ChatStore) ListConversations() (map[string][]models.ChatMessage, error) {
var rows []database.ChatMessageRow
if err := s.db.Order("account_id, sent_at ASC").Find(&rows).Error; err != nil {
return nil, err
}
result := make(map[string][]models.ChatMessage)
for _, r := range rows {
result[r.AccountID] = append(result[r.AccountID], chatRowToModel(r))
}
return result, nil
}
func (s *ChatStore) SendUserMessage(accountID, accountName, content string) (models.ChatMessage, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
if last, ok := s.lastSent[accountID]; ok && time.Since(last) < time.Second {
return models.ChatMessage{}, true, nil
}
s.lastSent[accountID] = time.Now()
row := database.ChatMessageRow{
ID: uuid.New().String(),
AccountID: accountID,
AccountName: accountName,
Content: content,
SentAt: time.Now(),
FromAdmin: false,
}
if err := s.db.Create(&row).Error; err != nil {
return models.ChatMessage{}, false, err
}
return chatRowToModel(row), false, nil
}
func (s *ChatStore) SendAdminMessage(accountID, content string) (models.ChatMessage, error) {
row := database.ChatMessageRow{
ID: uuid.New().String(),
AccountID: accountID,
AccountName: "管理员",
Content: content,
SentAt: time.Now(),
FromAdmin: true,
}
if err := s.db.Create(&row).Error; err != nil {
return models.ChatMessage{}, err
}
return chatRowToModel(row), nil
}
func (s *ChatStore) ClearConversation(accountID string) error {
return s.db.Where("account_id = ?", accountID).Delete(&database.ChatMessageRow{}).Error
}

View File

@@ -0,0 +1,140 @@
package storage
import (
"fmt"
"github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models"
)
type OrderStore struct {
db *gorm.DB
}
func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
return &OrderStore{db: db}, nil
}
func orderRowToModel(row database.OrderRow) models.Order {
return models.Order{
ID: row.ID,
ProductID: row.ProductID,
ProductName: row.ProductName,
UserAccount: row.UserAccount,
UserName: row.UserName,
Quantity: row.Quantity,
DeliveredCodes: row.DeliveredCodes,
Status: row.Status,
DeliveryMode: row.DeliveryMode,
Note: row.Note,
ContactPhone: row.ContactPhone,
ContactEmail: row.ContactEmail,
NotifyEmail: row.NotifyEmail,
CreatedAt: row.CreatedAt,
}
}
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
if order.ID == "" {
order.ID = uuid.NewString()
}
if len(order.DeliveredCodes) == 0 {
order.DeliveredCodes = []string{}
}
row := database.OrderRow{
ID: order.ID,
ProductID: order.ProductID,
ProductName: order.ProductName,
UserAccount: order.UserAccount,
UserName: order.UserName,
Quantity: order.Quantity,
DeliveredCodes: database.StringSlice(order.DeliveredCodes),
Status: order.Status,
DeliveryMode: order.DeliveryMode,
Note: order.Note,
ContactPhone: order.ContactPhone,
ContactEmail: order.ContactEmail,
NotifyEmail: order.NotifyEmail,
}
if err := s.db.Create(&row).Error; err != nil {
return models.Order{}, err
}
order.CreatedAt = row.CreatedAt
return order, nil
}
func (s *OrderStore) GetByID(id string) (models.Order, error) {
var row database.OrderRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Order{}, fmt.Errorf("order not found")
}
return orderRowToModel(row), nil
}
func (s *OrderStore) Confirm(id string) (models.Order, error) {
var row database.OrderRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Order{}, fmt.Errorf("order not found")
}
if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
return models.Order{}, err
}
row.Status = "completed"
return orderRowToModel(row), nil
}
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
var rows []database.OrderRow
if err := s.db.Where("user_account = ?", account).Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
orders := make([]models.Order, len(rows))
for i, r := range rows {
orders[i] = orderRowToModel(r)
}
return orders, nil
}
func (s *OrderStore) ListAll() ([]models.Order, error) {
var rows []database.OrderRow
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
orders := make([]models.Order, len(rows))
for i, r := range rows {
orders[i] = orderRowToModel(r)
}
return orders, nil
}
func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) {
var total int64
// 统计 pending手动待发货和 completed 两种状态,防止用户快速下单绕过购买数量限制。
err := s.db.Model(&database.OrderRow{}).
Where("user_account = ? AND product_id = ? AND status IN ?", account, productID, []string{"pending", "completed"}).
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
return int(total), err
}
// Count 返回所有订单的总数量。
func (s *OrderStore) Count() (int, error) {
var count int64
if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil {
return 0, err
}
return int(count), nil
}
// Delete 根据 ID 删除单条订单。
func (s *OrderStore) Delete(id string) error {
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
}
// UpdateCodes 更新订单的已发货卡密列表。
func (s *OrderStore) UpdateCodes(id string, codes []string) error {
return s.db.Model(&database.OrderRow{}).Where("id = ?", id).
Update("delivered_codes", database.StringSlice(codes)).Error
}

View File

@@ -0,0 +1,328 @@
package storage
import (
"crypto/sha256"
"fmt"
"strings"
"sync"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models"
)
const defaultCoverURL = "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png"
const viewCooldown = 6 * time.Hour
const maxScreenshotURLs = 5
type ProductStore struct {
db *gorm.DB
mu sync.Mutex
recentViews map[string]time.Time
}
func NewProductStore(db *gorm.DB) (*ProductStore, error) {
return &ProductStore{
db: db,
recentViews: make(map[string]time.Time),
}, nil
}
// rowToModel 将数据库行(含卡密)转换为业务模型。
func rowToModel(row database.ProductRow, codes []string) models.Product {
return models.Product{
ID: row.ID,
Name: row.Name,
Price: row.Price,
DiscountPrice: row.DiscountPrice,
Tags: row.Tags,
CoverURL: row.CoverURL,
ScreenshotURLs: row.ScreenshotURLs,
VerificationURL: row.VerificationURL,
Description: row.Description,
Active: row.Active,
RequireLogin: row.RequireLogin,
MaxPerAccount: row.MaxPerAccount,
TotalSold: row.TotalSold,
ViewCount: row.ViewCount,
DeliveryMode: row.DeliveryMode,
ShowNote: row.ShowNote,
ShowContact: row.ShowContact,
Codes: codes,
Quantity: len(codes),
CreatedAt: row.CreatedAt,
}
}
func (s *ProductStore) loadCodes(productID string) ([]string, error) {
var rows []database.ProductCodeRow
if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil {
return nil, err
}
codes := make([]string, len(rows))
for i, r := range rows {
codes[i] = r.Code
}
return codes, nil
}
func (s *ProductStore) replaceCodes(productID string, codes []string) error {
if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil {
return err
}
if len(codes) == 0 {
return nil
}
rows := make([]database.ProductCodeRow, 0, len(codes))
for _, code := range codes {
rows = append(rows, database.ProductCodeRow{ProductID: productID, Code: code})
}
return s.db.CreateInBatches(rows, 100).Error
}
func (s *ProductStore) ListAll() ([]models.Product, error) {
var rows []database.ProductRow
if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
products := make([]models.Product, 0, len(rows))
for _, row := range rows {
codes, _ := s.loadCodes(row.ID)
products = append(products, rowToModel(row, codes))
}
return products, nil
}
func (s *ProductStore) ListActive() ([]models.Product, error) {
var rows []database.ProductRow
if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
products := make([]models.Product, 0, len(rows))
for _, row := range rows {
// 公开接口不暴露卡密,但需要统计剩余库存数量
var count int64
s.db.Model(&database.ProductCodeRow{}).Where("product_id = ?", row.ID).Count(&count)
row.Active = true
p := rowToModel(row, nil)
p.Quantity = int(count)
p.Codes = nil
products = append(products, p)
}
return products, nil
}
func (s *ProductStore) GetByID(id string) (models.Product, error) {
var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Product{}, fmt.Errorf("product not found")
}
codes, _ := s.loadCodes(id)
return rowToModel(row, codes), nil
}
func (s *ProductStore) Create(p models.Product) (models.Product, error) {
p = normalizeProduct(p)
p.ID = uuid.NewString()
now := time.Now()
p.CreatedAt = now
row := database.ProductRow{
ID: p.ID,
Name: p.Name,
Price: p.Price,
DiscountPrice: p.DiscountPrice,
Tags: database.StringSlice(p.Tags),
CoverURL: p.CoverURL,
ScreenshotURLs: database.StringSlice(p.ScreenshotURLs),
VerificationURL: p.VerificationURL,
Description: p.Description,
Active: p.Active,
RequireLogin: p.RequireLogin,
MaxPerAccount: p.MaxPerAccount,
TotalSold: p.TotalSold,
ViewCount: p.ViewCount,
DeliveryMode: p.DeliveryMode,
ShowNote: p.ShowNote,
ShowContact: p.ShowContact,
CreatedAt: now,
}
if err := s.db.Create(&row).Error; err != nil {
return models.Product{}, err
}
if err := s.replaceCodes(p.ID, p.Codes); err != nil {
return models.Product{}, err
}
p.Quantity = len(p.Codes)
return p, nil
}
func (s *ProductStore) Update(id string, patch models.Product) (models.Product, error) {
var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Product{}, fmt.Errorf("product not found")
}
normalized := normalizeProduct(patch)
if err := s.db.Model(&row).Updates(map[string]interface{}{
"name": normalized.Name,
"price": normalized.Price,
"discount_price": normalized.DiscountPrice,
"tags": database.StringSlice(normalized.Tags),
"cover_url": normalized.CoverURL,
"screenshot_urls": database.StringSlice(normalized.ScreenshotURLs),
"verification_url": normalized.VerificationURL,
"description": normalized.Description,
"active": normalized.Active,
"require_login": normalized.RequireLogin,
"max_per_account": normalized.MaxPerAccount,
"delivery_mode": normalized.DeliveryMode,
"show_note": normalized.ShowNote,
"show_contact": normalized.ShowContact,
}).Error; err != nil {
return models.Product{}, err
}
if err := s.replaceCodes(id, normalized.Codes); err != nil {
return models.Product{}, err
}
var updated database.ProductRow
s.db.First(&updated, "id = ?", id)
codes, _ := s.loadCodes(id)
return rowToModel(updated, codes), nil
}
func (s *ProductStore) Toggle(id string, active bool) (models.Product, error) {
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
return models.Product{}, err
}
var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Product{}, fmt.Errorf("product not found")
}
codes, _ := s.loadCodes(id)
return rowToModel(row, codes), nil
}
func (s *ProductStore) IncrementSold(id string, count int) error {
return s.db.Model(&database.ProductRow{}).Where("id = ?", id).
UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error
}
func (s *ProductStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
s.cleanupRecentViews(now)
key := buildViewKey(id, fingerprint)
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Product{}, false, fmt.Errorf("product not found")
}
return rowToModel(row, nil), false, nil
}
if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).
UpdateColumn("view_count", gorm.Expr("view_count + 1")).Error; err != nil {
return models.Product{}, false, err
}
s.recentViews[key] = now
var row database.ProductRow
if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return models.Product{}, false, fmt.Errorf("product not found")
}
return rowToModel(row, nil), true, nil
}
func (s *ProductStore) Delete(id string) error {
if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
return err
}
return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
}
// normalizeProduct 对商品字段进行规范化处理(清理空白、设默认值等)。
func normalizeProduct(item models.Product) models.Product {
item.CoverURL = strings.TrimSpace(item.CoverURL)
if item.CoverURL == "" {
item.CoverURL = defaultCoverURL
}
if item.Tags == nil {
item.Tags = []string{}
}
item.Tags = sanitizeTags(item.Tags)
if item.ScreenshotURLs == nil {
item.ScreenshotURLs = []string{}
}
if len(item.ScreenshotURLs) > maxScreenshotURLs {
item.ScreenshotURLs = item.ScreenshotURLs[:maxScreenshotURLs]
}
if item.Codes == nil {
item.Codes = []string{}
}
if item.DiscountPrice <= 0 || item.DiscountPrice >= item.Price {
item.DiscountPrice = 0
}
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
item.Codes = sanitizeCodes(item.Codes)
item.Quantity = len(item.Codes)
if item.DeliveryMode == "" {
item.DeliveryMode = "auto"
}
return item
}
func sanitizeCodes(codes []string) []string {
clean := make([]string, 0, len(codes))
seen := map[string]bool{}
for _, code := range codes {
trimmed := strings.TrimSpace(code)
if trimmed == "" || seen[trimmed] {
continue
}
seen[trimmed] = true
clean = append(clean, trimmed)
}
return clean
}
func sanitizeTags(tags []string) []string {
clean := make([]string, 0, len(tags))
seen := map[string]bool{}
for _, tag := range tags {
t := strings.TrimSpace(tag)
if t == "" {
continue
}
key := strings.ToLower(t)
if seen[key] {
continue
}
seen[key] = true
clean = append(clean, t)
if len(clean) >= 20 {
break
}
}
return clean
}
func buildViewKey(id, fingerprint string) string {
sum := sha256.Sum256([]byte(id + "|" + fingerprint))
return fmt.Sprintf("%x", sum)
}
func (s *ProductStore) cleanupRecentViews(now time.Time) {
for key, lastViewedAt := range s.recentViews {
if now.Sub(lastViewedAt) >= viewCooldown {
delete(s.recentViews, key)
}
}
}

View File

@@ -0,0 +1,146 @@
package storage
import (
"strconv"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"mengyastore-backend/internal/database"
)
type SiteStore struct {
db *gorm.DB
}
func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
return &SiteStore{db: db}, nil
}
func (s *SiteStore) get(key string) (string, error) {
var row database.SiteSettingRow
// `key` 是 MySQL 保留字,需用反引号转义以避免 SQL 语法错误。
if err := s.db.Where("`key` = ?", key).First(&row).Error; err != nil {
return "", nil // 键不存在时返回零值
}
return row.Value, nil
}
func (s *SiteStore) set(key, value string) error {
return s.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "key"}},
DoUpdates: clause.AssignmentColumns([]string{"value"}),
}).Create(&database.SiteSettingRow{Key: key, Value: value}).Error
}
func (s *SiteStore) GetTotalVisits() (int, error) {
v, err := s.get("totalVisits")
if err != nil || v == "" {
return 0, err
}
n, _ := strconv.Atoi(v)
return n, nil
}
func (s *SiteStore) IncrementVisits() (int, error) {
current, err := s.GetTotalVisits()
if err != nil {
return 0, err
}
current++
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
return 0, err
}
return current, nil
}
func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
v, err := s.get("maintenance")
if err != nil {
return false, "", err
}
enabled = v == "true"
reason, err = s.get("maintenanceReason")
return enabled, reason, err
}
func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
v := "false"
if enabled {
v = "true"
}
if err := s.set("maintenance", v); err != nil {
return err
}
return s.set("maintenanceReason", reason)
}
// RecordVisit 递增访问计数,返回 (总访问量, 是否计入, 错误)。
// 去重逻辑由上层 handler 的内存指纹完成,此处无条件累加。
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
total, err := s.IncrementVisits()
return total, true, err
}
// SMTPConfig 存储数据库中的发件 SMTP 配置。
type SMTPConfig struct {
Enabled bool `json:"enabled"`
Email string `json:"email"`
Password string `json:"password"`
FromName string `json:"fromName"`
Host string `json:"host"`
Port string `json:"port"`
}
// IsConfiguredEmail 判断邮件通知是否已启用且 SMTP 配置完整。
func (c SMTPConfig) IsConfiguredEmail() bool {
return c.Enabled && c.Email != "" && c.Password != "" && c.Host != ""
}
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
cfg := SMTPConfig{
Enabled: true, // 默认启用
Host: "smtp.qq.com",
Port: "465",
}
if v, _ := s.get("smtpEnabled"); v == "false" {
cfg.Enabled = false
}
if v, _ := s.get("smtpEmail"); v != "" {
cfg.Email = v
}
if v, _ := s.get("smtpPassword"); v != "" {
cfg.Password = v
}
if v, _ := s.get("smtpFromName"); v != "" {
cfg.FromName = v
}
if v, _ := s.get("smtpHost"); v != "" {
cfg.Host = v
}
if v, _ := s.get("smtpPort"); v != "" {
cfg.Port = v
}
return cfg, nil
}
func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error {
enabledVal := "true"
if !cfg.Enabled {
enabledVal = "false"
}
pairs := [][2]string{
{"smtpEnabled", enabledVal},
{"smtpEmail", cfg.Email},
{"smtpPassword", cfg.Password},
{"smtpFromName", cfg.FromName},
{"smtpHost", cfg.Host},
{"smtpPort", cfg.Port},
}
for _, p := range pairs {
if err := s.set(p[0], p[1]); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,38 @@
package storage
import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
"mengyastore-backend/internal/database"
)
type WishlistStore struct {
db *gorm.DB
}
func NewWishlistStore(db *gorm.DB) (*WishlistStore, error) {
return &WishlistStore{db: db}, nil
}
func (s *WishlistStore) Get(accountID string) ([]string, error) {
var rows []database.WishlistRow
if err := s.db.Where("account_id = ?", accountID).Find(&rows).Error; err != nil {
return nil, err
}
ids := make([]string, len(rows))
for i, r := range rows {
ids[i] = r.ProductID
}
return ids, nil
}
func (s *WishlistStore) Add(accountID, productID string) error {
return s.db.Clauses(clause.OnConflict{DoNothing: true}).
Create(&database.WishlistRow{AccountID: accountID, ProductID: productID}).Error
}
func (s *WishlistStore) Remove(accountID, productID string) error {
return s.db.Where("account_id = ? AND product_id = ?", accountID, productID).
Delete(&database.WishlistRow{}).Error
}

View File

@@ -0,0 +1,114 @@
package main
import (
"log"
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/config"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/handlers"
"mengyastore-backend/internal/storage"
)
func main() {
cfg, err := config.Load("config.json")
if err != nil {
log.Fatalf("加载配置失败: %v", err)
}
// 初始化数据库连接
db, err := database.Open(cfg.DatabaseDSN)
if err != nil {
log.Fatalf("初始化数据库失败: %v", err)
}
store, err := storage.NewProductStore(db)
if err != nil {
log.Fatalf("初始化商品存储失败: %v", err)
}
orderStore, err := storage.NewOrderStore(db)
if err != nil {
log.Fatalf("初始化订单存储失败: %v", err)
}
siteStore, err := storage.NewSiteStore(db)
if err != nil {
log.Fatalf("初始化站点存储失败: %v", err)
}
wishlistStore, err := storage.NewWishlistStore(db)
if err != nil {
log.Fatalf("初始化收藏夹存储失败: %v", err)
}
chatStore, err := storage.NewChatStore(db)
if err != nil {
log.Fatalf("初始化聊天存储失败: %v", err)
}
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Admin-Token"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
}))
r.GET("/api/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)
publicHandler := handlers.NewPublicHandler(store)
adminHandler := handlers.NewAdminHandler(store, cfg, siteStore, orderStore, chatStore)
orderHandler := handlers.NewOrderHandler(store, orderStore, siteStore, authClient)
statsHandler := handlers.NewStatsHandler(orderStore, siteStore)
wishlistHandler := handlers.NewWishlistHandler(wishlistStore, authClient)
chatHandler := handlers.NewChatHandler(chatStore, authClient)
r.GET("/api/products", publicHandler.ListProducts)
r.POST("/api/checkout", orderHandler.CreateOrder)
r.POST("/api/products/:id/view", publicHandler.RecordProductView)
r.GET("/api/stats", statsHandler.GetStats)
r.POST("/api/site/visit", statsHandler.RecordVisit)
r.GET("/api/site/maintenance", statsHandler.GetMaintenance)
r.GET("/api/orders", orderHandler.ListMyOrders)
r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)
r.POST("/api/admin/verify", adminHandler.VerifyAdminToken)
r.GET("/api/admin/products", adminHandler.ListAllProducts)
r.POST("/api/admin/products", adminHandler.CreateProduct)
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)
r.POST("/api/admin/site/maintenance", adminHandler.SetMaintenance)
r.GET("/api/admin/site/smtp", adminHandler.GetSMTPConfig)
r.POST("/api/admin/site/smtp", adminHandler.SetSMTPConfig)
r.GET("/api/admin/orders", adminHandler.ListAllOrders)
r.DELETE("/api/admin/orders/:id", adminHandler.DeleteOrder)
r.GET("/api/wishlist", wishlistHandler.GetWishlist)
r.POST("/api/wishlist", wishlistHandler.AddToWishlist)
r.DELETE("/api/wishlist/:id", wishlistHandler.RemoveFromWishlist)
// 用户聊天路由
r.GET("/api/chat/messages", chatHandler.GetMyMessages)
r.POST("/api/chat/messages", chatHandler.SendMyMessage)
// 管理员聊天路由
r.GET("/api/admin/chat", adminHandler.GetAllConversations)
r.GET("/api/admin/chat/:account", adminHandler.GetConversation)
r.POST("/api/admin/chat/:account", adminHandler.AdminReply)
r.DELETE("/api/admin/chat/:account", adminHandler.ClearConversation)
log.Println("萌芽小店后端启动于 http://localhost:8080")
if err := r.Run(":8080"); err != nil {
log.Fatalf("服务器启动失败: %v", err)
}
}

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,119 +0,0 @@
[
{
"id": "0bea9606-51aa-4fe2-a932-ab0e36ee33ca",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"LINUX-INVITE-001"
],
"status": "pending",
"createdAt": "2026-03-19T17:23:46.1743551+08:00"
},
{
"id": "5be3ecbd-873b-4ea2-9209-e96f6eb528cd",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"LINUX-INVITE-002"
],
"status": "pending",
"createdAt": "2026-03-19T17:24:07.6045189+08:00"
},
{
"id": "c0cbb6c7-76be-49ef-9e67-8d2ae890e555",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"啊伟大伟大伟大我"
],
"status": "pending",
"createdAt": "2026-03-19T22:28:28.5393405+08:00"
},
{
"id": "f299bbb4-0de4-4824-84ab-d1ccfb3b35dd",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"啊伟大伟大伟大伟大"
],
"status": "pending",
"createdAt": "2026-03-20T10:32:38.352837+08:00"
},
{
"id": "413931af-2867-4855-89af-515747d4b5e5",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"你是傻逼哈哈哈被骗了吧"
],
"status": "pending",
"createdAt": "2026-03-20T10:32:55.2785291+08:00"
},
{
"id": "59ab54e0-8b98-48d3-bf63-a843ef2c95a4",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"唐"
],
"status": "pending",
"createdAt": "2026-03-20T10:39:37.9977301+08:00"
},
{
"id": "94e82c71-8237-429f-b593-2530314b72af",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "",
"userName": "",
"quantity": 1,
"deliveredCodes": [
"原神牛逼"
],
"status": "completed",
"createdAt": "2026-03-20T10:40:45.3820749+08:00"
},
{
"id": "058cad17-608c-4108-b012-af42f688a047",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "shumengya",
"userName": "树萌芽",
"quantity": 1,
"deliveredCodes": [
"123123123131"
],
"status": "completed",
"createdAt": "2026-03-20T10:44:21.375082+08:00"
},
{
"id": "e95f30ab-da4f-4dec-872c-3c9047cd8193",
"productId": "seed-1",
"productName": "Linux Do 邀请码",
"userAccount": "shumengya",
"userName": "树萌芽",
"quantity": 1,
"deliveredCodes": [
"131231231231231"
],
"status": "completed",
"createdAt": "2026-03-20T10:57:13.3436565+08:00"
}
]

View File

@@ -1,181 +0,0 @@
[
{
"id": "seed-1",
"name": "Linux Do 邀请码",
"price": 7,
"discountPrice": 4,
"tags": [
"邀请码",
"LinuxDo"
],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 10,
"description": "Linux.do论坛邀请码 默认每天可以生成一个,先到先得.",
"active": true,
"createdAt": "2026-03-15T10:00:00+08:00",
"updatedAt": "2026-03-20T11:37:16.2219815+08:00"
},
{
"id": "seed-2",
"name": "ChatGPT普号",
"price": 1,
"discountPrice": 0,
"tags": [],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 2,
"description": "ChatGPT 普号 纯手工注册 数量不多",
"active": true,
"createdAt": "2026-03-15T10:05:00+08:00",
"updatedAt": "2026-03-20T11:34:54.3522714+08:00"
},
{
"id": "2b6b6051-bca7-42da-b127-c7b721c50c06",
"name": "谷歌账号",
"price": 20,
"discountPrice": 0,
"tags": [],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 1,
"description": "谷歌账号 现货 可绑定F2A验证",
"active": true,
"createdAt": "2026-03-15T20:52:52.0381722+08:00",
"updatedAt": "2026-03-19T19:33:05.6844325+08:00"
},
{
"id": "b9922892-c197-44be-be87-637ccb6bebeb",
"name": "萌芽币",
"price": 999999,
"discountPrice": 0,
"tags": [],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 1,
"description": "非买品 仅展示",
"active": true,
"createdAt": "2026-03-15T21:03:00.0164528+08:00",
"updatedAt": "2026-03-19T19:33:07.508758+08:00"
},
{
"id": "ee8e0140-221c-4bfa-b10a-13b1f98ea4e5",
"name": "Keep校园跑 代刷4公里",
"price": 1,
"discountPrice": 0,
"tags": [],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 1,
"description": "keep校园跑带刷 每天4-5公里 下单后直接联系我发账号",
"active": true,
"createdAt": "2026-03-15T21:06:11.9820102+08:00",
"updatedAt": "2026-03-19T19:33:09.1800225+08:00"
},
{
"id": "00bbf5db-b99e-4e88-a8ee-e7747b5969fe",
"name": "学习通/慕课挂课脚本",
"price": 25,
"discountPrice": 0,
"tags": [],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 1,
"description": "学习通,慕课挂科脚本 手机 电脑都可以挂 不会弄可联系教你",
"active": true,
"createdAt": "2026-03-15T21:06:45.3807471+08:00",
"updatedAt": "2026-03-19T19:33:02.9673884+08:00"
},
{
"id": "6c7bf494-ef2c-4221-9bf7-ec3c94070d25",
"name": "smyhub.com后缀域名邮箱",
"price": 5,
"discountPrice": 0,
"tags": [],
"quantity": 0,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [],
"viewCount": 1,
"description": "纪念意义,比如我自己的mail@smyhub.com 目前已经续费了5年到2031年",
"active": true,
"createdAt": "2026-03-18T22:17:41.3034538+08:00",
"updatedAt": "2026-03-19T19:32:26.7674929+08:00"
},
{
"id": "a30a2275-1c9c-49e4-a402-3e446e3e0f5c",
"name": "萌芽账号邀请码",
"price": 10,
"discountPrice": 8,
"tags": [],
"quantity": 1,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [
"原神牛逼"
],
"viewCount": 0,
"description": "萌芽统一账号登录平台邀请码",
"active": true,
"createdAt": "2026-03-20T11:04:05.5787516+08:00",
"updatedAt": "2026-03-20T11:04:05.5787516+08:00"
},
{
"id": "bcd5d73b-6ad9-4ed9-8e18-42ea0482ceb3",
"name": "Keep 代跑脚本",
"price": 50,
"discountPrice": 0,
"tags": [],
"quantity": 1,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [
"傻逼"
],
"viewCount": 0,
"description": "Keep 校园跑脚本",
"active": true,
"createdAt": "2026-03-20T11:17:36.1915376+08:00",
"updatedAt": "2026-03-20T11:17:36.1915376+08:00"
},
{
"id": "7ab90d55-92c1-49d3-9d0a-01e5b1c08340",
"name": "原神牛逼",
"price": 0,
"discountPrice": 0,
"tags": [],
"quantity": 1,
"coverUrl": "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png",
"screenshotUrls": [],
"verificationUrl": "",
"codes": [
"原神牛逼"
],
"viewCount": 0,
"description": "购买后直接发送一句原神牛逼",
"active": true,
"createdAt": "2026-03-20T11:36:36.6726035+08:00",
"updatedAt": "2026-03-20T11:42:05.3303102+08:00"
}
]

View File

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

View File

@@ -1,3 +0,0 @@
{
"totalVisits": 3
}

View File

@@ -1,13 +0,0 @@
services:
backend:
build:
context: .
container_name: mengyastore-backend
ports:
- "28081:8080"
environment:
GIN_MODE: release
TZ: Asia/Shanghai
volumes:
- ./data:/app/data
restart: unless-stopped

View File

@@ -1,27 +0,0 @@
package config
import (
"encoding/json"
"fmt"
"os"
)
type Config struct {
AdminToken string `json:"adminToken"`
AuthAPIURL string `json:"authApiUrl"`
}
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
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
if cfg.AdminToken == "" {
cfg.AdminToken = "shumengya520"
}
return &cfg, nil
}

View File

@@ -1,183 +0,0 @@
package handlers
import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage"
)
const qrSize = "320x320"
type OrderHandler struct {
productStore *storage.JSONStore
orderStore *storage.OrderStore
authClient *auth.SproutGateClient
}
type checkoutPayload struct {
ProductID string `json:"productId"`
Quantity int `json:"quantity"`
}
func NewOrderHandler(productStore *storage.JSONStore, orderStore *storage.OrderStore, authClient *auth.SproutGateClient) *OrderHandler {
return &OrderHandler{productStore: productStore, orderStore: orderStore, authClient: authClient}
}
func (h *OrderHandler) tryExtractUser(c *gin.Context) (string, string) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
log.Println("[Order] 无 Authorization header匿名下单")
return "", ""
}
userToken := strings.TrimPrefix(authHeader, "Bearer ")
log.Printf("[Order] 检测到用户 token正在验证 (长度=%d)", len(userToken))
result, err := h.authClient.VerifyToken(userToken)
if err != nil {
log.Printf("[Order] 验证 token 失败: %v", err)
return "", ""
}
if !result.Valid {
log.Println("[Order] token 验证返回 valid=false")
return "", ""
}
if result.User == nil {
log.Println("[Order] token 验证成功但 user 为空")
return "", ""
}
log.Printf("[Order] 用户身份验证成功: account=%s username=%s", result.User.Account, result.User.Username)
return result.User.Account, result.User.Username
}
func (h *OrderHandler) CreateOrder(c *gin.Context) {
userAccount, userName := h.tryExtractUser(c)
var payload checkoutPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
payload.ProductID = strings.TrimSpace(payload.ProductID)
if payload.ProductID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing required fields"})
return
}
if payload.Quantity <= 0 {
payload.Quantity = 1
}
product, err := h.productStore.GetByID(payload.ProductID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
if !product.Active {
c.JSON(http.StatusBadRequest, gin.H{"error": "product is not available"})
return
}
if product.Quantity < payload.Quantity {
c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"})
return
}
deliveredCodes, ok := extractCodes(&product, payload.Quantity)
if !ok {
c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"})
return
}
product.Quantity = len(product.Codes)
updatedProduct, err := h.productStore.Update(product.ID, product)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
order := models.Order{
ProductID: updatedProduct.ID,
ProductName: updatedProduct.Name,
UserAccount: userAccount,
UserName: userName,
Quantity: payload.Quantity,
DeliveredCodes: deliveredCodes,
Status: "pending",
}
created, err := h.orderStore.Create(order)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
qrPayload := fmt.Sprintf("order:%s:%s", created.ID, created.ProductID)
qrURL := fmt.Sprintf("https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s", qrSize, url.QueryEscape(qrPayload))
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"orderId": created.ID,
"qrCodeUrl": qrURL,
"productId": created.ProductID,
"productQty": created.Quantity,
"viewCount": updatedProduct.ViewCount,
"status": created.Status,
},
})
}
func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
orderID := c.Param("id")
order, err := h.orderStore.Confirm(orderID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"orderId": order.ID,
"status": order.Status,
"deliveredCodes": order.DeliveredCodes,
},
})
}
func (h *OrderHandler) ListMyOrders(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
return
}
userToken := strings.TrimPrefix(authHeader, "Bearer ")
result, err := h.authClient.VerifyToken(userToken)
if err != nil || !result.Valid || result.User == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "登录已过期,请重新登录"})
return
}
orders, err := h.orderStore.ListByAccount(result.User.Account)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": orders})
}
func extractCodes(product *models.Product, count int) ([]string, bool) {
if count <= 0 {
return nil, false
}
if len(product.Codes) < count {
return nil, false
}
delivered := make([]string, count)
copy(delivered, product.Codes[:count])
product.Codes = product.Codes[count:]
return delivered, true
}

View File

@@ -1,331 +0,0 @@
package storage
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/google/uuid"
"mengyastore-backend/internal/models"
)
const defaultCoverURL = "https://img.shumengya.top/i/2026/01/04/695a55058c37f.png"
const viewCooldown = 6 * time.Hour
const maxScreenshotURLs = 5
type JSONStore struct {
path string
mu sync.Mutex
recentViews map[string]time.Time
}
func NewJSONStore(path string) (*JSONStore, error) {
if err := ensureProductsFile(path); err != nil {
return nil, err
}
return &JSONStore{
path: path,
recentViews: make(map[string]time.Time),
}, nil
}
func ensureProductsFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir data dir: %w", err)
}
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat data file: %w", err)
}
initial := []models.Product{}
bytes, err := json.MarshalIndent(initial, "", " ")
if err != nil {
return fmt.Errorf("init json: %w", err)
}
if err := os.WriteFile(path, bytes, 0o644); err != nil {
return fmt.Errorf("write init json: %w", err)
}
return nil
}
func (s *JSONStore) ListAll() ([]models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.readAll()
}
func (s *JSONStore) ListActive() ([]models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return nil, err
}
active := make([]models.Product, 0, len(items))
for _, item := range items {
if item.Active {
active = append(active, item)
}
}
return active, nil
}
func (s *JSONStore) GetByID(id string) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, err
}
for _, item := range items {
if item.ID == id {
return item, nil
}
}
return models.Product{}, fmt.Errorf("product not found")
}
func (s *JSONStore) Create(p models.Product) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, err
}
p = normalizeProduct(p)
p.ID = uuid.NewString()
now := time.Now()
p.CreatedAt = now
p.UpdatedAt = now
items = append(items, p)
if err := s.writeAll(items); err != nil {
return models.Product{}, err
}
return p, nil
}
func (s *JSONStore) Update(id string, patch models.Product) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, err
}
for i, item := range items {
if item.ID == id {
normalized := normalizeProduct(patch)
item.Name = normalized.Name
item.Price = normalized.Price
item.DiscountPrice = normalized.DiscountPrice
item.Tags = normalized.Tags
item.CoverURL = normalized.CoverURL
item.ScreenshotURLs = normalized.ScreenshotURLs
item.VerificationURL = normalized.VerificationURL
item.Codes = normalized.Codes
item.Quantity = normalized.Quantity
item.Description = normalized.Description
item.Active = normalized.Active
item.UpdatedAt = time.Now()
items[i] = item
if err := s.writeAll(items); err != nil {
return models.Product{}, err
}
return item, nil
}
}
return models.Product{}, fmt.Errorf("product not found")
}
func (s *JSONStore) Toggle(id string, active bool) (models.Product, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, err
}
for i, item := range items {
if item.ID == id {
item.Active = active
item.UpdatedAt = time.Now()
items[i] = item
if err := s.writeAll(items); err != nil {
return models.Product{}, err
}
return item, nil
}
}
return models.Product{}, fmt.Errorf("product not found")
}
func (s *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, false, err
}
now := time.Now()
s.cleanupRecentViews(now)
key := buildViewKey(id, fingerprint)
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
for _, item := range items {
if item.ID == id {
return item, false, nil
}
}
return models.Product{}, false, fmt.Errorf("product not found")
}
for i, item := range items {
if item.ID == id {
item.ViewCount++
item.UpdatedAt = now
items[i] = item
s.recentViews[key] = now
if err := s.writeAll(items); err != nil {
return models.Product{}, false, err
}
return item, true, nil
}
}
return models.Product{}, false, fmt.Errorf("product not found")
}
func (s *JSONStore) Delete(id string) error {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return err
}
filtered := make([]models.Product, 0, len(items))
for _, item := range items {
if item.ID != id {
filtered = append(filtered, item)
}
}
if err := s.writeAll(filtered); err != nil {
return err
}
return nil
}
func (s *JSONStore) readAll() ([]models.Product, error) {
bytes, err := os.ReadFile(s.path)
if err != nil {
return nil, fmt.Errorf("read products: %w", err)
}
var items []models.Product
if err := json.Unmarshal(bytes, &items); err != nil {
return nil, fmt.Errorf("parse products: %w", err)
}
for i, item := range items {
items[i] = normalizeProduct(item)
}
return items, nil
}
func (s *JSONStore) writeAll(items []models.Product) error {
for i, item := range items {
items[i] = normalizeProduct(item)
}
bytes, err := json.MarshalIndent(items, "", " ")
if err != nil {
return fmt.Errorf("encode products: %w", err)
}
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
return fmt.Errorf("write products: %w", err)
}
return nil
}
func normalizeProduct(item models.Product) models.Product {
item.CoverURL = strings.TrimSpace(item.CoverURL)
if item.CoverURL == "" {
item.CoverURL = defaultCoverURL
}
if item.Tags == nil {
item.Tags = []string{}
}
item.Tags = sanitizeTags(item.Tags)
if item.ScreenshotURLs == nil {
item.ScreenshotURLs = []string{}
}
if len(item.ScreenshotURLs) > maxScreenshotURLs {
item.ScreenshotURLs = item.ScreenshotURLs[:maxScreenshotURLs]
}
if item.Codes == nil {
item.Codes = []string{}
}
if item.DiscountPrice <= 0 || item.DiscountPrice >= item.Price {
item.DiscountPrice = 0
}
item.VerificationURL = strings.TrimSpace(item.VerificationURL)
item.Codes = sanitizeCodes(item.Codes)
item.Quantity = len(item.Codes)
return item
}
func sanitizeCodes(codes []string) []string {
clean := make([]string, 0, len(codes))
seen := map[string]bool{}
for _, code := range codes {
trimmed := strings.TrimSpace(code)
if trimmed == "" {
continue
}
if seen[trimmed] {
continue
}
seen[trimmed] = true
clean = append(clean, trimmed)
}
return clean
}
func sanitizeTags(tags []string) []string {
clean := make([]string, 0, len(tags))
seen := map[string]bool{}
for _, tag := range tags {
t := strings.TrimSpace(tag)
if t == "" {
continue
}
key := strings.ToLower(t)
if seen[key] {
continue
}
seen[key] = true
clean = append(clean, t)
if len(clean) >= 20 {
break
}
}
return clean
}
func buildViewKey(id, fingerprint string) string {
sum := sha256.Sum256([]byte(id + "|" + fingerprint))
return fmt.Sprintf("%x", sum)
}
func (s *JSONStore) cleanupRecentViews(now time.Time) {
for key, lastViewedAt := range s.recentViews {
if now.Sub(lastViewedAt) >= viewCooldown {
delete(s.recentViews, key)
}
}
}

View File

@@ -1,140 +0,0 @@
package storage
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/google/uuid"
"mengyastore-backend/internal/models"
)
type OrderStore struct {
path string
mu sync.Mutex
}
func NewOrderStore(path string) (*OrderStore, error) {
if err := ensureOrdersFile(path); err != nil {
return nil, err
}
return &OrderStore{path: path}, nil
}
func (s *OrderStore) Count() (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return 0, err
}
return len(items), nil
}
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return nil, err
}
matched := make([]models.Order, 0)
for i := len(items) - 1; i >= 0; i-- {
if items[i].UserAccount == account {
matched = append(matched, items[i])
}
}
return matched, nil
}
func (s *OrderStore) Confirm(id string) (models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Order{}, err
}
for i, item := range items {
if item.ID == id {
if item.Status == "completed" {
return item, nil
}
items[i].Status = "completed"
if err := s.writeAll(items); err != nil {
return models.Order{}, err
}
return items[i], nil
}
}
return models.Order{}, fmt.Errorf("order not found")
}
func (s *OrderStore) Create(order models.Order) (models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Order{}, err
}
order.ID = uuid.NewString()
order.CreatedAt = time.Now()
items = append(items, order)
if err := s.writeAll(items); err != nil {
return models.Order{}, err
}
return order, nil
}
func (s *OrderStore) readAll() ([]models.Order, error) {
bytes, err := os.ReadFile(s.path)
if err != nil {
return nil, fmt.Errorf("read orders: %w", err)
}
var items []models.Order
if err := json.Unmarshal(bytes, &items); err != nil {
return nil, fmt.Errorf("parse orders: %w", err)
}
return items, nil
}
func (s *OrderStore) writeAll(items []models.Order) error {
bytes, err := json.MarshalIndent(items, "", " ")
if err != nil {
return fmt.Errorf("encode orders: %w", err)
}
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
return fmt.Errorf("write orders: %w", err)
}
return nil
}
func ensureOrdersFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir data dir: %w", err)
}
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat data file: %w", err)
}
initial := []models.Order{}
bytes, err := json.MarshalIndent(initial, "", " ")
if err != nil {
return fmt.Errorf("init json: %w", err)
}
if err := os.WriteFile(path, bytes, 0o644); err != nil {
return fmt.Errorf("write init json: %w", err)
}
return nil
}

View File

@@ -1,128 +0,0 @@
package storage
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
)
const visitCooldown = 6 * time.Hour
type siteData struct {
TotalVisits int `json:"totalVisits"`
}
type SiteStore struct {
path string
mu sync.Mutex
recentVisits map[string]time.Time
}
func NewSiteStore(path string) (*SiteStore, error) {
if err := ensureSiteFile(path); err != nil {
return nil, err
}
return &SiteStore{
path: path,
recentVisits: make(map[string]time.Time),
}, nil
}
func (s *SiteStore) RecordVisit(fingerprint string) (int, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
s.cleanupRecentVisits(now)
key := buildSiteVisitKey(fingerprint)
if last, ok := s.recentVisits[key]; ok && now.Sub(last) < visitCooldown {
data, err := s.read()
if err != nil {
return 0, false, err
}
return data.TotalVisits, false, nil
}
data, err := s.read()
if err != nil {
return 0, false, err
}
data.TotalVisits++
s.recentVisits[key] = now
if err := s.write(data); err != nil {
return 0, false, err
}
return data.TotalVisits, true, nil
}
func (s *SiteStore) GetTotalVisits() (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
data, err := s.read()
if err != nil {
return 0, err
}
return data.TotalVisits, nil
}
func (s *SiteStore) read() (siteData, error) {
bytes, err := os.ReadFile(s.path)
if err != nil {
return siteData{}, fmt.Errorf("read site data: %w", err)
}
var data siteData
if err := json.Unmarshal(bytes, &data); err != nil {
return siteData{}, fmt.Errorf("parse site data: %w", err)
}
return data, nil
}
func (s *SiteStore) write(data siteData) error {
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return fmt.Errorf("encode site data: %w", err)
}
if err := os.WriteFile(s.path, bytes, 0o644); err != nil {
return fmt.Errorf("write site data: %w", err)
}
return nil
}
func (s *SiteStore) cleanupRecentVisits(now time.Time) {
for key, last := range s.recentVisits {
if now.Sub(last) >= visitCooldown {
delete(s.recentVisits, key)
}
}
}
func buildSiteVisitKey(fingerprint string) string {
sum := sha256.Sum256([]byte("site|" + fingerprint))
return fmt.Sprintf("%x", sum)
}
func ensureSiteFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir data dir: %w", err)
}
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat site file: %w", err)
}
initial := siteData{TotalVisits: 0}
bytes, err := json.MarshalIndent(initial, "", " ")
if err != nil {
return fmt.Errorf("init site json: %w", err)
}
if err := os.WriteFile(path, bytes, 0o644); err != nil {
return fmt.Errorf("write site json: %w", err)
}
return nil
}

View File

@@ -1,76 +0,0 @@
package main
import (
"log"
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth"
"mengyastore-backend/internal/config"
"mengyastore-backend/internal/handlers"
"mengyastore-backend/internal/storage"
)
func main() {
cfg, err := config.Load("data/json/settings.json")
if err != nil {
log.Fatalf("load config failed: %v", err)
}
store, err := storage.NewJSONStore("data/json/products.json")
if err != nil {
log.Fatalf("init store failed: %v", err)
}
orderStore, err := storage.NewOrderStore("data/json/orders.json")
if err != nil {
log.Fatalf("init order store failed: %v", err)
}
siteStore, err := storage.NewSiteStore("data/json/site.json")
if err != nil {
log.Fatalf("init site store failed: %v", err)
}
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
}))
r.GET("/api/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)
publicHandler := handlers.NewPublicHandler(store)
adminHandler := handlers.NewAdminHandler(store, cfg)
orderHandler := handlers.NewOrderHandler(store, orderStore, authClient)
statsHandler := handlers.NewStatsHandler(orderStore, siteStore)
r.GET("/api/products", publicHandler.ListProducts)
r.POST("/api/checkout", orderHandler.CreateOrder)
r.POST("/api/products/:id/view", publicHandler.RecordProductView)
r.GET("/api/stats", statsHandler.GetStats)
r.POST("/api/site/visit", statsHandler.RecordVisit)
r.GET("/api/orders", orderHandler.ListMyOrders)
r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)
r.GET("/api/admin/token", adminHandler.GetAdminToken)
r.GET("/api/admin/products", adminHandler.ListAllProducts)
r.POST("/api/admin/products", adminHandler.CreateProduct)
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)
log.Println("萌芽小店后端启动于 http://localhost:8080")
if err := r.Run(":8080"); err != nil {
log.Fatalf("server run failed: %v", err)
}
}

View File

@@ -0,0 +1,167 @@
# 萌芽小店 · 前端
基于 **Vue 3 + Vite** 构建的数字商品销售平台前端,采用组件化模块架构。
## 技术依赖
| 包 | 版本 | 用途 |
|----|------|------|
| vue | ^3.x | 核心框架 |
| vite | ^5.x | 构建工具 |
| vue-router | ^4.x | 路由管理 |
| pinia | ^2.x | 状态管理 |
| axios | ^1.6 | HTTP 请求 |
| markdown-it | ^14 | Markdown 渲染 |
## 目录结构
```
src/
├── assets/
│ └── styles.css # 全局 CSS 变量与公共样式
├── router/
│ └── index.js # 路由配置(含维护模式守卫)
├── modules/
│ ├── shared/
│ │ ├── api.js # 所有 API 请求封装
│ │ ├── auth.js # 认证状态Pinia store
│ │ └── useWishlist.js # 收藏夹 Composable
│ ├── store/
│ │ ├── StorePage.vue # 商品列表页
│ │ ├── ProductDetail.vue # 商品详情页
│ │ ├── CheckoutPage.vue # 结算页
│ │ └── components/
│ │ └── ProductCard.vue # 商品卡片组件
│ ├── admin/
│ │ ├── AdminPage.vue # 管理后台(编排层)
│ │ └── components/
│ │ ├── AdminTokenRow.vue # 令牌输入
│ │ ├── AdminMaintenanceRow.vue # 维护模式开关
│ │ ├── AdminProductTable.vue # 商品列表表格
│ │ ├── AdminProductModal.vue # 商品编辑弹窗
│ │ ├── AdminOrderTable.vue # 订单记录表格
│ │ └── AdminChatPanel.vue # 用户聊天管理
│ ├── user/
│ │ └── MyOrdersPage.vue # 我的订单
│ ├── wishlist/
│ │ └── WishlistPage.vue # 收藏夹页面
│ ├── maintenance/
│ │ └── MaintenancePage.vue # 站点维护页面
│ └── chat/
│ └── ChatWidget.vue # 用户悬浮聊天窗口
└── App.vue # 根组件(全局布局 + 导航)
```
## 路由列表
| 路径 | 组件 | 说明 |
|------|------|------|
| `/` | `StorePage` | 商品列表 |
| `/product/:id` | `ProductDetail` | 商品详情 |
| `/product/:id/checkout` | `CheckoutPage` | 结算页 |
| `/my/orders` | `MyOrdersPage` | 我的订单(需登录)|
| `/wishlist` | `WishlistPage` | 收藏夹(需登录)|
| `/admin` | `AdminPage` | 管理后台(需令牌)|
| `/maintenance` | `MaintenancePage` | 维护中页面 |
### 路由守卫
- **维护模式**`beforeEach` 检查 `GET /api/site/maintenance`,若站点维护中则重定向到 `/maintenance`(管理员访问 `/admin` 时豁免)
- 豁免路径:`/maintenance``/wishlist``/admin`
## 认证流程
使用 SproutGate OAuth 服务:
1. 未登录用户点击「萌芽账号登录」,跳转到 `https://auth.shumengya.top/login?callback=<当前页>`
2. 登录成功后回调携带 token存入 localStorage
3. `authState`reactive 对象)全局共享 `token``account``username``avatarUrl`
4. 所有需要认证的 API 请求在 `Authorization: Bearer <token>` 头部携带 token
## 主要功能模块
### 商品列表StorePage
- 视图模式(`viewMode`):全部 / 免费 / 新上架 / 最多购买 / 最多浏览 / 价格最高 / 价格最低
- 搜索:实时过滤商品名称
- 分页:桌面 20 条/页4×5手机 10 条/页5×2
- 响应式布局:`window.innerWidth <= 900` 切换为双列
### 结算页CheckoutPage
- 展示商品信息与价格
- 数量输入,最大值受 `product.maxPerAccount` 限制
- 若商品开启 `showNote`:展示备注文本框
- 若商品开启 `showContact`:展示手机号和邮箱输入框
- 手动发货商品:展示蓝色提示条,确认后显示"等待发货中"
- 自动发货商品:确认后展示卡密内容
### 收藏夹useWishlist Composable
```js
import { wishlistIds, wishlistCount, inWishlist, loadWishlist, toggleWishlist } from './useWishlist'
```
- 数据存储在后端,通过 API 同步
- `App.vue` 在登录状态变化时自动调用 `loadWishlist()`
- 收藏状态通过 `wishlistSet`computed Set提供 O(1) 查找
### 客服聊天ChatWidget
- 仅已登录用户显示(右下角悬浮按钮)
- 每 5 秒轮询新消息
- 客户端和服务端均限制每秒最多发送 1 条消息
## 开发启动
```bash
npm install
npm run dev # 开发服务器 :5173
npm run build # 生产构建 → dist/
npm run preview # 预览构建结果
```
### 环境变量
在项目根目录创建 `.env.local`
```env
VITE_API_BASE_URL=http://localhost:8080
```
生产部署时设置实际 API 地址。
## 全局样式
`src/assets/styles.css` 定义了全局 CSS 变量:
```css
:root {
--accent: #91a8d0; /* 主题色 */
--accent-2: #b8c8e4; /* 渐变色 */
--text: #2c2c3a; /* 文字色 */
--muted: #8e8e9e; /* 次要文字 */
--line: rgba(0,0,0,0.08); /* 边框色 */
--radius: 8px; /* 圆角 */
}
```
字体使用楷体KaiTi / STKaitifallback 到系统衬线字体。
## 构建与部署
```bash
npm run build
```
产物在 `dist/` 目录,为静态文件,部署到 Nginx / CDN 时需配置:
```nginx
location / {
try_files $uri $uri/ /index.html; # SPA 路由支持
}
location /api/ {
proxy_pass http://localhost:8080; # 反向代理到后端
}
```

View File

@@ -2,10 +2,24 @@
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>萌芽小店</title>
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" />
<!-- Favicon -->
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" href="/pwa-192x192.png" type="image/png" />
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
<!-- PWA / Theme -->
<meta name="theme-color" content="#1a1a1a" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="apple-mobile-web-app-title" content="萌芽小店" />
<!-- SEO -->
<meta name="description" content="萌芽小店 — 精选商品,一键购买" />
<meta name="keywords" content="萌芽小店,网上购物,精选商品" />
</head>
<body>
<div id="app"></div>

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,9 @@
"vue-router": "^4.3.0"
},
"devDependencies": {
"@vite-pwa/assets-generator": "^1.0.2",
"@vitejs/plugin-vue": "^5.0.4",
"vite": "^5.2.7"
"vite": "^5.2.7",
"vite-plugin-pwa": "^1.2.0"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 816 B

View File

@@ -0,0 +1,18 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="80" fill="#1a1a1a"/>
<!-- Sprouting seedling icon -->
<g transform="translate(256,280)">
<!-- Stem -->
<line x1="0" y1="60" x2="0" y2="-20" stroke="#4ade80" stroke-width="18" stroke-linecap="round"/>
<!-- Left leaf -->
<path d="M0,10 Q-80,-30 -60,-100 Q-20,-50 0,10" fill="#4ade80" opacity="0.85"/>
<!-- Right leaf -->
<path d="M0,10 Q80,-30 60,-100 Q20,-50 0,10" fill="#4ade80"/>
<!-- Center leaf / bud -->
<path d="M0,-20 Q-20,-80 0,-120 Q20,-80 0,-20" fill="#86efac"/>
<!-- Ground dots -->
<circle cx="-50" cy="75" r="7" fill="#4ade80" opacity="0.4"/>
<circle cx="50" cy="75" r="7" fill="#4ade80" opacity="0.4"/>
<circle cx="0" cy="80" r="7" fill="#4ade80" opacity="0.4"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 842 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

View File

@@ -1,5 +1,8 @@
<template>
<div class="app">
<!-- PWA Splash Screen -->
<SplashScreen :visible="showSplash" />
<header class="top-bar">
<div class="brand" @click="onLogoClick">
<div class="brand-mark">
@@ -12,6 +15,11 @@
<div class="top-actions">
<button class="ghost" @click="goHome">商店</button>
<template v-if="loggedIn">
<button class="ghost wishlist-nav" @click="goWishlist">
<span class="wishlist-icon"></span>
收藏夹
<span v-if="wishlistCount > 0" class="wishlist-badge">{{ wishlistCount }}</span>
</button>
<button class="ghost" @click="goMyOrders">我的订单</button>
<div class="user-badge" @click="goProfile">
<img
@@ -90,14 +98,42 @@
</div>
</footer>
</div>
<!-- Floating chat widget (visible to logged-in users only) -->
<ChatWidget
v-if="loggedIn && authState.token"
:user-token="authState.token"
:user-name="authState.username || authState.account"
:user-avatar="authState.avatarUrl"
/>
<!-- PWA update toast -->
<Transition name="pwa-toast">
<div v-if="needRefresh" class="pwa-update-toast">
<span>发现新版本</span>
<button @click="updateServiceWorker(true)">立即更新</button>
</div>
</Transition>
</div>
</template>
<script setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
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 { wishlistCount, loadWishlist } from './modules/shared/useWishlist'
import ChatWidget from './modules/chat/ChatWidget.vue'
import SplashScreen from './modules/shared/SplashScreen.vue'
import { useRegisterSW } from 'virtual:pwa-register/vue'
const { needRefresh, updateServiceWorker } = useRegisterSW({
onRegisteredSW(swUrl, r) {
if (r) setInterval(() => r.update(), 1000 * 60 * 60)
}
})
const showSplash = ref(true)
const router = useRouter()
const stats = reactive({ totalOrders: 0, totalVisits: 0 })
@@ -135,10 +171,10 @@ const submitAdminToken = async () => {
if (!input) return
tokenError.value = ''
try {
const correctToken = await fetchAdminToken()
if (input === correctToken) {
const valid = await verifyAdminToken(input)
if (valid) {
showAdminModal.value = false
router.push(`/admin?token=${encodeURIComponent(correctToken)}`)
router.push(`/admin?token=${encodeURIComponent(input)}`)
} else {
tokenError.value = '令牌错误,请重试'
}
@@ -149,6 +185,7 @@ const submitAdminToken = async () => {
const goHome = () => { router.push('/') }
const goMyOrders = () => { router.push('/my/orders') }
const goWishlist = () => { router.push('/wishlist') }
const goProfile = () => {
if (authState.account) {
@@ -158,7 +195,12 @@ const goProfile = () => {
const logout = () => { clearAuth() }
const SPLASH_MIN_MS = 1400
onMounted(async () => {
const splashStart = Date.now()
await loadWishlist()
try {
recordSiteVisit().then((result) => {
if (result.totalVisits) stats.totalVisits = result.totalVisits
@@ -170,5 +212,15 @@ onMounted(async () => {
} catch (e) {
statsLoaded.value = false
}
const elapsed = Date.now() - splashStart
const remaining = SPLASH_MIN_MS - elapsed
setTimeout(() => { showSplash.value = false }, remaining > 0 ? remaining : 0)
})
watch(() => authState.token, async (newToken) => {
if (newToken) {
await loadWishlist()
}
})
</script>

View File

@@ -1,4 +1,3 @@
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600&family=Source+Sans+3:wght@300;400;600&display=swap');
:root {
--bg-1: #f8f5f2;
@@ -12,17 +11,27 @@
--accent: #b49acb;
--accent-2: #91a8d0;
--shadow: 0 20px 50px rgba(33, 33, 40, 0.12);
--radius: 14px;
--radius: 8px;
}
* {
box-sizing: border-box;
}
/* Hide scrollbar but keep scroll functionality */
html {
scrollbar-width: none; /* Firefox */
}
html::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
}
body {
margin: 0;
min-height: 100vh;
font-family: 'Source Sans 3', sans-serif;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 18px;
color: var(--text);
background: radial-gradient(circle at top, var(--bg-2), transparent 60%),
radial-gradient(circle at 10% 20%, var(--bg-3), transparent 55%),
@@ -33,7 +42,7 @@ h1,
h2,
h3,
h4 {
font-family: 'Playfair Display', serif;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
margin: 0;
}
@@ -96,7 +105,7 @@ p {
padding: 36px 32px 28px;
background: var(--glass-strong);
border: 1px solid var(--line);
border-radius: 20px;
border-radius: 12px;
box-shadow: 0 24px 60px rgba(33, 33, 40, 0.22);
backdrop-filter: blur(20px);
text-align: center;
@@ -112,7 +121,7 @@ p {
color: var(--muted);
cursor: pointer;
padding: 4px 8px;
border-radius: 8px;
border-radius: 5px;
line-height: 1;
transition: color 0.2s ease;
}
@@ -128,19 +137,19 @@ p {
justify-content: center;
width: 56px;
height: 56px;
border-radius: 16px;
border-radius: 10px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white;
margin-bottom: 16px;
}
.admin-modal h3 {
font-size: 20px;
font-size: 22px;
margin-bottom: 6px;
}
.admin-modal-hint {
font-size: 13px;
font-size: 15px;
color: var(--muted);
margin-bottom: 20px;
}
@@ -148,11 +157,11 @@ p {
.admin-modal-input {
width: 100%;
padding: 12px 16px;
border-radius: 12px;
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.65);
font-family: 'Source Sans 3', sans-serif;
font-size: 15px;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 18px;
text-align: center;
letter-spacing: 2px;
outline: none;
@@ -165,7 +174,7 @@ p {
}
.admin-modal-error {
font-size: 13px;
font-size: 15px;
color: #d4566a;
margin-top: 8px;
}
@@ -174,7 +183,7 @@ p {
width: 100%;
margin-top: 16px;
padding: 12px;
font-size: 15px;
font-size: 17px;
}
.admin-modal-btn:disabled {
@@ -209,19 +218,19 @@ p {
}
.brand h1 {
font-size: 26px;
font-size: 28px;
letter-spacing: 1px;
}
.brand p {
color: var(--muted);
font-size: 14px;
font-size: 16px;
}
.brand-mark {
width: 46px;
height: 46px;
border-radius: 16px;
border-radius: 10px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.6);
background: var(--glass-strong);
@@ -273,14 +282,14 @@ p {
justify-content: center;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white;
font-size: 13px;
font-size: 15px;
font-weight: 600;
}
.user-name {
font-size: 13px;
font-size: 17px;
color: var(--text);
font-weight: 500;
font-weight: 700;
max-width: 100px;
overflow: hidden;
text-overflow: ellipsis;
@@ -291,12 +300,12 @@ p {
display: inline-flex;
align-items: center;
padding: 10px 18px;
border-radius: 12px;
border-radius: 8px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white;
text-decoration: none;
font-family: 'Source Sans 3', sans-serif;
font-size: 14px;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 17px;
box-shadow: 0 10px 30px rgba(145, 168, 208, 0.35);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
@@ -308,9 +317,9 @@ p {
button {
border: none;
cursor: pointer;
font-family: 'Source Sans 3', sans-serif;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
padding: 10px 18px;
border-radius: 12px;
border-radius: 8px;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
@@ -328,6 +337,8 @@ button.ghost {
background: rgba(255, 255, 255, 0.6);
color: var(--text);
border: 1px solid var(--line);
font-size: 17px;
font-weight: 700;
}
.main-content {
@@ -362,15 +373,15 @@ button.ghost {
.footer-logo {
width: 28px;
height: 28px;
border-radius: 8px;
border-radius: 5px;
object-fit: contain;
border: 1px solid rgba(255, 255, 255, 0.5);
box-shadow: 0 4px 12px rgba(33, 33, 40, 0.1);
}
.footer-title {
font-family: 'Playfair Display', serif;
font-size: 17px;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 19px;
font-weight: 600;
color: var(--text);
letter-spacing: 0.5px;
@@ -398,10 +409,10 @@ button.ghost {
gap: 6px;
color: var(--accent-2);
text-decoration: none;
font-size: 13px;
font-size: 15px;
font-weight: 500;
padding: 5px 12px;
border-radius: 8px;
border-radius: 5px;
background: rgba(145, 168, 208, 0.08);
transition: background 0.2s ease, color 0.2s ease;
}
@@ -415,11 +426,11 @@ button.ghost {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
font-size: 15px;
font-weight: 500;
color: var(--accent);
padding: 5px 12px;
border-radius: 8px;
border-radius: 5px;
background: rgba(180, 154, 203, 0.08);
}
@@ -429,7 +440,7 @@ button.ghost {
}
.footer-copy {
font-size: 12px;
font-size: 14px;
color: var(--muted);
opacity: 0.7;
letter-spacing: 0.3px;
@@ -456,7 +467,7 @@ button.ghost {
flex-direction: column;
gap: 12px;
padding: 18px;
border-radius: 14px;
border-radius: 8px;
background: var(--glass-strong);
border: 1px solid var(--line);
box-shadow: 0 12px 30px rgba(33, 33, 40, 0.1);
@@ -467,7 +478,7 @@ button.ghost {
width: 100%;
height: 140px;
object-fit: cover;
border-radius: 12px;
border-radius: 6px;
}
.product-meta {
@@ -489,11 +500,11 @@ button.ghost {
display: inline-flex;
justify-content: center;
padding: 8px 14px;
border-radius: 10px;
border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.6);
background: rgba(255, 255, 255, 0.6);
color: var(--text);
font-size: 13px;
font-size: 15px;
transition: background 0.2s ease;
}
@@ -503,8 +514,8 @@ button.ghost {
.badge {
padding: 4px 10px;
border-radius: 10px;
font-size: 12px;
border-radius: 6px;
font-size: 14px;
background: rgba(255, 255, 255, 0.7);
}
@@ -524,7 +535,7 @@ button.ghost {
width: 100%;
height: 360px;
object-fit: cover;
border-radius: 16px;
border-radius: 10px;
}
.detail-actions {
@@ -537,7 +548,7 @@ button.ghost {
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white;
padding: 12px 22px;
border-radius: 12px;
border-radius: 8px;
}
.form-field {
@@ -549,11 +560,11 @@ button.ghost {
.form-field input,
.form-field textarea {
border-radius: 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
padding: 10px 12px;
font-family: 'Source Sans 3', sans-serif;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
}
.form-field textarea {
@@ -576,7 +587,7 @@ button.ghost {
.table td {
text-align: left;
padding: 12px;
font-size: 14px;
font-size: 16px;
}
.table tr {
@@ -584,12 +595,12 @@ button.ghost {
}
.tag {
font-size: 12px;
font-size: 14px;
color: var(--muted);
}
.markdown {
font-size: 13px;
font-size: 15px;
color: var(--muted);
line-height: 1.6;
display: -webkit-box;
@@ -600,19 +611,86 @@ button.ghost {
@media (max-width: 900px) {
.app-body {
padding: 18px 4vw 28px;
padding: 12px 2vw 20px;
}
/* ── Navigation: keep everything on one row, compress ── */
.top-bar {
flex-direction: column;
align-items: flex-start;
padding: 14px 4vw;
gap: 12px;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
justify-content: space-between;
padding: 8px 3vw;
gap: 6px;
}
.brand {
gap: 8px;
flex-shrink: 0;
white-space: nowrap;
}
.brand h1 {
font-size: 16px;
white-space: nowrap;
}
.brand-mark {
width: 32px;
height: 32px;
flex-shrink: 0;
}
.top-actions {
gap: 3px;
flex-shrink: 0;
overflow: hidden;
}
/* Compress nav buttons on mobile */
button.ghost {
font-size: 12px;
font-weight: 700;
padding: 5px 7px;
white-space: nowrap;
}
.login-btn {
font-size: 12px;
padding: 5px 8px;
white-space: nowrap;
}
.user-badge {
padding: 3px 6px 3px 4px;
gap: 4px;
}
.user-name {
font-size: 12px;
max-width: 50px;
}
.user-avatar {
width: 20px;
height: 20px;
}
.wishlist-icon {
font-size: 12px;
}
.wishlist-badge {
min-width: 14px;
height: 14px;
font-size: 9px;
}
/* ── Product grid: tighter ── */
.grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
gap: 10px;
padding: 0 2px;
}
.admin-grid {
@@ -628,27 +706,97 @@ button.ghost {
}
.footer {
padding: 20px 18px;
padding: 20px 14px;
}
.footer-links {
flex-direction: column;
gap: 10px;
flex-direction: row;
flex-wrap: wrap;
gap: 10px 16px;
justify-content: center;
}
.page-card {
padding: 18px;
}
.product-card {
padding: 14px;
}
.product-card {
padding: 10px 8px;
}
.product-card img {
height: 120px;
height: 110px;
}
.markdown {
-webkit-line-clamp: 2;
}
}
/* ── Wishlist navigation ── */
.wishlist-nav {
position: relative;
display: inline-flex;
align-items: center;
gap: 4px;
}
.wishlist-icon {
font-size: 15px;
}
.wishlist-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 4px;
border-radius: 999px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: #fff;
font-size: 11px;
font-weight: 700;
line-height: 1;
}
/* PWA update toast */
.pwa-update-toast {
position: fixed;
bottom: 80px;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
display: flex;
align-items: center;
gap: 12px;
padding: 10px 18px;
border-radius: 24px;
background: #1a1a1a;
color: #fff;
font-size: 13px;
box-shadow: 0 4px 24px rgba(0,0,0,0.25);
white-space: nowrap;
}
.pwa-update-toast button {
background: #4ade80;
color: #111;
border: none;
border-radius: 12px;
padding: 4px 14px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
}
.pwa-toast-enter-active,
.pwa-toast-leave-active {
transition: opacity 0.3s, transform 0.3s;
}
.pwa-toast-enter-from,
.pwa-toast-leave-to {
opacity: 0;
transform: translateX(-50%) translateY(16px);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,605 @@
<template>
<div class="chat-panel-section">
<div class="chat-panel-header">
<h3>用户消息</h3>
<button class="refresh-btn" @click="load" :disabled="loading">刷新</button>
</div>
<div v-if="loading" class="chat-empty">加载中</div>
<div v-else-if="Object.keys(conversations).length === 0" class="chat-empty">暂无用户消息</div>
<div v-else class="chat-layout">
<!-- Left: conversation list -->
<div class="conv-list">
<div class="conv-list-title">对话列表</div>
<div
v-for="(msgs, account) in conversations"
:key="account"
:class="['conv-item', selectedAccount === account ? 'conv-item--active' : '']"
@click="selectConv(account, msgs)"
>
<div class="conv-avatar">{{ (getDisplayName(msgs) || account).slice(0, 1).toUpperCase() }}</div>
<div class="conv-info">
<div class="conv-name">{{ getDisplayName(msgs) || account }}</div>
<div class="conv-preview">{{ latestMsg(msgs) }}</div>
</div>
</div>
</div>
<!-- Right: message thread -->
<div class="conv-thread" v-if="selectedAccount">
<div class="thread-top">
<div class="thread-user">
<div class="thread-avatar">{{ (displayName || selectedAccount).slice(0, 1).toUpperCase() }}</div>
<div class="thread-user-info">
<span class="thread-name">{{ displayName || selectedAccount }}</span>
<span class="thread-account">{{ selectedAccount }}</span>
</div>
</div>
<button class="clear-btn" @click="clearConv" :disabled="clearing">清除记录</button>
</div>
<div class="thread-messages" ref="threadEl">
<div
v-for="msg in currentMessages"
:key="msg.id"
:class="['msg-row', msg.fromAdmin ? 'msg-row--admin' : 'msg-row--user']"
>
<div class="msg-bubble">
<div class="msg-meta">
<span class="msg-from">{{ msg.fromAdmin ? '客服' : (msg.accountName || msg.accountId) }}</span>
<span class="msg-time">{{ formatTime(msg.sentAt) }}</span>
</div>
<div class="msg-content">{{ msg.content }}</div>
</div>
</div>
</div>
<form class="reply-row" @submit.prevent="sendReply">
<input
v-model="replyText"
class="reply-input"
placeholder="输入回复内容…"
maxlength="500"
:disabled="replying"
/>
<button class="reply-send-btn" type="submit" :disabled="replying || !replyText.trim()">发送</button>
</form>
<p v-if="replyError" class="reply-error">{{ replyError }}</p>
</div>
<div class="conv-thread conv-thread--empty" v-else>
<div class="empty-hint">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.3"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
<p>选择左侧对话</p>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import {
fetchAdminAllConversations,
fetchAdminConversation,
adminSendChatReply,
adminClearConversation
} from '../../shared/api.js'
const props = defineProps({
adminToken: { type: String, default: '' }
})
const conversations = ref({})
const loading = ref(false)
const selectedAccount = ref('')
const currentMessages = ref([])
const displayName = ref('')
const replyText = ref('')
const replying = ref(false)
const replyError = ref('')
const clearing = ref(false)
const threadEl = ref(null)
let pollTimer = null
const formatTime = (iso) => {
if (!iso) return ''
const d = new Date(iso)
return d.toLocaleString('zh-CN', { hour12: false })
}
const getDisplayName = (msgs) => {
if (!msgs || msgs.length === 0) return '未知用户'
const userMsg = msgs.find((m) => !m.fromAdmin)
return userMsg?.accountName || userMsg?.accountId || '未知用户'
}
const latestMsg = (msgs) => {
if (!msgs || msgs.length === 0) return ''
const last = msgs[msgs.length - 1]
const prefix = last.fromAdmin ? '[客服] ' : ''
return prefix + (last.content.length > 20 ? last.content.slice(0, 20) + '…' : last.content)
}
const scrollThreadBottom = async () => {
await nextTick()
if (threadEl.value) {
threadEl.value.scrollTop = threadEl.value.scrollHeight
}
}
const load = async () => {
if (!props.adminToken) return
loading.value = true
try {
conversations.value = await fetchAdminAllConversations(props.adminToken)
// 若当前已选中某个会话,则刷新其消息列表
if (selectedAccount.value) {
currentMessages.value = conversations.value[selectedAccount.value] || []
await scrollThreadBottom()
}
} finally {
loading.value = false
}
}
const selectConv = async (account, msgs) => {
selectedAccount.value = account
currentMessages.value = msgs || []
displayName.value = getDisplayName(msgs)
replyError.value = ''
replyText.value = ''
await scrollThreadBottom()
}
const sendReply = async () => {
const content = replyText.value.trim()
if (!content || replying.value) return
replying.value = true
replyError.value = ''
try {
const msg = await adminSendChatReply(props.adminToken, selectedAccount.value, content)
if (msg) {
currentMessages.value.push(msg)
conversations.value[selectedAccount.value] = [...currentMessages.value]
replyText.value = ''
await scrollThreadBottom()
}
} catch (err) {
replyError.value = err?.response?.data?.error || '发送失败'
} finally {
replying.value = false
}
}
const clearConv = async () => {
if (!selectedAccount.value || clearing.value) return
if (!confirm(`确认清除与 ${selectedAccount.value} 的全部对话?`)) return
clearing.value = true
try {
await adminClearConversation(props.adminToken, selectedAccount.value)
delete conversations.value[selectedAccount.value]
selectedAccount.value = ''
currentMessages.value = []
} catch {
alert('清除失败,请重试')
} finally {
clearing.value = false
}
}
onMounted(() => {
load()
pollTimer = setInterval(load, 8000)
})
onUnmounted(() => {
if (pollTimer) clearInterval(pollTimer)
})
</script>
<style scoped>
.chat-panel-section {
margin-top: 32px;
}
.chat-panel-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 14px;
}
.chat-panel-header h3 {
font-size: 18px;
font-weight: 700;
color: var(--text);
}
.refresh-btn {
padding: 5px 14px;
border-radius: 6px;
border: 1px solid var(--line);
background: rgba(255,255,255,0.7);
font-size: 13px;
cursor: pointer;
color: var(--text);
font-family: inherit;
}
.chat-empty {
padding: 24px 0;
text-align: center;
color: var(--muted);
font-size: 14px;
}
.chat-layout {
display: grid;
grid-template-columns: 200px 1fr;
height: 520px;
border-radius: 12px;
border: 1px solid var(--line);
overflow: hidden;
background: rgba(255, 255, 255, 0.4);
box-shadow: 0 8px 24px rgba(33, 33, 40, 0.08);
}
/* Conversation list */
.conv-list {
border-right: 1px solid var(--line);
overflow-y: auto;
background: rgba(255, 255, 255, 0.65);
display: flex;
flex-direction: column;
}
.conv-list-title {
padding: 12px 14px 8px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.8px;
text-transform: uppercase;
color: var(--muted);
border-bottom: 1px solid var(--line);
flex-shrink: 0;
}
.conv-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
cursor: pointer;
border-bottom: 1px solid rgba(255,255,255,0.5);
transition: background 0.15s;
}
.conv-item:hover {
background: rgba(180, 154, 203, 0.08);
}
.conv-item--active {
background: rgba(180, 154, 203, 0.14);
border-left: 3px solid var(--accent);
padding-left: 9px;
}
.conv-avatar {
width: 34px;
height: 34px;
border-radius: 50%;
background: #e8e8e8;
color: #444;
font-size: 14px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.conv-info {
flex: 1;
min-width: 0;
}
.conv-name {
font-size: 13px;
font-weight: 600;
color: var(--text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.conv-preview {
font-size: 11px;
color: var(--muted);
margin-top: 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Message thread */
.conv-thread {
display: flex;
flex-direction: column;
overflow: hidden;
background: rgba(255, 255, 255, 0.3);
}
.conv-thread--empty {
align-items: center;
justify-content: center;
color: var(--muted);
font-size: 14px;
}
.empty-hint {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
color: var(--muted);
font-size: 14px;
}
.thread-top {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 16px;
border-bottom: 1px solid var(--line);
background: rgba(255, 255, 255, 0.75);
flex-shrink: 0;
}
.thread-user {
display: flex;
align-items: center;
gap: 10px;
}
.thread-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
background: #e8e8e8;
color: #444;
font-size: 13px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.thread-user-info {
display: flex;
flex-direction: column;
gap: 1px;
}
.thread-name {
font-size: 14px;
font-weight: 700;
color: var(--text);
line-height: 1.2;
}
.thread-account {
font-size: 11px;
color: var(--muted);
}
.clear-btn {
padding: 5px 12px;
border-radius: 6px;
border: 1px solid rgba(210, 70, 70, 0.3);
background: rgba(210, 70, 70, 0.06);
color: #c04040;
font-size: 12px;
cursor: pointer;
font-family: inherit;
transition: background 0.15s;
white-space: nowrap;
}
.clear-btn:hover:not(:disabled) {
background: rgba(210, 70, 70, 0.14);
}
.thread-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.msg-row {
display: flex;
}
.msg-row--user {
justify-content: flex-start;
}
.msg-row--admin {
justify-content: flex-end;
}
.msg-bubble {
display: flex;
flex-direction: column;
gap: 3px;
max-width: 72%;
}
.msg-row--admin .msg-bubble {
align-items: flex-end;
}
.msg-meta {
display: flex;
gap: 6px;
align-items: baseline;
padding: 0 2px;
}
.msg-from {
font-size: 11px;
font-weight: 600;
color: var(--muted);
}
.msg-time {
font-size: 10px;
color: var(--muted);
opacity: 0.75;
}
.msg-content {
padding: 9px 13px;
border-radius: 12px;
font-size: 14px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
}
.msg-row--user .msg-content {
background: rgba(255, 255, 255, 0.85);
color: var(--text);
border: 1px solid var(--line);
border-bottom-left-radius: 4px;
}
.msg-row--admin .msg-content {
background: #2c2b2d;
color: #fff;
border-bottom-right-radius: 4px;
}
.reply-row {
display: flex;
gap: 8px;
padding: 10px 14px;
border-top: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
}
.reply-input {
flex: 1;
padding: 8px 12px;
border-radius: 7px;
border: 1px solid var(--line);
font-size: 14px;
font-family: inherit;
background: rgba(255, 255, 255, 0.9);
color: var(--text);
outline: none;
}
.reply-input:focus {
border-color: var(--accent, #7c6af0);
}
.reply-send-btn {
padding: 8px 18px;
border-radius: 7px;
background: #2c2b2d;
color: #fff;
border: none;
cursor: pointer;
font-size: 14px;
font-family: inherit;
font-weight: 600;
transition: opacity 0.2s;
}
.reply-send-btn:disabled {
opacity: 0.45;
cursor: default;
}
.reply-send-btn:not(:disabled):hover {
opacity: 0.82;
}
.reply-error {
font-size: 12px;
color: #d64848;
padding: 0 14px 8px;
text-align: right;
}
@media (max-width: 900px) {
.chat-panel-section {
margin-top: 16px;
}
.chat-layout {
grid-template-columns: 1fr;
grid-template-rows: auto 1fr;
height: 520px;
}
.conv-list {
border-right: none;
border-bottom: 1px solid var(--line);
overflow-x: auto;
overflow-y: hidden;
flex-direction: row;
max-height: 72px;
scrollbar-width: none;
}
.conv-list::-webkit-scrollbar {
display: none;
}
.conv-list-title {
display: none;
}
.conv-item {
flex-shrink: 0;
flex-direction: column;
align-items: center;
gap: 4px;
min-width: 70px;
max-width: 80px;
padding: 8px 6px;
border-bottom: none;
border-right: 1px solid var(--line);
text-align: center;
}
.conv-info {
display: flex;
flex-direction: column;
align-items: center;
}
.conv-name {
font-size: 11px;
max-width: 64px;
}
.conv-preview {
display: none;
}
.conv-avatar {
width: 28px;
height: 28px;
font-size: 12px;
}
}
</style>

View File

@@ -0,0 +1,155 @@
<template>
<div class="maintenance-row">
<div class="maintenance-left">
<span class="maintenance-label">站点维护模式</span>
<button
:class="['maintenance-toggle', enabled ? 'toggle-on' : 'toggle-off']"
type="button"
@click="$emit('update:enabled', !enabled)"
>
{{ enabled ? '维护中' : '正常运行' }}
</button>
<span
v-if="message"
class="msg-tag"
:class="{ error: message.includes('失败') }"
>{{ message }}</span>
</div>
<div class="maintenance-right">
<input
:value="reason"
@input="$emit('update:reason', $event.target.value)"
class="maintenance-reason-input"
placeholder="维护原因(选填)"
/>
<button class="ghost" type="button" @click="$emit('save')">保存</button>
</div>
</div>
</template>
<script setup>
defineProps({
enabled: { type: Boolean, default: false },
reason: { type: String, default: '' },
message: { type: String, default: '' }
})
defineEmits(['update:enabled', 'update:reason', 'save'])
</script>
<style scoped>
.maintenance-row {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 16px;
padding: 14px 18px;
background: rgba(255, 255, 255, 0.5);
border: 1px solid var(--line);
border-radius: 8px;
}
.maintenance-left {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
.maintenance-label {
font-size: 15px;
font-weight: 600;
color: var(--text);
white-space: nowrap;
}
.maintenance-toggle {
padding: 6px 16px;
border-radius: 999px;
font-size: 14px;
font-weight: 600;
border: none;
cursor: pointer;
transition: background 0.2s ease, transform 0.15s ease;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
}
.toggle-on {
background: rgba(201, 90, 106, 0.15);
color: #c95a6a;
}
.toggle-on:hover {
background: rgba(201, 90, 106, 0.25);
}
.toggle-off {
background: rgba(100, 185, 140, 0.15);
color: #3a9a68;
}
.toggle-off:hover {
background: rgba(100, 185, 140, 0.25);
}
.maintenance-right {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 0;
}
.maintenance-reason-input {
flex: 1;
min-width: 0;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 15px;
outline: none;
transition: border-color 0.2s ease;
}
.maintenance-reason-input:focus {
border-color: var(--accent);
}
.msg-tag {
font-size: 15px;
color: var(--accent-2);
padding: 4px 10px;
border-radius: 5px;
background: rgba(145, 168, 208, 0.1);
white-space: nowrap;
}
.msg-tag.error {
color: #c95a6a;
background: rgba(201, 90, 106, 0.08);
}
@media (max-width: 900px) {
.maintenance-row {
flex-direction: column;
align-items: stretch;
padding: 10px 12px;
gap: 10px;
}
.maintenance-right {
flex-direction: row;
flex-wrap: nowrap;
}
.maintenance-reason-input {
flex: 1;
min-width: 0;
font-size: 14px;
padding: 7px 10px;
}
}
</style>

View File

@@ -0,0 +1,404 @@
<template>
<div class="orders-section">
<div class="orders-header">
<h3>下单记录</h3>
<p class="tag"> {{ orders.length }} 条订单含未登录用户</p>
</div>
<div v-if="orders.length === 0" class="empty-tip tag">暂无订单记录</div>
<div v-else class="table-wrap">
<!-- Pagination toolbar (top) -->
<div class="pagination-bar" v-if="totalPages > 1">
<button class="page-btn" :disabled="currentPage === 1" @click="currentPage--"></button>
<span class="page-info"> {{ currentPage }} / {{ totalPages }} {{ orders.length }} </span>
<button class="page-btn" :disabled="currentPage === totalPages" @click="currentPage++"></button>
</div>
<table class="table">
<thead>
<tr>
<th>商品</th>
<th>用户</th>
<th class="col-num">数量</th>
<th>发货</th>
<th>状态</th>
<th>下单时间</th>
<th class="col-action"></th>
</tr>
</thead>
<tbody>
<template v-for="order in pagedOrders" :key="order.id">
<tr :class="{ 'row-pending': order.status === 'pending' }">
<td>
<div class="order-product">
<span class="order-product-name">{{ order.productName }}</span>
<span class="order-id">{{ order.id }}</span>
</div>
</td>
<td>
<div v-if="order.userAccount" class="user-info">
<span class="user-name">{{ order.userName || order.userAccount }}</span>
<span class="user-account">{{ order.userAccount }}</span>
</div>
<span v-else class="anon-badge">匿名</span>
</td>
<td class="col-num">{{ order.quantity }}</td>
<td>
<span :class="['delivery-badge', order.deliveryMode === 'manual' ? 'delivery-manual' : 'delivery-auto']">
{{ order.deliveryMode === 'manual' ? '手动' : '自动' }}
</span>
</td>
<td>
<span :class="['status-badge', order.status === 'completed' ? 'status-done' : 'status-wait']">
{{ order.status === 'completed' ? '已完成' : '待付款' }}
</span>
</td>
<td class="col-time">{{ formatTime(order.createdAt) }}</td>
<td class="col-action">
<button class="del-btn" @click="remove(order.id)" title="删除此订单"></button>
</td>
</tr>
<tr v-if="order.note || order.contactPhone || order.contactEmail" class="extra-row">
<td colspan="7">
<div class="extra-info">
<span v-if="order.note" class="extra-item">
<span class="extra-label">备注</span>{{ order.note }}
</span>
<span v-if="order.contactPhone" class="extra-item">
<span class="extra-label">手机</span>{{ order.contactPhone }}
</span>
<span v-if="order.contactEmail" class="extra-item">
<span class="extra-label">邮箱</span>{{ order.contactEmail }}
</span>
</div>
</td>
</tr>
</template>
</tbody>
</table>
</div>
</div>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
const props = defineProps({
orders: { type: Array, default: () => [] }
})
const emit = defineEmits(['remove'])
const PAGE_SIZE = 10
const currentPage = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(props.orders.length / PAGE_SIZE)))
const pagedOrders = computed(() => {
const start = (currentPage.value - 1) * PAGE_SIZE
return props.orders.slice(start, start + PAGE_SIZE)
})
// 订单列表变化时重置到第一页
watch(() => props.orders.length, () => { currentPage.value = 1 })
const remove = (id) => {
if (confirm('确认删除此订单记录?此操作不可撤销。')) {
emit('remove', id)
}
}
const formatTime = (iso) => {
if (!iso) return '-'
const d = new Date(iso)
return d.toLocaleString('zh-CN', { hour12: false })
}
</script>
<style scoped>
.orders-section {
margin-top: 28px;
}
.orders-header {
display: flex;
align-items: baseline;
gap: 12px;
margin-bottom: 12px;
}
.orders-header h3 {
font-size: 18px;
font-weight: 700;
color: var(--text);
}
.empty-tip {
padding: 20px 0;
text-align: center;
color: var(--muted);
}
.table-wrap {
border-radius: 8px;
overflow: hidden;
border: 1px solid var(--line);
}
.table {
width: 100%;
border-collapse: collapse;
background: rgba(255, 255, 255, 0.45);
}
.table thead tr {
background: rgba(255, 255, 255, 0.7);
border-bottom: 2px solid var(--line);
}
.table th {
padding: 11px 14px;
font-size: 13px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--muted);
}
.table td {
padding: 12px 14px;
font-size: 15px;
vertical-align: middle;
}
.table tbody tr {
border-bottom: 1px solid var(--line);
transition: background 0.15s ease;
}
.table tbody tr:last-child {
border-bottom: none;
}
.table tbody tr:hover {
background: rgba(255, 255, 255, 0.7);
}
.table tbody tr.row-pending {
opacity: 0.7;
}
.col-num {
text-align: center;
}
.col-time {
font-size: 13px;
color: var(--muted);
white-space: nowrap;
}
.order-product {
display: flex;
flex-direction: column;
gap: 2px;
}
.order-product-name {
font-weight: 600;
color: var(--text);
font-size: 15px;
}
.order-id {
font-size: 12px;
color: var(--muted);
font-family: monospace;
}
.user-info {
display: flex;
flex-direction: column;
gap: 2px;
}
.user-name {
font-weight: 600;
font-size: 15px;
color: var(--text);
}
.user-account {
font-size: 12px;
color: var(--muted);
}
.anon-badge {
padding: 3px 10px;
border-radius: 999px;
background: rgba(140, 140, 145, 0.12);
color: var(--muted);
font-size: 13px;
}
.status-badge {
display: inline-block;
padding: 3px 10px;
border-radius: 999px;
font-size: 13px;
font-weight: 600;
}
.status-done {
background: rgba(100, 185, 140, 0.15);
color: #3a9a68;
}
.status-wait {
background: rgba(220, 178, 90, 0.15);
color: #b87e20;
}
.delivery-badge {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
}
.delivery-auto {
background: rgba(100, 185, 140, 0.12);
color: #3a9a68;
}
.delivery-manual {
background: rgba(90, 120, 200, 0.12);
color: #5a78c8;
}
.extra-row td {
padding: 6px 14px 10px;
background: rgba(250, 250, 255, 0.5);
}
.extra-info {
display: flex;
flex-wrap: wrap;
gap: 12px 20px;
font-size: 13px;
color: var(--text);
}
.extra-item {
display: inline-flex;
gap: 3px;
}
.extra-label {
color: var(--muted);
font-weight: 600;
}
.col-action {
text-align: center;
width: 40px;
}
.del-btn {
background: none;
border: none;
color: var(--muted);
font-size: 13px;
cursor: pointer;
padding: 3px 6px;
border-radius: 4px;
line-height: 1;
transition: color 0.15s, background 0.15s;
}
.del-btn:hover {
color: #d64848;
background: rgba(214, 72, 72, 0.1);
}
.tag {
font-size: 14px;
color: var(--muted);
}
.pagination-bar {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
border-bottom: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
}
.page-btn {
padding: 4px 12px;
border-radius: 6px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.8);
font-size: 16px;
cursor: pointer;
color: var(--text);
font-family: inherit;
transition: background 0.15s;
line-height: 1;
}
.page-btn:disabled {
opacity: 0.35;
cursor: default;
}
.page-btn:not(:disabled):hover {
background: rgba(124, 106, 240, 0.1);
}
.page-info {
font-size: 13px;
color: var(--muted);
}
@media (max-width: 900px) {
.orders-section {
margin-top: 12px;
}
.table-wrap {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.table {
min-width: 560px;
}
.table th,
.table td {
padding: 7px 8px;
font-size: 12px;
}
.col-time {
display: none;
}
.pagination-bar {
padding: 6px 10px;
gap: 8px;
}
.page-info {
font-size: 12px;
}
.page-btn {
width: 28px;
height: 28px;
font-size: 16px;
}
}
</style>

View File

@@ -0,0 +1,431 @@
<template>
<div v-if="open" class="modal-mask" @click.self="$emit('close')">
<section class="modal-card">
<div class="modal-header">
<div>
<h3>{{ form.id ? '编辑商品' : '添加新商品' }}</h3>
<p class="tag">封面图和最多 5 张商品截图共用这一套编辑表单</p>
</div>
<button class="ghost" @click="$emit('close')">关闭</button>
</div>
<div class="modal-body">
<div class="form-field">
<label>商品名称</label>
<input v-model="form.name" placeholder="商品名称" />
</div>
<div class="form-row">
<div class="form-field">
<label>原价</label>
<input v-model.number="form.price" type="number" step="0.01" />
</div>
<div class="form-field">
<label>折扣价可选</label>
<input v-model.number="form.discountPrice" type="number" step="0.01" />
<p class="tag">留空或不小于原价时将不启用折扣</p>
</div>
</div>
<div class="form-field">
<label>封面链接http</label>
<input v-model="form.coverUrl" placeholder="http://..." />
</div>
<div class="form-field">
<div class="field-head">
<label>商品库存</label>
<span class="tag"> {{ form.inventoryItems.length }} </span>
<button class="ghost small" type="button" @click="addInventoryItem">添加商品库存</button>
</div>
<p class="tag">每个输入框保存一条可发放内容购买后会直接展示给用户</p>
<div class="inventory-list">
<div v-for="(_, index) in form.inventoryItems" :key="index" class="inventory-row">
<input
:ref="(el) => setInventoryInputRef(el, index)"
v-model="form.inventoryItems[index]"
placeholder="库存内容,可填卡密、下载链接等"
/>
<button
v-if="form.inventoryItems.length > 1"
class="ghost small"
type="button"
@click="removeInventoryItem(index)"
>
删除
</button>
</div>
</div>
</div>
<div class="form-field">
<label>商品截图链接最多 5 </label>
<div class="screenshot-grid">
<input
v-for="(_, index) in screenshotInputSlots"
:key="index"
v-model="form.screenshotUrls[index]"
:placeholder="`截图链接 ${index + 1}http://...`"
/>
</div>
</div>
<div class="form-field">
<label>商品介绍Markdown</label>
<textarea v-model="form.description"></textarea>
</div>
<div class="form-field">
<label>商品标签英文逗号分隔</label>
<input v-model="form.tagsText" placeholder="例如: chatgpt, linux, 域名" />
<p class="tag">用于前端搜索与筛选多个标签用英文逗号分开</p>
</div>
<div class="form-field">
<label>是否上架</label>
<select v-model="form.active">
<option :value="true">上架</option>
<option :value="false">下架</option>
</select>
</div>
<div class="form-row">
<div class="form-field">
<label>
<input type="checkbox" v-model="form.requireLogin" class="inline-checkbox" />
需要登录才能购买
</label>
<p class="tag">开启后未登录用户将无法完成购买</p>
</div>
<div class="form-field">
<label>每账户最多购买数量0 = 不限</label>
<input v-model.number="form.maxPerAccount" type="number" min="0" step="1" placeholder="0 表示不限制" />
</div>
</div>
<div class="form-row">
<div class="form-field">
<label>发货模式</label>
<select v-model="form.deliveryMode">
<option value="auto">自动发货下单后自动提取内容</option>
<option value="manual">手动发货管理员手动处理</option>
</select>
<p class="tag">手动发货不会自动提取库存内容</p>
</div>
</div>
<div class="form-row">
<div class="form-field">
<label>
<input type="checkbox" v-model="form.showNote" class="inline-checkbox" />
下单时显示备注输入框
</label>
</div>
<div class="form-field">
<label>
<input type="checkbox" v-model="form.showContact" class="inline-checkbox" />
下单时显示联系方式输入框
</label>
<p class="tag">包含手机号和邮箱两个输入框</p>
</div>
</div>
</div>
<div class="modal-actions">
<button class="primary" @click="handleSubmit">{{ form.id ? '更新商品' : '新增商品' }}</button>
<button class="ghost" @click="resetForm">重置表单</button>
</div>
</section>
</div>
</template>
<script setup>
import { nextTick, reactive, ref, watch } from 'vue'
const MAX_SCREENSHOT_URLS = 5
const MAX_INVENTORY_ITEMS = 500
const screenshotInputSlots = Array.from({ length: MAX_SCREENSHOT_URLS })
const inventoryInputRefs = ref([])
const props = defineProps({
open: { type: Boolean, default: false },
editItem: { type: Object, default: null }
})
const emit = defineEmits(['close', 'submit'])
const createScreenshotSlots = (values = []) =>
Array.from({ length: MAX_SCREENSHOT_URLS }, (_, i) => values[i] || '')
const createInventoryItems = (values = []) => {
const items = values
.map((v) => (v || '').trim())
.filter((v) => v)
.slice(0, MAX_INVENTORY_ITEMS)
return items.length ? items : ['']
}
const normalizeInventoryItems = (values = []) =>
values
.map((item) => (item || '').trim())
.filter((item) => item)
.slice(0, MAX_INVENTORY_ITEMS)
const normalizeScreenshotUrls = (values = []) =>
values.map((item) => item.trim()).filter(Boolean).slice(0, MAX_SCREENSHOT_URLS)
const makeEmptyForm = () => ({
id: '',
name: '',
price: 0,
discountPrice: 0,
tagsText: '',
coverUrl: '',
screenshotUrls: createScreenshotSlots(),
inventoryItems: createInventoryItems(),
description: '',
active: true,
requireLogin: false,
maxPerAccount: 0,
deliveryMode: 'auto',
showNote: false,
showContact: false
})
const form = reactive(makeEmptyForm())
const fillForm = (item) => {
Object.assign(form, {
id: item?.id || '',
name: item?.name || '',
price: item?.price || 0,
discountPrice: item?.discountPrice || 0,
tagsText: (item?.tags || []).join(','),
coverUrl: item?.coverUrl || '',
screenshotUrls: createScreenshotSlots(item?.screenshotUrls || []),
inventoryItems: createInventoryItems(item?.codes || []),
description: item?.description || '',
active: item?.active ?? true,
requireLogin: item?.requireLogin ?? false,
maxPerAccount: item?.maxPerAccount ?? 0,
deliveryMode: item?.deliveryMode || 'auto',
showNote: item?.showNote ?? false,
showContact: item?.showContact ?? false
})
}
const resetForm = () => {
Object.assign(form, makeEmptyForm())
}
watch(
() => props.editItem,
(item) => {
if (item) {
fillForm(item)
} else {
resetForm()
}
},
{ immediate: true }
)
const setInventoryInputRef = (el, index) => {
if (!el) return
inventoryInputRefs.value[index] = el
}
const addInventoryItem = async () => {
form.inventoryItems.push('')
await nextTick()
const lastIndex = form.inventoryItems.length - 1
const input = inventoryInputRefs.value[lastIndex]
if (input?.focus) input.focus()
if (input?.scrollIntoView) input.scrollIntoView({ block: 'center', behavior: 'smooth' })
}
const removeInventoryItem = async (index) => {
if (form.inventoryItems.length <= 1) {
form.inventoryItems[0] = ''
return
}
form.inventoryItems.splice(index, 1)
inventoryInputRefs.value.splice(index, 1)
await nextTick()
const targetIndex = Math.min(index, form.inventoryItems.length - 1)
const input = inventoryInputRefs.value[targetIndex]
if (input?.focus) input.focus()
}
const handleSubmit = () => {
emit('submit', {
id: form.id,
name: form.name,
price: form.price,
discountPrice: form.discountPrice || 0,
tags: form.tagsText,
coverUrl: form.coverUrl,
codes: normalizeInventoryItems(form.inventoryItems),
screenshotUrls: normalizeScreenshotUrls(form.screenshotUrls),
description: form.description,
active: form.active,
requireLogin: form.requireLogin,
maxPerAccount: form.maxPerAccount || 0,
deliveryMode: form.deliveryMode || 'auto',
showNote: form.showNote,
showContact: form.showContact
})
}
</script>
<style scoped>
.modal-mask {
position: fixed;
inset: 0;
z-index: 40;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(30, 28, 32, 0.35);
backdrop-filter: blur(8px);
}
.modal-card {
width: min(920px, 100%);
max-height: calc(100vh - 48px);
overflow: auto;
padding: 28px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.95);
border: 1px solid var(--line);
box-shadow: 0 24px 60px rgba(33, 33, 40, 0.2);
}
.modal-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 22px;
}
.modal-body {
display: flex;
flex-direction: column;
gap: 2px;
}
.modal-actions {
display: flex;
gap: 12px;
margin-top: 20px;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.form-field {
display: flex;
flex-direction: column;
gap: 6px;
margin-bottom: 12px;
}
.form-field input,
.form-field textarea {
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
padding: 10px 12px;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
}
.form-field textarea {
min-height: 120px;
resize: vertical;
}
select {
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
padding: 10px 12px;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 15px;
}
.form-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.field-head {
display: flex;
align-items: center;
gap: 12px;
}
.inventory-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.inventory-row {
display: flex;
align-items: center;
gap: 8px;
}
.inventory-row input {
flex: 1;
}
.screenshot-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.small {
padding: 7px 13px;
font-size: 13px;
border-radius: 999px;
}
.tag {
font-size: 14px;
color: var(--muted);
}
.inline-checkbox {
width: auto;
margin-right: 6px;
accent-color: var(--accent);
cursor: pointer;
}
.form-field label {
display: flex;
align-items: center;
font-weight: 600;
color: var(--text);
cursor: default;
}
@media (max-width: 900px) {
.modal-mask {
padding: 12px;
}
.modal-card {
padding: 18px;
max-height: calc(100vh - 24px);
}
.form-row,
.screenshot-grid {
grid-template-columns: 1fr;
}
.field-head {
flex-wrap: wrap;
}
.inventory-row {
flex-direction: column;
align-items: stretch;
}
}
</style>

View File

@@ -0,0 +1,317 @@
<template>
<div class="table-wrap">
<table class="table">
<thead>
<tr>
<th>商品</th>
<th>价格</th>
<th class="col-num">库存</th>
<th class="col-num">浏览量</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in products" :key="item.id" :class="{ 'row-inactive': !item.active }">
<td>
<div class="admin-product-cell">
<img class="admin-product-thumb" :src="item.coverUrl" :alt="item.name" />
<div class="admin-product-info">
<span class="product-name">{{ item.name }}</span>
<span class="product-id">{{ item.id }}</span>
</div>
</div>
</td>
<td>
<div v-if="item.price === 0" class="price-cell">
<span class="price-free">免费</span>
</div>
<div
v-else-if="item.discountPrice > 0 && item.discountPrice < item.price"
class="price-cell"
>
<span class="price-original">¥{{ item.price.toFixed(2) }}</span>
<span class="price-discount">¥{{ item.discountPrice.toFixed(2) }}</span>
</div>
<span v-else class="price-normal">¥{{ item.price.toFixed(2) }}</span>
</td>
<td class="col-num">
<span :class="['stock-badge', item.quantity === 0 ? 'stock-empty' : 'stock-ok']">
{{ item.quantity }}
</span>
</td>
<td class="col-num">
<span class="view-count">{{ item.viewCount || 0 }}</span>
</td>
<td>
<span :class="['status-badge', item.active ? 'status-on' : 'status-off']">
{{ item.active ? '上架' : '下架' }}
</span>
</td>
<td>
<div class="row-actions">
<button class="act-edit" @click="$emit('edit', item)">编辑</button>
<button class="act-toggle" @click="$emit('toggle', item)">
{{ item.active ? '下架' : '上架' }}
</button>
<button class="act-delete" @click="$emit('remove', item)">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup>
defineProps({
products: { type: Array, default: () => [] }
})
defineEmits(['edit', 'toggle', 'remove'])
</script>
<style scoped>
.table-wrap {
border-radius: 8px;
overflow: hidden;
border: 1px solid var(--line);
}
.table {
width: 100%;
border-collapse: collapse;
background: rgba(255, 255, 255, 0.45);
}
.table thead tr {
background: rgba(255, 255, 255, 0.7);
border-bottom: 2px solid var(--line);
}
.table th {
padding: 12px 16px;
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.6px;
color: var(--muted);
}
.table td {
padding: 14px 16px;
font-size: 16px;
vertical-align: middle;
}
.table tbody tr {
border-bottom: 1px solid var(--line);
transition: background 0.15s ease;
}
.table tbody tr:last-child {
border-bottom: none;
}
.table tbody tr:hover {
background: rgba(255, 255, 255, 0.7);
}
.table tbody tr.row-inactive {
opacity: 0.55;
}
.col-num {
text-align: center;
}
.admin-product-cell {
display: flex;
align-items: center;
gap: 12px;
}
.admin-product-thumb {
width: 48px;
height: 48px;
border-radius: 6px;
object-fit: cover;
border: 1px solid var(--line);
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(33, 33, 40, 0.1);
}
.admin-product-info {
display: flex;
flex-direction: column;
gap: 3px;
}
.product-name {
font-size: 16px;
font-weight: 600;
color: var(--text);
}
.product-id {
font-size: 13px;
color: var(--muted);
font-family: monospace;
}
.price-cell {
display: flex;
flex-direction: column;
gap: 2px;
}
.price-original {
text-decoration: line-through;
color: var(--muted);
font-size: 14px;
}
.price-discount {
font-weight: 700;
color: #e8826a;
font-size: 17px;
}
.price-free {
font-weight: 900;
color: #3a9a68;
font-size: 17px;
}
.price-normal {
font-weight: 600;
color: var(--text);
}
.stock-badge {
display: inline-block;
padding: 3px 10px;
border-radius: 999px;
font-size: 15px;
font-weight: 600;
}
.stock-ok {
background: rgba(100, 185, 140, 0.15);
color: #3a9a68;
}
.stock-empty {
background: rgba(201, 90, 106, 0.12);
color: #c95a6a;
}
.view-count {
color: var(--muted);
font-size: 15px;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 12px;
border-radius: 999px;
font-size: 14px;
font-weight: 600;
letter-spacing: 0.3px;
}
.status-on {
background: rgba(100, 185, 140, 0.15);
color: #3a9a68;
}
.status-off {
background: rgba(140, 140, 145, 0.12);
color: var(--muted);
}
.row-actions {
display: flex;
gap: 6px;
align-items: center;
}
.act-edit,
.act-toggle,
.act-delete {
padding: 6px 12px;
border-radius: 5px;
font-size: 14px;
font-weight: 600;
border: none;
cursor: pointer;
transition: opacity 0.15s ease, transform 0.15s ease;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
}
.act-edit {
background: rgba(145, 168, 208, 0.15);
color: var(--accent-2);
}
.act-edit:hover {
background: rgba(145, 168, 208, 0.28);
}
.act-toggle {
background: rgba(180, 154, 203, 0.12);
color: var(--accent);
}
.act-toggle:hover {
background: rgba(180, 154, 203, 0.24);
}
.act-delete {
background: rgba(201, 90, 106, 0.1);
color: #c95a6a;
}
.act-delete:hover {
background: rgba(201, 90, 106, 0.2);
}
@media (max-width: 900px) {
.table-wrap {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.table {
min-width: 580px;
}
.table th,
.table td {
padding: 8px 10px;
font-size: 13px;
}
.admin-product-thumb {
width: 36px;
height: 36px;
}
.product-name {
font-size: 13px;
}
.product-id {
font-size: 11px;
}
.act-edit,
.act-toggle,
.act-delete {
padding: 4px 8px;
font-size: 12px;
}
}
</style>

View File

@@ -0,0 +1,239 @@
<template>
<div class="smtp-row">
<div class="smtp-header">
<span class="smtp-label">邮件通知配置</span>
<span class="smtp-desc tag">下单/发货时自动给用户发送通知邮件支持 QQ / 163 / Gmail / 自定义域名邮箱</span>
<span v-if="message" class="msg-tag" :class="{ error: message.includes('失败') }">{{ message }}</span>
</div>
<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">
<span>发件邮箱</span>
<input v-model="form.email" type="email" placeholder="noreply@yourdomain.com" :disabled="!form.enabled" />
</label>
<label class="smtp-field">
<span>SMTP 密码 / 授权码</span>
<input v-model="form.password" type="password" placeholder="QQ/163 填授权码;其他填密码" autocomplete="new-password" :disabled="!form.enabled" />
</label>
<label class="smtp-field">
<span>发件人名称</span>
<input v-model="form.fromName" type="text" placeholder="萌芽小店" :disabled="!form.enabled" />
</label>
<label class="smtp-field">
<span>SMTP 主机</span>
<input v-model="form.host" type="text" placeholder="smtp.qq.com" :disabled="!form.enabled" />
</label>
<label class="smtp-field smtp-field-port">
<span>端口</span>
<input v-model="form.port" type="text" placeholder="465" :disabled="!form.enabled" />
</label>
<button class="primary smtp-save-btn" type="button" :disabled="saving" @click="save">
{{ saving ? '保存中...' : '保存配置' }}
</button>
</div>
</div>
</template>
<script setup>
import { reactive, ref, watch } from 'vue'
const props = defineProps({
config: { type: Object, default: () => ({}) },
message: { type: String, default: '' }
})
const emit = defineEmits(['save'])
const saving = ref(false)
const form = reactive({
enabled: true,
email: '',
password: '',
fromName: '',
host: 'smtp.qq.com',
port: '465'
})
watch(() => props.config, (cfg) => {
if (!cfg) return
form.enabled = cfg.enabled !== false
form.email = cfg.email || ''
form.password = cfg.password || ''
form.fromName = cfg.fromName || ''
form.host = cfg.host || 'smtp.qq.com'
form.port = cfg.port || '465'
}, { immediate: true })
const save = async () => {
saving.value = true
try {
await emit('save', { ...form })
} finally {
saving.value = false
}
}
</script>
<style scoped>
.smtp-row {
padding: 14px 18px;
background: rgba(255, 255, 255, 0.5);
border: 1px solid var(--line);
border-radius: 8px;
margin-bottom: 16px;
}
.smtp-header {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.smtp-label {
font-size: 15px;
font-weight: 600;
color: var(--text);
white-space: nowrap;
}
.smtp-desc {
font-size: 13px;
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 {
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: flex-end;
}
.smtp-fields-disabled {
opacity: 0.45;
pointer-events: none;
}
.smtp-field {
display: flex;
flex-direction: column;
gap: 4px;
flex: 1;
min-width: 160px;
}
.smtp-field-port {
max-width: 90px;
flex: 0 0 90px;
}
.smtp-field span {
font-size: 13px;
color: var(--muted);
}
.smtp-field input {
padding: 8px 10px;
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 14px;
outline: none;
transition: border-color 0.2s ease;
width: 100%;
box-sizing: border-box;
}
.smtp-field input:focus {
border-color: var(--accent);
}
.smtp-save-btn {
align-self: flex-end;
padding: 8px 18px;
font-size: 14px;
white-space: nowrap;
}
.msg-tag {
font-size: 14px;
color: var(--accent-2);
padding: 3px 8px;
border-radius: 5px;
background: rgba(145, 168, 208, 0.1);
white-space: nowrap;
}
.msg-tag.error {
color: #c95a6a;
background: rgba(201, 90, 106, 0.08);
}
@media (max-width: 900px) {
.smtp-fields {
flex-direction: column;
}
.smtp-field {
min-width: 0;
width: 100%;
}
.smtp-field-port {
max-width: 100%;
flex: 1;
}
}
</style>

View File

@@ -0,0 +1,102 @@
<template>
<div v-if="show" class="token-row">
<div class="form-field token-field">
<label>管理 Token</label>
<div class="token-input-wrap">
<input :value="token" @input="$emit('update:token', $event.target.value)" placeholder="粘贴管理员令牌后自动加载…" />
</div>
</div>
<p
v-if="message"
class="msg-tag"
:class="{ error: message.includes('失败') || message.includes('错误') }"
>{{ message }}</p>
</div>
<p
v-if="inlineMessage"
class="msg-inline"
:class="{ error: inlineMessage.includes('失败') || inlineMessage.includes('错误') }"
>{{ inlineMessage }}</p>
</template>
<script setup>
defineProps({
show: { type: Boolean, default: true },
token: { type: String, default: '' },
message: { type: String, default: '' },
inlineMessage: { type: String, default: '' }
})
defineEmits(['update:token'])
</script>
<style scoped>
.token-row {
display: flex;
align-items: flex-end;
gap: 14px;
margin-bottom: 16px;
padding: 16px 18px;
background: rgba(255, 255, 255, 0.5);
border: 1px solid var(--line);
border-radius: 8px;
}
.token-field {
flex: 1;
max-width: 460px;
margin-bottom: 0;
}
.token-input-wrap {
display: flex;
gap: 8px;
align-items: center;
}
.token-input-wrap input {
flex: 1;
}
.msg-tag {
font-size: 15px;
color: var(--accent-2);
padding: 4px 10px;
border-radius: 5px;
background: rgba(145, 168, 208, 0.1);
white-space: nowrap;
}
.msg-tag.error {
color: #c95a6a;
background: rgba(201, 90, 106, 0.08);
}
.msg-inline {
font-size: 15px;
color: var(--accent-2);
margin-bottom: 12px;
}
.msg-inline.error {
color: #c95a6a;
}
.small {
padding: 7px 13px;
font-size: 13px;
border-radius: 999px;
}
@media (max-width: 900px) {
.token-row {
flex-direction: column;
align-items: stretch;
padding: 12px 12px;
}
.token-field {
max-width: 100%;
}
}
</style>

View File

@@ -22,7 +22,7 @@
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { setAuth } from '../shared/auth'
import { verifySproutGateToken, fetchSproutGateUser } from '../shared/api'
import { verifySproutGateToken } from '../shared/api'
const router = useRouter()
const status = ref('loading')
@@ -37,12 +37,13 @@ const parseFragment = () => {
return {
token: params.get('token') || '',
account: params.get('account') || '',
username: params.get('username') || ''
username: params.get('username') || '',
avatarUrl: params.get('avatarUrl') || ''
}
}
onMounted(async () => {
const { token, account, username } = parseFragment()
const { token, account, username, avatarUrl: fragmentAvatar } = parseFragment()
if (!token) {
status.value = 'error'
@@ -51,6 +52,7 @@ onMounted(async () => {
}
try {
// 验证 token 并从 SproutGate 获取最新用户信息
const verifyData = await verifySproutGateToken(token)
if (!verifyData.valid) {
status.value = 'error'
@@ -58,33 +60,19 @@ onMounted(async () => {
return
}
let avatarUrl = verifyData.user?.avatarUrl || ''
let finalAccount = verifyData.user?.account || account
let finalUsername = verifyData.user?.username || username
if (!avatarUrl) {
try {
const meData = await fetchSproutGateUser(token)
avatarUrl = meData.user?.avatarUrl || ''
finalAccount = meData.user?.account || finalAccount
finalUsername = meData.user?.username || finalUsername
} catch {
// /me failed, proceed with what we have
}
}
setAuth({
token,
account: finalAccount,
username: finalUsername,
avatarUrl
})
const user = verifyData.user || {}
const finalAccount = user.account || account
const finalUsername = user.username || username
const finalAvatarUrl = user.avatarUrl || fragmentAvatar
const finalEmail = user.email || ''
setAuth({ token, account: finalAccount, username: finalUsername, avatarUrl: finalAvatarUrl, email: finalEmail })
displayName.value = finalUsername || finalAccount
status.value = 'success'
setTimeout(() => router.push('/'), 1000)
} catch {
setAuth({ token, account, username, avatarUrl: '' })
// 验证失败(如网络异常)时,回退使用 URL fragment 中的数据
setAuth({ token, account, username, avatarUrl: fragmentAvatar })
displayName.value = username || account
status.value = 'success'
setTimeout(() => router.push('/'), 1000)

View File

@@ -0,0 +1,545 @@
<template>
<!-- Floating toggle button -->
<button class="chat-fab" @click="toggleOpen" :title="open ? '关闭' : '联系客服'" aria-label="联系客服">
<Transition name="icon-flip" mode="out-in">
<svg v-if="!open" key="chat" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
</svg>
<svg v-else key="close" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</Transition>
</button>
<!-- Chat panel -->
<Transition name="chat-slide">
<div v-if="open" class="chat-panel">
<!-- Header -->
<div class="chat-header">
<div class="chat-header-avatar">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
</div>
<div class="chat-header-info">
<span class="chat-title">在线客服</span>
<span class="chat-subtitle">有问题随时找我们</span>
</div>
<button class="chat-close-btn" @click="toggleOpen" title="关闭">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<!-- Messages -->
<div class="chat-messages" ref="messagesEl">
<div v-if="loading" class="chat-status">
<span class="loading-dots"><span>.</span><span>.</span><span>.</span></span>
</div>
<div v-else-if="messages.length === 0" class="chat-empty-state">
<div class="chat-empty-icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.4"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</div>
<p class="chat-empty-text">有任何疑问欢迎留言</p>
<p class="chat-empty-sub">客服在线时会尽快回复您</p>
</div>
<template v-else>
<div
v-for="msg in messages"
:key="msg.id"
:class="['msg-row', msg.fromAdmin ? 'msg-row--admin' : 'msg-row--me']"
>
<div v-if="msg.fromAdmin" class="msg-avatar msg-avatar--admin">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
</div>
<div class="msg-body">
<div class="msg-meta">
<span class="msg-name">{{ msg.fromAdmin ? '客服' : '我' }}</span>
<span class="msg-time">{{ formatTime(msg.sentAt) }}</span>
</div>
<div class="msg-content">{{ msg.content }}</div>
</div>
<div v-if="!msg.fromAdmin" class="msg-avatar msg-avatar--me">
<img v-if="props.userAvatar" :src="props.userAvatar" class="avatar-img" />
<span v-else>{{ (props.userName || '').charAt(0) }}</span>
</div>
</div>
</template>
</div>
<!-- Input -->
<form class="chat-input-row" @submit.prevent="send">
<input
v-model="inputText"
class="chat-input"
placeholder="输入消息Enter 发送…"
maxlength="500"
:disabled="sending"
@keydown.enter.exact.prevent="send"
/>
<button class="chat-send-btn" type="submit" :disabled="sending || !inputText.trim()">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2" fill="currentColor" stroke="none"/></svg>
</button>
</form>
<p class="chat-error" v-if="error">{{ error }}</p>
</div>
</Transition>
</template>
<script setup>
import { ref, nextTick, onUnmounted } from 'vue'
import { fetchMyChatMessages, sendChatMessage } from '../shared/api.js'
const props = defineProps({
userToken: { type: String, required: true },
userName: { type: String, default: '我' },
userAvatar: { type: String, default: '' }
})
const open = ref(false)
const messages = ref([])
const loading = ref(false)
const inputText = ref('')
const sending = ref(false)
const error = ref('')
const messagesEl = ref(null)
let pollTimer = null
const formatTime = (iso) => {
if (!iso) return ''
const d = new Date(iso)
return d.toLocaleString('zh-CN', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}
const scrollBottom = async () => {
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
}
const loadMessages = async () => {
try {
messages.value = await fetchMyChatMessages(props.userToken)
await scrollBottom()
} catch {
// 静默忽略轮询错误,避免频繁弹出错误提示
}
}
const startPolling = () => {
pollTimer = setInterval(loadMessages, 5000)
}
const stopPolling = () => {
if (pollTimer) {
clearInterval(pollTimer)
pollTimer = null
}
}
const toggleOpen = async () => {
open.value = !open.value
if (open.value) {
loading.value = true
await loadMessages()
loading.value = false
startPolling()
} else {
stopPolling()
}
}
const send = async () => {
const content = inputText.value.trim()
if (!content || sending.value) return
sending.value = true
error.value = ''
try {
const msg = await sendChatMessage(props.userToken, content)
if (msg) {
messages.value.push(msg)
inputText.value = ''
await scrollBottom()
}
} catch (err) {
error.value = err?.response?.data?.error || '发送失败,请稍后重试'
} finally {
sending.value = false
}
}
onUnmounted(stopPolling)
</script>
<style scoped>
/* ── FAB button ── */
.chat-fab {
position: fixed;
right: 24px;
bottom: 28px;
z-index: 1200;
width: 52px;
height: 52px;
border-radius: 50%;
background: #2c2b2d;
color: #fff;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.28);
transition: transform 0.2s, box-shadow 0.2s;
}
.chat-fab:hover {
transform: scale(1.08);
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.38);
}
/* ── Panel ── */
.chat-panel {
position: fixed;
right: 24px;
bottom: 94px;
z-index: 1200;
width: 340px;
height: 500px;
display: flex;
flex-direction: column;
border-radius: 16px;
background: rgba(255, 255, 255, 0.97);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 0 16px 56px rgba(0, 0, 0, 0.16);
border: 1px solid rgba(255, 255, 255, 0.6);
overflow: hidden;
}
/* ── Header ── */
.chat-header {
display: flex;
align-items: center;
gap: 10px;
padding: 13px 16px;
background: #fff;
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
flex-shrink: 0;
}
.chat-header-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
background: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: #555;
}
.chat-header-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 1px;
}
.chat-title {
font-size: 15px;
font-weight: 700;
color: #1a1a1a;
line-height: 1.2;
}
.chat-subtitle {
font-size: 11px;
color: #888;
}
.chat-close-btn {
background: rgba(0,0,0,0.1);
border: none;
width: 28px;
height: 28px;
border-radius: 50%;
color: #333;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.15s;
flex-shrink: 0;
}
.chat-close-btn:hover {
background: rgba(0,0,0,0.18);
}
/* ── Messages area ── */
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 14px 12px;
display: flex;
flex-direction: column;
gap: 12px;
scrollbar-width: none;
background: #f8f6fb;
}
.chat-messages::-webkit-scrollbar {
display: none;
}
/* Loading dots */
.chat-status {
text-align: center;
padding: 30px 0;
}
.loading-dots {
font-size: 26px;
color: var(--muted);
letter-spacing: 4px;
}
.loading-dots span {
animation: blink 1.2s infinite;
}
.loading-dots span:nth-child(2) { animation-delay: 0.2s; }
.loading-dots span:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink {
0%, 80%, 100% { opacity: 0.2; }
40% { opacity: 1; }
}
/* Empty state */
.chat-empty-state {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
padding: 40px 20px;
}
.chat-empty-icon {
color: var(--muted);
margin-bottom: 4px;
}
.chat-empty-text {
font-size: 14px;
font-weight: 600;
color: var(--text);
margin: 0;
}
.chat-empty-sub {
font-size: 12px;
color: var(--muted);
margin: 0;
}
/* Message rows */
.msg-row {
display: flex;
align-items: flex-end;
gap: 7px;
}
.msg-row--me {
flex-direction: row-reverse;
}
.msg-avatar {
width: 28px;
height: 28px;
border-radius: 50%;
font-size: 11px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.msg-avatar--admin {
background: #2c2b2d;
color: #fff;
}
.msg-avatar--me {
background: #e8e8e8;
color: #444;
overflow: hidden;
width: 28px;
height: 28px;
min-width: 28px;
min-height: 28px;
border-radius: 50%;
}
.avatar-img {
width: 28px;
height: 28px;
object-fit: cover;
border-radius: 50%;
display: block;
}
.msg-body {
display: flex;
flex-direction: column;
gap: 3px;
max-width: 76%;
}
.msg-row--me .msg-body {
align-items: flex-end;
}
.msg-meta {
display: flex;
gap: 5px;
align-items: baseline;
padding: 0 3px;
}
.msg-name {
font-size: 11px;
font-weight: 600;
color: var(--muted);
}
.msg-time {
font-size: 10px;
color: var(--muted);
opacity: 0.7;
}
.msg-content {
padding: 9px 13px;
border-radius: 14px;
font-size: 14px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.msg-row--admin .msg-content {
background: #fff;
color: #1a1a1a;
border-bottom-left-radius: 4px;
border: 1px solid rgba(0,0,0,0.08);
}
.msg-row--me .msg-content {
background: #2c2b2d;
color: #fff;
border-bottom-right-radius: 4px;
}
/* ── Input row ── */
.chat-input-row {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
border-top: 1px solid rgba(0,0,0,0.06);
background: #fff;
flex-shrink: 0;
}
.chat-input {
flex: 1;
padding: 9px 13px;
border-radius: 999px;
border: 1.5px solid rgba(180, 154, 203, 0.3);
font-size: 14px;
font-family: inherit;
background: #f8f6fb;
color: var(--text);
outline: none;
transition: border-color 0.2s;
}
.chat-input:focus {
border-color: #aaa;
background: #fff;
}
.chat-send-btn {
width: 38px;
height: 38px;
border-radius: 50%;
background: #2c2b2d;
color: #fff;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
transition: transform 0.15s, opacity 0.15s;
}
.chat-send-btn:disabled {
opacity: 0.55;
cursor: default;
background: #888;
}
.chat-send-btn:not(:disabled):hover {
transform: scale(1.08);
opacity: 0.85;
}
.chat-error {
font-size: 12px;
color: #d64848;
padding: 0 14px 8px;
text-align: center;
}
/* ── Animations ── */
.chat-slide-enter-active,
.chat-slide-leave-active {
transition: opacity 0.22s ease, transform 0.22s ease;
}
.chat-slide-enter-from,
.chat-slide-leave-to {
opacity: 0;
transform: translateY(20px) scale(0.96);
}
.icon-flip-enter-active,
.icon-flip-leave-active {
transition: opacity 0.15s, transform 0.15s;
}
.icon-flip-enter-from,
.icon-flip-leave-to {
opacity: 0;
transform: rotate(90deg) scale(0.7);
}
@media (max-width: 600px) {
.chat-panel {
right: 8px;
bottom: 80px;
width: calc(100vw - 16px);
height: 440px;
border-radius: 16px;
}
.chat-fab {
right: 16px;
bottom: 20px;
}
}
</style>

View File

@@ -0,0 +1,93 @@
<template>
<div class="maintenance-wrap">
<div class="maintenance-card">
<div class="maintenance-icon">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
</svg>
</div>
<h1>站点维护中</h1>
<p class="divider-line"></p>
<p class="reason" v-if="reason">{{ reason }}</p>
<p class="reason muted" v-else>暂无维护说明请稍后再试</p>
<p class="tip">如有紧急需求请联系管理员</p>
</div>
</div>
</template>
<script setup>
const props = defineProps({
reason: {
type: String,
default: ''
}
})
</script>
<style scoped>
.maintenance-wrap {
display: flex;
align-items: center;
justify-content: center;
min-height: 60vh;
padding: 40px 5vw;
}
.maintenance-card {
max-width: 480px;
width: 100%;
background: var(--glass-strong);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 48px 40px;
text-align: center;
box-shadow: var(--shadow);
backdrop-filter: blur(20px);
}
.maintenance-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
border-radius: 20px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white;
margin-bottom: 24px;
}
.maintenance-card h1 {
font-size: 28px;
font-weight: 700;
color: var(--text);
margin-bottom: 16px;
letter-spacing: 1px;
}
.divider-line {
width: 48px;
height: 3px;
border-radius: 2px;
background: linear-gradient(90deg, var(--accent), var(--accent-2));
margin: 0 auto 20px;
opacity: 0.6;
}
.reason {
font-size: 17px;
color: var(--text);
line-height: 1.7;
margin-bottom: 16px;
}
.reason.muted {
color: var(--muted);
}
.tip {
font-size: 15px;
color: var(--muted);
margin-top: 8px;
}
</style>

View File

@@ -0,0 +1,194 @@
<template>
<Transition name="splash-fade" appear>
<div v-if="visible" class="splash-screen">
<!-- Ambient glow -->
<div class="splash-glow splash-glow-1"></div>
<div class="splash-glow splash-glow-2"></div>
<!-- Content -->
<div class="splash-center">
<!-- Ripple rings -->
<div class="splash-rings">
<div class="ring ring-1"></div>
<div class="ring ring-2"></div>
<div class="ring ring-3"></div>
<!-- Logo -->
<div class="splash-logo-wrap">
<img src="/pwa-192x192.png" alt="萌芽小店" class="splash-logo" />
</div>
</div>
<!-- Title -->
<h1 class="splash-title">萌芽小店</h1>
<p class="splash-subtitle">加载中</p>
<!-- Dots loader -->
<div class="splash-dots">
<span class="dot dot-1"></span>
<span class="dot dot-2"></span>
<span class="dot dot-3"></span>
</div>
</div>
</div>
</Transition>
</template>
<script setup>
defineProps({
visible: { type: Boolean, default: true }
})
</script>
<style scoped>
.splash-screen {
position: fixed;
inset: 0;
z-index: 99999;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(145deg, #f8f5f2 0%, #e9f0f7 45%, #f4eaf1 100%);
overflow: hidden;
}
/* Ambient glow blobs */
.splash-glow {
position: absolute;
border-radius: 50%;
filter: blur(80px);
pointer-events: none;
animation: glow-pulse 3s ease-in-out infinite alternate;
}
.splash-glow-1 {
width: 420px;
height: 420px;
top: -80px;
left: -100px;
background: radial-gradient(circle, rgba(180, 154, 203, 0.35) 0%, transparent 70%);
}
.splash-glow-2 {
width: 380px;
height: 380px;
bottom: -60px;
right: -80px;
background: radial-gradient(circle, rgba(145, 168, 208, 0.3) 0%, transparent 70%);
animation-delay: 1.5s;
}
@keyframes glow-pulse {
from { opacity: 0.6; transform: scale(1); }
to { opacity: 1; transform: scale(1.12); }
}
/* Center content */
.splash-center {
display: flex;
flex-direction: column;
align-items: center;
gap: 0;
position: relative;
z-index: 1;
}
/* Rings + logo */
.splash-rings {
position: relative;
width: 160px;
height: 160px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 28px;
}
.ring {
position: absolute;
border-radius: 50%;
border: 2px solid rgba(180, 154, 203, 0.4);
animation: ring-expand 2.4s ease-out infinite;
}
.ring-1 { width: 100px; height: 100px; animation-delay: 0s; }
.ring-2 { width: 100px; height: 100px; animation-delay: 0.8s; }
.ring-3 { width: 100px; height: 100px; animation-delay: 1.6s; }
@keyframes ring-expand {
0% { width: 88px; height: 88px; opacity: 0.8; border-color: rgba(180, 154, 203, 0.5); }
100% { width: 200px; height: 200px; opacity: 0; border-color: rgba(180, 154, 203, 0); }
}
/* Logo */
.splash-logo-wrap {
position: relative;
z-index: 2;
animation: logo-float 2.8s ease-in-out infinite;
}
.splash-logo {
width: 88px;
height: 88px;
border-radius: 22px;
object-fit: cover;
box-shadow: 0 12px 40px rgba(33, 33, 40, 0.18), 0 2px 8px rgba(180, 154, 203, 0.25);
}
@keyframes logo-float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-8px); }
}
/* Title */
.splash-title {
font-size: 26px;
font-weight: 800;
color: #2c2b2d;
letter-spacing: 2px;
margin: 0 0 6px;
}
.splash-subtitle {
font-size: 13px;
color: #8a8690;
letter-spacing: 3px;
margin: 0 0 20px;
}
/* Dots */
.splash-dots {
display: flex;
gap: 8px;
align-items: center;
margin-top: 4px;
}
.dot {
display: block;
width: 8px;
height: 8px;
border-radius: 50%;
background: #4ade80;
animation: dot-bounce 1.2s ease-in-out infinite;
}
.dot-1 { animation-delay: 0s; }
.dot-2 { animation-delay: 0.2s; }
.dot-3 { animation-delay: 0.4s; }
@keyframes dot-bounce {
0%, 60%, 100% { transform: scale(0.7); opacity: 0.5; }
30% { transform: scale(1.2); opacity: 1; }
}
/* Exit transition */
.splash-fade-leave-active {
transition: opacity 0.45s ease, transform 0.45s ease;
}
.splash-fade-leave-to {
opacity: 0;
transform: scale(1.04);
}
</style>

View File

@@ -1,11 +1,18 @@
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({
baseURL: apiBaseURL
})
// 管理员请求头构建辅助函数,使用 X-Admin-Token 请求头。
// 后端保留 ?token= 查询参数作为旧版兼容,新请求统一使用请求头以兼容 Spring Security。
const adminHeaders = (token) => ({ 'X-Admin-Token': token })
const authApi = axios.create({
baseURL: 'https://auth.api.shumengya.top'
})
@@ -60,40 +67,136 @@ export const fetchMyOrders = async (authToken) => {
return data.data || []
}
export const fetchAdminToken = async () => {
const { data } = await api.get('/api/admin/token')
return data.token || ''
export const verifyAdminToken = async (token) => {
const { data } = await api.post('/api/admin/verify', { token })
return data.valid === true
}
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 || []
}
export const createProduct = async (token, payload) => {
const { data } = await api.post('/api/admin/products', payload, {
params: { token }
headers: adminHeaders(token)
})
return data.data
}
export const updateProduct = async (token, id, payload) => {
const { data } = await api.put(`/api/admin/products/${id}`, payload, {
params: { token }
headers: adminHeaders(token)
})
return data.data
}
export const toggleProduct = async (token, id, active) => {
const { data } = await api.patch(`/api/admin/products/${id}/status`, { active }, {
params: { token }
headers: adminHeaders(token)
})
return data.data
}
export const deleteProduct = async (token, id) => {
const { data } = await api.delete(`/api/admin/products/${id}`, {
params: { token }
headers: adminHeaders(token)
})
return data
}
export const fetchWishlist = async (token) => {
const { data } = await api.get('/api/wishlist', {
headers: { Authorization: `Bearer ${token}` }
})
return data.data?.items || []
}
export const addToWishlist = async (token, productId) => {
const { data } = await api.post('/api/wishlist', { productId }, {
headers: { Authorization: `Bearer ${token}` }
})
return data.data?.items || []
}
export const removeFromWishlist = async (token, productId) => {
const { data } = await api.delete(`/api/wishlist/${productId}`, {
headers: { Authorization: `Bearer ${token}` }
})
return data.data?.items || []
}
export const fetchAdminOrders = async (token) => {
const { data } = await api.get('/api/admin/orders', { headers: adminHeaders(token) })
return data.data || []
}
export const deleteAdminOrder = async (token, orderId) => {
await api.delete(`/api/admin/orders/${orderId}`, { headers: adminHeaders(token) })
}
export const fetchSiteMaintenance = async () => {
const { data } = await api.get('/api/site/maintenance')
return data.data || { maintenance: false, reason: '' }
}
export const setSiteMaintenance = async (token, maintenance, reason) => {
const { data } = await api.post('/api/admin/site/maintenance', { maintenance, reason }, {
headers: adminHeaders(token)
})
return data.data || {}
}
// ---- SMTP Config ----
export const fetchSMTPConfig = async (token) => {
const { data } = await api.get('/api/admin/site/smtp', { headers: adminHeaders(token) })
return data.data || {}
}
export const setSMTPConfig = async (token, cfg) => {
const { data } = await api.post('/api/admin/site/smtp', cfg, { headers: adminHeaders(token) })
return data.data
}
// ---- Chat (user) ----
export const fetchMyChatMessages = async (userToken) => {
const { data } = await api.get('/api/chat/messages', {
headers: { Authorization: `Bearer ${userToken}` }
})
return data.data?.messages || []
}
export const sendChatMessage = async (userToken, content) => {
const { data } = await api.post('/api/chat/messages', { content }, {
headers: { Authorization: `Bearer ${userToken}` }
})
return data.data?.message || null
}
// ---- Chat (admin) ----
export const fetchAdminAllConversations = async (adminToken) => {
const { data } = await api.get('/api/admin/chat', { headers: adminHeaders(adminToken) })
return data.data?.conversations || {}
}
export const fetchAdminConversation = async (adminToken, account) => {
const { data } = await api.get(`/api/admin/chat/${encodeURIComponent(account)}`, {
headers: adminHeaders(adminToken)
})
return data.data?.messages || []
}
export const adminSendChatReply = async (adminToken, account, content) => {
const { data } = await api.post(
`/api/admin/chat/${encodeURIComponent(account)}`,
{ content },
{ headers: adminHeaders(adminToken) }
)
return data.data?.message || null
}
export const adminClearConversation = async (adminToken, account) => {
await api.delete(`/api/admin/chat/${encodeURIComponent(account)}`, {
headers: adminHeaders(adminToken)
})
}

View File

@@ -18,7 +18,8 @@ export const authState = reactive({
token: saved?.token || '',
account: saved?.account || '',
username: saved?.username || '',
avatarUrl: saved?.avatarUrl || ''
avatarUrl: saved?.avatarUrl || '',
email: saved?.email || ''
})
export const isLoggedIn = () => !!authState.token
@@ -28,13 +29,15 @@ export const setAuth = (info) => {
authState.account = info.account || ''
authState.username = info.username || ''
authState.avatarUrl = info.avatarUrl || ''
authState.email = info.email || ''
localStorage.setItem(
AUTH_KEY,
JSON.stringify({
token: authState.token,
account: authState.account,
username: authState.username,
avatarUrl: authState.avatarUrl
avatarUrl: authState.avatarUrl,
email: authState.email
})
)
}
@@ -44,6 +47,7 @@ export const clearAuth = () => {
authState.account = ''
authState.username = ''
authState.avatarUrl = ''
authState.email = ''
localStorage.removeItem(AUTH_KEY)
}

View File

@@ -0,0 +1,66 @@
import { computed, ref } from 'vue'
import { authState, isLoggedIn } from './auth'
import {
fetchWishlist as apiFetchWishlist,
addToWishlist as apiAddToWishlist,
removeFromWishlist as apiRemoveFromWishlist
} from './api'
const wishlistIds = ref([])
const wishlistSet = computed(() => new Set(wishlistIds.value))
const wishlistCount = computed(() => wishlistIds.value.length)
const loadWishlist = async () => {
if (!isLoggedIn()) {
wishlistIds.value = []
return
}
try {
wishlistIds.value = await apiFetchWishlist(authState.token)
} catch {
wishlistIds.value = []
}
}
const isInWishlist = (productId) => wishlistSet.value.has(productId)
const addToWishlist = async (productId) => {
if (!isLoggedIn()) return
try {
wishlistIds.value = await apiAddToWishlist(authState.token, productId)
} catch {
// 忽略错误
}
}
const removeFromWishlist = async (productId) => {
if (!isLoggedIn()) return
try {
wishlistIds.value = await apiRemoveFromWishlist(authState.token, productId)
} catch {
// 忽略错误
}
}
const toggleWishlist = async (productId) => {
if (isInWishlist(productId)) {
await removeFromWishlist(productId)
} else {
await addToWishlist(productId)
}
}
const getWishlistProducts = (allProducts) => {
const idSet = wishlistSet.value
return allProducts.filter((p) => idSet.has(p.id))
}
export {
wishlistCount,
isInWishlist,
addToWishlist,
removeFromWishlist,
toggleWishlist,
getWishlistProducts,
loadWishlist
}

View File

@@ -29,15 +29,53 @@
</div>
</div>
<form class="checkout-form" @submit.prevent="submitOrder" v-if="!orderResult">
<div class="checkout-form" v-if="!orderResult && product.requireLogin && !loggedIn">
<div class="require-login-block">
<p class="require-login-title">该商品需要登录后才能购买</p>
<a class="primary btn-inline" :href="loginUrl">立即登录</a>
</div>
</div>
<form class="checkout-form" @submit.prevent="submitOrder" v-else-if="!orderResult">
<div class="form-field">
<label>下单数量</label>
<input v-model.number="form.quantity" min="1" type="number" />
<input
v-model.number="form.quantity"
min="1"
:max="product.maxPerAccount > 0 ? product.maxPerAccount : undefined"
type="number"
/>
</div>
<p class="tag">预计总价¥ {{ totalPrice.toFixed(2) }}</p>
<p class="tag login-hint" v-if="!loggedIn">
提示<a :href="loginUrl">登录萌芽账号</a> 后下单可查看历史订单记录
<p class="tag limit-hint" v-if="product.maxPerAccount > 0">
该商品每个账户最多可购买 {{ product.maxPerAccount }}
</p>
<div class="form-field" v-if="product.showNote">
<label>备注选填</label>
<textarea v-model="form.note" placeholder="填写您的备注信息…" rows="3"></textarea>
</div>
<template v-if="product.showContact">
<div class="form-row contact-row">
<div class="form-field">
<label>手机号选填</label>
<input v-model="form.contactPhone" type="tel" placeholder="138xxxx0000" />
</div>
<div class="form-field">
<label>邮箱选填</label>
<input v-model="form.contactEmail" type="email" placeholder="you@example.com" />
</div>
</div>
</template>
<p class="tag login-hint" v-if="!loggedIn">
<a :href="loginUrl">登录萌芽账号</a> 后购买可享受历史订单记录专属优惠商品及更多购买权益
</p>
<div class="delivery-tip" v-if="product.deliveryMode === 'manual'">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
该商品为手动发货付款后管理员将核验并处理您的订单
</div>
<button class="primary" type="submit" :disabled="submitting">
{{ submitting ? '生成中...' : '生成二维码下单' }}
</button>
@@ -66,6 +104,13 @@
<p class="tag">购买后内容</p>
<textarea class="delivery-box" readonly :value="deliveredCodes.join('\n')"></textarea>
</div>
<div v-else-if="isManualDelivery" class="manual-delivery-notice">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
<div>
<p class="manual-delivery-title">等待发货中</p>
<p class="tag">管理员将尽快处理您的订单并进行发货请关注您的邮箱或联系方式</p>
</div>
</div>
<p class="tag">感谢购买如有问题请联系售后邮箱</p>
</template>
</section>
@@ -108,8 +153,12 @@ const loggedIn = computed(() => isLoggedIn())
const loginUrl = computed(() => getLoginUrl())
const form = reactive({
quantity: 1
quantity: 1,
note: '',
contactPhone: '',
contactEmail: ''
})
const isManualDelivery = ref(false)
const renderMarkdown = (content) => md.render(content || '')
@@ -145,7 +194,11 @@ const submitOrder = async () => {
try {
const payload = {
productId: product.value.id,
quantity: form.quantity
quantity: form.quantity,
note: form.note || '',
contactPhone: form.contactPhone || '',
contactEmail: form.contactEmail || '',
notifyEmail: authState.email || ''
}
const token = isLoggedIn() ? authState.token : null
const response = await createOrder(payload, token)
@@ -166,6 +219,7 @@ const doConfirm = async () => {
try {
const result = await confirmOrder(orderResult.value.orderId)
deliveredCodes.value = result.deliveredCodes || []
isManualDelivery.value = result.isManual || result.deliveryMode === 'manual'
confirmed.value = true
} catch (err) {
confirmError.value = err?.response?.data?.error || '确认失败,请重试'
@@ -213,7 +267,7 @@ onMounted(async () => {
width: 140px;
height: 140px;
object-fit: cover;
border-radius: 12px;
border-radius: 8px;
}
.summary-content {
@@ -248,7 +302,7 @@ onMounted(async () => {
max-width: 320px;
margin: 12px auto;
width: 100%;
border-radius: 14px;
border-radius: 8px;
border: 1px solid var(--line);
}
@@ -266,7 +320,7 @@ onMounted(async () => {
border-radius: 999px;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white;
font-size: 13px;
font-size: 15px;
font-weight: 600;
margin-bottom: 12px;
}
@@ -283,18 +337,18 @@ onMounted(async () => {
width: min(520px, 100%);
min-height: 120px;
padding: 14px 16px;
border-radius: 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.9);
color: var(--text);
font-size: 14px;
font-size: 16px;
line-height: 1.7;
resize: none;
}
.error {
color: #d64848;
font-size: 13px;
font-size: 15px;
}
.status {
@@ -307,6 +361,87 @@ onMounted(async () => {
font-weight: 900;
}
.require-login-block {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
padding: 32px 24px;
text-align: center;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.6);
}
.require-login-title {
font-size: 18px;
font-weight: 600;
color: var(--text);
}
.btn-inline {
display: inline-block;
text-decoration: none;
padding: 10px 28px;
border-radius: 8px;
font-size: 16px;
font-weight: 700;
cursor: pointer;
}
.limit-hint {
color: var(--accent);
}
textarea {
width: 100%;
box-sizing: border-box;
padding: 10px 12px;
border-radius: 8px;
border: 1px solid var(--line);
font-size: 15px;
font-family: inherit;
background: rgba(255, 255, 255, 0.9);
color: var(--text);
resize: vertical;
}
.contact-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.delivery-tip {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 14px;
background: rgba(90, 120, 200, 0.08);
border: 1px solid rgba(90, 120, 200, 0.2);
border-radius: 8px;
color: #5a78c8;
font-size: 14px;
}
.manual-delivery-notice {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 16px;
background: rgba(90, 180, 120, 0.08);
border: 1px solid rgba(90, 180, 120, 0.25);
border-radius: 8px;
color: var(--text);
}
.manual-delivery-title {
font-size: 16px;
font-weight: 600;
color: #3a9a68;
margin: 0 0 4px 0;
}
@media (max-width: 900px) {
.checkout-grid {
grid-template-columns: 1fr;
@@ -321,5 +456,9 @@ onMounted(async () => {
width: 100%;
height: 200px;
}
.contact-row {
grid-template-columns: 1fr;
}
}
</style>

View File

@@ -68,6 +68,15 @@
<div class="detail-actions">
<button class="buy-button" @click="goCheckout">立即下单</button>
<button
v-if="loggedIn"
class="ghost wishlist-action"
:class="{ 'wishlist-active': inWishlist }"
type="button"
@click="onToggleWishlist"
>
{{ inWishlist ? '★ 已收藏' : '☆ 加入收藏夹' }}
</button>
<button class="ghost" @click="goBack">返回商店首页</button>
</div>
</div>
@@ -91,6 +100,8 @@ import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { fetchProducts, recordProductView } from '../shared/api'
import { isLoggedIn } from '../shared/auth'
import { isInWishlist, toggleWishlist } from '../shared/useWishlist'
const route = useRoute()
const router = useRouter()
@@ -140,6 +151,12 @@ const galleryImages = computed(() => {
return images
})
const loggedIn = computed(() => isLoggedIn())
const inWishlist = computed(() => product.value ? isInWishlist(product.value.id) : false)
const onToggleWishlist = () => {
if (product.value) toggleWishlist(product.value.id)
}
const goBack = () => {
router.push('/')
}
@@ -215,7 +232,7 @@ onMounted(async () => {
.detail-description {
display: block;
color: var(--text);
font-size: 15px;
font-size: 17px;
line-height: 1.8;
-webkit-line-clamp: initial;
-webkit-box-orient: initial;
@@ -231,7 +248,7 @@ onMounted(async () => {
.detail-gallery-main {
position: relative;
overflow: hidden;
border-radius: 18px;
border-radius: 10px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.45);
}
@@ -292,11 +309,11 @@ onMounted(async () => {
width: 100%;
height: 76px;
object-fit: cover;
border-radius: 10px;
border-radius: 6px;
}
.detail-thumb span {
font-size: 12px;
font-size: 14px;
color: var(--muted);
}
@@ -310,6 +327,16 @@ onMounted(async () => {
font-weight: 900;
}
.wishlist-action {
color: var(--muted);
}
.wishlist-action.wishlist-active {
color: #e8826a;
border-color: rgba(232, 130, 106, 0.35);
background: rgba(255, 240, 235, 0.6);
}
@media (max-width: 900px) {
.detail-thumb {
padding: 6px;

Some files were not shown because too many files have changed in this diff Show More