feat: major update - MySQL, chat, wishlist, PWA, admin overhaul

This commit is contained in:
2026-03-21 20:22:00 +08:00
committed by 树萌芽
parent 48fb818b8c
commit 84874707f5
71 changed files with 13457 additions and 2031 deletions

4
.gitignore vendored
View File

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

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>'
```

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

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 @@
{
"totalVisits": 3
}

View File

@@ -8,6 +8,9 @@ services:
environment: environment:
GIN_MODE: release GIN_MODE: release
TZ: Asia/Shanghai TZ: Asia/Shanghai
# Production MySQL DSN — uses internal network address.
# Change to TestDSN or override via .env file for local testing.
DATABASE_DSN: "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
volumes: volumes:
- ./data:/app/data - ./config.json:/app/config.json:ro
restart: unless-stopped restart: unless-stopped

View File

@@ -1,6 +1,6 @@
module mengyastore-backend module mengyastore-backend
go 1.21 go 1.21.0
require ( require (
github.com/gin-contrib/cors v1.7.2 github.com/gin-contrib/cors v1.7.2
@@ -9,6 +9,7 @@ require (
) )
require ( require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // 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/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.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-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/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/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/kr/text v0.2.0 // 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/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.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 google.golang.org/protobuf v1.34.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // 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 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= github.com/bytedance/sonic/loader v0.1.1 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/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 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= 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 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5 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/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 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 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 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.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/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 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 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 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4= google.golang.org/protobuf v1.34.0 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.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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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= nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@@ -26,6 +26,8 @@ type SproutGateUser struct {
Account string `json:"account"` Account string `json:"account"`
Username string `json:"username"` Username string `json:"username"`
AvatarURL string `json:"avatarUrl"` AvatarURL string `json:"avatarUrl"`
Level int `json:"level"`
Email string `json:"email"`
} }
func NewSproutGateClient(apiURL string) *SproutGateClient { func NewSproutGateClient(apiURL string) *SproutGateClient {

View File

@@ -9,8 +9,18 @@ import (
type Config struct { type Config struct {
AdminToken string `json:"adminToken"` AdminToken string `json:"adminToken"`
AuthAPIURL string `json:"authApiUrl"` AuthAPIURL string `json:"authApiUrl"`
// Database DSN. If empty, falls back to the test DB DSN.
// Format: "user:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
DatabaseDSN string `json:"databaseDsn"`
} }
// Default DSNs for each environment.
const (
TestDSN = "mengyastore-test:mengyastore-test@tcp(10.1.1.100:3306)/mengyastore-test?charset=utf8mb4&parseTime=True&loc=Local"
ProdDSN = "mengyastore:mengyastore@tcp(192.168.1.100:3306)/mengyastore?charset=utf8mb4&parseTime=True&loc=Local"
)
func Load(path string) (*Config, error) { func Load(path string) (*Config, error) {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
@@ -23,5 +33,12 @@ func Load(path string) (*Config, error) {
if cfg.AdminToken == "" { if cfg.AdminToken == "" {
cfg.AdminToken = "shumengya520" cfg.AdminToken = "shumengya520"
} }
// Default to test DB if not configured; environment variable overrides config file.
if dsn := os.Getenv("DATABASE_DSN"); dsn != "" {
cfg.DatabaseDSN = dsn
}
if cfg.DatabaseDSN == "" {
cfg.DatabaseDSN = TestDSN
}
return &cfg, nil 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 initialises a GORM DB connection and runs AutoMigrate for all models.
func Open(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Warn),
})
if err != nil {
return nil, err
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
sqlDB.SetMaxIdleConns(5)
sqlDB.SetMaxOpenConns(20)
sqlDB.SetConnMaxLifetime(time.Hour)
if err := autoMigrate(db); err != nil {
return nil, err
}
log.Println("[DB] 数据库连接成功,表结构已同步")
return db, nil
}
func autoMigrate(db *gorm.DB) error {
return db.AutoMigrate(
&ProductRow{},
&ProductCodeRow{},
&OrderRow{},
&SiteSettingRow{},
&WishlistRow{},
&ChatMessageRow{},
)
}

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,192 @@
package email
import (
"crypto/tls"
"fmt"
"net/smtp"
"strings"
"time"
)
// Config holds SMTP sender configuration.
type Config struct {
SMTPHost string // e.g. smtp.qq.com
SMTPPort string // e.g. 465 (SSL) or 587 (STARTTLS)
From string // sender email address
Password string // SMTP auth password / app password
FromName string // display name, e.g. "萌芽小店"
}
// IsConfigured returns true if enough config is present to send mail.
func (c *Config) IsConfigured() bool {
return c.From != "" && c.Password != "" && c.SMTPHost != ""
}
// OrderNotifyData contains the data for an order notification email.
type OrderNotifyData struct {
ToEmail string
ToName string
ProductName string
OrderID string
Quantity int
Codes []string // empty for manual delivery
IsManual bool
}
// SendOrderNotify sends an order delivery notification email.
// Returns nil if config is not ready or ToEmail is empty (silently skip).
func SendOrderNotify(cfg Config, data OrderNotifyData) error {
if !cfg.IsConfigured() || data.ToEmail == "" {
return nil
}
if cfg.SMTPPort == "" {
cfg.SMTPPort = "465"
}
if cfg.SMTPHost == "" {
cfg.SMTPHost = "smtp.qq.com"
}
fromName := cfg.FromName
if fromName == "" {
fromName = "萌芽小店"
}
subject := "【萌芽小店】您的订单已发货"
if data.IsManual {
subject = "【萌芽小店】您的订单正在处理中"
}
body := buildBody(data)
msg := buildMIMEMessage(cfg.From, fromName, data.ToEmail, subject, body)
addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)
auth := smtp.PlainAuth("", cfg.From, cfg.Password, cfg.SMTPHost)
// QQ mail uses SSL on port 465; use TLS dial directly.
if cfg.SMTPPort == "465" {
return sendSSL(addr, cfg.SMTPHost, auth, cfg.From, data.ToEmail, msg)
}
return smtp.SendMail(addr, auth, cfg.From, []string{data.ToEmail}, []byte(msg))
}
func buildBody(data OrderNotifyData) string {
var sb strings.Builder
now := time.Now().Format("2006 年 01 月 02 日 15:04:05")
recipient := data.ToName
if recipient == "" {
recipient = "用户"
}
sb.WriteString("尊敬的 ")
sb.WriteString(recipient)
sb.WriteString("\n\n")
sb.WriteString(" 您好!感谢您在萌芽小店的支持与购买。\n\n")
sb.WriteString("────────────────────────────────\n")
sb.WriteString(" 订单信息\n")
sb.WriteString("────────────────────────────────\n")
sb.WriteString(fmt.Sprintf(" 商品名称:%s\n", data.ProductName))
sb.WriteString(fmt.Sprintf(" 订单编号:%s\n", data.OrderID))
sb.WriteString(fmt.Sprintf(" 购买数量:%d 件\n", data.Quantity))
sb.WriteString(fmt.Sprintf(" 通知时间:%s\n", now))
sb.WriteString("────────────────────────────────\n\n")
if data.IsManual {
sb.WriteString(" 您的订单已成功提交,目前正在等待人工审核与处理。\n")
sb.WriteString(" 工作人员将尽快为您安排发货,请耐心等候。\n")
sb.WriteString(" 发货完成后,我们将另行发送邮件通知。\n\n")
} else {
sb.WriteString(" 您的订单已完成自动发货,发货内容如下:\n\n")
if len(data.Codes) > 0 {
for i, code := range data.Codes {
sb.WriteString(fmt.Sprintf(" [%d] %s\n", i+1, code))
}
sb.WriteString("\n")
}
sb.WriteString(" 请妥善保管以上发货内容,切勿泄露给他人。\n\n")
}
sb.WriteString(" 如有任何疑问,请联系在线客服,我们将竭诚为您服务。\n\n")
sb.WriteString("────────────────────────────────\n")
sb.WriteString(" 此邮件由系统自动发送,请勿直接回复。\n")
sb.WriteString("────────────────────────────────\n")
return sb.String()
}
func buildMIMEMessage(from, fromName, to, subject, body string) string {
encodedFromName := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(fromName))
encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", encodeBase64(subject))
return fmt.Sprintf(
"From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s",
encodedFromName, from, to, encodedSubject, encodeBase64(body),
)
}
func encodeBase64(s string) string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
b := []byte(s)
var buf strings.Builder
for i := 0; i < len(b); i += 3 {
remaining := len(b) - i
b0 := b[i]
b1 := byte(0)
b2 := byte(0)
if remaining > 1 {
b1 = b[i+1]
}
if remaining > 2 {
b2 = b[i+2]
}
buf.WriteByte(chars[b0>>2])
buf.WriteByte(chars[((b0&0x03)<<4)|(b1>>4)])
if remaining > 1 {
buf.WriteByte(chars[((b1&0x0f)<<2)|(b2>>6)])
} else {
buf.WriteByte('=')
}
if remaining > 2 {
buf.WriteByte(chars[b2&0x3f])
} else {
buf.WriteByte('=')
}
}
return buf.String()
}
func sendSSL(addr, host string, auth smtp.Auth, from, to string, msg string) error {
tlsConfig := &tls.Config{
ServerName: host,
MinVersion: tls.VersionTLS12,
}
conn, err := tls.Dial("tcp", addr, tlsConfig)
if err != nil {
return fmt.Errorf("tls dial: %w", err)
}
defer conn.Close()
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("smtp new client: %w", err)
}
defer client.Quit() //nolint:errcheck
if err = client.Auth(auth); err != nil {
return fmt.Errorf("smtp auth: %w", err)
}
if err = client.Mail(from); err != nil {
return fmt.Errorf("smtp MAIL FROM: %w", err)
}
if err = client.Rcpt(to); err != nil {
return fmt.Errorf("smtp RCPT TO: %w", err)
}
w, err := client.Data()
if err != nil {
return fmt.Errorf("smtp DATA: %w", err)
}
if _, err = fmt.Fprint(w, msg); err != nil {
return fmt.Errorf("smtp write body: %w", err)
}
return w.Close()
}

View File

@@ -1,160 +1,24 @@
package handlers package handlers
import ( import (
"net/http"
"strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http"
"mengyastore-backend/internal/config" "mengyastore-backend/internal/config"
"mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage" "mengyastore-backend/internal/storage"
) )
// AdminHandler holds dependencies for all admin-related routes.
type AdminHandler struct { type AdminHandler struct {
store *storage.JSONStore store *storage.JSONStore
cfg *config.Config cfg *config.Config
siteStore *storage.SiteStore
orderStore *storage.OrderStore
chatStore *storage.ChatStore
} }
type productPayload struct { func NewAdminHandler(store *storage.JSONStore, cfg *config.Config, siteStore *storage.SiteStore, orderStore *storage.OrderStore, chatStore *storage.ChatStore) *AdminHandler {
Name string `json:"name"` return &AdminHandler{store: store, cfg: cfg, siteStore: siteStore, orderStore: orderStore, chatStore: chatStore}
Price float64 `json:"price"`
DiscountPrice float64 `json:"discountPrice"`
Tags string `json:"tags"`
CoverURL string `json:"coverUrl"`
Codes []string `json:"codes"`
ScreenshotURLs []string `json:"screenshotUrls"`
Description string `json:"description"`
Active *bool `json:"active"`
}
type togglePayload struct {
Active bool `json:"active"`
}
func NewAdminHandler(store *storage.JSONStore, cfg *config.Config) *AdminHandler {
return &AdminHandler{store: store, cfg: cfg}
}
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"token": h.cfg.AdminToken})
}
func (h *AdminHandler) ListAllProducts(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
items, err := h.store.ListAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": items})
}
func (h *AdminHandler) CreateProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
return
}
active := true
if payload.Active != nil {
active = *payload.Active
}
product := models.Product{
Name: payload.Name,
Price: payload.Price,
DiscountPrice: payload.DiscountPrice,
Tags: normalizeTags(payload.Tags),
CoverURL: strings.TrimSpace(payload.CoverURL),
Codes: payload.Codes,
ScreenshotURLs: screenshotURLs,
Description: payload.Description,
Active: active,
}
created, err := h.store.Create(product)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": created})
}
func (h *AdminHandler) UpdateProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
id := c.Param("id")
var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
return
}
active := false
if payload.Active != nil {
active = *payload.Active
}
patch := models.Product{
Name: payload.Name,
Price: payload.Price,
DiscountPrice: payload.DiscountPrice,
Tags: normalizeTags(payload.Tags),
CoverURL: strings.TrimSpace(payload.CoverURL),
Codes: payload.Codes,
ScreenshotURLs: screenshotURLs,
Description: payload.Description,
Active: active,
}
updated, err := h.store.Update(id, patch)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": updated})
}
func (h *AdminHandler) ToggleProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
id := c.Param("id")
var payload togglePayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
updated, err := h.store.Toggle(id, payload.Active)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": updated})
}
func (h *AdminHandler) DeleteProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
id := c.Param("id")
if err := h.store.Delete(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
} }
func (h *AdminHandler) requireAdmin(c *gin.Context) bool { func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
@@ -168,43 +32,3 @@ func (h *AdminHandler) requireAdmin(c *gin.Context) bool {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return false return false
} }
func normalizeScreenshotURLs(urls []string) ([]string, bool) {
cleaned := make([]string, 0, len(urls))
for _, url := range urls {
trimmed := strings.TrimSpace(url)
if trimmed == "" {
continue
}
cleaned = append(cleaned, trimmed)
if len(cleaned) > 5 {
return nil, false
}
}
return cleaned, true
}
func normalizeTags(tagsCSV string) []string {
if tagsCSV == "" {
return []string{}
}
parts := strings.Split(tagsCSV, ",")
clean := make([]string, 0, len(parts))
seen := map[string]bool{}
for _, p := range parts {
t := strings.TrimSpace(p)
if t == "" {
continue
}
key := strings.ToLower(t)
if seen[key] {
continue
}
seen[key] = true
clean = append(clean, t)
if len(clean) >= 20 {
break
}
}
return clean
}

View File

@@ -0,0 +1,88 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// GetAllConversations returns all conversations (map of accountID -> messages).
func (h *AdminHandler) GetAllConversations(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
convs, err := h.chatStore.ListConversations()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"conversations": convs}})
}
// GetConversation returns all messages for a specific account.
func (h *AdminHandler) GetConversation(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
accountID := c.Param("account")
if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing account"})
return
}
msgs, err := h.chatStore.GetMessages(accountID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
}
type adminChatPayload struct {
Content string `json:"content"`
}
// AdminReply sends a reply from admin to a specific user.
func (h *AdminHandler) AdminReply(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
accountID := c.Param("account")
if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing account"})
return
}
var payload adminChatPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
content := strings.TrimSpace(payload.Content)
if content == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
return
}
msg, err := h.chatStore.SendAdminMessage(accountID, content)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
}
// ClearConversation deletes all messages with a specific user.
func (h *AdminHandler) ClearConversation(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
accountID := c.Param("account")
if accountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing account"})
return
}
if err := h.chatStore.ClearConversation(accountID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
}

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": "missing order id"})
return
}
if err := h.orderStore.Delete(orderID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"ok": true}})
}

View File

@@ -0,0 +1,202 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"mengyastore-backend/internal/models"
)
type productPayload struct {
Name string `json:"name"`
Price float64 `json:"price"`
DiscountPrice float64 `json:"discountPrice"`
Tags string `json:"tags"`
CoverURL string `json:"coverUrl"`
Codes []string `json:"codes"`
ScreenshotURLs []string `json:"screenshotUrls"`
Description string `json:"description"`
Active *bool `json:"active"`
RequireLogin bool `json:"requireLogin"`
MaxPerAccount int `json:"maxPerAccount"`
DeliveryMode string `json:"deliveryMode"`
ShowNote bool `json:"showNote"`
ShowContact bool `json:"showContact"`
}
type togglePayload struct {
Active bool `json:"active"`
}
func (h *AdminHandler) GetAdminToken(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"token": h.cfg.AdminToken})
}
func (h *AdminHandler) ListAllProducts(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
items, err := h.store.ListAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": items})
}
func (h *AdminHandler) CreateProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
return
}
active := true
if payload.Active != nil {
active = *payload.Active
}
product := models.Product{
Name: payload.Name,
Price: payload.Price,
DiscountPrice: payload.DiscountPrice,
Tags: normalizeTags(payload.Tags),
CoverURL: strings.TrimSpace(payload.CoverURL),
Codes: payload.Codes,
ScreenshotURLs: screenshotURLs,
Description: payload.Description,
Active: active,
RequireLogin: payload.RequireLogin,
MaxPerAccount: payload.MaxPerAccount,
DeliveryMode: payload.DeliveryMode,
ShowNote: payload.ShowNote,
ShowContact: payload.ShowContact,
}
created, err := h.store.Create(product)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": created})
}
func (h *AdminHandler) UpdateProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
id := c.Param("id")
var payload productPayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
screenshotURLs, valid := normalizeScreenshotURLs(payload.ScreenshotURLs)
if !valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "screenshot urls must be 5 or fewer"})
return
}
active := false
if payload.Active != nil {
active = *payload.Active
}
patch := models.Product{
Name: payload.Name,
Price: payload.Price,
DiscountPrice: payload.DiscountPrice,
Tags: normalizeTags(payload.Tags),
CoverURL: strings.TrimSpace(payload.CoverURL),
Codes: payload.Codes,
ScreenshotURLs: screenshotURLs,
Description: payload.Description,
Active: active,
RequireLogin: payload.RequireLogin,
MaxPerAccount: payload.MaxPerAccount,
DeliveryMode: payload.DeliveryMode,
ShowNote: payload.ShowNote,
ShowContact: payload.ShowContact,
}
updated, err := h.store.Update(id, patch)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": updated})
}
func (h *AdminHandler) ToggleProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
id := c.Param("id")
var payload togglePayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
updated, err := h.store.Toggle(id, payload.Active)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": updated})
}
func (h *AdminHandler) DeleteProduct(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
id := c.Param("id")
if err := h.store.Delete(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
func normalizeScreenshotURLs(urls []string) ([]string, bool) {
cleaned := make([]string, 0, len(urls))
for _, url := range urls {
trimmed := strings.TrimSpace(url)
if trimmed == "" {
continue
}
cleaned = append(cleaned, trimmed)
if len(cleaned) > 5 {
return nil, false
}
}
return cleaned, true
}
func normalizeTags(tagsCSV string) []string {
if tagsCSV == "" {
return []string{}
}
parts := strings.Split(tagsCSV, ",")
clean := make([]string, 0, len(parts))
seen := map[string]bool{}
for _, p := range parts {
t := strings.TrimSpace(p)
if t == "" {
continue
}
key := strings.ToLower(t)
if seen[key] {
continue
}
seen[key] = true
clean = append(clean, t)
if len(clean) >= 20 {
break
}
}
return clean
}

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": "invalid payload"})
return
}
if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"data": gin.H{
"maintenance": payload.Maintenance,
"reason": payload.Reason,
},
})
}
func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
cfg, err := h.siteStore.GetSMTPConfig()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Mask password in response
masked := cfg
if masked.Password != "" {
masked.Password = "••••••••"
}
c.JSON(http.StatusOK, gin.H{"data": masked})
}
func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
if !h.requireAdmin(c) {
return
}
var payload storage.SMTPConfig
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
// If password is the masked sentinel, preserve the existing one
if payload.Password == "••••••••" {
existing, _ := h.siteStore.GetSMTPConfig()
payload.Password = existing.Password
}
if err := h.siteStore.SetSMTPConfig(payload); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": "ok"})
}

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 returns all chat messages for the currently logged-in user.
func (h *ChatHandler) GetMyMessages(c *gin.Context) {
account, _, ok := h.requireChatUser(c)
if !ok {
return
}
msgs, err := h.chatStore.GetMessages(account)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"messages": msgs}})
}
type chatMessagePayload struct {
Content string `json:"content"`
}
// SendMyMessage sends a message from the current user to admin.
func (h *ChatHandler) SendMyMessage(c *gin.Context) {
account, name, ok := h.requireChatUser(c)
if !ok {
return
}
var payload chatMessagePayload
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
return
}
content := strings.TrimSpace(payload.Content)
if content == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "消息不能为空"})
return
}
msg, rateLimited, err := h.chatStore.SendUserMessage(account, name, content)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if rateLimited {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "发送太频繁,请稍候"})
return
}
c.JSON(http.StatusOK, gin.H{"data": gin.H{"message": msg}})
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"mengyastore-backend/internal/auth" "mengyastore-backend/internal/auth"
"mengyastore-backend/internal/email"
"mengyastore-backend/internal/models" "mengyastore-backend/internal/models"
"mengyastore-backend/internal/storage" "mengyastore-backend/internal/storage"
) )
@@ -19,47 +20,70 @@ const qrSize = "320x320"
type OrderHandler struct { type OrderHandler struct {
productStore *storage.JSONStore productStore *storage.JSONStore
orderStore *storage.OrderStore orderStore *storage.OrderStore
siteStore *storage.SiteStore
authClient *auth.SproutGateClient authClient *auth.SproutGateClient
} }
type checkoutPayload struct { type checkoutPayload struct {
ProductID string `json:"productId"` ProductID string `json:"productId"`
Quantity int `json:"quantity"` Quantity int `json:"quantity"`
Note string `json:"note"`
ContactPhone string `json:"contactPhone"`
ContactEmail string `json:"contactEmail"`
NotifyEmail string `json:"notifyEmail"`
} }
func NewOrderHandler(productStore *storage.JSONStore, orderStore *storage.OrderStore, authClient *auth.SproutGateClient) *OrderHandler { func NewOrderHandler(productStore *storage.JSONStore, orderStore *storage.OrderStore, siteStore *storage.SiteStore, authClient *auth.SproutGateClient) *OrderHandler {
return &OrderHandler{productStore: productStore, orderStore: orderStore, authClient: authClient} return &OrderHandler{productStore: productStore, orderStore: orderStore, siteStore: siteStore, authClient: authClient}
} }
func (h *OrderHandler) tryExtractUser(c *gin.Context) (string, string) { func (h *OrderHandler) sendOrderNotify(toEmail, toName, productName, orderID string, qty int, codes []string, isManual bool) {
if toEmail == "" {
return
}
cfg, err := h.siteStore.GetSMTPConfig()
if err != nil || !cfg.IsConfiguredEmail() {
return
}
go func() {
emailCfg := email.Config{
SMTPHost: cfg.Host,
SMTPPort: cfg.Port,
From: cfg.Email,
Password: cfg.Password,
FromName: cfg.FromName,
}
if err := email.SendOrderNotify(emailCfg, email.OrderNotifyData{
ToEmail: toEmail,
ToName: toName,
ProductName: productName,
OrderID: orderID,
Quantity: qty,
Codes: codes,
IsManual: isManual,
}); err != nil {
log.Printf("[Email] 发送通知失败 order=%s to=%s: %v", orderID, toEmail, err)
} else {
log.Printf("[Email] 发送通知成功 order=%s to=%s", orderID, toEmail)
}
}()
}
func (h *OrderHandler) tryExtractUserWithEmail(c *gin.Context) (account, username, userEmail string) {
authHeader := c.GetHeader("Authorization") authHeader := c.GetHeader("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") { if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
log.Println("[Order] 无 Authorization header匿名下单") return "", "", ""
return "", ""
} }
userToken := strings.TrimPrefix(authHeader, "Bearer ") userToken := strings.TrimPrefix(authHeader, "Bearer ")
log.Printf("[Order] 检测到用户 token正在验证 (长度=%d)", len(userToken))
result, err := h.authClient.VerifyToken(userToken) result, err := h.authClient.VerifyToken(userToken)
if err != nil { if err != nil || !result.Valid || result.User == nil {
log.Printf("[Order] 验证 token 失败: %v", err) return "", "", ""
return "", ""
} }
if !result.Valid { return result.User.Account, result.User.Username, result.User.Email
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) { func (h *OrderHandler) CreateOrder(c *gin.Context) {
userAccount, userName := h.tryExtractUser(c) userAccount, userName, userEmail := h.tryExtractUserWithEmail(c)
var payload checkoutPayload var payload checkoutPayload
if err := c.ShouldBindJSON(&payload); err != nil { if err := c.ShouldBindJSON(&payload); err != nil {
@@ -85,22 +109,73 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "product is not available"}) c.JSON(http.StatusBadRequest, gin.H{"error": "product is not available"})
return 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 { if product.Quantity < payload.Quantity {
c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"}) c.JSON(http.StatusBadRequest, gin.H{"error": "库存不足"})
return return
} }
deliveredCodes, ok := extractCodes(&product, payload.Quantity) 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 { if !ok {
c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"}) c.JSON(http.StatusBadRequest, gin.H{"error": "卡密不足"})
return return
} }
product.Quantity = len(product.Codes) product.Quantity = len(product.Codes)
updatedProduct, err := h.productStore.Update(product.ID, product) updatedProduct, err = h.productStore.Update(product.ID, product)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
}
deliveryMode := product.DeliveryMode
if deliveryMode == "" {
deliveryMode = "auto"
}
// Notification email priority:
// 1. SproutGate account email (logged-in user, most reliable)
// 2. notifyEmail passed by frontend (also comes from authState.email)
// 3. contactEmail explicitly filled by user in checkout form
// 4. empty → skip sending
notifyEmail := strings.TrimSpace(userEmail)
if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.NotifyEmail)
}
if notifyEmail == "" {
notifyEmail = strings.TrimSpace(payload.ContactEmail)
}
order := models.Order{ order := models.Order{
ProductID: updatedProduct.ID, ProductID: updatedProduct.ID,
@@ -110,6 +185,11 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
Quantity: payload.Quantity, Quantity: payload.Quantity,
DeliveredCodes: deliveredCodes, DeliveredCodes: deliveredCodes,
Status: "pending", Status: "pending",
DeliveryMode: deliveryMode,
Note: strings.TrimSpace(payload.Note),
ContactPhone: strings.TrimSpace(payload.ContactPhone),
ContactEmail: strings.TrimSpace(payload.ContactEmail),
NotifyEmail: notifyEmail,
} }
created, err := h.orderStore.Create(order) created, err := h.orderStore.Create(order)
if err != nil { if err != nil {
@@ -117,6 +197,17 @@ func (h *OrderHandler) CreateOrder(c *gin.Context) {
return return
} }
if !isManual {
if err := h.productStore.IncrementSold(updatedProduct.ID, payload.Quantity); err != nil {
log.Printf("[Order] 更新销量失败 (非致命): %v", err)
}
// Send delivery notification for auto-delivery orders immediately
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, deliveredCodes, false)
} else {
// For manual delivery, notify user that order is received and pending
h.sendOrderNotify(notifyEmail, userName, updatedProduct.Name, created.ID, payload.Quantity, nil, true)
}
qrPayload := fmt.Sprintf("order:%s:%s", created.ID, created.ProductID) 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)) qrURL := fmt.Sprintf("https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s", qrSize, url.QueryEscape(qrPayload))
@@ -139,11 +230,25 @@ func (h *OrderHandler) ConfirmOrder(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return return
} }
isManual := order.DeliveryMode == "manual"
// For manual delivery, send a "delivered" notification when admin confirms
if isManual {
confirmNotifyEmail := order.NotifyEmail
if confirmNotifyEmail == "" {
confirmNotifyEmail = order.ContactEmail
}
h.sendOrderNotify(confirmNotifyEmail, order.UserName, order.ProductName, order.ID, order.Quantity, order.DeliveredCodes, false)
}
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"data": gin.H{ "data": gin.H{
"orderId": order.ID, "orderId": order.ID,
"status": order.Status, "status": order.Status,
"deliveryMode": order.DeliveryMode,
"deliveredCodes": order.DeliveredCodes, "deliveredCodes": order.DeliveredCodes,
"isManual": isManual,
}, },
}) })
} }

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": "invalid payload"})
return
}
if err := h.wishlistStore.Add(account, payload.ProductID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ids, _ := h.wishlistStore.Get(account)
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}
func (h *WishlistHandler) RemoveFromWishlist(c *gin.Context) {
account, ok := h.requireUser(c)
if !ok {
return
}
productID := c.Param("id")
if productID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing product id"})
return
}
if err := h.wishlistStore.Remove(account, productID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ids, _ := h.wishlistStore.Get(account)
c.JSON(http.StatusOK, gin.H{"data": gin.H{"items": ids}})
}

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"` Quantity int `json:"quantity"`
DeliveredCodes []string `json:"deliveredCodes"` DeliveredCodes []string `json:"deliveredCodes"`
Status string `json:"status"` 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"` CreatedAt time.Time `json:"createdAt"`
} }

View File

@@ -16,6 +16,12 @@ type Product struct {
ViewCount int `json:"viewCount"` ViewCount int `json:"viewCount"`
Description string `json:"description"` Description string `json:"description"`
Active bool `json:"active"` 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"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` 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

@@ -2,16 +2,15 @@ package storage
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/json"
"fmt" "fmt"
"os"
"path/filepath"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models" "mengyastore-backend/internal/models"
) )
@@ -20,238 +19,235 @@ const viewCooldown = 6 * time.Hour
const maxScreenshotURLs = 5 const maxScreenshotURLs = 5
type JSONStore struct { type JSONStore struct {
path string db *gorm.DB
mu sync.Mutex mu sync.Mutex
recentViews map[string]time.Time recentViews map[string]time.Time
} }
func NewJSONStore(path string) (*JSONStore, error) { func NewJSONStore(db *gorm.DB) (*JSONStore, error) {
if err := ensureProductsFile(path); err != nil {
return nil, err
}
return &JSONStore{ return &JSONStore{
path: path, db: db,
recentViews: make(map[string]time.Time), recentViews: make(map[string]time.Time),
}, nil }, nil
} }
func ensureProductsFile(path string) error { // rowToModel converts a ProductRow (+ codes) to a models.Product.
dir := filepath.Dir(path) func rowToModel(row database.ProductRow, codes []string) models.Product {
if err := os.MkdirAll(dir, 0o755); err != nil { return models.Product{
return fmt.Errorf("mkdir data dir: %w", err) 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,
} }
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{} func (s *JSONStore) loadCodes(productID string) ([]string, error) {
bytes, err := json.MarshalIndent(initial, "", " ") var rows []database.ProductCodeRow
if err != nil { if err := s.db.Where("product_id = ?", productID).Find(&rows).Error; err != nil {
return fmt.Errorf("init json: %w", err) return nil, err
} }
if err := os.WriteFile(path, bytes, 0o644); err != nil { codes := make([]string, len(rows))
return fmt.Errorf("write init json: %w", err) for i, r := range rows {
codes[i] = r.Code
} }
return codes, nil
}
func (s *JSONStore) replaceCodes(productID string, codes []string) error {
if err := s.db.Where("product_id = ?", productID).Delete(&database.ProductCodeRow{}).Error; err != nil {
return err
}
if len(codes) == 0 {
return nil return nil
} }
rows := make([]database.ProductCodeRow, 0, len(codes))
for _, code := range codes {
rows = append(rows, database.ProductCodeRow{ProductID: productID, Code: code})
}
return s.db.CreateInBatches(rows, 100).Error
}
func (s *JSONStore) ListAll() ([]models.Product, error) { func (s *JSONStore) ListAll() ([]models.Product, error) {
s.mu.Lock() var rows []database.ProductRow
defer s.mu.Unlock() if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
return s.readAll() return nil, err
}
products := make([]models.Product, 0, len(rows))
for _, row := range rows {
codes, _ := s.loadCodes(row.ID)
products = append(products, rowToModel(row, codes))
}
return products, nil
} }
func (s *JSONStore) ListActive() ([]models.Product, error) { func (s *JSONStore) ListActive() ([]models.Product, error) {
s.mu.Lock() var rows []database.ProductRow
defer s.mu.Unlock() if err := s.db.Where("active = ?", true).Order("created_at DESC").Find(&rows).Error; err != nil {
items, err := s.readAll()
if err != nil {
return nil, err return nil, err
} }
active := make([]models.Product, 0, len(items)) products := make([]models.Product, 0, len(rows))
for _, item := range items { for _, row := range rows {
if item.Active { // For public listing we don't expose codes, but we still need Quantity
active = append(active, item) 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
return active, nil
} }
func (s *JSONStore) GetByID(id string) (models.Product, error) { func (s *JSONStore) GetByID(id string) (models.Product, error) {
s.mu.Lock() var row database.ProductRow
defer s.mu.Unlock() if err := s.db.First(&row, "id = ?", id).Error; err != nil {
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") return models.Product{}, fmt.Errorf("product not found")
} }
codes, _ := s.loadCodes(id)
return rowToModel(row, codes), nil
}
func (s *JSONStore) Create(p models.Product) (models.Product, error) { 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 = normalizeProduct(p)
p.ID = uuid.NewString() p.ID = uuid.NewString()
now := time.Now() now := time.Now()
p.CreatedAt = now p.CreatedAt = now
p.UpdatedAt = now
items = append(items, p) row := database.ProductRow{
if err := s.writeAll(items); err != nil { 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 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 return p, nil
} }
func (s *JSONStore) Update(id string, patch models.Product) (models.Product, error) { func (s *JSONStore) Update(id string, patch models.Product) (models.Product, error) {
s.mu.Lock() var row database.ProductRow
defer s.mu.Unlock() if err := s.db.First(&row, "id = ?", id).Error; err != nil {
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") 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 *JSONStore) Toggle(id string, active bool) (models.Product, error) { func (s *JSONStore) Toggle(id string, active bool) (models.Product, error) {
s.mu.Lock() if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).Update("active", active).Error; err != nil {
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, err return models.Product{}, err
} }
for i, item := range items { var row database.ProductRow
if item.ID == id { if err := s.db.First(&row, "id = ?", id).Error; err != nil {
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") return models.Product{}, fmt.Errorf("product not found")
} }
codes, _ := s.loadCodes(id)
return rowToModel(row, codes), nil
}
func (s *JSONStore) IncrementSold(id string, count int) error {
return s.db.Model(&database.ProductRow{}).Where("id = ?", id).
UpdateColumn("total_sold", gorm.Expr("total_sold + ?", count)).Error
}
func (s *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool, error) { func (s *JSONStore) IncrementView(id, fingerprint string) (models.Product, bool, error) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Product{}, false, err
}
now := time.Now() now := time.Now()
s.cleanupRecentViews(now) s.cleanupRecentViews(now)
key := buildViewKey(id, fingerprint) key := buildViewKey(id, fingerprint)
if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown { if lastViewedAt, ok := s.recentViews[key]; ok && now.Sub(lastViewedAt) < viewCooldown {
for _, item := range items { var row database.ProductRow
if item.ID == id { if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return item, false, nil
}
}
return models.Product{}, false, fmt.Errorf("product not found") return models.Product{}, false, fmt.Errorf("product not found")
} }
return rowToModel(row, nil), false, nil
}
for i, item := range items { if err := s.db.Model(&database.ProductRow{}).Where("id = ?", id).
if item.ID == id { UpdateColumn("view_count", gorm.Expr("view_count + 1")).Error; err != nil {
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 models.Product{}, false, err
} }
return item, true, nil 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 models.Product{}, false, fmt.Errorf("product not found")
} }
return rowToModel(row, nil), true, nil
}
func (s *JSONStore) Delete(id string) error { func (s *JSONStore) Delete(id string) error {
s.mu.Lock() if err := s.db.Where("product_id = ?", id).Delete(&database.ProductCodeRow{}).Error; err != nil {
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return err return err
} }
filtered := make([]models.Product, 0, len(items)) return s.db.Delete(&database.ProductRow{}, "id = ?", id).Error
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
} }
// normalizeProduct cleans up product fields (same logic as before, no file I/O).
func normalizeProduct(item models.Product) models.Product { func normalizeProduct(item models.Product) models.Product {
item.CoverURL = strings.TrimSpace(item.CoverURL) item.CoverURL = strings.TrimSpace(item.CoverURL)
if item.CoverURL == "" { if item.CoverURL == "" {
@@ -276,6 +272,9 @@ func normalizeProduct(item models.Product) models.Product {
item.VerificationURL = strings.TrimSpace(item.VerificationURL) item.VerificationURL = strings.TrimSpace(item.VerificationURL)
item.Codes = sanitizeCodes(item.Codes) item.Codes = sanitizeCodes(item.Codes)
item.Quantity = len(item.Codes) item.Quantity = len(item.Codes)
if item.DeliveryMode == "" {
item.DeliveryMode = "auto"
}
return item return item
} }
@@ -284,10 +283,7 @@ func sanitizeCodes(codes []string) []string {
seen := map[string]bool{} seen := map[string]bool{}
for _, code := range codes { for _, code := range codes {
trimmed := strings.TrimSpace(code) trimmed := strings.TrimSpace(code)
if trimmed == "" { if trimmed == "" || seen[trimmed] {
continue
}
if seen[trimmed] {
continue continue
} }
seen[trimmed] = true seen[trimmed] = true

View File

@@ -1,140 +1,139 @@
package storage package storage
import ( import (
"encoding/json"
"fmt" "fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/google/uuid" "github.com/google/uuid"
"gorm.io/gorm"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/models" "mengyastore-backend/internal/models"
) )
type OrderStore struct { type OrderStore struct {
path string db *gorm.DB
mu sync.Mutex
} }
func NewOrderStore(path string) (*OrderStore, error) { func NewOrderStore(db *gorm.DB) (*OrderStore, error) {
if err := ensureOrdersFile(path); err != nil { return &OrderStore{db: db}, nil
return nil, err
}
return &OrderStore{path: path}, nil
} }
func (s *OrderStore) Count() (int, error) { func orderRowToModel(row database.OrderRow) models.Order {
s.mu.Lock() return models.Order{
defer s.mu.Unlock() ID: row.ID,
ProductID: row.ProductID,
items, err := s.readAll() ProductName: row.ProductName,
if err != nil { UserAccount: row.UserAccount,
return 0, err UserName: row.UserName,
Quantity: row.Quantity,
DeliveredCodes: row.DeliveredCodes,
Status: row.Status,
DeliveryMode: row.DeliveryMode,
Note: row.Note,
ContactPhone: row.ContactPhone,
ContactEmail: row.ContactEmail,
NotifyEmail: row.NotifyEmail,
CreatedAt: row.CreatedAt,
} }
return len(items), nil
}
func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return nil, err
}
matched := make([]models.Order, 0)
for i := len(items) - 1; i >= 0; i-- {
if items[i].UserAccount == account {
matched = append(matched, items[i])
}
}
return matched, nil
}
func (s *OrderStore) Confirm(id string) (models.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Order{}, err
}
for i, item := range items {
if item.ID == id {
if item.Status == "completed" {
return item, nil
}
items[i].Status = "completed"
if err := s.writeAll(items); err != nil {
return models.Order{}, err
}
return items[i], nil
}
}
return models.Order{}, fmt.Errorf("order not found")
} }
func (s *OrderStore) Create(order models.Order) (models.Order, error) { func (s *OrderStore) Create(order models.Order) (models.Order, error) {
s.mu.Lock() if order.ID == "" {
defer s.mu.Unlock()
items, err := s.readAll()
if err != nil {
return models.Order{}, err
}
order.ID = uuid.NewString() order.ID = uuid.NewString()
order.CreatedAt = time.Now() }
items = append(items, order) if len(order.DeliveredCodes) == 0 {
if err := s.writeAll(items); err != nil { 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 return models.Order{}, err
} }
order.CreatedAt = row.CreatedAt
return order, nil return order, nil
} }
func (s *OrderStore) readAll() ([]models.Order, error) { func (s *OrderStore) GetByID(id string) (models.Order, error) {
bytes, err := os.ReadFile(s.path) var row database.OrderRow
if err != nil { if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return nil, fmt.Errorf("read orders: %w", err) return models.Order{}, fmt.Errorf("order not found")
} }
var items []models.Order return orderRowToModel(row), nil
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 { func (s *OrderStore) Confirm(id string) (models.Order, error) {
bytes, err := json.MarshalIndent(items, "", " ") var row database.OrderRow
if err != nil { if err := s.db.First(&row, "id = ?", id).Error; err != nil {
return fmt.Errorf("encode orders: %w", err) return models.Order{}, fmt.Errorf("order not found")
} }
if err := os.WriteFile(s.path, bytes, 0o644); err != nil { if err := s.db.Model(&row).Update("status", "completed").Error; err != nil {
return fmt.Errorf("write orders: %w", err) return models.Order{}, err
} }
return nil row.Status = "completed"
return orderRowToModel(row), nil
} }
func ensureOrdersFile(path string) error { func (s *OrderStore) ListByAccount(account string) ([]models.Order, error) {
dir := filepath.Dir(path) var rows []database.OrderRow
if err := os.MkdirAll(dir, 0o755); err != nil { if err := s.db.Where("user_account = ?", account).Order("created_at DESC").Find(&rows).Error; err != nil {
return fmt.Errorf("mkdir data dir: %w", err) return nil, err
} }
if _, err := os.Stat(path); err == nil { orders := make([]models.Order, len(rows))
return nil for i, r := range rows {
} else if !os.IsNotExist(err) { orders[i] = orderRowToModel(r)
return fmt.Errorf("stat data file: %w", err) }
return orders, nil
} }
initial := []models.Order{} func (s *OrderStore) ListAll() ([]models.Order, error) {
bytes, err := json.MarshalIndent(initial, "", " ") var rows []database.OrderRow
if err != nil { if err := s.db.Order("created_at DESC").Find(&rows).Error; err != nil {
return fmt.Errorf("init json: %w", err) return nil, err
} }
if err := os.WriteFile(path, bytes, 0o644); err != nil { orders := make([]models.Order, len(rows))
return fmt.Errorf("write init json: %w", err) for i, r := range rows {
orders[i] = orderRowToModel(r)
} }
return nil return orders, nil
}
func (s *OrderStore) CountPurchasedByAccount(account, productID string) (int, error) {
var total int64
err := s.db.Model(&database.OrderRow{}).
Where("user_account = ? AND product_id = ? AND status = ?", account, productID, "completed").
Select("COALESCE(SUM(quantity), 0)").Scan(&total).Error
return int(total), err
}
// Count returns the total number of orders.
func (s *OrderStore) Count() (int, error) {
var count int64
if err := s.db.Model(&database.OrderRow{}).Count(&count).Error; err != nil {
return 0, err
}
return int(count), nil
}
// Delete removes a single order by ID.
func (s *OrderStore) Delete(id string) error {
return s.db.Delete(&database.OrderRow{}, "id = ?", id).Error
}
// UpdateCodes replaces the delivered codes for an order (used by auto-delivery to set codes after extracting).
func (s *OrderStore) UpdateCodes(id string, codes []string) error {
return s.db.Model(&database.OrderRow{}).Where("id = ?", id).
Update("delivered_codes", database.StringSlice(codes)).Error
} }

View File

@@ -1,128 +1,135 @@
package storage package storage
import ( import (
"crypto/sha256" "strconv"
"encoding/json"
"fmt" "gorm.io/gorm"
"os" "gorm.io/gorm/clause"
"path/filepath"
"sync" "mengyastore-backend/internal/database"
"time"
) )
const visitCooldown = 6 * time.Hour
type siteData struct {
TotalVisits int `json:"totalVisits"`
}
type SiteStore struct { type SiteStore struct {
path string db *gorm.DB
mu sync.Mutex
recentVisits map[string]time.Time
} }
func NewSiteStore(path string) (*SiteStore, error) { func NewSiteStore(db *gorm.DB) (*SiteStore, error) {
if err := ensureSiteFile(path); err != nil { return &SiteStore{db: db}, nil
return nil, err
}
return &SiteStore{
path: path,
recentVisits: make(map[string]time.Time),
}, nil
} }
func (s *SiteStore) RecordVisit(fingerprint string) (int, bool, error) { func (s *SiteStore) get(key string) (string, error) {
s.mu.Lock() var row database.SiteSettingRow
defer s.mu.Unlock() if err := s.db.First(&row, "key = ?", key).Error; err != nil {
return "", nil // key not found → return zero value
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 return row.Value, nil
} }
data, err := s.read() func (s *SiteStore) set(key, value string) error {
if err != nil { return s.db.Clauses(clause.OnConflict{
return 0, false, err Columns: []clause.Column{{Name: "key"}},
} DoUpdates: clause.AssignmentColumns([]string{"value"}),
data.TotalVisits++ }).Create(&database.SiteSettingRow{Key: key, Value: value}).Error
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) { func (s *SiteStore) GetTotalVisits() (int, error) {
s.mu.Lock() v, err := s.get("totalVisits")
defer s.mu.Unlock() if err != nil || v == "" {
data, err := s.read() return 0, err
}
n, _ := strconv.Atoi(v)
return n, nil
}
func (s *SiteStore) IncrementVisits() (int, error) {
current, err := s.GetTotalVisits()
if err != nil { if err != nil {
return 0, err return 0, err
} }
return data.TotalVisits, nil current++
if err := s.set("totalVisits", strconv.Itoa(current)); err != nil {
return 0, err
}
return current, nil
} }
func (s *SiteStore) read() (siteData, error) { func (s *SiteStore) GetMaintenance() (enabled bool, reason string, err error) {
bytes, err := os.ReadFile(s.path) v, err := s.get("maintenance")
if err != nil { if err != nil {
return siteData{}, fmt.Errorf("read site data: %w", err) return false, "", err
} }
var data siteData enabled = v == "true"
if err := json.Unmarshal(bytes, &data); err != nil { reason, err = s.get("maintenanceReason")
return siteData{}, fmt.Errorf("parse site data: %w", err) return enabled, reason, err
}
return data, nil
} }
func (s *SiteStore) write(data siteData) error { func (s *SiteStore) SetMaintenance(enabled bool, reason string) error {
bytes, err := json.MarshalIndent(data, "", " ") v := "false"
if err != nil { if enabled {
return fmt.Errorf("encode site data: %w", err) v = "true"
}
if err := s.set("maintenance", v); err != nil {
return err
}
return s.set("maintenanceReason", reason)
}
// RecordVisit increments the visit counter. Returns (totalVisits, counted, error).
// For simplicity, every call increments (fingerprint dedup is handled in-memory by the handler layer).
func (s *SiteStore) RecordVisit(_ string) (int, bool, error) {
total, err := s.IncrementVisits()
return total, true, err
}
// SMTPConfig holds the mail sender configuration stored in the DB.
type SMTPConfig struct {
Email string `json:"email"`
Password string `json:"password"`
FromName string `json:"fromName"`
Host string `json:"host"`
Port string `json:"port"`
}
// IsConfiguredEmail returns true if the SMTP config is ready to send mail.
func (c SMTPConfig) IsConfiguredEmail() bool {
return c.Email != "" && c.Password != "" && c.Host != ""
}
func (s *SiteStore) GetSMTPConfig() (SMTPConfig, error) {
cfg := SMTPConfig{
Host: "smtp.qq.com",
Port: "465",
}
if v, _ := s.get("smtpEmail"); v != "" {
cfg.Email = v
}
if v, _ := s.get("smtpPassword"); v != "" {
cfg.Password = v
}
if v, _ := s.get("smtpFromName"); v != "" {
cfg.FromName = v
}
if v, _ := s.get("smtpHost"); v != "" {
cfg.Host = v
}
if v, _ := s.get("smtpPort"); v != "" {
cfg.Port = v
}
return cfg, nil
}
func (s *SiteStore) SetSMTPConfig(cfg SMTPConfig) error {
pairs := [][2]string{
{"smtpEmail", cfg.Email},
{"smtpPassword", cfg.Password},
{"smtpFromName", cfg.FromName},
{"smtpHost", cfg.Host},
{"smtpPort", cfg.Port},
}
for _, p := range pairs {
if err := s.set(p[0], p[1]); err != nil {
return err
} }
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 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

@@ -10,6 +10,7 @@ import (
"mengyastore-backend/internal/auth" "mengyastore-backend/internal/auth"
"mengyastore-backend/internal/config" "mengyastore-backend/internal/config"
"mengyastore-backend/internal/database"
"mengyastore-backend/internal/handlers" "mengyastore-backend/internal/handlers"
"mengyastore-backend/internal/storage" "mengyastore-backend/internal/storage"
) )
@@ -20,18 +21,32 @@ func main() {
log.Fatalf("load config failed: %v", err) log.Fatalf("load config failed: %v", err)
} }
store, err := storage.NewJSONStore("data/json/products.json") // Initialise database
db, err := database.Open(cfg.DatabaseDSN)
if err != nil {
log.Fatalf("init database failed: %v", err)
}
store, err := storage.NewJSONStore(db)
if err != nil { if err != nil {
log.Fatalf("init store failed: %v", err) log.Fatalf("init store failed: %v", err)
} }
orderStore, err := storage.NewOrderStore("data/json/orders.json") orderStore, err := storage.NewOrderStore(db)
if err != nil { if err != nil {
log.Fatalf("init order store failed: %v", err) log.Fatalf("init order store failed: %v", err)
} }
siteStore, err := storage.NewSiteStore("data/json/site.json") siteStore, err := storage.NewSiteStore(db)
if err != nil { if err != nil {
log.Fatalf("init site store failed: %v", err) log.Fatalf("init site store failed: %v", err)
} }
wishlistStore, err := storage.NewWishlistStore(db)
if err != nil {
log.Fatalf("init wishlist store failed: %v", err)
}
chatStore, err := storage.NewChatStore(db)
if err != nil {
log.Fatalf("init chat store failed: %v", err)
}
r := gin.Default() r := gin.Default()
r.Use(cors.New(cors.Config{ r.Use(cors.New(cors.Config{
@@ -50,15 +65,18 @@ func main() {
authClient := auth.NewSproutGateClient(cfg.AuthAPIURL) authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)
publicHandler := handlers.NewPublicHandler(store) publicHandler := handlers.NewPublicHandler(store)
adminHandler := handlers.NewAdminHandler(store, cfg) adminHandler := handlers.NewAdminHandler(store, cfg, siteStore, orderStore, chatStore)
orderHandler := handlers.NewOrderHandler(store, orderStore, authClient) orderHandler := handlers.NewOrderHandler(store, orderStore, siteStore, authClient)
statsHandler := handlers.NewStatsHandler(orderStore, siteStore) statsHandler := handlers.NewStatsHandler(orderStore, siteStore)
wishlistHandler := handlers.NewWishlistHandler(wishlistStore, authClient)
chatHandler := handlers.NewChatHandler(chatStore, authClient)
r.GET("/api/products", publicHandler.ListProducts) r.GET("/api/products", publicHandler.ListProducts)
r.POST("/api/checkout", orderHandler.CreateOrder) r.POST("/api/checkout", orderHandler.CreateOrder)
r.POST("/api/products/:id/view", publicHandler.RecordProductView) r.POST("/api/products/:id/view", publicHandler.RecordProductView)
r.GET("/api/stats", statsHandler.GetStats) r.GET("/api/stats", statsHandler.GetStats)
r.POST("/api/site/visit", statsHandler.RecordVisit) r.POST("/api/site/visit", statsHandler.RecordVisit)
r.GET("/api/site/maintenance", statsHandler.GetMaintenance)
r.GET("/api/orders", orderHandler.ListMyOrders) r.GET("/api/orders", orderHandler.ListMyOrders)
r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder) r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)
@@ -68,6 +86,25 @@ func main() {
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct) r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct) r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct) r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)
r.POST("/api/admin/site/maintenance", adminHandler.SetMaintenance)
r.GET("/api/admin/site/smtp", adminHandler.GetSMTPConfig)
r.POST("/api/admin/site/smtp", adminHandler.SetSMTPConfig)
r.GET("/api/admin/orders", adminHandler.ListAllOrders)
r.DELETE("/api/admin/orders/:id", adminHandler.DeleteOrder)
r.GET("/api/wishlist", wishlistHandler.GetWishlist)
r.POST("/api/wishlist", wishlistHandler.AddToWishlist)
r.DELETE("/api/wishlist/:id", wishlistHandler.RemoveFromWishlist)
// Chat routes (user)
r.GET("/api/chat/messages", chatHandler.GetMyMessages)
r.POST("/api/chat/messages", chatHandler.SendMyMessage)
// Chat routes (admin)
r.GET("/api/admin/chat", adminHandler.GetAllConversations)
r.GET("/api/admin/chat/:account", adminHandler.GetConversation)
r.POST("/api/admin/chat/:account", adminHandler.AdminReply)
r.DELETE("/api/admin/chat/:account", adminHandler.ClearConversation)
log.Println("萌芽小店后端启动于 http://localhost:8080") log.Println("萌芽小店后端启动于 http://localhost:8080")
if err := r.Run(":8080"); err != nil { if err := r.Run(":8080"); err != nil {

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"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8" /> <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> <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="/icon.svg" type="image/svg+xml" />
<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> </head>
<body> <body>
<div id="app"></div> <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" "vue-router": "^4.3.0"
}, },
"devDependencies": { "devDependencies": {
"@vite-pwa/assets-generator": "^1.0.2",
"@vitejs/plugin-vue": "^5.0.4", "@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: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

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: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,5 +1,8 @@
<template> <template>
<div class="app"> <div class="app">
<!-- PWA Splash Screen -->
<SplashScreen :visible="showSplash" />
<header class="top-bar"> <header class="top-bar">
<div class="brand" @click="onLogoClick"> <div class="brand" @click="onLogoClick">
<div class="brand-mark"> <div class="brand-mark">
@@ -12,6 +15,11 @@
<div class="top-actions"> <div class="top-actions">
<button class="ghost" @click="goHome">商店</button> <button class="ghost" @click="goHome">商店</button>
<template v-if="loggedIn"> <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> <button class="ghost" @click="goMyOrders">我的订单</button>
<div class="user-badge" @click="goProfile"> <div class="user-badge" @click="goProfile">
<img <img
@@ -90,14 +98,42 @@
</div> </div>
</footer> </footer>
</div> </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> </div>
</template> </template>
<script setup> <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 { useRouter } from 'vue-router'
import { fetchAdminToken, fetchStats, recordSiteVisit } from './modules/shared/api' import { fetchAdminToken, fetchStats, recordSiteVisit } from './modules/shared/api'
import { authState, isLoggedIn, clearAuth, getLoginUrl } from './modules/shared/auth' import { authState, isLoggedIn, clearAuth, getLoginUrl } from './modules/shared/auth'
import { wishlistCount, loadWishlist } from './modules/shared/useWishlist'
import 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 router = useRouter()
const stats = reactive({ totalOrders: 0, totalVisits: 0 }) const stats = reactive({ totalOrders: 0, totalVisits: 0 })
@@ -149,6 +185,7 @@ const submitAdminToken = async () => {
const goHome = () => { router.push('/') } const goHome = () => { router.push('/') }
const goMyOrders = () => { router.push('/my/orders') } const goMyOrders = () => { router.push('/my/orders') }
const goWishlist = () => { router.push('/wishlist') }
const goProfile = () => { const goProfile = () => {
if (authState.account) { if (authState.account) {
@@ -158,7 +195,12 @@ const goProfile = () => {
const logout = () => { clearAuth() } const logout = () => { clearAuth() }
const SPLASH_MIN_MS = 1400
onMounted(async () => { onMounted(async () => {
const splashStart = Date.now()
await loadWishlist()
try { try {
recordSiteVisit().then((result) => { recordSiteVisit().then((result) => {
if (result.totalVisits) stats.totalVisits = result.totalVisits if (result.totalVisits) stats.totalVisits = result.totalVisits
@@ -170,5 +212,15 @@ onMounted(async () => {
} catch (e) { } catch (e) {
statsLoaded.value = false 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> </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 { :root {
--bg-1: #f8f5f2; --bg-1: #f8f5f2;
@@ -12,17 +11,27 @@
--accent: #b49acb; --accent: #b49acb;
--accent-2: #91a8d0; --accent-2: #91a8d0;
--shadow: 0 20px 50px rgba(33, 33, 40, 0.12); --shadow: 0 20px 50px rgba(33, 33, 40, 0.12);
--radius: 14px; --radius: 8px;
} }
* { * {
box-sizing: border-box; box-sizing: border-box;
} }
/* Hide scrollbar but keep scroll functionality */
html {
scrollbar-width: none; /* Firefox */
}
html::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
}
body { body {
margin: 0; margin: 0;
min-height: 100vh; min-height: 100vh;
font-family: 'Source Sans 3', sans-serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 18px;
color: var(--text); color: var(--text);
background: radial-gradient(circle at top, var(--bg-2), transparent 60%), background: radial-gradient(circle at top, var(--bg-2), transparent 60%),
radial-gradient(circle at 10% 20%, var(--bg-3), transparent 55%), radial-gradient(circle at 10% 20%, var(--bg-3), transparent 55%),
@@ -33,7 +42,7 @@ h1,
h2, h2,
h3, h3,
h4 { h4 {
font-family: 'Playfair Display', serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
margin: 0; margin: 0;
} }
@@ -96,7 +105,7 @@ p {
padding: 36px 32px 28px; padding: 36px 32px 28px;
background: var(--glass-strong); background: var(--glass-strong);
border: 1px solid var(--line); border: 1px solid var(--line);
border-radius: 20px; border-radius: 12px;
box-shadow: 0 24px 60px rgba(33, 33, 40, 0.22); box-shadow: 0 24px 60px rgba(33, 33, 40, 0.22);
backdrop-filter: blur(20px); backdrop-filter: blur(20px);
text-align: center; text-align: center;
@@ -112,7 +121,7 @@ p {
color: var(--muted); color: var(--muted);
cursor: pointer; cursor: pointer;
padding: 4px 8px; padding: 4px 8px;
border-radius: 8px; border-radius: 5px;
line-height: 1; line-height: 1;
transition: color 0.2s ease; transition: color 0.2s ease;
} }
@@ -128,19 +137,19 @@ p {
justify-content: center; justify-content: center;
width: 56px; width: 56px;
height: 56px; height: 56px;
border-radius: 16px; border-radius: 10px;
background: linear-gradient(135deg, var(--accent), var(--accent-2)); background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white; color: white;
margin-bottom: 16px; margin-bottom: 16px;
} }
.admin-modal h3 { .admin-modal h3 {
font-size: 20px; font-size: 22px;
margin-bottom: 6px; margin-bottom: 6px;
} }
.admin-modal-hint { .admin-modal-hint {
font-size: 13px; font-size: 15px;
color: var(--muted); color: var(--muted);
margin-bottom: 20px; margin-bottom: 20px;
} }
@@ -148,11 +157,11 @@ p {
.admin-modal-input { .admin-modal-input {
width: 100%; width: 100%;
padding: 12px 16px; padding: 12px 16px;
border-radius: 12px; border-radius: 8px;
border: 1px solid var(--line); border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.65); background: rgba(255, 255, 255, 0.65);
font-family: 'Source Sans 3', sans-serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 15px; font-size: 18px;
text-align: center; text-align: center;
letter-spacing: 2px; letter-spacing: 2px;
outline: none; outline: none;
@@ -165,7 +174,7 @@ p {
} }
.admin-modal-error { .admin-modal-error {
font-size: 13px; font-size: 15px;
color: #d4566a; color: #d4566a;
margin-top: 8px; margin-top: 8px;
} }
@@ -174,7 +183,7 @@ p {
width: 100%; width: 100%;
margin-top: 16px; margin-top: 16px;
padding: 12px; padding: 12px;
font-size: 15px; font-size: 17px;
} }
.admin-modal-btn:disabled { .admin-modal-btn:disabled {
@@ -209,19 +218,19 @@ p {
} }
.brand h1 { .brand h1 {
font-size: 26px; font-size: 28px;
letter-spacing: 1px; letter-spacing: 1px;
} }
.brand p { .brand p {
color: var(--muted); color: var(--muted);
font-size: 14px; font-size: 16px;
} }
.brand-mark { .brand-mark {
width: 46px; width: 46px;
height: 46px; height: 46px;
border-radius: 16px; border-radius: 10px;
overflow: hidden; overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.6); border: 1px solid rgba(255, 255, 255, 0.6);
background: var(--glass-strong); background: var(--glass-strong);
@@ -273,14 +282,14 @@ p {
justify-content: center; justify-content: center;
background: linear-gradient(135deg, var(--accent), var(--accent-2)); background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white; color: white;
font-size: 13px; font-size: 15px;
font-weight: 600; font-weight: 600;
} }
.user-name { .user-name {
font-size: 13px; font-size: 17px;
color: var(--text); color: var(--text);
font-weight: 500; font-weight: 700;
max-width: 100px; max-width: 100px;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
@@ -291,12 +300,12 @@ p {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
padding: 10px 18px; padding: 10px 18px;
border-radius: 12px; border-radius: 8px;
background: linear-gradient(135deg, var(--accent), var(--accent-2)); background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white; color: white;
text-decoration: none; text-decoration: none;
font-family: 'Source Sans 3', sans-serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 14px; font-size: 17px;
box-shadow: 0 10px 30px rgba(145, 168, 208, 0.35); box-shadow: 0 10px 30px rgba(145, 168, 208, 0.35);
transition: transform 0.2s ease, box-shadow 0.2s ease; transition: transform 0.2s ease, box-shadow 0.2s ease;
} }
@@ -308,9 +317,9 @@ p {
button { button {
border: none; border: none;
cursor: pointer; cursor: pointer;
font-family: 'Source Sans 3', sans-serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
padding: 10px 18px; padding: 10px 18px;
border-radius: 12px; border-radius: 8px;
transition: transform 0.2s ease, box-shadow 0.2s ease; transition: transform 0.2s ease, box-shadow 0.2s ease;
} }
@@ -328,6 +337,8 @@ button.ghost {
background: rgba(255, 255, 255, 0.6); background: rgba(255, 255, 255, 0.6);
color: var(--text); color: var(--text);
border: 1px solid var(--line); border: 1px solid var(--line);
font-size: 17px;
font-weight: 700;
} }
.main-content { .main-content {
@@ -362,15 +373,15 @@ button.ghost {
.footer-logo { .footer-logo {
width: 28px; width: 28px;
height: 28px; height: 28px;
border-radius: 8px; border-radius: 5px;
object-fit: contain; object-fit: contain;
border: 1px solid rgba(255, 255, 255, 0.5); border: 1px solid rgba(255, 255, 255, 0.5);
box-shadow: 0 4px 12px rgba(33, 33, 40, 0.1); box-shadow: 0 4px 12px rgba(33, 33, 40, 0.1);
} }
.footer-title { .footer-title {
font-family: 'Playfair Display', serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 17px; font-size: 19px;
font-weight: 600; font-weight: 600;
color: var(--text); color: var(--text);
letter-spacing: 0.5px; letter-spacing: 0.5px;
@@ -398,10 +409,10 @@ button.ghost {
gap: 6px; gap: 6px;
color: var(--accent-2); color: var(--accent-2);
text-decoration: none; text-decoration: none;
font-size: 13px; font-size: 15px;
font-weight: 500; font-weight: 500;
padding: 5px 12px; padding: 5px 12px;
border-radius: 8px; border-radius: 5px;
background: rgba(145, 168, 208, 0.08); background: rgba(145, 168, 208, 0.08);
transition: background 0.2s ease, color 0.2s ease; transition: background 0.2s ease, color 0.2s ease;
} }
@@ -415,11 +426,11 @@ button.ghost {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 6px; gap: 6px;
font-size: 13px; font-size: 15px;
font-weight: 500; font-weight: 500;
color: var(--accent); color: var(--accent);
padding: 5px 12px; padding: 5px 12px;
border-radius: 8px; border-radius: 5px;
background: rgba(180, 154, 203, 0.08); background: rgba(180, 154, 203, 0.08);
} }
@@ -429,7 +440,7 @@ button.ghost {
} }
.footer-copy { .footer-copy {
font-size: 12px; font-size: 14px;
color: var(--muted); color: var(--muted);
opacity: 0.7; opacity: 0.7;
letter-spacing: 0.3px; letter-spacing: 0.3px;
@@ -456,7 +467,7 @@ button.ghost {
flex-direction: column; flex-direction: column;
gap: 12px; gap: 12px;
padding: 18px; padding: 18px;
border-radius: 14px; border-radius: 8px;
background: var(--glass-strong); background: var(--glass-strong);
border: 1px solid var(--line); border: 1px solid var(--line);
box-shadow: 0 12px 30px rgba(33, 33, 40, 0.1); box-shadow: 0 12px 30px rgba(33, 33, 40, 0.1);
@@ -467,7 +478,7 @@ button.ghost {
width: 100%; width: 100%;
height: 140px; height: 140px;
object-fit: cover; object-fit: cover;
border-radius: 12px; border-radius: 6px;
} }
.product-meta { .product-meta {
@@ -489,11 +500,11 @@ button.ghost {
display: inline-flex; display: inline-flex;
justify-content: center; justify-content: center;
padding: 8px 14px; padding: 8px 14px;
border-radius: 10px; border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.6); border: 1px solid rgba(255, 255, 255, 0.6);
background: rgba(255, 255, 255, 0.6); background: rgba(255, 255, 255, 0.6);
color: var(--text); color: var(--text);
font-size: 13px; font-size: 15px;
transition: background 0.2s ease; transition: background 0.2s ease;
} }
@@ -503,8 +514,8 @@ button.ghost {
.badge { .badge {
padding: 4px 10px; padding: 4px 10px;
border-radius: 10px; border-radius: 6px;
font-size: 12px; font-size: 14px;
background: rgba(255, 255, 255, 0.7); background: rgba(255, 255, 255, 0.7);
} }
@@ -524,7 +535,7 @@ button.ghost {
width: 100%; width: 100%;
height: 360px; height: 360px;
object-fit: cover; object-fit: cover;
border-radius: 16px; border-radius: 10px;
} }
.detail-actions { .detail-actions {
@@ -537,7 +548,7 @@ button.ghost {
background: linear-gradient(135deg, var(--accent), var(--accent-2)); background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white; color: white;
padding: 12px 22px; padding: 12px 22px;
border-radius: 12px; border-radius: 8px;
} }
.form-field { .form-field {
@@ -549,11 +560,11 @@ button.ghost {
.form-field input, .form-field input,
.form-field textarea { .form-field textarea {
border-radius: 14px; border-radius: 8px;
border: 1px solid var(--line); border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7); background: rgba(255, 255, 255, 0.7);
padding: 10px 12px; padding: 10px 12px;
font-family: 'Source Sans 3', sans-serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
} }
.form-field textarea { .form-field textarea {
@@ -576,7 +587,7 @@ button.ghost {
.table td { .table td {
text-align: left; text-align: left;
padding: 12px; padding: 12px;
font-size: 14px; font-size: 16px;
} }
.table tr { .table tr {
@@ -584,12 +595,12 @@ button.ghost {
} }
.tag { .tag {
font-size: 12px; font-size: 14px;
color: var(--muted); color: var(--muted);
} }
.markdown { .markdown {
font-size: 13px; font-size: 15px;
color: var(--muted); color: var(--muted);
line-height: 1.6; line-height: 1.6;
display: -webkit-box; display: -webkit-box;
@@ -600,19 +611,86 @@ button.ghost {
@media (max-width: 900px) { @media (max-width: 900px) {
.app-body { .app-body {
padding: 18px 4vw 28px; padding: 12px 2vw 20px;
} }
/* ── Navigation: keep everything on one row, compress ── */
.top-bar { .top-bar {
flex-direction: column; flex-direction: row;
align-items: flex-start; flex-wrap: nowrap;
padding: 14px 4vw; align-items: center;
gap: 12px; 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 {
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px; gap: 10px;
padding: 0 2px;
} }
.admin-grid { .admin-grid {
@@ -628,27 +706,97 @@ button.ghost {
} }
.footer { .footer {
padding: 20px 18px; padding: 20px 14px;
} }
.footer-links { .footer-links {
flex-direction: column; flex-direction: row;
gap: 10px; flex-wrap: wrap;
gap: 10px 16px;
justify-content: center;
} }
.page-card { .page-card {
padding: 18px;
}
.product-card {
padding: 14px; padding: 14px;
} }
.product-card {
padding: 10px 8px;
}
.product-card img { .product-card img {
height: 120px; height: 110px;
} }
.markdown { .markdown {
-webkit-line-clamp: 2; -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)
// Refresh current conversation messages if one is selected
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)
})
// Reset to page 1 when orders list changes
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,182 @@
<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-fields">
<label class="smtp-field">
<span>发件邮箱</span>
<input v-model="form.email" type="email" placeholder="noreply@yourdomain.com" />
</label>
<label class="smtp-field">
<span>SMTP 密码 / 授权码</span>
<input v-model="form.password" type="password" placeholder="QQ/163 填授权码;其他填密码" autocomplete="new-password" />
</label>
<label class="smtp-field">
<span>发件人名称</span>
<input v-model="form.fromName" type="text" placeholder="萌芽小店" />
</label>
<label class="smtp-field">
<span>SMTP 主机</span>
<input v-model="form.host" type="text" placeholder="smtp.qq.com" />
</label>
<label class="smtp-field smtp-field-port">
<span>端口</span>
<input v-model="form.port" type="text" placeholder="465" />
</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({
email: '',
password: '',
fromName: '',
host: 'smtp.qq.com',
port: '465'
})
watch(() => props.config, (cfg) => {
if (!cfg) return
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-fields {
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: flex-end;
}
.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,103 @@
<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="粘贴 token 后自动加载…" />
<button class="ghost small" type="button" @click="$emit('auto-get')">自动获取</button>
</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', 'auto-get'])
</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 { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { setAuth } from '../shared/auth' import { setAuth } from '../shared/auth'
import { verifySproutGateToken, fetchSproutGateUser } from '../shared/api' import { verifySproutGateToken } from '../shared/api'
const router = useRouter() const router = useRouter()
const status = ref('loading') const status = ref('loading')
@@ -37,12 +37,13 @@ const parseFragment = () => {
return { return {
token: params.get('token') || '', token: params.get('token') || '',
account: params.get('account') || '', account: params.get('account') || '',
username: params.get('username') || '' username: params.get('username') || '',
avatarUrl: params.get('avatarUrl') || ''
} }
} }
onMounted(async () => { onMounted(async () => {
const { token, account, username } = parseFragment() const { token, account, username, avatarUrl: fragmentAvatar } = parseFragment()
if (!token) { if (!token) {
status.value = 'error' status.value = 'error'
@@ -51,6 +52,7 @@ onMounted(async () => {
} }
try { try {
// Verify token and get up-to-date user info from SproutGate
const verifyData = await verifySproutGateToken(token) const verifyData = await verifySproutGateToken(token)
if (!verifyData.valid) { if (!verifyData.valid) {
status.value = 'error' status.value = 'error'
@@ -58,33 +60,19 @@ onMounted(async () => {
return return
} }
let avatarUrl = verifyData.user?.avatarUrl || '' const user = verifyData.user || {}
let finalAccount = verifyData.user?.account || account const finalAccount = user.account || account
let finalUsername = verifyData.user?.username || username const finalUsername = user.username || username
const finalAvatarUrl = user.avatarUrl || fragmentAvatar
if (!avatarUrl) { const finalEmail = user.email || ''
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
})
setAuth({ token, account: finalAccount, username: finalUsername, avatarUrl: finalAvatarUrl, email: finalEmail })
displayName.value = finalUsername || finalAccount displayName.value = finalUsername || finalAccount
status.value = 'success' status.value = 'success'
setTimeout(() => router.push('/'), 1000) setTimeout(() => router.push('/'), 1000)
} catch { } catch {
setAuth({ token, account, username, avatarUrl: '' }) // If verify fails (network issue), fall back to fragment data
setAuth({ token, account, username, avatarUrl: fragmentAvatar })
displayName.value = username || account displayName.value = username || account
status.value = 'success' status.value = 'success'
setTimeout(() => router.push('/'), 1000) 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 {
// silently ignore polling errors
}
}
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

@@ -97,3 +97,99 @@ export const deleteProduct = async (token, id) => {
}) })
return data 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', { params: { token } })
return data.data || []
}
export const deleteAdminOrder = async (token, orderId) => {
await api.delete(`/api/admin/orders/${orderId}`, { params: { 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 }, {
params: { token }
})
return data.data || {}
}
// ---- SMTP Config ----
export const fetchSMTPConfig = async (token) => {
const { data } = await api.get('/api/admin/site/smtp', { params: { token } })
return data.data || {}
}
export const setSMTPConfig = async (token, cfg) => {
const { data } = await api.post('/api/admin/site/smtp', cfg, { params: { 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', { params: { token: adminToken } })
return data.data?.conversations || {}
}
export const fetchAdminConversation = async (adminToken, account) => {
const { data } = await api.get(`/api/admin/chat/${encodeURIComponent(account)}`, {
params: { token: adminToken }
})
return data.data?.messages || []
}
export const adminSendChatReply = async (adminToken, account, content) => {
const { data } = await api.post(
`/api/admin/chat/${encodeURIComponent(account)}`,
{ content },
{ params: { token: adminToken } }
)
return data.data?.message || null
}
export const adminClearConversation = async (adminToken, account) => {
await api.delete(`/api/admin/chat/${encodeURIComponent(account)}`, {
params: { token: adminToken }
})
}

View File

@@ -18,7 +18,8 @@ export const authState = reactive({
token: saved?.token || '', token: saved?.token || '',
account: saved?.account || '', account: saved?.account || '',
username: saved?.username || '', username: saved?.username || '',
avatarUrl: saved?.avatarUrl || '' avatarUrl: saved?.avatarUrl || '',
email: saved?.email || ''
}) })
export const isLoggedIn = () => !!authState.token export const isLoggedIn = () => !!authState.token
@@ -28,13 +29,15 @@ export const setAuth = (info) => {
authState.account = info.account || '' authState.account = info.account || ''
authState.username = info.username || '' authState.username = info.username || ''
authState.avatarUrl = info.avatarUrl || '' authState.avatarUrl = info.avatarUrl || ''
authState.email = info.email || ''
localStorage.setItem( localStorage.setItem(
AUTH_KEY, AUTH_KEY,
JSON.stringify({ JSON.stringify({
token: authState.token, token: authState.token,
account: authState.account, account: authState.account,
username: authState.username, username: authState.username,
avatarUrl: authState.avatarUrl avatarUrl: authState.avatarUrl,
email: authState.email
}) })
) )
} }
@@ -44,6 +47,7 @@ export const clearAuth = () => {
authState.account = '' authState.account = ''
authState.username = '' authState.username = ''
authState.avatarUrl = '' authState.avatarUrl = ''
authState.email = ''
localStorage.removeItem(AUTH_KEY) 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 {
// ignore
}
}
const removeFromWishlist = async (productId) => {
if (!isLoggedIn()) return
try {
wishlistIds.value = await apiRemoveFromWishlist(authState.token, productId)
} catch {
// ignore
}
}
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>
</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"> <div class="form-field">
<label>下单数量</label> <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> </div>
<p class="tag">预计总价¥ {{ totalPrice.toFixed(2) }}</p> <p class="tag">预计总价¥ {{ totalPrice.toFixed(2) }}</p>
<p class="tag login-hint" v-if="!loggedIn"> <p class="tag limit-hint" v-if="product.maxPerAccount > 0">
提示<a :href="loginUrl">登录萌芽账号</a> 后下单可查看历史订单记录 该商品每个账户最多可购买 {{ product.maxPerAccount }}
</p> </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"> <button class="primary" type="submit" :disabled="submitting">
{{ submitting ? '生成中...' : '生成二维码下单' }} {{ submitting ? '生成中...' : '生成二维码下单' }}
</button> </button>
@@ -66,6 +104,13 @@
<p class="tag">购买后内容</p> <p class="tag">购买后内容</p>
<textarea class="delivery-box" readonly :value="deliveredCodes.join('\n')"></textarea> <textarea class="delivery-box" readonly :value="deliveredCodes.join('\n')"></textarea>
</div> </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> <p class="tag">感谢购买如有问题请联系售后邮箱</p>
</template> </template>
</section> </section>
@@ -108,8 +153,12 @@ const loggedIn = computed(() => isLoggedIn())
const loginUrl = computed(() => getLoginUrl()) const loginUrl = computed(() => getLoginUrl())
const form = reactive({ const form = reactive({
quantity: 1 quantity: 1,
note: '',
contactPhone: '',
contactEmail: ''
}) })
const isManualDelivery = ref(false)
const renderMarkdown = (content) => md.render(content || '') const renderMarkdown = (content) => md.render(content || '')
@@ -145,7 +194,11 @@ const submitOrder = async () => {
try { try {
const payload = { const payload = {
productId: product.value.id, 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 token = isLoggedIn() ? authState.token : null
const response = await createOrder(payload, token) const response = await createOrder(payload, token)
@@ -166,6 +219,7 @@ const doConfirm = async () => {
try { try {
const result = await confirmOrder(orderResult.value.orderId) const result = await confirmOrder(orderResult.value.orderId)
deliveredCodes.value = result.deliveredCodes || [] deliveredCodes.value = result.deliveredCodes || []
isManualDelivery.value = result.isManual || result.deliveryMode === 'manual'
confirmed.value = true confirmed.value = true
} catch (err) { } catch (err) {
confirmError.value = err?.response?.data?.error || '确认失败,请重试' confirmError.value = err?.response?.data?.error || '确认失败,请重试'
@@ -213,7 +267,7 @@ onMounted(async () => {
width: 140px; width: 140px;
height: 140px; height: 140px;
object-fit: cover; object-fit: cover;
border-radius: 12px; border-radius: 8px;
} }
.summary-content { .summary-content {
@@ -248,7 +302,7 @@ onMounted(async () => {
max-width: 320px; max-width: 320px;
margin: 12px auto; margin: 12px auto;
width: 100%; width: 100%;
border-radius: 14px; border-radius: 8px;
border: 1px solid var(--line); border: 1px solid var(--line);
} }
@@ -266,7 +320,7 @@ onMounted(async () => {
border-radius: 999px; border-radius: 999px;
background: linear-gradient(135deg, var(--accent), var(--accent-2)); background: linear-gradient(135deg, var(--accent), var(--accent-2));
color: white; color: white;
font-size: 13px; font-size: 15px;
font-weight: 600; font-weight: 600;
margin-bottom: 12px; margin-bottom: 12px;
} }
@@ -283,18 +337,18 @@ onMounted(async () => {
width: min(520px, 100%); width: min(520px, 100%);
min-height: 120px; min-height: 120px;
padding: 14px 16px; padding: 14px 16px;
border-radius: 14px; border-radius: 8px;
border: 1px solid var(--line); border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
color: var(--text); color: var(--text);
font-size: 14px; font-size: 16px;
line-height: 1.7; line-height: 1.7;
resize: none; resize: none;
} }
.error { .error {
color: #d64848; color: #d64848;
font-size: 13px; font-size: 15px;
} }
.status { .status {
@@ -307,6 +361,87 @@ onMounted(async () => {
font-weight: 900; 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) { @media (max-width: 900px) {
.checkout-grid { .checkout-grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
@@ -321,5 +456,9 @@ onMounted(async () => {
width: 100%; width: 100%;
height: 200px; height: 200px;
} }
.contact-row {
grid-template-columns: 1fr;
}
} }
</style> </style>

View File

@@ -68,6 +68,15 @@
<div class="detail-actions"> <div class="detail-actions">
<button class="buy-button" @click="goCheckout">立即下单</button> <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> <button class="ghost" @click="goBack">返回商店首页</button>
</div> </div>
</div> </div>
@@ -91,6 +100,8 @@ import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it' import MarkdownIt from 'markdown-it'
import { fetchProducts, recordProductView } from '../shared/api' import { fetchProducts, recordProductView } from '../shared/api'
import { isLoggedIn } from '../shared/auth'
import { isInWishlist, toggleWishlist } from '../shared/useWishlist'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
@@ -140,6 +151,12 @@ const galleryImages = computed(() => {
return images 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 = () => { const goBack = () => {
router.push('/') router.push('/')
} }
@@ -215,7 +232,7 @@ onMounted(async () => {
.detail-description { .detail-description {
display: block; display: block;
color: var(--text); color: var(--text);
font-size: 15px; font-size: 17px;
line-height: 1.8; line-height: 1.8;
-webkit-line-clamp: initial; -webkit-line-clamp: initial;
-webkit-box-orient: initial; -webkit-box-orient: initial;
@@ -231,7 +248,7 @@ onMounted(async () => {
.detail-gallery-main { .detail-gallery-main {
position: relative; position: relative;
overflow: hidden; overflow: hidden;
border-radius: 18px; border-radius: 10px;
border: 1px solid var(--line); border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.45); background: rgba(255, 255, 255, 0.45);
} }
@@ -292,11 +309,11 @@ onMounted(async () => {
width: 100%; width: 100%;
height: 76px; height: 76px;
object-fit: cover; object-fit: cover;
border-radius: 10px; border-radius: 6px;
} }
.detail-thumb span { .detail-thumb span {
font-size: 12px; font-size: 14px;
color: var(--muted); color: var(--muted);
} }
@@ -310,6 +327,16 @@ onMounted(async () => {
font-weight: 900; 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) { @media (max-width: 900px) {
.detail-thumb { .detail-thumb {
padding: 6px; padding: 6px;

View File

@@ -1,28 +1,19 @@
<template> <template>
<section class="page-card"> <section class="page-card">
<div class="hero"> <div class="hero">
<div>
<h2>所有商品</h2> <h2>所有商品</h2>
<div class="filter-search-row">
<div class="filters"> <div class="filters">
<button <button
v-for="opt in VIEW_OPTIONS"
:key="opt.value"
class="filter-btn" class="filter-btn"
:class="{ active: filter === 'all' }" :class="{ active: viewMode === opt.value }"
type="button" type="button"
@click="setFilter('all')" @click="setViewMode(opt.value)"
> >
全部 {{ opt.label }}
</button>
<button
class="filter-btn"
:class="{ active: filter === 'free' }"
type="button"
@click="setFilter('free')"
>
免费
</button> </button>
</div> </div>
<div class="search-row">
<input <input
v-model="searchQuery" v-model="searchQuery"
class="search-input" class="search-input"
@@ -30,62 +21,24 @@
placeholder="搜索商品/标签" placeholder="搜索商品/标签"
/> />
</div> </div>
</div>
</div>
</div>
<div v-if="loading" class="status">加载中...</div> <div v-if="loading" class="status">加载中...</div>
<div v-else> <div v-else>
<div class="grid"> <div class="grid">
<div <ProductCard
v-for="item in pagedProducts" v-for="item in pagedProducts"
:key="item.id" :key="item.id"
:class="['product-link', { 'is-disabled': isSoldOut(item) }]" :item="item"
@click="handleCardClick(item)" @click="handleCardClick"
> />
<article class="product-card">
<div class="cover-wrap">
<img :src="item.coverUrl" :alt="item.name" />
<div v-if="isSoldOut(item)" class="soldout-badge">已售空</div>
</div>
<div class="card-top">
<h3 class="card-name">{{ item.name }}</h3>
<div class="card-price">
<span v-if="isFree(item)" class="product-price free-price">免费</span>
<span
v-else-if="item.discountPrice > 0 && item.discountPrice < item.price"
class="product-price"
>
<span class="price-original">¥ {{ item.price.toFixed(2) }}</span>
<span class="price-discount">¥ {{ item.discountPrice.toFixed(2) }}</span>
</span>
<span v-else class="product-price">¥ {{ item.price.toFixed(2) }}</span>
</div>
</div>
<div class="card-mid">
<div class="markdown" v-html="renderMarkdown(item.description)"></div>
</div>
<div class="card-bottom">
<div class="meta-row">
<div class="tag">库存{{ item.quantity }}</div>
<div class="tag">浏览量{{ item.viewCount || 0 }}</div>
</div>
<div v-if="item.tags && item.tags.length" class="tag-row">
<span v-for="tag in item.tags" :key="tag" class="tag-chip">
{{ tag }}
</span>
</div>
</div>
</article>
</div>
</div> </div>
<div class="pagination" v-if="totalPages > 1"> <div class="pagination" v-if="totalPages > 1">
<button class="ghost" :disabled="page === 1" @click="page--">上一</button> <button class="ghost pg-btn" :disabled="page === 1" @click="page = 1"></button>
<span class="tag"> {{ page }} / {{ totalPages }} </span> <button class="ghost pg-btn" :disabled="page === 1" @click="page--">上一</button>
<button class="ghost" :disabled="page === totalPages" @click="page++">下一</button> <span class="pg-info"> {{ page }} / {{ totalPages }} </span>
<button class="ghost pg-btn" :disabled="page === totalPages" @click="page++">下一页</button>
<button class="ghost pg-btn" :disabled="page === totalPages" @click="page = totalPages">末页</button>
</div> </div>
</div> </div>
</section> </section>
@@ -94,38 +47,43 @@
<script setup> <script setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { fetchProducts } from '../shared/api' import { fetchProducts } from '../shared/api'
import ProductCard from './components/ProductCard.vue'
const router = useRouter() const router = useRouter()
const VIEW_OPTIONS = [
{ value: 'all', label: '全部' },
{ value: 'free', label: '免费' },
{ value: 'newest', label: '新上架' },
{ value: 'most-sold', label: '最多购买' },
{ value: 'most-viewed', label: '最多浏览' },
{ value: 'price-high', label: '价格最高' },
{ value: 'price-low', label: '价格最低' }
]
const products = ref([]) const products = ref([])
const loading = ref(true) const loading = ref(true)
const md = new MarkdownIt()
const page = ref(1) const page = ref(1)
const perPage = ref(20) const perPage = ref(20)
const filter = ref('all') const viewMode = ref('all')
const searchQuery = ref('') const searchQuery = ref('')
const renderMarkdown = (content) => md.render(content || '')
const updatePerPage = () => { const updatePerPage = () => {
perPage.value = window.innerWidth <= 900 ? 6 : 20 perPage.value = window.innerWidth <= 900 ? 10 : 20
page.value = 1 page.value = 1
} }
const getPayPrice = (item) => { const getPayPrice = (item) => {
if (!item) return 0 if (!item) return 0
// 折扣规则: // 折扣规则:discountPrice > 0 且小于原价时启用price = 0 时显示"免费"
// - 未填/无效折扣discountPrice <= 0 或 >= price => 不启用折扣
// - 只有当 discountPrice > 0 且小于原价,才用折扣价
// - 只有 price = 0实付价为 0才显示“免费”
if (item.price === 0) return 0 if (item.price === 0) return 0
if (item.discountPrice > 0 && item.discountPrice < item.price) return item.discountPrice if (item.discountPrice > 0 && item.discountPrice < item.price) return item.discountPrice
return item.price return item.price
} }
const isFree = (item) => getPayPrice(item) === 0 const isFree = (item) => getPayPrice(item) === 0
const isSoldOut = (item) => item && item.quantity === 0
const matchesSearch = (item) => { const matchesSearch = (item) => {
const q = (searchQuery.value || '').trim().toLowerCase() const q = (searchQuery.value || '').trim().toLowerCase()
@@ -136,9 +94,32 @@ const matchesSearch = (item) => {
} }
const filteredProducts = computed(() => { const filteredProducts = computed(() => {
let list = products.value let list = [...products.value]
if (filter.value === 'free') list = list.filter((p) => isFree(p))
if (viewMode.value === 'free') list = list.filter((p) => isFree(p))
if ((searchQuery.value || '').trim()) list = list.filter((p) => matchesSearch(p)) if ((searchQuery.value || '').trim()) list = list.filter((p) => matchesSearch(p))
switch (viewMode.value) {
case 'newest':
list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
break
case 'most-sold':
list.sort((a, b) => (b.totalSold || 0) - (a.totalSold || 0))
break
case 'most-viewed':
list.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0))
break
case 'price-high':
list.sort((a, b) => getPayPrice(b) - getPayPrice(a))
break
case 'price-low':
list.sort((a, b) => getPayPrice(a) - getPayPrice(b))
break
default:
break
}
return list return list
}) })
@@ -151,17 +132,13 @@ const pagedProducts = computed(() => {
return filteredProducts.value.slice(start, start + perPage.value) return filteredProducts.value.slice(start, start + perPage.value)
}) })
const isSoldOut = (item) => item && item.quantity === 0
const handleCardClick = (item) => { const handleCardClick = (item) => {
if (!item || isSoldOut(item)) { if (!item || isSoldOut(item)) return
return
}
router.push(`/product/${item.id}`) router.push(`/product/${item.id}`)
} }
const setFilter = (next) => { const setViewMode = (next) => {
filter.value = next viewMode.value = next
page.value = 1 page.value = 1
} }
@@ -175,13 +152,8 @@ onMounted(async () => {
} }
}) })
watch(filter, () => { watch(viewMode, () => { page.value = 1 })
page.value = 1 watch(searchQuery, () => { page.value = 1 })
})
watch(searchQuery, () => {
page.value = 1
})
onUnmounted(() => { onUnmounted(() => {
window.removeEventListener('resize', updatePerPage) window.removeEventListener('resize', updatePerPage)
@@ -192,30 +164,17 @@ onUnmounted(() => {
.hero { .hero {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; gap: 16px;
flex-wrap: wrap;
margin-bottom: 20px; margin-bottom: 20px;
} }
.filters { .filters {
display: flex; display: flex;
gap: 12px; gap: 12px;
margin-top: 0;
flex-wrap: wrap; flex-wrap: wrap;
} }
.filter-search-row {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 16px;
flex-wrap: wrap;
margin-top: 12px;
}
.search-row {
margin-top: 0;
}
.search-input { .search-input {
width: 320px; width: 320px;
max-width: 100%; max-width: 100%;
@@ -223,8 +182,8 @@ onUnmounted(() => {
border: 1px solid var(--line); border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7); background: rgba(255, 255, 255, 0.7);
padding: 10px 14px; padding: 10px 14px;
font-family: 'Source Sans 3', sans-serif; font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 14px; font-size: 16px;
outline: none; outline: none;
} }
@@ -233,30 +192,13 @@ onUnmounted(() => {
box-shadow: 0 0 0 3px rgba(180, 154, 203, 0.18); box-shadow: 0 0 0 3px rgba(180, 154, 203, 0.18);
} }
.tag-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
.tag-chip {
padding: 4px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 700;
color: var(--accent-2);
background: rgba(145, 168, 208, 0.08);
border: 1px solid rgba(145, 168, 208, 0.18);
}
.filter-btn { .filter-btn {
padding: 8px 14px; padding: 8px 14px;
border-radius: 999px; border-radius: 999px;
border: 1px solid var(--line); border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.6); background: rgba(255, 255, 255, 0.6);
color: var(--text); color: var(--text);
font-size: 13px; font-size: 15px;
font-weight: 700; font-weight: 700;
transition: background 0.2s ease, color 0.2s ease, transform 0.15s ease; transition: background 0.2s ease, color 0.2s ease, transform 0.15s ease;
} }
@@ -272,140 +214,79 @@ onUnmounted(() => {
box-shadow: 0 10px 30px rgba(145, 168, 208, 0.35); box-shadow: 0 10px 30px rgba(145, 168, 208, 0.35);
} }
.free-price {
color: #3a9a68;
font-weight: 900;
}
.product-link {
display: block;
text-decoration: none;
color: inherit;
height: 100%;
}
.product-link.is-disabled {
opacity: 0.6;
cursor: not-allowed;
}
.product-card {
display: flex;
flex-direction: column;
flex: 1;
gap: 12px;
height: 100%;
}
.card-top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.card-name {
font-size: 16px;
font-weight: 700;
color: var(--text);
line-height: 1.2;
}
.card-price {
display: flex;
align-items: center;
justify-content: flex-end;
}
.card-mid {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
.card-mid .markdown {
text-align: center;
}
.card-bottom {
display: flex;
flex-direction: column;
gap: 6px;
align-items: flex-start;
}
.meta-row {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.cover-wrap {
position: relative;
border-radius: 12px;
overflow: hidden;
}
.cover-wrap img {
width: 100%;
height: 140px;
object-fit: cover;
display: block;
}
.soldout-badge {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(20, 18, 22, 0.52);
backdrop-filter: blur(3px);
color: #fff;
font-family: 'Playfair Display', serif;
font-size: 22px;
font-weight: 600;
letter-spacing: 4px;
pointer-events: none;
}
.price-original {
text-decoration: line-through;
color: var(--muted);
margin-right: 6px;
font-size: 13px;
}
.price-discount {
color: var(--accent-2);
font-weight: 600;
}
.status { .status {
padding: 24px 0; padding: 24px 0;
color: var(--muted); color: var(--muted);
} }
.tag {
font-size: 14px;
color: var(--muted);
}
.pagination { .pagination {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 12px; gap: 8px;
margin-top: 22px; margin-top: 22px;
flex-wrap: wrap;
}
.pg-btn {
padding: 6px 14px;
font-size: 14px;
border-radius: 999px;
min-width: 60px;
}
.pg-btn:disabled {
opacity: 0.38;
cursor: not-allowed;
}
.pg-info {
font-size: 14px;
color: var(--muted);
padding: 0 6px;
} }
@media (max-width: 900px) { @media (max-width: 900px) {
.filter-search-row { .hero {
flex-direction: column; flex-direction: column;
align-items: stretch; align-items: flex-start;
gap: 10px; gap: 10px;
margin-bottom: 12px;
}
.hero h2 {
font-size: 20px;
}
/* Filter buttons: scrollable horizontal row, no wrap */
.filters {
flex-wrap: nowrap;
overflow-x: auto;
gap: 8px;
width: 100%;
padding-bottom: 4px;
scrollbar-width: none;
}
.filters::-webkit-scrollbar {
display: none;
}
.filter-btn {
flex-shrink: 0;
padding: 6px 10px;
font-size: 13px;
} }
.search-input { .search-input {
width: 100%; width: 100%;
font-size: 14px;
padding: 8px 12px;
} }
} }
</style> </style>

View File

@@ -0,0 +1,342 @@
<template>
<div
:class="['product-link', { 'is-disabled': isSoldOut }]"
@click="$emit('click', item)"
>
<article class="product-card">
<div class="cover-wrap">
<img :src="item.coverUrl" :alt="item.name" />
<div v-if="isSoldOut" class="soldout-badge">已售空</div>
<div v-else-if="item.requireLogin" class="require-login-badge">需登录</div>
<button
v-if="loggedIn"
class="wishlist-btn"
:class="{ 'in-wishlist': inWishlist }"
type="button"
@click="onWishlistClick"
:title="inWishlist ? '取消收藏' : '加入收藏'"
>
{{ inWishlist ? '★' : '☆' }}
</button>
</div>
<div class="card-top">
<h3 class="card-name">{{ item.name }}</h3>
<div class="card-price">
<span v-if="isFree" class="product-price free-price">免费</span>
<span
v-else-if="item.discountPrice > 0 && item.discountPrice < item.price"
class="product-price"
>
<span class="price-original">¥ {{ item.price.toFixed(2) }}</span>
<span class="price-discount">¥ {{ item.discountPrice.toFixed(2) }}</span>
</span>
<span v-else class="product-price">¥ {{ item.price.toFixed(2) }}</span>
</div>
</div>
<div class="card-mid">
<div class="markdown" v-html="renderedDescription"></div>
</div>
<div class="card-bottom">
<div v-if="item.tags && item.tags.length" class="tag-row">
<span v-for="tag in item.tags" :key="tag" class="tag-chip">{{ tag }}</span>
</div>
<div class="meta-row">
<div class="tag">库存{{ item.quantity }}</div>
<div class="tag">浏览量{{ item.viewCount || 0 }}</div>
</div>
</div>
</article>
</div>
</template>
<script setup>
import { computed } from 'vue'
import MarkdownIt from 'markdown-it'
import { isLoggedIn } from '../../shared/auth'
import { isInWishlist, toggleWishlist } from '../../shared/useWishlist'
const md = new MarkdownIt()
const props = defineProps({
item: { type: Object, required: true }
})
const emit = defineEmits(['click'])
const inWishlist = computed(() => isInWishlist(props.item.id))
const loggedIn = computed(() => isLoggedIn())
const onWishlistClick = (e) => {
e.stopPropagation()
toggleWishlist(props.item.id)
}
const payPrice = computed(() => {
if (!props.item) return 0
if (props.item.price === 0) return 0
if (props.item.discountPrice > 0 && props.item.discountPrice < props.item.price) {
return props.item.discountPrice
}
return props.item.price
})
const isFree = computed(() => payPrice.value === 0)
const isSoldOut = computed(() => props.item && props.item.quantity === 0)
const renderedDescription = computed(() => md.render(props.item.description || ''))
</script>
<style scoped>
.product-link {
display: block;
text-decoration: none;
color: inherit;
height: 100%;
}
.product-link.is-disabled {
opacity: 0.6;
cursor: not-allowed;
}
.product-card {
display: flex;
flex-direction: column;
flex: 1;
gap: 12px;
height: 100%;
}
.card-top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.card-name {
font-size: 18px;
font-weight: 700;
color: var(--text);
line-height: 1.2;
}
.card-price {
display: flex;
align-items: center;
justify-content: flex-end;
}
.card-mid {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
.card-mid .markdown {
text-align: center;
font-size: 15px;
color: var(--muted);
line-height: 1.6;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
.card-bottom {
display: flex;
flex-direction: column;
gap: 6px;
align-items: flex-start;
}
.meta-row {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.cover-wrap {
position: relative;
border-radius: 6px;
overflow: hidden;
}
.cover-wrap img {
width: 100%;
height: 140px;
object-fit: cover;
display: block;
}
.soldout-badge {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(20, 18, 22, 0.52);
backdrop-filter: blur(3px);
color: #fff;
font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
font-size: 22px;
font-weight: 600;
letter-spacing: 4px;
pointer-events: none;
}
.require-login-badge {
position: absolute;
top: 8px;
right: 8px;
padding: 3px 10px;
border-radius: 999px;
background: rgba(180, 154, 203, 0.85);
color: #fff;
font-size: 13px;
font-weight: 700;
pointer-events: none;
backdrop-filter: blur(4px);
letter-spacing: 0.5px;
}
.wishlist-btn {
position: absolute;
bottom: 8px;
right: 8px;
width: auto;
height: auto;
border-radius: 0;
border: none;
background: none;
backdrop-filter: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
line-height: 1;
color: rgba(255, 255, 255, 0.9);
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
transition: color 0.2s ease, transform 0.15s ease;
padding: 0;
box-shadow: none;
}
.wishlist-btn:hover {
transform: scale(1.2);
}
.wishlist-btn.in-wishlist {
color: #ffb347;
text-shadow: 0 1px 6px rgba(255, 140, 0, 0.6);
}
.tag-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
.tag-chip {
padding: 4px 10px;
border-radius: 999px;
font-size: 14px;
font-weight: 700;
color: var(--accent-2);
background: rgba(145, 168, 208, 0.08);
border: 1px solid rgba(145, 168, 208, 0.18);
}
.tag {
font-size: 14px;
color: var(--muted);
}
.free-price {
color: #3a9a68;
font-weight: 900;
}
.price-original {
text-decoration: line-through;
color: var(--muted);
margin-right: 6px;
font-size: 15px;
}
.price-discount {
color: var(--accent-2);
font-weight: 600;
}
@media (max-width: 900px) {
.cover-wrap img {
height: 100px;
}
/* Name + price on one line, compressed */
.card-top {
flex-direction: row;
align-items: flex-start;
gap: 4px;
}
.card-name {
font-size: 14px;
line-height: 1.3;
flex: 1;
min-width: 0;
word-break: break-all;
}
.card-price {
flex-shrink: 0;
font-size: 13px;
}
.price-original {
font-size: 11px;
margin-right: 2px;
}
.free-price {
font-size: 13px;
}
.card-mid {
display: flex;
}
.card-mid .markdown {
font-size: 12px;
-webkit-line-clamp: 2;
}
.card-bottom {
gap: 4px;
font-size: 12px;
}
.tag-row {
display: flex;
gap: 4px;
margin-top: 4px;
}
.tag-chip {
font-size: 11px;
padding: 2px 7px;
}
.tag {
font-size: 11px;
}
}
</style>

View File

@@ -9,43 +9,70 @@
<section class="page-card" v-else> <section class="page-card" v-else>
<div class="orders-header"> <div class="orders-header">
<div> <div class="header-info">
<h2>我的订单</h2> <h2>我的订单</h2>
<p class="tag"> <p class="tag">
已登录{{ authState.username || authState.account }} {{ authState.username || authState.account }}
<span v-if="orders.length">· {{ orders.length }} 订单</span> <span v-if="orders.length" class="order-count"> {{ orders.length }} </span>
</p> </p>
</div> </div>
<div class="orders-actions"> <div class="orders-actions">
<button class="ghost" @click="refresh">刷新</button> <button class="ghost small-act" @click="refresh">
<button class="ghost" @click="goHome">返回商店</button> <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
刷新
</button>
<button class="ghost small-act" @click="goHome"> 返回商店</button>
</div> </div>
</div> </div>
<div v-if="loading" class="status">加载中...</div> <div v-if="loading" class="status">加载中</div>
<div v-else-if="orders.length === 0" class="status">暂无订单记录</div> <div v-else-if="orders.length === 0" class="empty-state">
<svg width="44" height="44" 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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
<p>暂无订单记录</p>
</div>
<div v-else class="orders-list"> <div v-else class="orders-list">
<div v-for="order in orders" :key="order.id" class="order-card"> <div v-for="order in orders" :key="order.id" class="order-card">
<div class="order-head"> <!-- Card header -->
<div> <div class="order-card-header">
<h4>{{ order.productName }}</h4> <div class="order-product-name">{{ order.productName }}</div>
<span class="tag">订单号{{ order.id }}</span> <div class="order-status-badge" :class="order.deliveryMode === 'manual' && !order.deliveredCodes?.length ? 'badge-pending' : 'badge-done'">
</div> {{ order.deliveryMode === 'manual' && !order.deliveredCodes?.length ? '等待发货' : '已完成' }}
<div class="order-meta">
<span class="badge">数量 {{ order.quantity }}</span>
<span class="tag">{{ formatTime(order.createdAt) }}</span>
</div> </div>
</div> </div>
<!-- Meta row -->
<div class="order-meta-row">
<span class="meta-item">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
{{ formatTime(order.createdAt) }}
</span>
<span class="meta-item">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12V22H4V12"/><path d="M22 7H2v5h20V7z"/><path d="M12 22V7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>
× {{ order.quantity }}
</span>
<span class="order-id-tag">{{ order.id.slice(0, 8) }}</span>
</div>
<!-- Delivered codes -->
<div class="order-codes" v-if="order.deliveredCodes?.length"> <div class="order-codes" v-if="order.deliveredCodes?.length">
<p class="tag">购买内容</p> <div class="codes-label">
<textarea <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
class="codes-box" 发货内容
readonly </div>
:value="order.deliveredCodes.join('\n')" <div class="codes-list">
:rows="Math.min(order.deliveredCodes.length, 5)" <div v-for="(code, i) in order.deliveredCodes" :key="i" class="code-item">
></textarea> <span class="code-index">{{ i + 1 }}</span>
<span class="code-text">{{ code }}</span>
</div>
</div>
</div>
<!-- Manual delivery pending -->
<div class="pending-notice" v-else-if="order.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> </div>
</div> </div>
</div> </div>
@@ -105,6 +132,7 @@ onMounted(() => {
</script> </script>
<style scoped> <style scoped>
/* ── Auth prompt ── */
.auth-prompt { .auth-prompt {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -114,86 +142,223 @@ onMounted(() => {
text-align: center; text-align: center;
} }
/* ── Header ── */
.orders-header { .orders-header {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 14px;
margin-bottom: 20px; margin-bottom: 22px;
flex-wrap: wrap;
}
.header-info h2 {
margin: 0 0 4px;
font-size: 22px;
}
.order-count {
margin-left: 6px;
font-size: 13px;
color: var(--muted);
background: rgba(180, 154, 203, 0.12);
padding: 2px 8px;
border-radius: 999px;
} }
.orders-actions { .orders-actions {
display: flex; display: flex;
gap: 10px; gap: 8px;
flex-shrink: 0;
} }
.small-act {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 13px;
padding: 6px 12px;
}
/* ── Empty & loading ── */
.status {
padding: 24px 0;
color: var(--muted);
font-size: 14px;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 48px 0;
color: var(--muted);
font-size: 14px;
}
/* ── Order list ── */
.orders-list { .orders-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 14px; gap: 14px;
} }
/* ── Order card ── */
.order-card { .order-card {
padding: 18px; padding: 0;
border-radius: var(--radius); border-radius: 10px;
background: rgba(255, 255, 255, 0.7); background: rgba(255, 255, 255, 0.72);
border: 1px solid var(--line); border: 1px solid var(--line);
display: flex; overflow: hidden;
flex-direction: column; transition: box-shadow 0.2s;
gap: 12px;
} }
.order-head { .order-card:hover {
box-shadow: 0 4px 16px rgba(0,0,0,0.08);
}
.order-card-header {
display: flex; display: flex;
align-items: flex-start; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
padding: 14px 16px 10px;
} }
.order-meta { .order-product-name {
display: flex; font-size: 16px;
flex-direction: column; font-weight: 700;
align-items: flex-end; color: var(--text);
gap: 4px; flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.order-status-badge {
padding: 3px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
flex-shrink: 0; flex-shrink: 0;
} }
.badge-done {
background: rgba(100, 185, 140, 0.15);
color: #3a9a68;
}
.badge-pending {
background: rgba(145, 168, 208, 0.15);
color: #5a7db0;
}
/* Meta row */
.order-meta-row {
display: flex;
align-items: center;
gap: 14px;
padding: 0 16px 12px;
flex-wrap: wrap;
border-bottom: 1px solid var(--line);
}
.meta-item {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 13px;
color: var(--muted);
}
.order-id-tag {
font-size: 11px;
color: var(--muted);
font-family: monospace;
background: rgba(0,0,0,0.04);
padding: 2px 7px;
border-radius: 4px;
}
/* Codes */
.order-codes { .order-codes {
padding: 12px 16px;
}
.codes-label {
display: flex;
align-items: center;
gap: 5px;
font-size: 12px;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 8px;
}
.codes-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
} }
.codes-box { .code-item {
width: 100%; display: flex;
padding: 10px 12px; align-items: baseline;
border-radius: 10px; gap: 10px;
border: 1px solid var(--line); padding: 8px 12px;
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
color: var(--text); border: 1px solid var(--line);
font-size: 13px; border-radius: 6px;
line-height: 1.7;
resize: none;
} }
.status { .code-index {
padding: 24px 0; font-size: 11px;
color: var(--muted); color: var(--muted);
font-weight: 700;
min-width: 16px;
flex-shrink: 0;
}
.code-text {
font-size: 14px;
color: var(--text);
word-break: break-all;
font-family: monospace;
line-height: 1.5;
}
/* Pending notice */
.pending-notice {
display: flex;
align-items: center;
gap: 8px;
margin: 12px 16px;
padding: 10px 14px;
background: rgba(145, 168, 208, 0.1);
border-radius: 6px;
border-left: 3px solid var(--accent-2);
font-size: 13px;
color: #5a7db0;
} }
@media (max-width: 900px) { @media (max-width: 900px) {
.orders-header { .orders-header {
flex-direction: column; gap: 10px;
align-items: stretch;
} }
.order-head { .header-info h2 {
flex-direction: column; font-size: 18px;
} }
.order-meta { .order-product-name {
align-items: flex-start; font-size: 15px;
flex-direction: row; }
.order-meta-row {
gap: 10px; gap: 10px;
} }
} }

View File

@@ -0,0 +1,108 @@
<template>
<section class="page-card">
<div class="hero">
<h2>我的收藏夹</h2>
<p class="tag"> {{ wishlistItems.length }} 件商品</p>
</div>
<div v-if="loading" class="status">加载中...</div>
<div v-else-if="wishlistItems.length === 0" class="empty">
<div class="empty-icon"></div>
<p class="empty-title">收藏夹是空的</p>
<p class="tag">在商品卡片上点击 即可加入收藏</p>
<button class="ghost" @click="$router.push('/')">去逛逛</button>
</div>
<div v-else class="grid">
<ProductCard
v-for="item in wishlistItems"
:key="item.id"
:item="item"
:class="{ 'card-dimmed': !item.active || item.quantity === 0 }"
@click="handleClick"
/>
</div>
</section>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { fetchProducts } from '../shared/api'
import { getWishlistProducts, loadWishlist } from '../shared/useWishlist'
import ProductCard from '../store/components/ProductCard.vue'
const router = useRouter()
const allProducts = ref([])
const loading = ref(true)
const wishlistItems = computed(() => {
const items = getWishlistProducts(allProducts.value)
return items.sort((a, b) => {
const aOk = a.active && a.quantity > 0 ? 0 : 1
const bOk = b.active && b.quantity > 0 ? 0 : 1
return aOk - bOk
})
})
const handleClick = (item) => {
if (!item) return
if (!item.active || item.quantity === 0) return
router.push(`/product/${item.id}`)
}
onMounted(async () => {
try {
const [prods] = await Promise.all([fetchProducts(), loadWishlist()])
allProducts.value = prods
} finally {
loading.value = false
}
})
</script>
<style scoped>
.hero {
display: flex;
align-items: baseline;
gap: 12px;
margin-bottom: 20px;
}
.status {
padding: 24px 0;
color: var(--muted);
}
.tag {
font-size: 14px;
color: var(--muted);
}
.empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 60px 0;
text-align: center;
}
.empty-icon {
font-size: 52px;
color: var(--muted);
opacity: 0.4;
line-height: 1;
}
.empty-title {
font-size: 20px;
font-weight: 600;
color: var(--text);
}
.card-dimmed {
opacity: 0.5;
}
</style>

View File

@@ -5,6 +5,11 @@ import ProductDetail from '../modules/store/ProductDetail.vue'
import CheckoutPage from '../modules/store/CheckoutPage.vue' import CheckoutPage from '../modules/store/CheckoutPage.vue'
import AuthCallback from '../modules/auth/AuthCallback.vue' import AuthCallback from '../modules/auth/AuthCallback.vue'
import MyOrdersPage from '../modules/user/MyOrdersPage.vue' import MyOrdersPage from '../modules/user/MyOrdersPage.vue'
import MaintenancePage from '../modules/maintenance/MaintenancePage.vue'
import WishlistPage from '../modules/wishlist/WishlistPage.vue'
import { fetchSiteMaintenance } from '../modules/shared/api'
const BYPASS_ROUTES = ['/admin', '/auth/callback', '/maintenance', '/wishlist']
const router = createRouter({ const router = createRouter({
history: createWebHistory(), history: createWebHistory(),
@@ -14,8 +19,30 @@ const router = createRouter({
{ path: '/checkout/:id', name: 'checkout', component: CheckoutPage }, { path: '/checkout/:id', name: 'checkout', component: CheckoutPage },
{ path: '/admin', name: 'admin', component: AdminPage }, { path: '/admin', name: 'admin', component: AdminPage },
{ path: '/auth/callback', name: 'auth-callback', component: AuthCallback }, { path: '/auth/callback', name: 'auth-callback', component: AuthCallback },
{ path: '/my/orders', name: 'my-orders', component: MyOrdersPage } { path: '/my/orders', name: 'my-orders', component: MyOrdersPage },
{
path: '/maintenance',
name: 'maintenance',
component: MaintenancePage,
props: (route) => ({ reason: route.query.reason || '' })
},
{ path: '/wishlist', name: 'wishlist', component: WishlistPage }
] ]
}) })
router.beforeEach(async (to) => {
if (BYPASS_ROUTES.some((p) => to.path.startsWith(p))) {
return true
}
try {
const { maintenance, reason } = await fetchSiteMaintenance()
if (maintenance) {
return { name: 'maintenance', query: { reason } }
}
} catch {
// 接口异常时放行,不阻断用户
}
return true
})
export default router export default router

View File

@@ -1,8 +1,57 @@
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue' import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [
vue(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.ico', 'logo.png', 'apple-touch-icon-180x180.png'],
manifest: {
name: '萌芽小店',
short_name: '萌芽小店',
description: '萌芽小店 — 精选商品,一键购买',
theme_color: '#1a1a1a',
background_color: '#ffffff',
display: 'standalone',
orientation: 'portrait',
scope: '/',
start_url: '/',
lang: 'zh-CN',
icons: [
{ src: 'pwa-64x64.png', sizes: '64x64', type: 'image/png' },
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
{ src: 'maskable-icon-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }
]
},
workbox: {
maximumFileSizeToCacheInBytes: 8 * 1024 * 1024,
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
runtimeCaching: [
{
urlPattern: /^https:\/\/fonts\.(googleapis|gstatic)\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-cache',
expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 },
cacheableResponse: { statuses: [0, 200] }
}
},
{
urlPattern: /^\/api\//,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: { maxEntries: 50, maxAgeSeconds: 60 * 5 },
cacheableResponse: { statuses: [0, 200] }
}
}
]
}
})
],
server: { server: {
port: 5173 port: 5173
} }