79 Commits

Author SHA1 Message Date
richarjiang
d91282ecbd fix: 修复身体画像约课阻断、页面响应式丢失及多项边界问题
- fix(booking): 修复未认领画像阻断约课问题,支持约课事务内自动认领绑定
- fix(app): 修复 Pinia 状态解构导致响应式失效,补齐 PortraitRadar 组件实例传参
- fix(admin): 修复经营助手复测待办点击 404,优化体验课后线索回访文案
- fix(server): 线下评估日期间隔按中国时区校验,复测按期次单项核销,优化单次评估分享卡与限流清理
- test: 补齐 body-portrait-offline 与 booking 来源画像单元测试

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:45:44 +08:00
richarjiang
ab6602e41d feat: 新增个人身体画像评估与馆主经营助手
把 3 分钟身体状态评估做成独立获客链路,匿名测评后登录认领完整报告,并接入体验预约与今日待办。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:09:19 +08:00
richarjiang
b8c0dd6781 fix(server): hide CLOSED rows from preview for legacy mini-program compatibility
The previous fix made publishDaySlots CLOSE rows instead of DELETE them.
That works correctly on the server, but the live mini-program still ships
the old schedule.vue which only knows about isPublished (no status
field). It would re-render the CLOSED rows with the '已发布' badge,
making it look like 'clear day' did nothing.

Hide CLOSED rows from getSchedulePreview so the legacy client shows
'当日暂无排课' for rest days — the same UX it had before this fix
shipped. All-CLOSED days return []; days with a mix return only the
non-CLOSED rows; days the cron hasn't touched still return the ghost
template.

The republished mini-program (with status-aware rendering) will see the
same [] for rest days, which is consistent. Tests: 4 new specs covering
all-OPEN / all-CLOSED / mixed / empty-day cases.
2026-09-10 22:36:41 +08:00
richarjiang
806f3ee770 fix(server): preserve admin 'rest day' intent across cron runs
publishDaySlots used to DELETE the TimeSlot rows of a day that an admin
just 'cleared', which made the nightly slot-generation cron resurrect
the default schedule the next morning — a real production bug where
classes would reappear on a teacher's rest day.

Changes:
- publishDaySlots now CLOSEs (never DELETEs) orphaned rows, and materializes
  the default template for days with no rows so an empty publish still
  records intent. update on existing rows preserves their current status,
  so re-publishing the page cannot silently reopen a CLOSED rest day.
- SlotGeneratorService.generateSlots pre-fetches dates that already have any
  TimeSlot row and skips them, so the cron no longer overwrites admin-touched
  days even when admin only set status without changing times.
- SlotGeneratorService.prunePastClosedSlots (new) deletes past CLOSED slots
  with no bookings, scheduled nightly at 02:35, so the 'no DELETE' rule
  above does not leak rows forever.
- schedule.vue surfaces the CLOSED state with a grey '已关闭' badge and
  card style.

Tests: 12 new specs across time-slot.service.spec.ts (publishDaySlots
behaviour) and slot-generator.service.spec.ts (skip touched dates +
prune conditions). Full suite: 315 / 315 passing.
2026-09-10 22:32:32 +08:00
richarjiang
9af558286b chore: 清理管理中心 fetchDashboardStats 与 GET /admin/stats 已无用的接口 2026-09-10 19:23:08 +08:00
richarjiang
99814f3720 refactor(app): 移除管理中心顶部统计卡,数据已在统计分析页提供 2026-09-10 19:22:44 +08:00
richarjiang
014685ed04 refactor(app): 管理中心列表改为纯文字入口并按业务重组分组 2026-09-10 19:22:18 +08:00
richarjiang
9f5608f13c fix(app): 教学报告两张卡片合并为同一列表组,去掉四周圆角 2026-09-10 19:21:18 +08:00
richarjiang
3e049d2c1d feat: 优化微信订阅消息体系并新增约课取消通知与开课前1小时提醒
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 16:20:13 +08:00
richarjiang
d32f592e54 fix(app): 修复预约页首次进入定位当前时段不生效
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 15:33:37 +08:00
richarjiang
d793749134 fix(app): 在确认手势内同步调起订阅,预约页首次进入定位到当前时段
微信要求授权框落在 tap 同步栈,先 await 会丢失弹层;订阅失败不再打断预约或支付。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 14:53:14 +08:00
richarjiang
57edd8dcc0 perf: 移除秒杀相关功能 2026-09-10 11:33:19 +08:00
richarjiang
51dea488f6 feat: 优化预定页面UI和交互 2026-09-10 11:00:13 +08:00
richarjiang
22407a7ff9 fix(booking): 允许管理员/老师通过同一接口取消任意预约
将 cancelBooking 改为接收 actor({ id, isAdmin }),服务端按 JWT role
分流:普通成员仅能取消自己的预约,管理员跳过 owner check。
history 备注自动按 actor 选择「学员/管理员」前缀,审计可追溯。

客户端无感,仍调 PUT /booking/:id/cancel,前端零改动。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-09 19:50:41 +08:00
richarjiang
d941f1b6a9 perf: 优化进度条 2026-09-09 19:19:18 +08:00
richarjiang
6fab1155c7 fix: 防止成长档案编辑弹窗被误关
微信端点击输入会冒泡到遮罩,且 onShow 刷新会清空编辑态,导致体测、笔记和照片无法填写。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 16:02:24 +08:00
richarjiang
139882d7a1 feat: 支持课后评价与成长档案
完成后即可评价并订阅提醒,馆主可记录体测、笔记与成长照片,首页展示匿名星级均分。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 15:55:48 +08:00
richarjiang
c3e46f7ffa fix(teaching-schedule): 当日课表展示所有状态,并支持点入课程详情
- 后端 getTeachingScheduleByDate 在查询当天时不再以 PENDING/CONFIRMED 过滤 timeSlot
  也不限制 include.bookings 的状态,但仍保留 EXISTS 守卫过滤空 slot
- 其他日期维持原「只看待上课」语义
- 抽出私有 formatLocalDate 工具方法,消除服务端 YYYY-MM-DD 构造的 3 处重复
- 前端 teaching-schedule 的 session 卡片可点击跳到 /pages/booking/detail?slotId=
- 补全 student__status--completed / --cancelled 样式
2026-09-09 14:51:06 +08:00
richarjiang
75ef5e94a6 refactor: 调整 admin 目录结构并精简个人中心快捷区
- 将 admin 相关的 store/utils 移入对应子目录(pages/admin/stores、pages/admin/utils)
- 更新 manifest.json、pages.json 路由与配置
- 个人中心 ProfileMenu 移除顶部「我的会员卡 / 我的预约」快捷卡片,与 UserCard 会员卡入口合并
- 「我的预约」下移至菜单列表,紧邻「个人信息」
- 清理 profile/index.vue 中不再使用的 bookingStore / 计算属性 / 透传
2026-09-09 14:36:34 +08:00
richarjiang
57107c02dc perf: 优化个人中心会员卡进度展示 2026-09-09 11:27:03 +08:00
richarjiang
726c65f0f0 perf: 会员卡页面支持分享 2026-09-09 10:28:11 +08:00
richarjiang
6e8fc45138 fix: 修复默认启动入口 2026-09-09 10:26:16 +08:00
richarjiang
fcd9531b3c 0.0.2 2026-09-09 10:11:07 +08:00
richarjiang
f4cee127ce feat: 优化个人中心邀请卡片 2026-09-09 10:10:52 +08:00
richarjiang
99c5c211ad feat: 支持上课统计功能;优化会员管理默认筛选状态 2026-09-09 10:04:29 +08:00
richarjiang
30ebc1c344 feat: 支持邀请好友功能 2026-09-08 22:31:39 +08:00
richarjiang
5a4d2c7a1b perf: 优化 预约详情 UI 2026-09-08 17:47:38 +08:00
richarjiang
b7e339e40c 0.0.1 2026-09-08 17:31:39 +08:00
richarjiang
8e2db3a74a perf: 优化我的课程 UI 2026-09-08 17:31:26 +08:00
richarjiang
f54a12efbd perf: 优化预订页面 UI 2026-09-08 16:35:18 +08:00
richarjiang
b937895bc9 perf: 优化会员卡购买页面 2026-09-08 15:52:34 +08:00
richarjiang
b4b3caac70 perf: 支持课程补录 2026-09-08 15:08:29 +08:00
richarjiang
d1f193e13e feat: 优化首页、个人中心页面 UI 2026-09-08 14:20:43 +08:00
richarjiang
301f9ae385 feat: 优化页面 UI 以及支持个人中心 练习足迹 2026-09-08 11:26:46 +08:00
richarjiang
87d946adb5 fix: 修复月卡无法编辑次数的问题 2026-09-07 18:10:39 +08:00
richarjiang
86ad9ee64f fix: 老师代约只允许已发布课表,去掉临时加开时段
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 17:21:19 +08:00
richarjiang
f5c7b7eaac perf: 优化订阅刷新逻辑 2026-09-07 16:17:57 +08:00
richarjiang
88cd8419c8 feat: 支持同卡种续卡叠加并修复过期登录态
支付成功后将次数或有效期叠加到已有会员卡,首页与详情页引导续卡;接口 401 时同步清掉本地登录态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:04:11 +08:00
richarjiang
801e2f47da feat: 补充月卡退卡按次卡单价结算说明
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 20:23:51 +08:00
richarjiang
15d96c722b feat: 调整默认排课节奏并限制时间选择
第一节 08:00-09:00,之后从 09:30 起每小时一节至 21:30;排课时间仅可选整点或半点。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 20:12:52 +08:00
richarjiang
14d7c03b05 perf: 更新微信开发者工具调用 skill 2026-04-19 22:45:43 +08:00
richarjiang
bd3d519b4f feat(app): 新增个人中心课表视图 2026-04-19 22:23:23 +08:00
richarjiang
9575210b06 feat: 支持分享邀请好友功能 2026-04-19 14:12:25 +08:00
richarjiang
b02f38dcc7 feat(card): add cover image support for card types 2026-04-15 23:50:12 +08:00
richarjiang
4dacd908a6 feat: 优化排课管理 2026-04-15 23:25:09 +08:00
richarjiang
6ab16f508a feat: 支持画廊图片更新 2026-04-15 13:58:51 +08:00
richarjiang
7ce7cef77c feat: UI 页面优化 2026-04-14 10:07:31 +08:00
richarjiang
52cc3a2985 fix(app): 修复分享页返回首页 2026-04-13 19:23:16 +08:00
richarjiang
497837c1d8 feat(app): refine teacher profile page content 2026-04-13 19:19:33 +08:00
richarjiang
d45a5b2c14 fix(server): support rebooking cancelled slots 2026-04-13 17:50:14 +08:00
richarjiang
f78cdcc9d1 feat: 添加教练详情页面及相关数据模型 2026-04-13 17:08:17 +08:00
richarjiang
1f45c3dc3f perf: 个人中心支持展示约课数量 2026-04-12 22:27:36 +08:00
richarjiang
6cee28bf66 feat: 支持管理员消息推送 2026-04-12 22:18:34 +08:00
richarjiang
c60821c5ff perf: 支持约课以及消息推送能力 2026-04-12 21:44:44 +08:00
richarjiang
9639f44698 fix: 修复订单管理功能 2026-04-12 18:16:18 +08:00
richarjiang
0810f71250 fix: 修复订单列表不能查看的问题 2026-04-10 23:07:56 +08:00
richarjiang
54e30da003 fix(app): 优化首页会员卡闪烁和即将上课卡片交互
- CardShop: 采用 stale-while-revalidate 模式,仅首次加载显示骨架屏,
  切换 tab 回来时保留旧数据静默刷新,消除列表闪烁
- UpcomingBooking: 补充 PENDING_CONFIRMATION 状态的中文映射和样式
- UpcomingBooking: 卡片点击跳转到预约详情页
2026-04-10 11:29:09 +08:00
richarjiang
57e3227af0 fix(app): 移除已废弃的 uni.getUserProfile 调用修复首次登录失败
uni.getUserProfile 在微信基础库 2.27.1+ 已被移除,调用时抛出 TypeError
导致整个登录流程中断。新用户昵称由后端默认生成,用户可在资料页修改。

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 09:04:16 +08:00
richarjiang
54104c16d2 perf: 支持教师、场馆介绍 2026-04-09 14:29:13 +08:00
richarjiang
a40b4e47e5 perf: 优化 UI 2026-04-09 11:31:12 +08:00
richarjiang
74551085e3 feat: 支持秒杀活动 2026-04-09 10:24:44 +08:00
richarjiang
23bdd05811 feat: 支持会员卡设置 2026-04-07 16:47:56 +08:00
richarjiang
91abedcb86 fix(app): prevent modal disappearing when switching to edit tab
Root cause: there was a stale loading overlay outside the tab content
(added by a previous subagent) that rendered when editLoading was true,
covering the entire modal body. Also loadDetailMembership incorrectly
managed editLoading causing state inconsistencies.

Fix:
- Remove the orphaned loading overlay outside tab content blocks
- loadDetailMembership no longer touches editLoading (switchTab owns it)
- switchTab uses Promise.all for parallel loading with formReady guard
- openDetail resets editLoading/formReady to clean state

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 10:22:02 +08:00
richarjiang
0a20aef678 fix(app): ensure edit form initializes after async data loads
- switchTab('edit') now awaits fetchCardTypes and loadDetailMembership
  before calling initEditForm, fixing blank form fields for new cards

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 10:13:20 +08:00
richarjiang
e6056bcab1 fix(server): add definite assignment assertions to UpdateUserMembershipDto
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:53:14 +08:00
richarjiang
f14da2c538 feat(app): add membership edit modal with tab UI
- Replace detail-only modal with tab-based (detail/edit) modal
- Detail tab shows membership card info, stats, and action buttons
- Edit tab provides form to modify card type, remaining times, start/expire dates
- Add loadDetailMembership, switchTab, initEditForm, onSaveMembership, onClearMembership functions
- Add computed isTimeBasedCard for edit form conditional rendering
- Append new styles for modal-header, tab-bar, membership-card, edit-form, etc.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:51:10 +08:00
richarjiang
b281990808 feat(app): add membership management actions to admin store
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:44:41 +08:00
richarjiang
cea78aa8d0 feat(server): add admin membership management endpoints
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:43:45 +08:00
richarjiang
0776bd8630 feat(server): add membership CRUD methods to UserService
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:42:42 +08:00
richarjiang
867461f892 feat(server): add UpdateUserMembershipDto for admin member card management
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:41:16 +08:00
richarjiang
13b75c3bed docs: 补充会员卡编辑功能实现计划
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:39:43 +08:00
richarjiang
f7f18f5178 docs: 添加会员卡编辑功能设计文档
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 09:35:28 +08:00
richarjiang
0ca93ec97e feat: 支持会员管理筛选 2026-04-07 09:22:58 +08:00
richarjiang
58c7588a96 chore: 添加 CLAUDE.md 和 .env 配置文件
- 添加项目文档 CLAUDE.md,包含常用命令和架构说明
- 添加 packages/server/.env 环境变量配置文件

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 21:46:15 +08:00
richarjiang
f94b48203f feat: 新的预约列表样式 2026-04-06 21:22:18 +08:00
richarjiang
168968f073 feat: 将课程预约卡片改造为电影票风格设计
### 改动内容

#### 1. SlotCard 组件完全重新设计
- **新增票据风格装饰**:左右两侧添加圆角凹陷(打孔效果)
- **三栏布局**:
  - 左:时间(开始时间大号、分割线、结束时间小号)
  - 中:课程名称、时长、剩余名额 + 虚线分割符
  - 右:操作按钮或状态徽章
- **日期展示**:卡片上方显示完整日期 (YYYY-MM-DD)
- **状态指示器**:
  - 绿色:有空位
  - 橙色:接近满额(80% 以上)
  - 红色:已满
  - 灰色:已关闭/已过期
- **响应式样式**:根据预约、满额、已过期等状态自动调整背景颜色和透明度

#### 2. 预约页面 (booking/index.vue) 样式调整
- 移除卡片列表的间距(`gap: 20rpx` → `padding: 24rpx 0 0`)
- 更新日期摘要的内边距(`0 8rpx 4rpx` → `0 24rpx 16rpx`)
- 调整加载骨架屏的尺寸和间距
- 优化预加载动画匹配新卡片设计

### 设计特点
 票据风格的视觉设计
🎯 改进的信息层级和易读性
🎨 精细的状态指示和颜色编码
📱 保持响应式和易用性

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:12:53 +08:00
richarjiang
ba4e4bb301 perf: 优化首页效果 2026-04-06 16:50:28 +08:00
richarjiang
f8268cb6f6 perf: 完善新用户引导 2026-04-06 15:50:22 +08:00
richarjiang
66d47ec162 perf: 优化 UI 2026-04-06 11:15:10 +08:00
243 changed files with 27621 additions and 13803 deletions

View File

@@ -0,0 +1,252 @@
---
name: wechat-devtools-http-preview
description: '通过微信开发者工具 HTTP V2 接口完成小程序登录检查、自动预览、上传体验版等操作。适用于用户提到微信开发者工具 HTTP、自动预览、体验版上传、命令行发布体验版、流水线触发开发者工具发布时。'
license: MIT
allowed-tools: Bash
---
# 微信开发者工具 HTTP V2 体验版发布
## 适用场景
当用户出现以下意图时使用本 skill
- 希望通过命令行或脚本调用微信开发者工具。
- 希望上传小程序体验版。
- 希望生成或刷新预览二维码。
- 希望把开发者工具 HTTP 能力接入本地自动化流程。
- 提到 `HTTP V2``/v2/upload``/v2/preview``/v2/autopreview``微信开发者工具端口` 等关键词。
## 核心结论
微信开发者工具在启动后会自动开启本地 HTTP 服务。对于“通过命令行发布体验版”这个目标,最直接的路径是:
1. 确认开发者工具已启动并拿到本地端口。
2. 确认工具已登录。
3. 如有需要先执行 `/v2/open` 打开项目。
4. 如项目依赖 npm必要时先执行 `/v2/buildnpm`
5. 调用 `/v2/upload` 上传体验版代码。
6. 如需同时给测试同学扫码,调用 `/v2/preview``/v2/autopreview`
文档同时明确说明:如果场景是完全不依赖开发者工具的 CI/CD官方更推荐 `miniprogram-ci`。因此本 skill 的定位是“基于本机已安装且已运行的微信开发者工具做自动化”,不是替代纯 CI 方案。
## 文档沉淀
根据微信开发者工具 HTTP 文档,需要记住这些约束:
- 接口路径统一使用 `/v2` 前缀。
- HTTP 服务会在开发者工具启动后自动开启。
- 端口号记录在用户目录下的 `.ide` 文件。
- `project` 参数一般都要求传项目绝对路径,且必须 URL encode。
- 项目目录必须存在合法的 `project.config.json`,并至少包含 `appid``projectname`
- `upload` 用于上传代码,也就是生成体验版。
- `preview` 返回预览二维码。
- `autopreview` 会自动刷新并预览项目,适合频繁本地联调。
- `islogin` 可用于判断当前开发者工具是否已登录。
- `login` 可输出二维码,支持 `image``base64``terminal` 三种格式。
- `info-output` 可把预览或上传附加信息输出到 JSON 文件,适合自动化流程记录产物。
## 端口定位
开发者工具端口号文件:
- macOS: `~/Library/Application Support/微信开发者工具/<MD5>/Default/.ide`
- Windows: `~/AppData/Local/微信开发者工具/User Data/<MD5>/Default/.ide`
文档给出的 MD5 规则:`MD5(${installPath}${nwVersion})`
已知默认值:
- macOS: `installPath = /Applications/wechatwebdevtools.app/Contents/MacOS`
- macOS: `nwVersion = ''`
- Windows: `installPath = 微信开发者工具.exe 所在目录`
- Windows: `nwVersion = installPath/version` 文件中 `latestNw` 的值
## 标准工作流
### 1. 检查工具是否启动
先读取 `.ide` 文件中的端口号;如果没有端口文件,说明工具大概率未启动,先提示用户启动微信开发者工具。
### 2. 检查是否已登录
调用:
```bash
curl "http://127.0.0.1:${PORT}/v2/islogin"
```
如果未登录,调用 `/v2/login`,按需要输出二维码:
```bash
curl "http://127.0.0.1:${PORT}/v2/login?qr-format=terminal"
curl "http://127.0.0.1:${PORT}/v2/login?qr-format=base64&qr-output=%2Ftmp%2Fwechat-login.txt"
curl "http://127.0.0.1:${PORT}/v2/login?result-output=%2Ftmp%2Fwechat-login-result.json"
```
### 3. 打开或刷新项目
```bash
curl "http://127.0.0.1:${PORT}/v2/open?project=${ENCODED_PROJECT}"
```
当用户只要求上传或预览时,这一步不是必选,但执行后通常更稳定。
### 4. 构建 npm
当项目启用了小程序 npm 并且近期依赖有变更时执行:
```bash
curl "http://127.0.0.1:${PORT}/v2/buildnpm?project=${ENCODED_PROJECT}&compile-type=miniprogram"
```
### 5. 上传体验版
体验版发布的核心接口就是:
```bash
curl "http://127.0.0.1:${PORT}/v2/upload?project=${ENCODED_PROJECT}&version=${VERSION}&desc=${DESC}"
```
推荐同时加 `info-output`
```bash
curl "http://127.0.0.1:${PORT}/v2/upload?project=${ENCODED_PROJECT}&version=${VERSION}&desc=${DESC}&info-output=${ENCODED_INFO_OUTPUT}"
```
参数要求:
- `project`:必填,项目绝对路径。
- `version`:必填,版本号。
- `desc`:可选,版本备注。
- `info-output`:可选,输出上传附加信息 JSON。
### 6. 生成预览二维码
如果用户还需要扫码体验,可继续调用:
```bash
curl "http://127.0.0.1:${PORT}/v2/preview?project=${ENCODED_PROJECT}&qr-format=terminal"
curl "http://127.0.0.1:${PORT}/v2/preview?project=${ENCODED_PROJECT}&qr-format=base64&qr-output=${ENCODED_QR_PATH}"
curl "http://127.0.0.1:${PORT}/v2/autopreview?project=${ENCODED_PROJECT}&info-output=${ENCODED_INFO_OUTPUT}"
```
区别:
- `/v2/preview`:单次预览,拿二维码最直接。
- `/v2/autopreview`:更适合联调时自动刷新预览。
## 推荐命令模板
### macOS 读取端口
如果已知是默认安装路径,可用下面的方式快速算出 `.ide` 路径:
```bash
MD5=$(printf '/Applications/wechatwebdevtools.app/Contents/MacOS' | md5)
PORT_FILE="$HOME/Library/Application Support/微信开发者工具/${MD5}/Default/.ide"
PORT=$(cat "$PORT_FILE")
```
### URL encode 项目路径
```bash
PROJECT="/absolute/path/to/miniprogram"
ENCODED_PROJECT=$(python3 - <<'PY'
import os, urllib.parse
print(urllib.parse.quote(os.environ['PROJECT'], safe=''))
PY
)
```
### 上传体验版完整示例
```bash
PROJECT="/absolute/path/to/miniprogram"
VERSION="1.2.3"
DESC="体验版发布:修复预约课表"
INFO_OUTPUT="/tmp/wechat-upload-info.json"
ENCODED_PROJECT=$(python3 - <<'PY'
import os, urllib.parse
print(urllib.parse.quote(os.environ['PROJECT'], safe=''))
PY
)
ENCODED_DESC=$(python3 - <<'PY'
import os, urllib.parse
print(urllib.parse.quote(os.environ['DESC'], safe=''))
PY
)
ENCODED_INFO_OUTPUT=$(python3 - <<'PY'
import os, urllib.parse
print(urllib.parse.quote(os.environ['INFO_OUTPUT'], safe=''))
PY
)
curl "http://127.0.0.1:${PORT}/v2/upload?project=${ENCODED_PROJECT}&version=${VERSION}&desc=${ENCODED_DESC}&info-output=${ENCODED_INFO_OUTPUT}"
```
## 执行规则
当你代表用户执行这个流程时,按下面顺序做:
1. 先确认当前系统是否安装并启动了微信开发者工具。
2. 优先读取 `.ide` 端口文件,而不是盲猜端口。
3. 上传前先验证 `project.config.json` 是否存在且含 `appid``projectname`
4. 涉及路径、备注、输出文件参数时,一律 URL encode。
5. 如果 `islogin` 未登录,先引导用户扫码登录,不要直接继续上传。
6. 如果用户目标是“发布体验版”,优先使用 `/v2/upload`;不要误用 `/preview` 代替。
7. 如果用户目标是“出二维码给别人扫”,优先使用 `/v2/preview`
8. 如果用户目标是“边改边自动刷新”,优先使用 `/v2/autopreview`
## 故障排查
### 端口文件不存在
说明通常是开发者工具没启动,或者安装路径/MD5 推导错了。
排查顺序:
1. 让用户先手动打开微信开发者工具。
2. 检查是否使用了正确安装路径。
3. 重新计算 MD5。
### 调用 HTTP 接口失败
优先检查:
1. 是否能访问 `http://127.0.0.1:${PORT}/v2/islogin`
2. `PORT` 是否来自正确的 `.ide` 文件。
3. 开发者工具版本是否支持 `HTTP V2`
### 上传失败
优先检查:
1. `project` 是否为绝对路径。
2. 是否已 URL encode。
3. `project.config.json` 是否存在。
4. `project.config.json` 里是否包含 `appid``projectname`
5. 是否已登录工具。
6. npm 依赖是否需要先执行 `/v2/buildnpm`
## 输出要求
当用户让你“帮我发布体验版”时,最终回复必须明确交代:
- 是否成功调用了 `/v2/upload`
- 使用的版本号与备注
- 是否生成了 `info-output` 文件
- 如果还做了预览,二维码输出到哪里或以什么格式返回
如果没有成功执行,必须明确停在哪一步,不要模糊地说“可能发布了”。
## 引用来源
本 skill 基于微信开放文档:
- 页面:微信开发者工具 HTTP V2
- 关键接口:`/v2/login``/v2/islogin``/v2/open``/v2/buildnpm``/v2/upload``/v2/preview``/v2/autopreview`

15
.deploy-tmp/check-fk.js Normal file
View File

@@ -0,0 +1,15 @@
// One-off diagnostic — list FK constraints on orders.flash_sale_id
// Run from packages/server so .env is loaded.
const { PrismaClient } = require('@prisma/client')
const p = new PrismaClient()
;(async () => {
const rows = await p.$queryRawUnsafe(`
SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME IN ('orders', 'flash_sales', 'flash_sale_orders')
ORDER BY TABLE_NAME, ORDINAL_POSITION
`)
console.log('FK rows:', JSON.stringify(rows, null, 2))
await p.$disconnect()
})().catch((e) => { console.error(e); process.exit(1) })

View File

@@ -0,0 +1,33 @@
// Mark the failed drop_flash_sale migration as rolled_back so deploy can retry.
const { PrismaClient } = require('@prisma/client')
const p = new PrismaClient()
const dump = (x) => JSON.stringify(x, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2)
;(async () => {
const before = await p.$queryRawUnsafe(
`SELECT migration_name, finished_at, rolled_back_at, applied_steps_count
FROM _prisma_migrations
WHERE migration_name = ?`,
'20260910030338_drop_flash_sale'
)
console.log('before:', dump(before))
const result = await p.$executeRawUnsafe(
`UPDATE _prisma_migrations
SET rolled_back_at = NOW()
WHERE migration_name = ?
AND finished_at IS NULL
AND rolled_back_at IS NULL`,
'20260910030338_drop_flash_sale'
)
console.log('rows updated:', result)
const after = await p.$queryRawUnsafe(
`SELECT migration_name, finished_at, rolled_back_at, applied_steps_count
FROM _prisma_migrations
WHERE migration_name = ?`,
'20260910030338_drop_flash_sale'
)
console.log('after:', dump(after))
await p.$disconnect()
})().catch((e) => { console.error(e); process.exit(1) })

View File

@@ -0,0 +1,27 @@
// Verify migration result on production
const { PrismaClient } = require('@prisma/client')
const p = new PrismaClient()
;(async () => {
const tables = await p.$queryRawUnsafe(`
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME LIKE '%flash%'
`)
const ordersCol = await p.$queryRawUnsafe(`
SELECT COLUMN_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'orders'
AND COLUMN_NAME = 'flash_sale_id'
`)
const mig = await p.$queryRawUnsafe(`
SELECT migration_name, finished_at, rolled_back_at
FROM _prisma_migrations
WHERE migration_name = '20260910030338_drop_flash_sale'
`)
console.log('flash tables:', tables)
console.log('orders.flash_sale_id col:', ordersCol)
console.log('migration row:', mig)
await p.$disconnect()
})().catch((e) => { console.error(e); process.exit(1) })

View File

@@ -1,803 +0,0 @@
# WeChat Mini-Program Admin Scheduling/排课设置 - Complete Exploration Report
**Date**: 2026-04-05
**Project**: mp-pilates (WeChat mini-program for pilates studio bookings)
---
## 📋 Executive Summary
This is a **Pilates studio booking management system** with a comprehensive admin scheduling UI. The "排课设置" (Schedule Setup) feature allows admins to:
1. Define recurring weekly class templates (时间模板)
2. Manually add time slots for specific dates
3. Close slots (临时调整 → 关闭时段)
4. Batch generate slots from templates
The architecture uses:
- **Frontend**: Vue 3 + TypeScript (WeChat mini-program with Taro/UNI framework)
- **Backend**: NestJS + Prisma ORM
- **State Management**: Pinia (Vue state management)
- **Database**: Likely PostgreSQL/MySQL with Prisma
---
## 🗂️ File Structure
### Frontend Admin Pages
```
packages/app/src/pages/admin/
├── index.vue # Admin dashboard with nav grid
├── week-template.vue # 📅 Scheduling/排课设置 - Main feature
├── slot-adjust.vue # 🔧 Temporary adjustments (3 tabs)
├── members.vue # 👥 Member management
├── orders.vue # 📋 Order management
├── card-types.vue # 💳 Card type management
└── studio.vue # 🏢 Studio settings
```
### Stores
```
packages/app/src/stores/
└── admin.ts # Pinia store with all admin API calls
```
### Backend API
```
packages/server/src/
├── time-slot/
│ ├── time-slot.controller.ts # Admin & member endpoints for slots
│ ├── time-slot.service.ts # Business logic for slots
│ ├── slot-generator.service.ts # Template-based slot generation
│ └── dto/
│ ├── week-template.dto.ts # Input validation
│ ├── create-manual-slot.dto.ts
│ └── query-slots.dto.ts
├── studio/
│ └── studio.controller.ts # Studio config (admin endpoints)
└── scheduler/ # Cron scheduler for auto-generation
```
### Shared Types
```
packages/shared/src/types/
├── week-template.ts # WeekTemplate interface
├── time-slot.ts # TimeSlot interface
└── constants.ts # WEEKDAY_LABELS, SLOT_GENERATION_DAYS
```
---
## 🔑 Key Components
### 1. **Admin Dashboard (index.vue)**
**File**: `packages/app/src/pages/admin/index.vue`
**Features**:
- Display stats: today's bookings, total orders, total bookings
- Navigation grid to 6 admin modules:
- 📅 **排课设置**`/pages/admin/week-template`
- 🔧 **临时调整**`/pages/admin/slot-adjust`
- 👥 **会员管理**`/pages/admin/members`
- 📋 **订单管理**`/pages/admin/orders`
- 💳 **卡种管理**`/pages/admin/card-types`
- 🏢 **工作室设置**`/pages/admin/studio`
**Key Functions**:
```typescript
- navigate(path): Navigates to admin pages
- loadStats(): Fetches dashboard statistics via adminStore.fetchDashboardStats()
```
**State**:
```typescript
const stats = ref<AdminStats>({ todayBookings: 0, totalOrders: 0, totalBookings: 0 })
const statsLoading = ref(false)
```
---
### 2. **Week Template Management (week-template.vue)** ✨ MAIN SCHEDULING UI
**File**: `packages/app/src/pages/admin/week-template.vue`
**Route**: `/pages/admin/week-template`
#### Purpose
Manage recurring weekly schedule templates. These are used to **auto-generate** time slots for future weeks.
#### Data Structure
```typescript
interface WeekTemplate {
readonly id: string
readonly dayOfWeek: number // 1=Mon, 2=Tue, ..., 7=Sun (ISO format)
readonly startTime: string // HH:MM format
readonly endTime: string // HH:MM format
readonly capacity: number // Max bookings per slot
readonly isActive: boolean // Enable/disable template
readonly createdAt: string
readonly updatedAt: string
}
```
#### UI Sections
1. **Toolbar**
- Display template count: "共 N 条模板"
- "+ 新增时段" (Add new slot) button
2. **Template List** (Grouped by weekday)
- Days are sorted (Monday → Sunday)
- Each day shows count: "3 个时段"
- Each template row displays:
- Time range: "09:00 10:00"
- Capacity: "10 人"
- Actions:
- Toggle button: "启用"/"停用" (Enable/Disable)
- "编辑" (Edit)
- "删除" (Delete)
- Inactive templates are grayed out (opacity: 0.5)
3. **Modal for Add/Edit**
- Star date picker (1-7 for weekday)
- Start time picker
- End time picker
- Capacity input (number)
- Validation: time and capacity required
- Cancel/Confirm buttons
4. **Save Bar** (Fixed at bottom)
- Only shows when `isDirty` flag is true
- "保存全部更改" button with loading state
#### Key Functions
```typescript
async fetchTemplates()
- Fetches all templates from backend
- Groups by dayOfWeek for display
- Clears isDirty flag
async handleSave()
- Maps local template state to API payload
- Calls adminStore.saveWeekTemplates(payload)
- Refreshes templates after save
- Shows success/error toast
function openAdd()
- Opens modal for creating new template
- Clears form
function openEdit(tpl)
- Opens modal in edit mode
- Populates form with existing values
function submitForm()
- Validates form (time and capacity required)
- Creates or updates template in memory
- Sets isDirty = true (triggers save bar)
function toggleTemplate(tpl)
- Toggles isActive flag
- Sets isDirty = true
function deleteTemplate(tpl)
- Shows confirmation modal
- Removes from array
- Sets isDirty = true
```
#### Local State Management
```typescript
const templates = ref<LocalTemplate[]>([])
const loading = ref(false)
const saving = ref(false)
const isDirty = ref(false) // Tracks unsaved changes
const showModal = ref(false)
const editTarget = ref<LocalTemplate | null>(null)
const form = ref({
dayIdx: 0, // Selected day index (0-6)
startTime: '09:00',
endTime: '10:00',
capacityStr: '10',
})
const grouped = computed(() => {
// Groups templates by dayOfWeek for rendering
return Object.fromEntries(
Object.entries(map).sort(([a], [b]) => Number(a) - Number(b))
)
})
```
#### Example: Adding a Monday 9AM-10AM class
1. User taps "+ 新增时段"
2. Modal opens, form is reset to defaults
3. User selects "周一" (Monday) from picker
4. User confirms times and capacity
5. New template object is pushed to `templates` array
6. `isDirty` is set to true → save bar appears
7. User taps "保存全部更改"
8. Store calls `PUT /admin/week-template` with all templates
9. Backend deletes all old templates and creates new ones
10. Frontend refetches and displays updated list
---
### 3. **Slot Adjustment (slot-adjust.vue)** - Temporary Slot Management
**File**: `packages/app/src/pages/admin/slot-adjust.vue`
**Route**: `/pages/admin/slot-adjust`
#### Purpose
Handle temporary/manual time slot operations:
1. Add one-off slots for specific dates
2. Close available slots
3. Batch-generate slots from templates
#### UI Structure (3 Tabs)
##### Tab 0: "新增时段" (Add Manual Slot)
- Date picker (defaults to today)
- Start/End time pickers
- Capacity input
- Submit button: "新增时段"
- **Endpoint**: `POST /admin/time-slot/manual`
```typescript
interface CreateManualSlotDto {
date: string // YYYY-MM-DD
startTime: string // HH:MM
endTime: string // HH:MM
capacity?: number // Defaults to DEFAULT_SLOT_CAPACITY (1)
}
```
##### Tab 1: "关闭时段" (Close Slots)
- Date picker (defaults to today)
- Loads all slots for selected date
- Displays slot list with:
- Time range
- Status badge (OPEN/FULL/CLOSED)
- Booked count: "X/Y"
- Close button (if not already closed)
- Confirmation modal when closing
- **Endpoint**: `PUT /admin/time-slot/:id/close`
**Slot Status Colors**:
```
OPEN → Green badge #27ae60
FULL → Orange badge #e67e22
CLOSED → Gray badge #999
```
##### Tab 2: "批量生成" (Batch Generate)
- Start date picker
- End date picker (defaults to +7 days)
- Hint: "将根据排课模板,自动生成所选日期范围内的时段"
- *"Will auto-generate slots for selected date range based on schedule template"*
- Submit button: "批量生成"
- **Endpoint**: `POST /admin/generate-slots`
**How it works**:
1. Frontend sends date range to backend
2. Backend fetches all **active** WeekTemplates
3. For each day in range, finds matching templates by weekday
4. Creates TimeSlot records with `source: TEMPLATE`
5. Uses `skipDuplicates: true` to avoid re-generating existing slots
```typescript
// Backend example: If templates include:
// - Monday: 09:00-10:00, 18:00-19:00 (2 templates)
// - Wednesday: 10:00-11:00 (1 template)
//
// And user selects 2026-04-05 to 2026-04-11:
// - Mon 04-06: 2 slots generated
// - Wed 04-08: 1 slot generated
// Total: 3 slots (if these dates fall in range)
```
#### Key Functions
```typescript
async submitAddSlot()
- POST /admin/time-slot/manual
- Shows success/error toast
async loadSlotsForClose()
- Fetches slots for closeDate via adminStore.fetchSlotsByDate(date)
- Sets slotsLoading flag
async closeSlot(slot)
- Confirmation modal
- PUT /admin/time-slot/:id/close
- Reloads slot list
async submitGenerate()
- POST /admin/generate-slots with date range
- Shows toast with count of generated slots
```
#### Local State
```typescript
const activeTab = ref(0) // 0=Add, 1=Close, 2=Generate
const submitting = ref(false)
const slotsLoading = ref(false)
// Tab 0: Add form
const addForm = ref({
date: formatDate(new Date()),
startTime: '09:00',
endTime: '10:00',
capacityStr: '10',
})
// Tab 1: Close slots
const closeDate = ref(formatDate(new Date()))
const daySlots = ref<TimeSlot[]>([])
// Tab 2: Generate form
const genForm = ref({
startDate: formatDate(new Date()),
endDate: formatDate(new Date(Date.now() + 7 * 86400000)), // +7 days
})
```
---
### 4. **Admin Store (Pinia)**
**File**: `packages/app/src/stores/admin.ts`
#### API Methods Related to Scheduling
```typescript
// ── Week templates ───────────────────────────────────────────────
async fetchWeekTemplates(): Promise<WeekTemplate[]>
// GET /admin/week-template
// Returns all templates for current studio
// Usage: Gets templates for display in week-template.vue
async saveWeekTemplates(templates: WeekTemplateInput[]): Promise<WeekTemplate[]>
// PUT /admin/week-template
// Body: { templates: [...] }
// Replaces ALL templates with new set (delete all, create new)
// Note: Backend uses transaction for atomicity
// ── Time slots ───────────────────────────────────────────────────
async fetchSlotsByDate(date: string): Promise<TimeSlot[]>
// GET /admin/time-slots?date=YYYY-MM-DD
// Returns all slots for a specific date
// Used in slot-adjust.vue Tab 1 (close slots)
async createManualSlot(dto: CreateManualSlotDto): Promise<TimeSlot>
// POST /admin/time-slot/manual
// Creates a one-off time slot
// Used in slot-adjust.vue Tab 0
async closeSlot(id: string): Promise<TimeSlot>
// PUT /admin/time-slot/:id/close
// Changes slot status from OPEN to CLOSED
// Used in slot-adjust.vue Tab 1
async generateSlots(startDate: string, endDate: string): Promise<{ count: number }>
// POST /admin/generate-slots
// Generates slots from active templates for date range
// Used in slot-adjust.vue Tab 2
// Returns: { count: number of newly created slots }
// ── Dashboard ────────────────────────────────────────────────────
async fetchDashboardStats(): Promise<AdminStats>
// GET /admin/stats
// Returns: { todayBookings, totalOrders, totalBookings }
// Used in index.vue
```
#### API Response Types
```typescript
interface AdminStats {
todayBookings: number
totalOrders: number
totalBookings: number
}
interface WeekTemplate {
id: string
dayOfWeek: number // 1-7 (ISO weekday)
startTime: string // HH:MM
endTime: string // HH:MM
capacity: number
isActive: boolean
createdAt: string
updatedAt: string
}
interface TimeSlot {
id: string
date: string // YYYY-MM-DD
startTime: string
endTime: string
capacity: number
bookedCount: number
status: TimeSlotStatus // OPEN | FULL | CLOSED
source: TimeSlotSource // TEMPLATE | MANUAL
templateId: string | null
createdAt: string
updatedAt: string
}
```
---
## 🔌 Backend Architecture
### Time Slot Controller
**File**: `packages/server/src/time-slot/time-slot.controller.ts`
#### Member Endpoints (Public)
```
GET /time-slot/available?date=YYYY-MM-DD
- Get available slots for a date
- Include booking status for current user
GET /time-slot/:id
- Get specific slot details
```
#### Admin Endpoints (Requires JWT + ADMIN role)
```
GET /admin/week-template
- Returns all WeekTemplates
- Ordered by: dayOfWeek ASC, startTime ASC
PUT /admin/week-template
- Request body: { templates: [...] }
- Replaces all templates (transaction-based)
- Validation: dayOfWeek 1-7, startTime/endTime strings
POST /admin/time-slot/manual
- Request body: { date, startTime, endTime, capacity? }
- Creates manual slot with source=MANUAL
- Capacity defaults to DEFAULT_SLOT_CAPACITY
PUT /admin/time-slot/:id/close
- Changes slot status to CLOSED
- Returns updated slot
POST /admin/generate-slots
- Generates slots from active templates
- Fetches templates where isActive=true
- Creates slots for next SLOT_GENERATION_DAYS (14 days by default)
- Uses skipDuplicates to make re-runs safe
- Returns: { count: number }
```
### Time Slot Service
**File**: `packages/server/src/time-slot/time-slot.service.ts`
Key methods:
```typescript
async getWeekTemplates(): Promise<WeekTemplate[]>
// Returns all templates sorted by day/time
async replaceWeekTemplates(items: Array<{...}>): Promise<any>
// Transaction-based replacement:
// 1. Delete all existing templates
// 2. Create new ones from items array
// 3. Return count of created
async createManualSlot(dto): Promise<TimeSlot>
// Creates slot with source=MANUAL, status=OPEN
async closeSlot(id: string): Promise<TimeSlot>
// Updates status to CLOSED
```
### Slot Generator Service
**File**: `packages/server/src/time-slot/slot-generator.service.ts`
Key method:
```typescript
async generateSlots(daysAhead: number = 14): Promise<number>
// 1. Fetches all WeekTemplates where isActive=true
// 2. For each of next N days:
// - Calculate ISO weekday (1=Mon, 7=Sun)
// - Find matching templates by dayOfWeek
// - Create TimeSlot records with source=TEMPLATE, templateId=id
// 3. Uses createMany with skipDuplicates=true
// 4. Returns count of newly created slots
//
// Key: Converts JS getDay() (0=Sun) to ISO weekday (1=Mon, 7=Sun)
async cleanupExpiredSlots(): Promise<number>
// Called by scheduler
// Closes all OPEN slots with date < today
async checkExpiredMemberships(): Promise<number>
// Called by scheduler
// Expires memberships past end date or with 0 sessions left
async completeBookings(): Promise<number>
// Called by scheduler
// Marks CONFIRMED bookings as COMPLETED if slot date passed
```
---
## 📊 Data Flow: "排课设置" User Journey
### Scenario: Admin sets up class schedule for next week
1. **Admin opens dashboard**`index.vue`
- Taps "排课设置" nav item
2. **Admin navigates to Week Template page**`week-template.vue`
- `onMounted()``fetchTemplates()`
- Frontend: `GET /admin/week-template`
- Shows existing templates grouped by day
- Example display:
```
周一
09:00-10:00 10人 [启用] [编辑] [删除]
18:00-19:00 8人 [启用] [编辑] [删除]
周三
10:00-11:00 12人 [启用] [编辑] [删除]
```
3. **Admin adds a new class** → Click "+ 新增时段"
- Modal opens
- Select day, time, capacity
- Click "确认"
- Template added to local `templates` array
- **Save bar appears** at bottom
4. **Admin edits existing template** → Click "编辑"
- Modal opens with existing values
- Modify time/capacity
- Click "确认"
- Updated in local array
- Save bar shows if changed
5. **Admin disables a template** → Click "停用"
- `isActive` flipped to false
- Template grayed out
- Save bar shows
6. **Admin saves all changes** → Click "保存全部更改"
- Loading state
- Frontend: `PUT /admin/week-template` with all templates
- Backend transaction:
```
BEGIN TRANSACTION
DELETE FROM week_template
INSERT INTO week_template (day_of_week, start_time, end_time, capacity, is_active) VALUES (...)
COMMIT TRANSACTION
```
- Success toast
- Frontend refetches templates
- Save bar disappears
7. **Backend scheduler auto-generates slots**
- Nightly cron (scheduler module)
- Calls `SlotGeneratorService.generateSlots(14)`
- Queries active WeekTemplates
- For each day in next 14 days:
- Checks what templates apply (by ISO weekday)
- Creates TimeSlot records
- Uses `skipDuplicates` to avoid duplicates on re-run
- Example output:
```
date: 2026-04-06 (Monday)
09:00-10:00 source=TEMPLATE templateId=abc123
18:00-19:00 source=TEMPLATE templateId=def456
date: 2026-04-08 (Wednesday)
10:00-11:00 source=TEMPLATE templateId=ghi789
```
8. **Members can see and book the generated slots**
- Frontend: `GET /time-slot/available?date=2026-04-06`
- Members choose a slot and confirm booking
---
## 📅 Constants & Utilities
### Shared Constants
**File**: `packages/shared/src/constants.ts`
```typescript
export const SLOT_GENERATION_DAYS = 14
// Number of days ahead to generate slots for
export const DEFAULT_SLOT_CAPACITY = 1
// Default capacity if not specified (for private lessons)
export const WEEKDAY_LABELS = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日']
// Index 0 is unused, 1-7 map to weekdays
// Used in dropdowns and display
export const DEFAULT_CANCEL_HOURS_LIMIT = 2
// Hours before slot to allow free cancellation
export const TIME_PERIODS = {
MORNING: { label: '上午', start: '06:00', end: '12:00' },
AFTERNOON: { label: '下午', start: '12:00', end: '18:00' },
EVENING: { label: '晚上', start: '18:00', end: '22:00' }
}
export const DATE_SELECTOR_DAYS = 7
```
### Format Utilities
**File**: `packages/app/src/utils/format.ts`
```typescript
formatDate(date: Date | string): string
// Converts to YYYY-MM-DD format
// Used for date pickers and API calls
getWeekdayLabel(date: Date | string): string
// Returns Chinese weekday (周一-周日)
isToday(date: Date | string): boolean
// Checks if date is today
getDateRange(days: number): Array<{ date, weekday, isToday }>
// Generates future N days' dates
```
### Request Utility
**File**: `packages/app/src/utils/request.ts`
```typescript
function request<T>(options: RequestOptions): Promise<T>
// Makes HTTP request with JWT auth
// Auto-refreshes token on 401
function get<T>(url: string, data?: Record<string, unknown>): Promise<T>
function post<T>(url: string, data?: Record<string, unknown>): Promise<T>
function put<T>(url: string, data?: Record<string, unknown>): Promise<T>
function del<T>(url: string, data?: Record<string, unknown>): Promise<T>
// Base URL logic:
// - Production: https://focus.richarjiang.com/api
// - Development: http://localhost:3000/api
```
---
## 🔐 Permission Model
**Role**: `UserRole.ADMIN`
### Protected Endpoints
All `/admin/*` endpoints require:
1. Valid JWT token
2. Header: `Authorization: Bearer <token>`
3. User role must be `ADMIN`
Protected by:
- `@UseGuards(JwtAuthGuard, RolesGuard)`
- `@Roles(UserRole.ADMIN)`
### Auth Flow
1. Admin logs in via auth module
2. JWT token returned, stored in `uni.setStorageSync('token')`
3. All requests include token in Authorization header
4. If 401 response: clear token, show login prompt
5. If 4xx/5xx: show error toast
---
## 🐛 Current Implementation Notes
### Implemented Features ✅
- [x] Week template CRUD (Create, Read, Update via replace)
- [x] Manual slot creation
- [x] Close individual slots
- [x] Batch slot generation from templates
- [x] UI for all three slot adjustment tabs
- [x] Local state change tracking (isDirty)
- [x] Modal form for adding/editing templates
- [x] Grouping templates by weekday
- [x] Status badges for slots (OPEN/FULL/CLOSED)
### Missing/Stub Features ⚠️
- [ ] `fetchDashboardStats()` API endpoint appears to be stubbed
- `index.vue` calls it but endpoint not found in backend
- May need to implement in studio or payment controller
- [ ] No client-side validation errors displayed on API failures
- [ ] No confirmation before overwriting all templates
- [ ] No undo/restore from past template versions
### Edge Cases to Watch 🔍
1. **Timezone handling**: All dates are treated as UTC midnight
- Slot generation uses `setUTCHours(0,0,0,0)`
- Frontend format displays as YYYY-MM-DD (local string)
2. **Duplicate slot prevention**:
- Backend uses `skipDuplicates: true` in createMany
- Assumes date + startTime + endTime forms unique key
3. **Template replacement is atomic**:
- All templates deleted, all new ones created in transaction
- If one row fails, entire operation rolls back
4. **ISO weekday vs JS getDay()**:
- Shared code uses ISO: 1=Mon, 7=Sun
- Frontend picker displays Chinese labels
- Backend slot-generator converts JS getDay() to ISO
---
## 📱 UI Design Patterns
### Colors & Styling
- **Primary**: `#1a1a2e` (dark navy)
- **Accent**: `#c9a87c` (gold)
- **Success**: `#27ae60` (green)
- **Warning**: `#e67e22` (orange)
- **Danger**: `#c0392b` (red)
- **Background**: `#f5f3f0` (light beige)
### Component Patterns
1. **Skeleton loaders**: Shimmer animation for loading states
2. **Save bar**: Fixed bottom bar shows only when changes exist
3. **Toggle buttons**: Color indicates state (on=green, off=orange)
4. **Modals**: Bottom-sheet style with backdrop
5. **Pickers**: WeChat native pickers for date/time
6. **Badges**: Color-coded status indicators
---
## 🚀 Deployment & Configuration
### Frontend
- WeChat mini-program environment
- Base URL logic in `packages/app/src/utils/request.ts`:
```typescript
// Production
https://focus.richarjiang.com/api
// Development
http://localhost:3000/api
```
### Backend
- NestJS server on port 3000
- Prisma ORM with database
- JWT authentication
- Role-based access control (RBAC)
---
## 📚 Related Files Summary
| File | Purpose | Type |
|------|---------|------|
| `admin/index.vue` | Admin dashboard | Component |
| `admin/week-template.vue` | Schedule templates | Component ⭐ |
| `admin/slot-adjust.vue` | Manual slot ops | Component |
| `stores/admin.ts` | Admin API calls | Store |
| `time-slot.service.ts` | Slot business logic | Service |
| `slot-generator.service.ts` | Template-based generation | Service |
| `time-slot.controller.ts` | API endpoints | Controller |
| `week-template.ts` | Type definitions | Type |
| `constants.ts` | Shared constants | Config |
| `format.ts` | Date/time utilities | Utility |
---
## 🎯 Key Takeaways
1. **"排课设置"** is the master schedule template management page
2. **Templates are ISO-weekday based** (1=Monday, 7=Sunday)
3. **Slot generation is automated** via backend scheduler, triggered by:
- Nightly cron job
- Or manual POST to `/admin/generate-slots` endpoint
4. **Save pattern**: Local changes tracked, one "save all" API call with full template array
5. **Timezone**: All operations use UTC midnight as boundaries
6. **Atomicity**: Backend uses Prisma transactions for template replacement
7. **Permissions**: All admin endpoints protected by JWT + ADMIN role guard

37
AGENTS.md Normal file
View File

@@ -0,0 +1,37 @@
# Repository Guidelines
## Project Structure & Module Organization
This repository is a `pnpm` workspace with three packages under `packages/`:
- `packages/app`: Vue 3 + `uni-app` WeChat mini-program. Pages live in `src/pages`, shared UI in `src/components`, state in `src/stores`, and utilities in `src/utils`.
- `packages/server`: NestJS API with Prisma. Feature modules live in `src/<domain>`, unit tests are colocated in `__tests__`, and the database schema and seed script are in `prisma/`.
- `packages/shared`: shared TypeScript enums, constants, and types used by both app and server.
Reference docs and implementation notes are under `docs/`.
## Build, Test, and Development Commands
- `pnpm dev:server`: start the NestJS API with watch mode.
- `pnpm dev:app`: build and serve the `uni-app` target for WeChat mini-program development.
- `pnpm build:shared`: compile shared types before consuming package changes.
- `pnpm build:server`: build the backend into `packages/server/dist`.
- `pnpm build:app`: produce the WeChat mini-program build.
- `pnpm test`: run workspace tests; today this mainly executes server Jest tests.
- `pnpm lint`: run workspace linting; currently defined for the server.
For Prisma tasks, work in `packages/server`: `pnpm prisma:generate`, `pnpm prisma:migrate`, `pnpm prisma:seed`.
## Coding Style & Naming Conventions
Use TypeScript throughout. Follow the existing style: 2-space indentation in JSON/Markdown, `camelCase` for variables/functions, `PascalCase` for Vue components and NestJS classes, and `kebab-case` for page/component filenames such as `flash-sales.vue`. Keep modules feature-oriented and prefer colocating DTOs and tests with their domain module.
Linting is configured in the server via ESLint. The app relies on `vue-tsc` for type checks: run `pnpm --filter @mp-pilates/app type-check` before shipping UI changes.
## Testing Guidelines
Server tests use Jest with `*.spec.ts` naming. Place tests in `packages/server/src/**/__tests__/` and focus on service-level behavior and edge cases around booking, membership, payment, and scheduling logic. Run `pnpm test` for the full suite or `pnpm --filter @mp-pilates/server test:cov` when touching business-critical paths.
## Commit & Pull Request Guidelines
Recent history uses Conventional Commit prefixes such as `feat:`, `fix:`, `fix(app):`, and `perf:`. Keep subjects short and specific, preferably describing the user-visible effect.
Pull requests should include a concise summary, linked issue or task reference, test notes, and screenshots or recordings for mini-program UI changes. Call out Prisma schema changes, new environment variables, or deployment steps explicitly.
## Security & Configuration Tips
Do not commit real secrets. Review `packages/server/certs/` and environment-specific payment or WeChat credentials carefully before pushing. When changing shared types or enums, update both consumers and rebuild `@mp-pilates/shared` to avoid runtime drift.

View File

@@ -1,552 +0,0 @@
# Booking Page - Architecture Diagram
## 🏛️ Complete System Architecture
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ WECHAT MINI-PROGRAM │
│ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ FRONTEND (Vue 3 + Uni-app) │ │
│ │ │ │
│ │ ┌────────────────────────────────────────────────────────────────┐ │ │
│ │ │ pages/booking/index.vue (Main Page Component) │ │ │
│ │ │ ───────────────────────────────────────────────────────────── │ │ │
│ │ │ State: │ │ │
│ │ │ • selectedDate: string │ │ │
│ │ │ • selectedPeriod: PeriodKey | null │ │ │
│ │ │ • showConfirmPopup: boolean │ │ │
│ │ │ • pendingSlot: TimeSlotWithBookingStatus | null │ │ │
│ │ │ • refreshing: boolean │ │ │
│ │ │ │ │ │
│ │ │ Computed: │ │ │
│ │ │ • scrollHeight (responsive) │ │ │
│ │ │ • filteredSlots (depends on period) │ │ │
│ │ │ │ │ │
│ │ │ Lifecycle: │ │ │
│ │ │ • onMounted() → Load memberships + today's slots │ │ │
│ │ │ │ │ │
│ │ │ Event Handlers: │ │ │
│ │ │ • onDateSelect() → loadSlots(newDate) │ │ │
│ │ │ • onPeriodChange() → Auto-filter via computed │ │ │
│ │ │ • onRefresh() → Reload slots │ │ │
│ │ │ • onBookTap() → Auth check → Show popup │ │ │
│ │ │ • onConfirmBooking() → Create booking → Refresh │ │ │
│ │ │ • onCancelTap() → Cancel booking → Refresh │ │ │
│ │ └────────────────────────────────────────────────────────────────┘ │ │
│ │ ↓ │ │
│ │ ┌─────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Child Components (All reactive & event-driven) │ │ │
│ │ │ │ │ │
│ │ │ ┌──────────────────┐ ┌──────────────────┐ │ │ │
│ │ │ │ DateSelector.vue │ │ TimePeriod...vue │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ [Today] [5] [4] │ │ 全部 上午 下午... │ │ │ │
│ │ │ │ Props: modelValue│ │ Props: modelValue│ │ │ │
│ │ │ │ Emit: @select │ │ Emit: @change │ │ │ │
│ │ │ └──────────────────┘ └──────────────────┘ │ │ │
│ │ │ ↓ ↓ │ │ │
│ │ │ (Updates selectedDate) (Updates selectedPeriod) │ │ │
│ │ │ ↓ ↓ │ │ │
│ │ │ (Triggers loadSlots) (Recomputes filteredSlots) │ │ │
│ │ │ │ │ │
│ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │
│ │ │ │ SlotCard.vue (Rendered via v-for over filteredSlots) │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ │
│ │ │ │ │ [09:00-10:00] [0/1 人] │ │ │ │ │
│ │ │ │ │ [可预约] │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ Props: slot (TimeSlotWithBookingStatus) │ │ │ │ │
│ │ │ │ │ Emit: @book | @cancel │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ Computed: │ │ │ │ │
│ │ │ │ │ • capacityLabel ("0/1 人" | "已关闭") │ │ │ │ │
│ │ │ │ │ • capacityClass (cap-open | cap-almost | ...) │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ Button States (4 conditions): │ │ │ │ │
│ │ │ │ │ 1. OPEN + not booked → "可预约" │ │ │ │ │
│ │ │ │ │ 2. OPEN + booked → "已预约" + "取消" │ │ │ │ │
│ │ │ │ │ 3. FULL → "已约满" │ │ │ │ │
│ │ │ │ │ 4. CLOSED → "已关闭" │ │ │ │ │
│ │ │ │ └─────────────────────────────────────────────────────┘ │ │ │ │
│ │ │ │ ↓ ↓ │ │ │ │
│ │ │ │ (onBookTap) (onCancelTap) │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ │
│ │ │ │ │ BookingConfirmPopup.vue (Modal) │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ Props: │ │ │ │ │
│ │ │ │ │ • visible: boolean │ │ │ │ │
│ │ │ │ │ • slot: TimeSlotWithBookingStatus │ │ │ │ │
│ │ │ │ │ • memberships: MembershipWithCardType[] │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ State: │ │ │ │ │
│ │ │ │ │ • selectedMembershipId (auto-selected on show) │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ │ │ Display: │ │ │ │ │
│ │ │ │ │ ┌─────────────────────────────────┐ │ │ │ │ │
│ │ │ │ │ │ 确认预约 ✕ │ │ │ │ │
│ │ │ │ │ ├─────────────────────────────────┤ │ │ │ │ │
│ │ │ │ │ │ 日期: 2026-04-05 │ │ │ │ │ │
│ │ │ │ │ │ 时间: 09:00 - 10:00 │ │ │ │ │ │
│ │ │ │ │ │ 剩余: 1 个名额 │ │ │ │ │ │
│ │ │ │ │ ├─────────────────────────────────┤ │ │ │ │ │
│ │ │ │ │ │ 💳 私教课程 │ │ │ │ │ │
│ │ │ │ │ │ 剩余 10 次 ✓ │ │ │ │ │ │
│ │ │ │ │ ├─────────────────────────────────┤ │ │ │ │ │
│ │ │ │ │ │ [取消] [确认预约] │ │ │ │ │ │
│ │ │ │ │ └─────────────────────────────────┘ │ │ │ │ │
│ │ │ │ │ ↓ │ │ │ │ │
│ │ │ │ │ Emit: @confirm({timeSlotId, membershipId}) │ │ │ │ │
│ │ │ │ │ or @cancel │ │ │ │ │
│ │ │ │ └──────────────────────────────────────────────────────┘ │ │ │ │
│ │ │ └──────────────────────────────────────────────────────────┘ │ │ │
│ │ └────────────────────────────────────────────────────────────────┘ │ │
│ │ ↓ │ │
│ │ ┌────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Pinia Stores (Reactive State Management) │ │ │
│ │ │ │ │ │
│ │ │ stores/booking.ts: │ │ │
│ │ │ State: │ │ │
│ │ │ • slots: TimeSlotWithBookingStatus[] │ │ │
│ │ │ • myBookings: BookingWithDetails[] │ │ │
│ │ │ • upcomingBookings: BookingWithDetails[] │ │ │
│ │ │ • loadingSlots: boolean │ │ │
│ │ │ • loadingBookings: boolean │ │ │
│ │ │ │ │ │
│ │ │ Actions: │ │ │
│ │ │ • fetchSlots(date) │ │ │
│ │ │ • createBooking(dto) │ │ │
│ │ │ • cancelBooking(bookingId) │ │ │
│ │ │ • fetchMyBookings() │ │ │
│ │ │ • fetchUpcomingBookings() │ │ │
│ │ │ │ │ │
│ │ │ stores/user.ts: │ │ │
│ │ │ State: │ │ │
│ │ │ • user: UserProfileResponse | null │ │ │
│ │ │ • memberships: MembershipWithCardType[] │ │ │
│ │ │ • token: string (from localStorage) │ │ │
│ │ │ │ │ │
│ │ │ Computed: │ │ │
│ │ │ • loggedIn: !!token │ │ │
│ │ │ • hasValidMembership: activeMemberships.length > 0 │ │ │
│ │ │ • activeMemberships: memberships filtered by ACTIVE │ │ │
│ │ │ │ │ │
│ │ │ Actions: │ │ │
│ │ │ • login() │ │ │
│ │ │ • fetchMemberships() │ │ │
│ │ │ • fetchProfile() │ │ │
│ │ │ • logout() │ │ │
│ │ └────────────────────────────────────────────────────────────────┘ │ │
│ │ ↓ │ │
│ │ ┌────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Utils & Helpers │ │ │
│ │ │ │ │ │
│ │ │ utils/request.ts (HTTP Client): │ │ │
│ │ │ • request<T>(options): Promise<T> │ │ │
│ │ │ • get<T>(url, data?): Promise<T> │ │ │
│ │ │ • post<T>(url, data?): Promise<T> │ │ │
│ │ │ • put<T>(url, data?): Promise<T> │ │ │
│ │ │ │ │ │
│ │ │ utils/format.ts (Date Utilities): │ │ │
│ │ │ • formatDate(date): string │ │ │
│ │ │ • getWeekdayLabel(date): string │ │ │
│ │ │ • isToday(date): boolean │ │ │
│ │ │ • getDateRange(days): DateInfo[] │ │ │
│ │ └────────────────────────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
│ ↕ │
│ HTTP Requests │
│ (Bearer Token in Header) │
│ ↓ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ BACKEND API │ │
│ │ (packages/server/src/time-slot, booking, membership modules) │ │
│ │ │ │
│ │ GET /api/time-slot/available?date=YYYY-MM-DD │ │
│ │ → TimeSlotWithBookingStatus[] │ │
│ │ │ │
│ │ POST /api/booking │ │
│ │ Body: { timeSlotId, membershipId } │ │
│ │ → BookingWithDetails │ │
│ │ │ │
│ │ PUT /api/booking/:bookingId/cancel │ │
│ │ → BookingWithDetails (status: CANCELLED) │ │
│ │ │ │
│ │ GET /api/membership/my │ │
│ │ → MembershipWithCardType[] │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
│ ↕ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ DATABASE │ │
│ │ (TimeSlot, Booking, Membership, User tables) │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 📊 Data Flow Lifecycle
```
╔══════════════════════════════════════════════════════════════════════════╗
║ BOOKING PAGE LIFECYCLE ║
╚══════════════════════════════════════════════════════════════════════════╝
1. PAGE LOAD
┌─ onMounted()
│ ├─ IF loggedIn AND no memberships
│ │ └─ userStore.fetchMemberships()
│ │ GET /membership/my
│ │ → memberships array
│ │
│ └─ loadSlots(today)
│ → bookingStore.fetchSlots(date)
│ GET /time-slot/available?date=YYYY-MM-DD
│ → slots array
│ → Render SlotCard components
└─ READY ✓
2. USER SELECTS DATE
├─ onDateSelect(newDate)
├─ selectedDate.value = newDate
└─ loadSlots(newDate)
→ bookingStore.fetchSlots(newDate)
→ slots array (for new date)
→ SlotCard components re-render
3. USER SELECTS TIME PERIOD
├─ onPeriodChange(period)
├─ selectedPeriod.value = period
└─ filteredSlots computed updates automatically
→ Vue watches TIME_PERIODS[period]
→ Filters slots by startTime
→ SlotCard components re-render (subset)
4. USER PULLS TO REFRESH
├─ onRefresh()
├─ refreshing.value = true
├─ loadSlots(selectedDate.value)
│ → bookingStore.fetchSlots()
│ → slots array (refreshed)
└─ refreshing.value = false
5. USER TAPS "可预约" (Book)
├─ onBookTap(slot)
├─ CHECK: loggedIn?
│ ├─ NO → Show login modal
│ │ User clicks confirm
│ │ → userStore.login()
│ │ POST /auth/wxLogin
│ │ → token + user
│ │ → userStore.fetchMemberships()
│ │ GET /membership/my
│ │ → memberships array
│ │ → RETRY onBookTap(slot)
│ │
│ └─ YES → Continue
├─ CHECK: hasValidMembership?
│ ├─ NO → Show purchase modal
│ │ User clicks confirm
│ │ → uni.navigateTo('/pages/store/index')
│ │
│ └─ YES → Continue
├─ pendingSlot.value = slot
├─ showConfirmPopup.value = true
└─ POPUP SHOWN ✓
├─ selectedMembershipId auto-selected (first one)
├─ Watch on popup visibility + memberships
│ → Auto-select first membership when shown
└─ User sees:
• Slot date/time
• Membership card options
• Deduction message
6. USER CONFIRMS BOOKING
├─ onConfirmBooking({timeSlotId, membershipId})
├─ showConfirmPopup.value = false
├─ uni.showLoading('预约中...')
├─ bookingStore.createBooking(payload)
│ └─ POST /booking
│ Body: { timeSlotId, membershipId }
│ → BookingWithDetails
├─ uni.hideLoading()
├─ uni.showToast('预约成功!')
├─ loadSlots(selectedDate.value) // REFRESH
│ → bookingStore.fetchSlots()
│ GET /time-slot/available?date=
│ → slots array (UPDATED)
│ • slot.isBookedByMe = true
│ • slot.myBookingId = bookingId
│ • Button now shows "已预约"
└─ BOOKING COMPLETE ✓
7. USER TAPS "取消" (Cancel)
├─ onCancelTap(slot)
├─ Show confirmation modal
├─ User confirms
├─ uni.showLoading('取消中...')
├─ bookingStore.cancelBooking(slot.myBookingId)
│ └─ PUT /booking/:id/cancel
│ → BookingWithDetails (status: CANCELLED)
├─ uni.hideLoading()
├─ uni.showToast('已取消预约')
├─ loadSlots(selectedDate.value) // REFRESH
│ → bookingStore.fetchSlots()
│ GET /time-slot/available?date=
│ → slots array (UPDATED)
│ • slot.isBookedByMe = false
│ • slot.myBookingId = null
│ • Button now shows "可预约"
└─ CANCELLATION COMPLETE ✓
```
---
## 🔄 State Synchronization
```
Component ←→ Pinia Store ←→ API ←→ Database
┌──────────────────────────────────────────────────────────┐
│ Component (Vue Template) │
│ │
│ {{ bookingStore.slots }} ← Reactive binding │
│ {{ filteredSlots }} ← Computed from slots │
│ {{ userStore.hasValidMembership }} ← Computed from store │
│ │
│ @click="onBookTap(slot)" ← User action │
│ │
└──────────────────────────────────────────────────────────┘
↑ ↓
│ Read │ Mutate
│ ↓
┌──────────────────────────────────────────────────────────┐
│ Pinia Store State │
│ │
│ slots: TimeSlotWithBookingStatus[] │
│ ↓ Recomputed when: │
│ - fetchSlots() returns data │
│ - createBooking() succeeds │
│ - cancelBooking() succeeds │
│ │
│ memberships: MembershipWithCardType[] │
│ ↓ Set when: │
│ - fetchMemberships() returns data │
│ │
│ loadingSlots: boolean │
│ ↓ Set to: │
│ - true on fetchSlots() start │
│ - false on fetchSlots() end │
│ │
└──────────────────────────────────────────────────────────┘
↑ ↓
│ Response │ Request
│ ↓
┌──────────────────────────────────────────────────────────┐
│ API Layer (utils/request.ts) │
│ │
│ GET /time-slot/available?date=2026-04-05 │
│ ↓ Returns ApiResponse<TimeSlotWithBookingStatus[]> │
│ { success: true, data: [...], message: null } │
│ │
│ POST /booking │
│ ↓ Body: { timeSlotId, membershipId } │
│ ↓ Returns ApiResponse<BookingWithDetails> │
│ { success: true, data: {...}, message: null } │
│ │
│ PUT /booking/:id/cancel │
│ ↓ Returns ApiResponse<BookingWithDetails> │
│ { success: true, data: {...}, message: null } │
│ │
└──────────────────────────────────────────────────────────┘
↑ ↓
│ SELECT/UPDATE │ INSERT/UPDATE
│ ↓
┌──────────────────────────────────────────────────────────┐
│ Database │
│ │
│ TimeSlot Table │
│ id, date, startTime, endTime, capacity, │
│ bookedCount, status, source, templateId │
│ │
│ Booking Table │
│ id, userId, timeSlotId, membershipId, │
│ status (CONFIRMED/CANCELLED/...), bookedAt │
│ │
│ Membership Table │
│ id, userId, cardTypeId, status, remainingTimes, │
│ expireDate, createdAt, updatedAt │
│ │
└──────────────────────────────────────────────────────────┘
```
---
## 🎯 Component Communication
```
Root: pages/booking/index.vue
├─ PROPS DOWN ──→ DateSelector.vue
│ └─ modelValue: string (YYYY-MM-DD)
├─ PROPS DOWN ──→ TimePeriodFilter.vue
│ └─ modelValue: PeriodKey | null
├─ PROPS DOWN ──→ SlotCard.vue (v-for)
│ └─ slot: TimeSlotWithBookingStatus
├─ PROPS DOWN ──→ BookingConfirmPopup.vue
│ ├─ visible: boolean
│ ├─ slot: TimeSlotWithBookingStatus | null
│ └─ memberships: MembershipWithCardType[]
├─ EVENTS UP ←── DateSelector.vue
│ ├─ @select(date) → onDateSelect()
│ └─ @update:modelValue(date)
├─ EVENTS UP ←── TimePeriodFilter.vue
│ ├─ @change(period) → onPeriodChange()
│ └─ @update:modelValue(period)
├─ EVENTS UP ←── SlotCard.vue
│ ├─ @book(slot) → onBookTap()
│ └─ @cancel(slot) → onCancelTap()
└─ EVENTS UP ←── BookingConfirmPopup.vue
├─ @confirm({timeSlotId, membershipId}) → onConfirmBooking()
└─ @cancel → showConfirmPopup = false
```
---
## 🧬 Reactive Dependency Chain
```
LocalStorage (token)
userStore.token
userStore.loggedIn (computed)
pages/booking → Check login status
userStore.memberships
userStore.activeMemberships (computed, filtered by ACTIVE)
userStore.hasValidMembership (computed)
pages/booking → Show/hide booking button & membership popup
BookingConfirmPopup ← receives activeMemberships as props
selectedMembershipId (auto-selected on popup show)
bookingStore.slots (array)
pages/booking.selectedPeriod
pages/booking.filteredSlots (computed, filtered by TIME_PERIODS)
v-for → SlotCard components render
Each SlotCard → capacityLabel (computed)
→ capacityClass (computed)
→ Button state determined
bookingStore.loadingSlots (boolean)
pages/booking template
v-if → Show skeleton | Show slots | Show empty state
```
---
## 📋 API Request/Response Chain
```
USER TAPS DATE
pages/booking/onDateSelect()
loadSlots(date)
bookingStore.fetchSlots(date)
get('/time-slot/available', { date })
utils/request.get()
uni.request({
url: 'http://localhost:3000/api/time-slot/available',
method: 'GET',
data: { date: '2026-04-05' },
header: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
}
})
BACKEND: GET /api/time-slot/available?date=2026-04-05
(Queries database for TimeSlot records matching date)
(Fetches current user's bookings for those slots)
(Enriches response with isBookedByMe, myBookingId)
Response: {
"success": true,
"data": [
{
"id": "...",
"date": "2026-04-05",
"startTime": "09:00",
"endTime": "10:00",
"capacity": 1,
"bookedCount": 0,
"status": "OPEN",
"source": "MANUAL",
"templateId": null,
"isBookedByMe": false,
"myBookingId": null
},
...
],
"message": null
}
request.ts success callback
├─ Check: statusCode < 400 ✓
├─ Check: body.success === true ✓
├─ Extract: body.data (TimeSlotWithBookingStatus[])
└─ Resolve promise with data
bookingStore.fetchSlots() try block
├─ slots.value = data
└─ loadingSlots.value = false
Component template reactivity
├─ Re-render with new slots
├─ Compute filteredSlots
└─ Render SlotCard components
```

View File

@@ -1,894 +0,0 @@
# WeChat Mini-Program Booking Page Analysis
## mp-pilates Project (Uni-app + Vue 3)
---
## 📋 Project Structure Overview
```
packages/app/src/
├── pages/
│ └── booking/
│ └── index.vue # 📍 Main booking page
├── components/
│ ├── DateSelector.vue # Date picker (7 days)
│ ├── TimePeriodFilter.vue # Morning/Afternoon/Evening filter
│ ├── SlotCard.vue # Individual time slot card
│ └── BookingConfirmPopup.vue # Confirmation modal
├── stores/
│ ├── booking.ts # 📍 Booking state management
│ └── user.ts # User/membership state
└── utils/
├── request.ts # API request utilities
└── format.ts # Date/time formatting utilities
```
---
## 🎯 API Flow
### Endpoint: `/api/time-slot/available?date=YYYY-MM-DD`
**Request:**
- Method: `GET`
- Query params: `date` (YYYY-MM-DD format)
- Authentication: Bearer token from localStorage
**Response Format (from your example):**
```json
{
"success": true,
"data": [
{
"id": "string (UUID)",
"date": "2026-04-05",
"startTime": "09:00",
"endTime": "10:00",
"capacity": 1,
"bookedCount": 0,
"status": "OPEN",
"source": "MANUAL",
"templateId": null,
"isBookedByMe": false,
"myBookingId": null
}
],
"message": null
}
```
**Status Values:**
- `OPEN` - Available to book
- `FULL` - All slots booked
- `CLOSED` - Time slot closed
**Source Values:**
- `MANUAL` - Manually created
- `TEMPLATE` - Generated from template
---
## 🔄 Complete Data Flow Diagram
```
User Opens Booking Page
[onMounted] Lifecycle Hook
1. Check if logged in + fetch memberships (if needed)
2. Load today's slots: bookingStore.fetchSlots(today)
bookingStore.fetchSlots(date: string)
request.get<TimeSlotWithBookingStatus[]>(
'/time-slot/available',
{ date }
)
Sets: bookingStore.slots = [TimeSlotWithBookingStatus[], ...]
Vue renders via computed: filteredSlots
User selects date OR filters by time period
Updates: selectedDate.value or selectedPeriod.value
Computed filteredSlots re-calculates
Renders SlotCard components
User taps "可预约" (Book Button)
[onBookTap(slot)]
- Check login (if not → show login modal)
- Check valid membership (if not → show purchase modal)
- Show BookingConfirmPopup
User selects membership + confirms
[onConfirmBooking(payload)]
- bookingStore.createBooking({timeSlotId, membershipId})
- POST /api/booking
- Refresh slots: loadSlots(selectedDate.value)
Success/Error Toast
```
---
## 📄 File-by-File Analysis
### 1⃣ **pages/booking/index.vue** (Main Component)
**Template Structure:**
```
.booking-page
├── .sticky-header (z-index: 100)
│ ├── DateSelector (v-model="selectedDate")
│ └── TimePeriodFilter (v-model="selectedPeriod")
├── scroll-view.slot-scroll
│ ├── Loading skeleton (4 cards) - when loadingSlots
│ ├── Empty state - when no slots
│ └── SlotCard list - main content
│ └── SlotCard (v-for="slot in filteredSlots")
└── BookingConfirmPopup (conditional)
```
**Script Setup - State Variables:**
```typescript
selectedDate: ref<string> // YYYY-MM-DD format
selectedPeriod: ref<PeriodKey> // 'MORNING'|'AFTERNOON'|'EVENING'|null
showConfirmPopup: ref<boolean> // Modal visibility
pendingSlot: ref<Slot | null> // Slot being booked
refreshing: ref<boolean> // Pull-to-refresh state
```
**Computed Properties:**
```typescript
scrollHeight: computed(() => {
// Calculates scroll area height:
// windowHeight - headerHeight (220rpx) - tabbarHeight (100rpx)
// Converts rpx to pixels dynamically
})
filteredSlots: computed(() => {
// If no period selected: return all slots
// If period selected: filter by TIME_PERIODS[selectedPeriod].start/.end
// Compares slot.startTime with period.start and period.end
})
```
**Key Lifecycle - onMounted():**
```typescript
1. If logged in but no memberships fetched yet:
await userStore.fetchMemberships()
2. Load today's slots:
await loadSlots(formatDate(new Date()))
```
**Event Handlers:**
**onDateSelect(date: string)** → Changes selectedDate, calls loadSlots()
**onPeriodChange(period)** → Updates selectedPeriod (filtering is automatic via computed)
**onRefresh()** → Pull-to-refresh handler
```typescript
refreshing.value = true
await loadSlots(selectedDate.value)
refreshing.value = false
```
**onBookTap(slot)** → Book button clicked:
1. Check login status → show login modal if needed
2. Check hasValidMembership → show purchase modal if needed
3. Set pendingSlot = slot
4. Show BookingConfirmPopup
**onConfirmBooking(payload)** → User confirms booking:
```typescript
await bookingStore.createBooking(payload)
// payload: { timeSlotId, membershipId }
await loadSlots(selectedDate.value) // Refresh
```
**onCancelTap(slot)** → Cancel booking:
```typescript
if (!slot.myBookingId) return
// Show confirmation modal
await bookingStore.cancelBooking(slot.myBookingId)
await loadSlots(selectedDate.value) // Refresh
```
**Styles:**
- Page background: `#f5f3f0` (light beige)
- Sticky header with box-shadow
- Loading skeleton with shimmer animation
- Empty state centered with image
---
### 2⃣ **stores/booking.ts** (State Management)
**State:**
```typescript
slots: ref<readonly TimeSlotWithBookingStatus[]>([])
myBookings: ref<readonly BookingWithDetails[]>([])
upcomingBookings: ref<readonly BookingWithDetails[]>([])
loadingSlots: ref<boolean>(false)
loadingBookings: ref<boolean>(false)
```
**Actions:**
**fetchSlots(date: string)**
```typescript
async function fetchSlots(date: string) {
loadingSlots.value = true
try {
slots.value = await get<TimeSlotWithBookingStatus[]>(
'/time-slot/available',
{ date } // ← date as query param
)
} catch (err) {
console.error('Fetch slots failed:', err)
slots.value = []
} finally {
loadingSlots.value = false
}
}
```
⚠️ **CRITICAL:** If request fails, slots.value becomes empty []
**createBooking(dto: CreateBookingDto)**
```typescript
// dto: { timeSlotId: string; membershipId: string }
const result = await post<BookingWithDetails>('/booking', dto)
return result
```
**cancelBooking(bookingId: string)**
```typescript
const result = await put<BookingWithDetails>(`/booking/${bookingId}/cancel`)
return result
```
**fetchMyBookings(status?: string)**
```typescript
const params = status ? { status } : {}
myBookings.value = await get<BookingWithDetails[]>('/booking/my', params)
```
**fetchUpcomingBookings()**
```typescript
upcomingBookings.value = await get<BookingWithDetails[]>('/booking/my/upcoming')
```
---
### 3⃣ **components/SlotCard.vue** (Individual Slot)
**Props:**
```typescript
interface Props {
slot: TimeSlotWithBookingStatus
}
```
**Emits:**
```typescript
book: [slot] // User wants to book
cancel: [slot] // User wants to cancel
```
**Template Sections:**
**1. Time & Capacity:**
```vue
<text>{{ slot.startTime.slice(0, 5) }} - {{ slot.endTime.slice(0, 5) }}</text>
<!-- e.g., "09:00 - 10:00" -->
<view class="slot-capacity" :class="capacityClass">
{{ capacityLabel }}
</view>
```
**2. Action Buttons (4 States):**
**State A: OPEN + not booked by me**
```vue
<view class="btn btn-book">可预约</view>
<!-- Tan/brown button, emits: book -->
```
**State B: OPEN + booked by me**
```vue
<view class="badge-booked">已预约</view>
<view class="btn-cancel">取消</view>
<!-- Badge + cancel link, emits: cancel -->
```
**State C: FULL**
```vue
<view class="btn btn-disabled">已约满</view>
<!-- Gray disabled button -->
```
**State D: CLOSED**
```vue
<view class="btn btn-disabled">已关闭</view>
<!-- Gray disabled button -->
```
**3. Booked Indicator:**
```vue
<view v-if="slot.isBookedByMe" class="booked-bar" />
<!-- Tan bar on left side of card when booked by me -->
```
**Computed Properties:**
**capacityLabel:**
```typescript
if (status === CLOSED) return '已关闭'
return `${bookedCount}/${capacity}` // e.g., "0/1 人"
```
**capacityClass:** Determines background color
```
CLOSED → cap-closed (gray)
FULL → cap-full (red bg, red text)
≥80% → cap-almost (orange bg, orange text)
<80% → cap-open (green bg, green text)
```
**Styles:**
- Card: white background, 20rpx border-radius, shadow
- Time text: 36rpx, bold, dark
- Capacity badge: 22rpx, inline-flex, colored backgrounds
- Buttons: rounded pills (68rpx height, 34rpx border-radius)
- Cancel text: underlined, red (#ef4444)
- Booked bar: 6rpx tan bar on left edge
---
### 4⃣ **components/DateSelector.vue** (Date Picker)
**Props:**
```typescript
interface Props {
modelValue: string // YYYY-MM-DD
}
```
**Emits:**
- `update:modelValue` - v-model update
- `select` - Custom event on selection
**Data:**
```typescript
dateRange: computed(() => getDateRange(DATE_SELECTOR_DAYS))
// DATE_SELECTOR_DAYS = 7
// Returns array of { date, weekday, isToday }
```
**Template:**
```vue
<scroll-view scroll-x>
<view class="track">
<view v-for="item in dateRange" class="date-item"
:class="{ active: item.date === modelValue, today: item.isToday }">
<text class="weekday">{{ item.isToday ? '今天' : item.weekday }}</text>
<text class="day">{{ getDayNumber(item.date) }}</text>
<text class="month">{{ getMonthNumber(item.date) }}</text>
</view>
</view>
</scroll-view>
```
**Date Display Format:**
- Weekday: "周一", "周二", or "今天"
- Day: Large bold number (e.g., "5")
- Month: Small number (e.g., "4月")
**Styles:**
- Active state: tan background (#c9a87c), white text
- Today highlight: tan-colored weekday text (even if not active)
- Horizontal scroll, no scrollbar
---
### 5⃣ **components/TimePeriodFilter.vue** (Period Filter)
**Props:**
```typescript
type PeriodKey = keyof typeof TIME_PERIODS | null
interface Props {
modelValue: PeriodKey
}
```
**Emits:**
- `update:modelValue` - v-model update
- `change` - Custom event
**Constants:**
```typescript
const TIME_PERIODS = {
MORNING: { label: '上午', start: '06:00', end: '12:00' },
AFTERNOON: { label: '下午', start: '12:00', end: '18:00' },
EVENING: { label: '晚上', start: '18:00', end: '22:00' },
}
```
**Tabs Generated:**
```typescript
[
{ key: null, label: '全部' },
{ key: 'MORNING', label: '上午' },
{ key: 'AFTERNOON', label: '下午' },
{ key: 'EVENING', label: '晚上' },
]
```
**Template:**
```vue
<view v-for="tab in tabs" :class="{ active: modelValue === tab.key }">
{{ tab.label }}
</view>
```
**Active State:**
- Text color: tan (#c9a87c), weight: 600
- Bottom border: 4rpx tan underline (CSS ::after)
---
### 6⃣ **components/BookingConfirmPopup.vue** (Confirmation Modal)
**Props:**
```typescript
visible: boolean
slot: TimeSlotWithBookingStatus | null
memberships: MembershipWithCardType[]
```
**Emits:**
- `confirm` - { timeSlotId, membershipId }
- `cancel` - Popup closes
- `update:visible` - Manual visibility control
**Template Sections:**
**1. Overlay Mask:**
```vue
<view v-if="visible" class="popup-mask" @tap="handleMaskTap">
<!-- Clicking mask closes popup -->
</view>
```
**2. Header:**
```vue
<text class="popup-title">确认预约</text>
<view class="close-btn"></view>
```
**3. Info Section (read-only display):**
```
日期: 2026-04-05
时间: 09:00 - 10:00
剩余: 1 个名额
```
**4. Membership Card Selection:**
**Case A: 1 membership**
```vue
<view class="card-item selected">
💳
{{ membership.cardType.name }}
剩余 {{ remainingTimes }}
</view>
```
(Auto-selected, pre-filled)
**Case B: Multiple memberships**
```vue
<view v-for="m in memberships" class="card-item"
:class="{ selected: selectedMembershipId === m.id }">
<!-- User taps to select -->
</view>
```
**5. Deduction Tip:**
```vue
<view v-if="selectedMembership" class="deduction-tip">
确认后将从{{ selectedMembership.cardType.name }}扣除 1 次课时
</view>
```
**6. Action Buttons:**
```
[取消] [确认预约]
(Outline) (Tan solid)
(Disabled if no membership selected)
```
**Auto-selection Logic:**
```typescript
watch([() => props.visible, () => props.memberships],
([visible, memberships]) => {
if (visible && memberships.length > 0) {
selectedMembershipId.value = memberships[0].id
}
},
{ immediate: true }
)
```
**Confirm Handler:**
```typescript
function handleConfirm() {
emit('confirm', {
timeSlotId: props.slot.id,
membershipId: selectedMembershipId.value,
})
}
```
**Styles:**
- Modal: Fixed positioning, rgba(0,0,0,0.45) dark overlay
- Panel: White background, rounded top corners, 32rpx padding
- Card items: 24rpx padding, border, transition on select
- Buttons: 88rpx height, rounded pills (44rpx)
- Cancel: Outline style, gray text
- Confirm: Solid tan background, white text
---
### 7⃣ **stores/user.ts** (User State)
**Key State:**
```typescript
user: ref<UserProfileResponse | null>(null)
memberships: ref<readonly MembershipWithCardType[]>([])
token: ref<string>(uni.getStorageSync('token'))
```
**Key Computed:**
```typescript
loggedIn: computed(() => !!token.value)
activeMemberships: computed(() =>
memberships.value.filter(m => m.status === MembershipStatus.ACTIVE)
)
hasValidMembership: computed(() => activeMemberships.value.length > 0)
```
**Key Actions:**
```typescript
async function login()
async function fetchMemberships()
// GET /membership/my
async function logout()
```
---
### 8⃣ **utils/request.ts** (API Client)
**Base URL Logic:**
```typescript
const BASE_URL = (() => {
const { miniProgram } = uni.getAccountInfoSync()
if (miniProgram.envVersion !== 'develop') {
return 'https://focus.richarjiang.com/api'
}
return 'http://localhost:3000/api'
})()
```
**Main request() function:**
```typescript
function request<T>(options: RequestOptions): Promise<T> {
// 1. Get token from localStorage
const token = uni.getStorageSync('token')
// 2. Call uni.request with:
// - Authorization header (Bearer token)
// - Content-Type: application/json
// 3. Response handling:
// - 401 → Clear token, show "please login", reject
// - ≥400 → Extract error from response.message, reject
// - <400 & success: true → Resolve with data
// - <400 & success: false → Reject with message
// 4. Network fail → Reject with errMsg
}
export function get<T>(url, data?): Promise<T>
export function post<T>(url, data?): Promise<T>
export function put<T>(url, data?): Promise<T>
```
**⚠️ GET Request Issue:**
```typescript
// In get(), data becomes the request body
// But uni.request with GET should NOT have a body
// Query params should be in the URL string
// This might cause issues on some platforms!
```
---
### 9⃣ **utils/format.ts** (Date Utilities)
```typescript
formatDate(date): string
// Returns YYYY-MM-DD
getWeekdayLabel(date): string
// Returns "周一", "周二", ..., "周日"
isToday(date): boolean
// Compares year/month/day
getDateRange(days: number): ReadonlyArray
// Returns array of:
// {
// date: YYYY-MM-DD,
// weekday: "周一" | "今天" (if i===0),
// isToday: boolean
// }
// Uses i * 86400000ms for date increment
```
---
## 🔍 Data Types Overview
### TimeSlotWithBookingStatus (Extended from TimeSlot)
```typescript
interface TimeSlotWithBookingStatus extends TimeSlot {
readonly isBookedByMe: boolean // Has user already booked?
readonly myBookingId: string | null // ID needed to cancel
}
interface TimeSlot {
readonly id: string // UUID
readonly date: string // YYYY-MM-DD
readonly startTime: string // HH:MM
readonly endTime: string // HH:MM
readonly capacity: number // Max people
readonly bookedCount: number // Already booked
readonly status: TimeSlotStatus // OPEN|FULL|CLOSED
readonly source: TimeSlotSource // TEMPLATE|MANUAL
readonly templateId: string | null
}
```
### MembershipWithCardType
```typescript
interface MembershipWithCardType {
readonly id: string
readonly cardType: CardType
readonly status: MembershipStatus // ACTIVE|EXPIRED|USED_UP
readonly remainingTimes: number | null
readonly expireDate: string // YYYY-MM-DD
}
```
### CreateBookingDto
```typescript
interface CreateBookingDto {
readonly timeSlotId: string
readonly membershipId: string
}
```
---
## 🎨 Color Scheme
| Element | Color | Hex | Usage |
|---------|-------|-----|-------|
| Primary (Accent) | Tan/Brown | #c9a87c | Buttons, active tabs, highlights |
| Background | Light Beige | #f5f3f0 | Page background |
| Text Primary | Dark Gray | #1a1a1a | Main headings |
| Text Secondary | Medium Gray | #666/#999 | Labels, descriptions |
| Text Tertiary | Light Gray | #bbb | Disabled, hints |
| Success | Green | #4caf50 | Open slots (capacity label) |
| Warning | Orange | #f59e0b | Almost full (capacity label) |
| Error | Red | #ef4444 | Full/closed, cancel button |
| Borders | Very Light Gray | #f0f0f0/#f0ece8 | Dividers, borders |
---
## ⚠️ Potential Issues & Problems
### 1. **GET Request Body Issue**
**File:** `utils/request.ts` in `get()` function
```typescript
export function get<T>(url: string, data?: Record<string, unknown>): Promise<T> {
return request<T>({ url, method: 'GET', data }) // ← data as body!
}
```
**Problem:** GET requests shouldn't have a body. Query params should be in the URL.
**Impact:** `/time-slot/available?date=2026-04-05` might not work on all platforms.
### 2. **Empty Slots Array on Error**
**File:** `stores/booking.ts`, `fetchSlots()`
```typescript
catch (err) {
console.error('Fetch slots failed:', err)
slots.value = [] // ← Clears state on error!
}
```
**Problem:** Network error → page shows "empty state" instead of error message.
**Impact:** Users can't tell if there's an error or truly no slots available.
### 3. **No Error Handling in Main Page**
**File:** `pages/booking/index.vue`, `loadSlots()`
```typescript
async function loadSlots(date: string) {
await bookingStore.fetchSlots(date)
// ← No error handling, no user feedback
}
```
**Problem:** If fetchSlots() fails, user sees empty page with no explanation.
### 4. **Manual Date Calculation**
**File:** `utils/format.ts`, `getDateRange()`
```typescript
const d = new Date(now.getTime() + i * 86400000)
```
**Problem:** Doesn't account for DST transitions. Using `Date.setDate()` would be safer.
### 5. **No Loading State for Slots**
**File:** `pages/booking/index.vue`
```typescript
<view v-if="bookingStore.loadingSlots && !refreshing" class="loading-wrap">
```
**Problem:** Skeleton appears only on initial load, not when changing dates or refreshing.
**Impact:** Date changes appear instant (good UX but confusing if slow network).
### 6. **Hardcoded Membership Message**
**File:** `components/BookingConfirmPopup.vue`
```typescript
{{ selectedMembership.cardType.name }} 1
// ← Always says "1 次" even if card might deduct different amounts
```
**Problem:** Doesn't show actual deduction amount if dynamic.
---
## 📊 Event Flow Sequence
```
1. PAGE LOAD (onMounted)
├─ Check: userStore.loggedIn?
├─ If yes & no memberships: fetchMemberships()
└─ loadSlots(today)
└─ GET /time-slot/available?date=today
└─ bookingStore.slots = [...]
└─ render SlotCard components
2. USER TAPS DATE
├─ selectedDate.value = newDate
└─ onDateSelect(newDate)
└─ loadSlots(newDate)
└─ fetchSlots()
3. USER FILTERS PERIOD
├─ selectedPeriod.value = MORNING|AFTERNOON|EVENING|null
└─ filteredSlots computed updates
└─ SlotCards re-render (no new API call)
4. USER PULLS TO REFRESH
├─ onRefresh()
└─ loadSlots(selectedDate.value)
5. USER TAPS "可预约" BUTTON
├─ onBookTap(slot)
├─ Check login (if not → login modal)
├─ Check membership (if not → purchase modal)
└─ Show BookingConfirmPopup
└─ Pre-select first membership
6. USER CONFIRMS BOOKING
├─ onConfirmBooking({timeSlotId, membershipId})
├─ POST /booking
│ └─ bookingStore.createBooking()
├─ Show success toast
└─ loadSlots(selectedDate.value) // Refresh
└─ Updated slot.isBookedByMe = true
7. USER TAPS "取消" BUTTON
├─ onCancelTap(slot)
├─ Confirm modal
├─ PUT /booking/:id/cancel
│ └─ bookingStore.cancelBooking()
├─ Show success toast
└─ loadSlots(selectedDate.value) // Refresh
└─ Updated slot.isBookedByMe = false
```
---
## 🧪 Testing Scenarios
### ✅ Happy Path
- [ ] Load page → today's slots display
- [ ] Tap date → slots for that date display
- [ ] Filter by period → slots filtered correctly
- [ ] Tap "可预约" → popup shows with correct time/date
- [ ] Select membership → deduction message updates
- [ ] Confirm → booking created, slot shows "已预约"
- [ ] Pull to refresh → slots reload
- [ ] Tap "取消" → booking cancelled, slot back to "可预约"
### ⚠️ Edge Cases
- [ ] No slots for date → empty state appears
- [ ] User not logged in → login modal shows
- [ ] No valid membership → purchase modal shows
- [ ] Network error → ??? (currently shows empty)
- [ ] Slot changes to FULL → button becomes disabled
- [ ] Slot changes to CLOSED → button becomes disabled
---
## 🔧 Integration Points
**From Backend:**
1. ✅ GET `/time-slot/available?date=...` → Returns slots
2. ✅ POST `/booking` → Create booking
3. ✅ PUT `/booking/:id/cancel` → Cancel booking
4. ✅ GET `/membership/my` → List memberships
5. ✅ Auth via Bearer token
**From Frontend:**
1. ✅ LocalStorage for token persistence
2. ✅ uni.showModal, uni.showToast for UI feedback
3. ✅ uni.getSystemInfoSync() for responsive sizing
4. ✅ uni.navigateTo() for page navigation
---
## 📱 Responsive Layout
**Design Breakpoint:**
- Base: 750rpx (WeChat standard width unit)
- Window height: dynamic via uni.getSystemInfoSync().windowHeight
**Scroll Area Height Calculation:**
```typescript
scrollHeight = windowHeight - headerHeight(220rpx) - tabbarHeight(100rpx)
= windowHeight - (220 * (windowWidth / 750)) - (100 * (windowWidth / 750))
```
**Sticky Header:**
- Position: sticky (CSS)
- Top: 0
- Z-index: 100
- Contains: DateSelector + TimePeriodFilter
---
## 🎯 Summary
The booking system is well-architected with:
- ✅ Clear separation of concerns (component, store, utils)
- ✅ Proper type safety with TypeScript
- ✅ Responsive date/time selection
- ✅ Membership-based booking validation
- ✅ Optimistic loading states
- ✅ Accessible UI patterns
But needs:
- ⚠️ Better error handling
- ⚠️ Fix GET request implementation
- ⚠️ Loading state during date/period changes
- ⚠️ Network error user feedback

View File

@@ -1,395 +0,0 @@
# Booking Page Documentation
## 📚 Overview
This folder contains comprehensive documentation for the WeChat Mini-Program booking system in the mp-pilates project (Uni-app + Vue 3).
### 📄 Documentation Files
1. **BOOKING_PAGE_ANALYSIS.md** ⭐ START HERE
- Complete file-by-file breakdown of all components
- Data flow diagrams
- API contract documentation
- Color scheme and styling details
- Potential issues and problems
2. **COMPONENT_HIERARCHY.md**
- Visual component tree structure
- State management flow (Pinia stores)
- API sequence diagrams
- State machine for slot cards
- Data transformations
3. **QUICK_REFERENCE.md**
- Code snippets for quick lookup
- Debugging tips and console commands
- Common issues and solutions
- Debugging checklist
- API examples
---
## 🎯 Quick Navigation
### I want to understand...
**...the overall flow**
→ Read: BOOKING_PAGE_ANALYSIS.md → "Complete Data Flow Diagram" section
**...how the UI is structured**
→ Read: COMPONENT_HIERARCHY.md → "Component Tree" + "UI Layout Breakdown"
**...where specific code is**
→ Read: QUICK_REFERENCE.md → "Finding Specific Things"
**...how to debug an issue**
→ Read: QUICK_REFERENCE.md → "Common Issues & Solutions"
**...the API contracts**
→ Read: QUICK_REFERENCE.md → "API Contract Summary"
**...the store state**
→ Read: COMPONENT_HIERARCHY.md → "State Management Flow"
---
## 🏗️ Project Structure
```
packages/app/src/
├── pages/
│ └── booking/
│ └── index.vue # Main booking page (311 lines)
├── components/
│ ├── DateSelector.vue # Date picker (50 lines)
│ ├── TimePeriodFilter.vue # Time period filter (50 lines)
│ ├── SlotCard.vue # Individual slot card (230 lines)
│ └── BookingConfirmPopup.vue # Booking confirmation modal (430 lines)
├── stores/
│ ├── booking.ts # Booking state (72 lines)
│ └── user.ts # User/membership state (110 lines)
└── utils/
├── request.ts # API request utilities (80 lines)
└── format.ts # Date formatting utilities (50 lines)
packages/shared/src/
├── types/
│ ├── time-slot.ts # TimeSlot types
│ ├── api.ts # API response types
│ └── booking.ts # Booking types
├── constants.ts # TIME_PERIODS, etc
└── enums.ts # Enums (TimeSlotStatus, etc)
```
---
## 🔄 Data Flow at a Glance
```
Page Load
[Check login + load memberships]
Store: fetchSlots(today)
API: GET /time-slot/available?date=TODAY
State: bookingStore.slots = [TimeSlotWithBookingStatus[], ...]
Computed: filteredSlots (optionally filtered by period)
Render: SlotCard components
User interaction:
- Tap date → loadSlots(newDate)
- Filter period → filteredSlots re-computed
- Book slot → onBookTap() → popup
- Confirm → createBooking() → refresh slots
- Cancel → cancelBooking() → refresh slots
```
---
## 🎭 Key Components
### 1. pages/booking/index.vue
**Role:** Main page that orchestrates everything
**State:** selectedDate, selectedPeriod, showConfirmPopup, pendingSlot
**Stores:** bookingStore, userStore
**Key computed:** scrollHeight, filteredSlots
### 2. components/SlotCard.vue
**Role:** Displays individual time slot
**Props:** slot (TimeSlotWithBookingStatus)
**Emits:** book, cancel
**States:** 4 button states based on status + isBookedByMe
### 3. components/DateSelector.vue
**Role:** Horizontal date picker
**Props:** modelValue (YYYY-MM-DD)
**Data:** dateRange (7 days from today)
**Display:** Shows weekday, day number, month
### 4. components/TimePeriodFilter.vue
**Role:** Horizontal tab filter
**Props:** modelValue (MORNING|AFTERNOON|EVENING|null)
**Constants:** TIME_PERIODS from shared
### 5. components/BookingConfirmPopup.vue
**Role:** Modal for confirming booking
**Props:** visible, slot, memberships
**State:** selectedMembershipId (auto-selected on show)
**Logic:** Auto-select first membership when popup opens
### 6. stores/booking.ts
**Actions:**
- fetchSlots(date) → GET /time-slot/available?date=
- createBooking(dto) → POST /booking
- cancelBooking(bookingId) → PUT /booking/:id/cancel
- fetchMyBookings(status?) → GET /booking/my
- fetchUpcomingBookings() → GET /booking/my/upcoming
### 7. stores/user.ts
**Computed:**
- loggedIn: !!token.value
- hasValidMembership: activeMemberships.length > 0
- activeMemberships: memberships filtered by ACTIVE status
---
## 📊 State Types
### TimeSlotWithBookingStatus
```typescript
{
id: string // UUID
date: "2026-04-05" // YYYY-MM-DD
startTime: "09:00" // HH:MM
endTime: "10:00" // HH:MM
capacity: 1 // Max slots
bookedCount: 0 // Currently booked
status: "OPEN" | "FULL" | "CLOSED"
source: "MANUAL" | "TEMPLATE"
templateId: null
isBookedByMe: boolean // User has booked this
myBookingId: string | null // Booking ID (for cancel)
}
```
### MembershipWithCardType
```typescript
{
id: string
cardType: { name: string, ... }
status: "ACTIVE" | "EXPIRED" | "USED_UP"
remainingTimes: number | null
expireDate: "2026-12-31"
}
```
---
## 🎨 Visual States
### Slot Card Button States
| Condition | Button | Color | Action |
|-----------|--------|-------|--------|
| OPEN, not booked | "可预约" | Tan (#c9a87c) | Show popup |
| OPEN, booked by me | "已预约" + "取消" link | Tan + Red | Show cancel confirm |
| FULL | "已约满" | Gray (#f0f0f0) | Disabled |
| CLOSED | "已关闭" | Gray (#f0f0f0) | Disabled |
### Capacity Badge Colors
| Condition | Background | Text | Meaning |
|-----------|------------|------|---------|
| <80% booked | #f0faf3 | #4caf50 | Green - Plenty of spots |
| ≥80% booked | #fff8ed | #f59e0b | Orange - Almost full |
| FULL | #fef0f0 | #ef4444 | Red - No spots |
| CLOSED | #f5f5f5 | #999 | Gray - Unavailable |
---
## 🔐 Authentication
- Token stored in localStorage
- Automatically included in request headers
- 401 response → Clear token + show "please login" toast
- onBookTap checks loggedIn → shows login modal if needed
- onBookTap checks hasValidMembership → shows purchase modal if needed
---
## 📡 API Endpoints
### GET /time-slot/available?date=YYYY-MM-DD
```
Query: date (required, YYYY-MM-DD format)
Returns: TimeSlotWithBookingStatus[]
Auth: Bearer token required
```
### POST /booking
```
Body: { timeSlotId, membershipId }
Returns: BookingWithDetails
Auth: Bearer token required
```
### PUT /booking/:bookingId/cancel
```
Path: bookingId
Returns: BookingWithDetails (with status: CANCELLED)
Auth: Bearer token required
```
### GET /membership/my
```
Returns: MembershipWithCardType[]
Auth: Bearer token required
```
---
## ⚠️ Known Issues
### 1. GET Request Body Issue
- File: `utils/request.ts`, `get()` function
- Problem: Data passed as body instead of query params
- Impact: Might not work on all platforms
### 2. Error Handling
- File: `stores/booking.ts`, `fetchSlots()`
- Problem: Network error → empty array instead of error message
- Impact: Users can't tell if error or truly no slots
### 3. Loading State
- File: `pages/booking/index.vue`
- Problem: Skeleton only appears on initial load
- Impact: Date changes appear instant (confusing on slow network)
### 4. Date Math
- File: `utils/format.ts`, `getDateRange()`
- Problem: Uses ms arithmetic (86400000ms per day)
- Impact: Doesn't account for DST transitions
---
## 🧪 Testing Checklist
### Happy Path
- [ ] Load page → today's slots display
- [ ] Tap date → slots change for that date
- [ ] Filter by period → slots filtered correctly
- [ ] Tap "可预约" → popup shows
- [ ] Confirm booking → slot shows "已预约"
- [ ] Tap "取消" → booking cancelled, slot resets
- [ ] Pull to refresh → slots reload
### Edge Cases
- [ ] No slots for date → empty state appears
- [ ] Not logged in → login modal on book tap
- [ ] No valid membership → purchase modal on book tap
- [ ] Network error → ??? (currently shows empty)
- [ ] Slot becomes FULL → button updates to disabled
- [ ] Multiple memberships → can select different card
---
## 📝 File Sizes
| File | Lines | Purpose |
|------|-------|---------|
| pages/booking/index.vue | 311 | Main page orchestration |
| components/BookingConfirmPopup.vue | 430 | Booking modal |
| components/SlotCard.vue | 230 | Slot display |
| stores/booking.ts | 72 | Booking state |
| utils/request.ts | 80 | API client |
| components/DateSelector.vue | 50 | Date picker |
| components/TimePeriodFilter.vue | 50 | Period filter |
| utils/format.ts | 50 | Date utilities |
---
## 🎓 Learning Path
**Level 1: Overview**
1. Read this file
2. Look at BOOKING_PAGE_ANALYSIS.md → "Complete Data Flow Diagram"
**Level 2: Components**
1. Read COMPONENT_HIERARCHY.md → "Component Tree"
2. Read BOOKING_PAGE_ANALYSIS.md → "File-by-File Analysis"
**Level 3: Implementation**
1. Read QUICK_REFERENCE.md → "Where Slots Come From"
2. Read actual source files in order:
- stores/booking.ts
- pages/booking/index.vue
- components/SlotCard.vue
- components/BookingConfirmPopup.vue
**Level 4: Debugging**
1. Read QUICK_REFERENCE.md → "Debugging Tips"
2. Read QUICK_REFERENCE.md → "Common Issues & Solutions"
**Level 5: Deep Dive**
1. Read COMPONENT_HIERARCHY.md → "State Management Flow"
2. Read COMPONENT_HIERARCHY.md → "API Calls Sequence"
3. Study utils/request.ts for request handling
---
## 🔗 Related Documentation
- Backend: `/packages/server/src/time-slot/`
- Shared types: `/packages/shared/src/types/`
- Auth: `/packages/app/src/utils/auth.ts`
- User store: `/packages/app/src/stores/user.ts`
---
## 📞 Quick Answers
**Q: Why doesn't the page load?**
A: Check 1) Is API returning data? 2) Is token valid? 3) Check console for errors
**Q: Why doesn't filtering work?**
A: Check 1) Is selectedPeriod.value being set? 2) Is slot.startTime correct format?
**Q: Why doesn't the booking button work?**
A: Check 1) Is slot.status === OPEN? 2) Is isBookedByMe === false? 3) Is user logged in?
**Q: How do I add error handling?**
A: See QUICK_REFERENCE.md → "Issue 1: Slots not loading" → Solution
**Q: How do I test the booking flow?**
A: See "Testing Checklist" section above
---
## 🚀 Common Tasks
### Add loading indicator during date change
→ Use bookingStore.loadingSlots in template
### Show error message for API failures
→ Add error state to bookingStore, show in template
### Change colors/styling
→ Edit style blocks in .vue files (see color scheme in BOOKING_PAGE_ANALYSIS.md)
### Modify time period ranges
→ Edit TIME_PERIODS in packages/shared/src/constants.ts
### Change initial date or time range
→ Edit pages/booking/index.vue onMounted() or DATE_SELECTOR_DAYS constant
### Add/remove date selector days
→ Edit DATE_SELECTOR_DAYS in packages/shared/src/constants.ts
---
Generated: 2026-04-05
Last Updated: BOOKING_PAGE_ANALYSIS.md

View File

@@ -1,218 +0,0 @@
# Card Types Bug Fix - Completion Index
## Quick Links
**Bug Fix Commit**: [a85270e](https://github.com/richarjiang/mp-pilates/commit/a85270e)
**Files Modified**:
- `packages/app/src/pages/admin/card-types.vue` - Added `.stop` modifiers to 3 action buttons
**Documentation Files**:
- `CARD_TYPES_BUG_FIX.md` - Complete bug explanation and fix details
- `MODAL_EVENT_HANDLING_AUDIT.md` - Audit of all application modals
- `CARD_TYPES_ANALYSIS.md` - Deep technical analysis
- `CARD_TYPES_QUICK_REFERENCE.md` - Quick lookup guide
- `EXPLORATION_SUMMARY.md` - Full system overview
---
## The Bug in 30 Seconds
**Problem**: Edit modal closes immediately after opening
**Cause**: Vue event propagation - tap events bubble from action buttons to modal-mask's close handler
**Solution**: Add `.stop` modifier to prevent event bubbling
**Impact**: Users can now edit card types successfully
---
## What Was Changed
### File: packages/app/src/pages/admin/card-types.vue
Three lines modified:
```diff
- <view class="ct-action-btn edit-btn" @tap="openEdit(ct)">
+ <view class="ct-action-btn edit-btn" @tap.stop="openEdit(ct)">
- <view class="ct-action-btn toggle-btn" @tap="toggleActive(ct)">
+ <view class="ct-action-btn toggle-btn" @tap.stop="toggleActive(ct)">
- <view class="ct-action-btn delete-btn" @tap="confirmDelete(ct)">
+ <view class="ct-action-btn delete-btn" @tap.stop="confirmDelete(ct)">
```
---
## Why It Works
The `.stop` modifier calls `event.stopPropagation()`, which prevents the tap event from bubbling to parent elements. This prevents the modal-mask's close handler from being triggered.
**Event flow with fix**:
1. User taps action button ✓
2. Event handler executes (edit/toggle/delete) ✓
3. Event propagation is stopped ✗ (no bubbling)
4. Modal-mask close handler is NOT triggered ✓
5. Modal stays open ✓
---
## Testing Instructions
### Quick Test
1. Go to Admin → Card Types
2. Click any [编辑] (Edit) button
3. Modal should open and stay open
4. Edit a field and click [确认] (Confirm)
5. Changes should save
### Full Test Suite
See `CARD_TYPES_BUG_FIX.md` for complete testing checklist
---
## Documentation Overview
### Bug Fix Documentation
- **CARD_TYPES_BUG_FIX.md** - Complete fix documentation with testing instructions
- **MODAL_EVENT_HANDLING_AUDIT.md** - Audit of all modals + preventive measures
### Feature Documentation
- **CARD_TYPES_ANALYSIS.md** - Deep dive into card types system
- **CARD_TYPES_QUICK_REFERENCE.md** - Quick lookup guide
- **EXPLORATION_SUMMARY.md** - Full system overview
- **CARD_TYPES_INDEX.md** - Master index
### Diagrams
- **CARD_TYPES_FLOW_DIAGRAM.txt** - ASCII art workflows
---
## Key Findings from Audit
**card-types.vue** - FIXED (event propagation issue resolved)
**week-template.vue** - SAFE (separate DOM structure)
**members.vue** - SAFE (single tap handler pattern)
**BookingConfirmPopup.vue** - SAFE (dedicated component)
**Conclusion**: No other files have the same issue.
---
## Commit Information
```
Hash: a85270e
Author: richarjiang <richarjiang@tencent.com>
Date: Sun Apr 5 12:53:03 2026 +0800
Message: fix(admin): prevent edit modal from closing immediately on tap
Fix the card types management edit modal that was closing
immediately after opening due to event propagation. Added
.stop modifier to all action button tap handlers (edit, toggle,
delete) to prevent bubbling to parent modal-mask element.
- Changed @tap="openEdit(ct)" to @tap.stop="openEdit(ct)"
- Changed @tap="toggleActive(ct)" to @tap.stop="toggleActive(ct)"
- Changed @tap="confirmDelete(ct)" to @tap.stop="confirmDelete(ct)"
This fixes the bug where the edit modal would open and close in
the same event cycle, making it impossible to edit card types.
```
---
## Files Changed Summary
| File | Changes | Lines | Type |
|------|---------|-------|------|
| card-types.vue | `.stop` modifiers added | 3 | Fix |
| CARD_TYPES_BUG_FIX.md | New documentation | 132 | Doc |
| MODAL_EVENT_HANDLING_AUDIT.md | New audit report | 200+ | Doc |
**Total**: 2 files modified/created
---
## Next Steps
### Immediate (Before Merge)
1. ✅ Code changes applied
2. ✅ Commit created
3. ✅ Documentation completed
4. □ Manual testing required
5. □ Code review approval needed
### For Deployment
1. Test the fix manually
2. Review commit in GitHub
3. Get team approval
4. Merge to main branch
5. Deploy to staging
6. Deploy to production
### For Prevention
1. Review `MODAL_EVENT_HANDLING_AUDIT.md` guidelines
2. Apply best practices to new code
3. Add E2E tests for modal interactions
4. Consider ESLint rules for modal event handling
---
## Technical Deep Dive
### Problem Pattern
This is a classic Vue event propagation issue that occurs when:
1. List items have action buttons
2. Tap handlers on buttons trigger state changes
3. Modal appears as overlay
4. Modal-mask has a tap handler to close
5. Event bubbles from button → card → list → modal-mask
### Solution Pattern
The fix is to add `.stop` modifier to any event handler that triggers state changes that render overlays:
```vue
<!-- Before: Event bubbles to parent handlers -->
<button @tap="openModal(item)">Edit</button>
<!-- After: Event stops propagating -->
<button @tap.stop="openModal(item)">Edit</button>
```
### Why This Is Safe
- `.stop` only prevents propagation, not default behavior
- Event still executes on the clicked element
- All three buttons work independently
- No side effects or unexpected behavior
- Follows Vue best practices
---
## References
- **Vue Event Modifiers**: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers
- **Event Propagation**: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
- **Uni-app Events**: https://uniapp.dcloud.io/api/ui/intersection-observer
---
## Support & Questions
For questions about this fix:
1. Read `CARD_TYPES_BUG_FIX.md` for detailed explanation
2. Check `MODAL_EVENT_HANDLING_AUDIT.md` for similar patterns
3. Review the commit diff for exact changes
4. Consult Vue 3 event handling documentation
---
**Status**: ✅ COMPLETE - Ready for testing and deployment
**Last Updated**: 2026-04-05

View File

@@ -1,548 +0,0 @@
# Card Types Management Feature - Comprehensive Analysis
## Project Structure
- **Frontend**: `packages/app` (Vue 3 + Uni-app mini-program)
- **Backend**: `packages/server` (NestJS)
- **Shared**: `packages/shared` (types, enums, DTOs)
---
## 1. DATABASE SCHEMA (Prisma)
### CardType Model
**File**: `packages/server/prisma/schema.prisma` (lines 73-91)
```prisma
model CardType {
id String @id @default(uuid())
name String
type CardTypeCategory // TIMES | DURATION | TRIAL
totalTimes Int? // For TIMES/TRIAL cards
durationDays Int // How many days card is valid
price Decimal(10, 0) // Current price (in cents internally)
originalPrice Decimal?(10, 0) // Optional strikethrough price
description String?
isActive Boolean @default(true) // For 上架/下架
sortOrder Int @default(0) // Display order
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships Membership[]
orders Order[]
}
```
### Card Type Category Enum
**File**: `packages/server/prisma/schema.prisma` (lines 17-21)
```prisma
enum CardTypeCategory {
TIMES // Time-based card (e.g., 10 classes)
DURATION // Month card (e.g., 30 days)
TRIAL // Trial card
}
```
**Shared Enum**: `packages/shared/src/enums.ts` (lines 8-12)
```typescript
export enum CardTypeCategory {
TIMES = 'TIMES',
DURATION = 'DURATION',
TRIAL = 'TRIAL',
}
```
---
## 2. SHARED TYPES & DTOs
### CardType Interface
**File**: `packages/shared/src/types/card-type.ts`
```typescript
export interface CardType {
readonly id: string
readonly name: string
readonly type: CardTypeCategory // TIMES | DURATION | TRIAL
readonly totalTimes: number | null // null for DURATION cards
readonly durationDays: number
readonly price: number // In cents, e.g., 98000 = ¥980
readonly originalPrice: number | null
readonly description: string | null
readonly isActive: boolean // true = 销售中, false = 已下架
readonly sortOrder: number
readonly createdAt: string
readonly updatedAt: string
}
```
### CreateCardTypeDto
```typescript
export interface CreateCardTypeDto {
readonly name: string
readonly type: CardTypeCategory
readonly totalTimes?: number
readonly durationDays: number
readonly price: number
readonly originalPrice?: number
readonly description?: string
readonly sortOrder?: number
}
```
### UpdateCardTypeDto
```typescript
export interface UpdateCardTypeDto {
readonly name?: string
readonly totalTimes?: number
readonly durationDays?: number
readonly price?: number
readonly originalPrice?: number
readonly description?: string
readonly isActive?: boolean // For toggling 上架/下架
readonly sortOrder?: number
}
```
---
## 3. SERVER-SIDE IMPLEMENTATION
### Membership Controller
**File**: `packages/server/src/membership/membership.controller.ts`
**Endpoints**:
```typescript
// Public (no auth)
GET /membership/card-types getActiveCardTypes()
// Admin only (JWT + RolesGuard)
GET /admin/card-types getAllCardTypes()
POST /admin/card-types createCardType(dto)
PUT /admin/card-types/:id updateCardType(id, dto)
DELETE /admin/card-types/:id deleteCardType(id)
```
### Membership Service
**File**: `packages/server/src/membership/membership.service.ts`
#### getActiveCardTypes()
- Returns only cards where `isActive: true`
- Sorted by `sortOrder` (ascending)
- Used by regular users/public
#### getAllCardTypes()
- Returns all cards (including inactive)
- Sorted by `sortOrder`
- Admin-only
#### createCardType(dto: CreateCardTypeDto)
- Creates a new card type
- Sets `isActive: true` by default
- `totalTimes` and `description` are optional (default to null)
#### updateCardType(id: string, dto: UpdateCardTypeDto)
- Updates card (all fields optional)
- **Can toggle `isActive`** for 上架/下架
- Can update name, price, duration, etc.
#### deleteCardType(id: string)
- **Soft delete**: doesn't remove from DB
- Sets `isActive: false` instead
- Updates the record
---
## 4. FRONTEND ADMIN PAGE
### Card-Types Page
**File**: `packages/app/src/pages/admin/card-types.vue`
#### Layout Structure:
1. **Toolbar** (top)
- Shows count: "共 X 个卡种"
- "+ 新增卡种" button → `openAdd()`
2. **Card List** (scrollable)
- Each card shows:
- Header band (colored by type: 次卡/月卡/体验卡)
- Status tag (销售中 or 已下架)
- Card name, price, description
- Meta info: times, duration, sort order
- Three action buttons: 编辑, 下架/上架, 删除
3. **Modal/Popup** (add/edit form)
- Title: "新增卡种" or "编辑卡种"
- Input fields:
* 卡种名称 (name)
* 类型 (picker: 次卡, 月卡, 体验卡)
* 现价 (price, digit input)
* 原价 (originalPrice, optional)
* 次数 (totalTimes, optional, required for 次卡)
* 有效天数 (durationDays, required)
* 排序值 (sortOrder, defaults to 0)
* 描述 (description, optional textarea)
- Cancel and Confirm buttons
#### Key Ref Variables:
```typescript
const cardTypes = ref<CardType[]>([])
const loading = ref(false)
const showModal = ref(false)
const submitting = ref(false)
const editTarget = ref<CardType | null>(null)
const form = ref({
name: '',
typeIdx: 0, // Index into typeOptions
priceStr: '', // String, parsed to number
originalPriceStr: '',
totalTimesStr: '',
durationDaysStr: '90', // Default 90 days
sortOrderStr: '0', // Default 0
description: '',
})
```
#### Functions:
**fetchCardTypes()**
- Calls `adminStore.fetchCardTypes()`
- Sets loading state
- Updates `cardTypes` ref
**openAdd()**
- Sets `editTarget = null`
- Resets `form` to initial state
- Sets `showModal = true`
-**Opens new card form**
**openEdit(ct: CardType)**
- Sets `editTarget = ct`
- Populates `form` from card data
- Finds `typeIdx` from typeOptions
- Sets `showModal = true`
-**Opens edit form with card data**
**closeModal()**
- Sets `showModal = false`
- Clears `editTarget`
**submitForm()**
- Validates: name (required), price (required, > 0), durationDays (required, >= 1)
- Parses string inputs to numbers
- Builds payload object
- If `editTarget` exists: calls `adminStore.updateCardType()`
- Else: calls `adminStore.createCardType()`
- Shows success toast and refetches list
- Catches errors and shows error toast
**toggleActive(ct: CardType)**
- Calls `adminStore.updateCardType(ct.id, { isActive: !ct.isActive })`
- Refetches list
-**上架/下架 button action**
**confirmDelete(ct: CardType)**
- Shows confirmation modal: "删除卡种「X」此操作不可恢复。"
- If confirmed: calls `adminStore.deleteCardType(ct.id)`
- Soft deletes (sets isActive: false)
- Shows success toast
- Refetches list
#### Helper Functions:
**typeLabel(ct: CardType): string**
- Maps enum to Chinese: TIMES → '次卡', DURATION → '月卡', TRIAL → '体验卡'
**headerClass(ct: CardType): string**
- Returns CSS class for colored header banner
---
## 5. ADMIN STORE (Pinia)
**File**: `packages/app/src/stores/admin.ts`
```typescript
export const useAdminStore = defineStore('admin', () => {
// ─── Card types ───────────────────
const cardTypes = ref<CardType[]>([])
async function fetchCardTypes(): Promise<CardType[]> {
const data = await get<CardType[]>('/admin/card-types')
cardTypes.value = [...data].sort((a, b) => a.sortOrder - b.sortOrder)
return cardTypes.value
}
async function createCardType(dto: CreateCardTypeDto): Promise<CardType> {
const data = await post<CardType>('/admin/card-types', dto)
await fetchCardTypes() // Refetch to get updated list
return data
}
async function updateCardType(id: string, dto: UpdateCardTypeDto): Promise<CardType> {
const data = await put<CardType>(`/admin/card-types/${id}`, dto)
await fetchCardTypes() // Refetch to get updated list
return data
}
async function deleteCardType(id: string): Promise<void> {
await del(`/admin/card-types/${id}`)
await fetchCardTypes() // Refetch to get updated list
}
return {
cardTypes,
fetchCardTypes,
createCardType,
updateCardType,
deleteCardType,
// ... other admin functions
}
})
```
---
## 6. WORKFLOW FLOWS
### Adding a New Card Type
1. User taps "+ 新增卡种" button
2. `openAdd()` is called
- `editTarget = null`
- `form` reset to defaults
- `showModal = true`
3. Modal appears with empty form
4. User fills in form fields
5. User taps "确认" button
6. `submitForm()` validates, builds payload, calls `adminStore.createCardType(payload)`
7. Backend creates new CardType (with `isActive: true` by default)
8. Admin store refetches list
9. Page updates with new card
10. Modal closes automatically
### Editing a Card Type
1. User taps "编辑" button on a card
2. `openEdit(ct)` is called
- `editTarget = ct`
- `form` populated from card data
- `showModal = true`
3. Modal appears with prefilled form
4. User modifies fields
5. User taps "确认" button
6. `submitForm()` validates, builds payload, calls `adminStore.updateCardType(id, payload)`
7. Backend updates CardType
8. Admin store refetches list
9. Page updates with new data
10. Modal closes automatically
### Toggling Active Status (上架/下架)
1. User taps "下架" or "上架" button
2. `toggleActive(ct)` is called
- Calls `adminStore.updateCardType(ct.id, { isActive: !ct.isActive })`
3. Backend updates `isActive` field
4. Admin store refetches list
5. Page re-renders:
- If `isActive: false`: card becomes semi-transparent (opacity: 0.6)
- Status tag changes from "销售中" to "已下架"
- Button text changes
### Deleting a Card Type
1. User taps "删除" button
2. `confirmDelete(ct)` is called
- Shows confirmation dialog
3. User confirms deletion
4. `adminStore.deleteCardType(ct.id)` called
5. Backend does soft delete: sets `isActive: false`
6. Admin store refetches list
7. Page updates (card marked as inactive)
---
## 7. API COMMUNICATION
### Request Utility
**File**: `packages/app/src/utils/request.ts`
```typescript
const BASE_URL = 'http://localhost:3000/api' // or production URL
// Helper functions
async function get<T>(url: string, data?: Record<string, unknown>): Promise<T>
async function post<T>(url: string, data?: Record<string, unknown>): Promise<T>
async function put<T>(url: string, data?: Record<string, unknown>): Promise<T>
async function del<T>(url: string, data?: Record<string, unknown>): Promise<T>
```
**Response Format**:
```typescript
interface ApiResponse<T> {
success: boolean
data: T | null
message: string | null
}
```
All admin endpoints require:
- JWT Bearer token (from storage)
- User role must be ADMIN
---
## 8. PRICE HANDLING
**Important**: Prices are stored as integers (cents) in DB and API
- ¥980 is stored as `98000` cents
- Frontend displays formatted: `¥980.00`
**Formatting**:
```typescript
export function formatPrice(cents: number): string {
return (cents / 100).toFixed(2) // 98000 → "980.00"
}
```
**In Page**: `¥{{ formatPrice(ct.price) }}`
---
## 9. CARD TYPE CATEGORIES
### TIMES Card (次卡)
- Used for class count-based purchases
- Example: "10次课套餐"
- **Required fields**: `totalTimes` (e.g., 10)
- Optional fields: `originalPrice`, `description`
- Color: Dark blue gradient (`#1a1a2e` to `#2d2d5e`)
### DURATION Card (月卡)
- Used for time-period-based purchases
- Example: "30天卡"
- **Required fields**: `durationDays`
- `totalTimes` is optional/not used
- Color: Purple gradient (`#6c3483` to `#9b59b6`)
### TRIAL Card (体验卡)
- Used for trial/sample purchases
- Color: Gold/tan gradient (`#7d6608` to `#c9a87c`)
---
## 10. FIELD REQUIREMENTS & VALIDATION
| Field | Create | Update | Type | Validation |
|-------|--------|--------|------|-----------|
| name | ✓ Required | Optional | string | Trimmed, non-empty |
| type | ✓ Required | Optional | enum | TIMES \| DURATION \| TRIAL |
| totalTimes | Optional | Optional | integer | Min: 1 |
| durationDays | ✓ Required | Optional | integer | Min: 1 |
| price | ✓ Required | Optional | number | Min: 0 |
| originalPrice | Optional | Optional | number | Min: 0 |
| description | Optional | Optional | string | Max: 200 chars |
| sortOrder | Optional | Optional | integer | Min: 0, default: 0 |
| isActive | N/A | Optional | boolean | default: true on create |
---
## 11. POTENTIAL ISSUES & BUG: Edit Popup Closes Immediately
### Issue Description
When user taps "编辑" button, the edit modal popup closes immediately instead of staying open.
### Root Cause Analysis
Looking at the template structure (lines 85-195 of card-types.vue):
```vue
<view v-if="showModal" class="modal-mask" @tap.self="closeModal">
<scroll-view scroll-y class="modal">
<!-- Form content -->
</scroll-view>
</view>
```
**The problem**:
1. User taps "编辑" button on a card (line 67)
2. `openEdit(ct)` sets `showModal = true`
3. Modal appears
4. BUT: The tap event likely **bubbles** or there's a **race condition**
5. The click that triggered `openEdit()` might also trigger `closeModal()`
### Potential Causes:
1. **Event Propagation Issue**:
- The edit button tap might bubble to parent elements
- The modal-mask has `@tap.self="closeModal"`
- If the modal appears in the same frame, the tap event might close it
2. **Modal Rendering Timing**:
- If modal renders synchronously in the same event tick
- The tap event (which hasn't finished propagating) might hit the modal-mask
3. **Vue/Uni-app Quirk**:
- Some mini-program frameworks have event timing issues
- The `.self` modifier might not work as expected with rapid re-renders
### Solution Approaches:
1. **Add click guard**: Prevent tap on edit button from propagating
```vue
<view class="ct-action-btn edit-btn" @tap.stop="openEdit(ct)">
```
2. **Add delay for modal rendering**: Let Vue finish the current cycle
```typescript
function openEdit(ct: CardType) {
editTarget.value = ct
form.value = { ... }
// Delay modal show to next tick
nextTick(() => {
showModal.value = true
})
}
```
3. **Track modal state change**: Ignore tap events for a brief moment after modal opens
```typescript
const modalJustOpened = ref(false)
function openEdit(ct: CardType) {
editTarget.value = ct
form.value = { ... }
showModal.value = true
modalJustOpened.value = true
setTimeout(() => {
modalJustOpened.value = false
}, 100)
}
function closeModal() {
if (!modalJustOpened.value) {
showModal.value = false
editTarget.value = null
}
}
```
4. **Restructure modal trigger**:
- Separate the button from the modal in the DOM
- Or use a completely different event model
---
## SUMMARY OF ALL FILES REVIEWED
1. ✅ Frontend page: `packages/app/src/pages/admin/card-types.vue` (607 lines)
2. ✅ Admin store: `packages/app/src/stores/admin.ts` (198 lines)
3. ✅ Shared types: `packages/shared/src/types/card-type.ts` (39 lines)
4. ✅ Server controller: `packages/server/src/membership/membership.controller.ts` (68 lines)
5. ✅ Server service: `packages/server/src/membership/membership.service.ts` (173 lines)
6. ✅ Create DTO: `packages/server/src/membership/dto/create-card-type.dto.ts` (45 lines)
7. ✅ Update DTO: `packages/server/src/membership/dto/update-card-type.dto.ts` (49 lines)
8. ✅ Prisma schema: `packages/server/prisma/schema.prisma` (205 lines)
9. ✅ Shared enums: `packages/shared/src/enums.ts` (47 lines)
10. ✅ Format utils: `packages/app/src/utils/format.ts` (46 lines)
11. ✅ Request utils: `packages/app/src/utils/request.ts` (80 lines)
12. ✅ Membership types: `packages/shared/src/types/membership.ts` (19 lines)
13. ✅ API types: `packages/shared/src/types/api.ts` (20 lines)

View File

@@ -1,132 +0,0 @@
# Card Types Edit Modal Bug Fix
## Bug Description
When a user taps the **[编辑]** (Edit) button in the card types admin page, the edit modal opens briefly but **closes immediately** in the same event cycle. This makes it impossible to edit card types.
### Root Cause
The bug was caused by Vue event propagation/bubbling:
1. User taps edit button → `@tap="openEdit(ct)"` fires
2. `openEdit()` sets `showModal.value = true`
3. Modal is rendered and displayed
4. The tap event **bubbles up** to the parent modal-mask element
5. Modal-mask has `@tap.self="closeModal"` which immediately closes the modal
6. Result: Modal opens and closes in the same event tick
### Code Location
File: `packages/app/src/pages/admin/card-types.vue`
**Before (buggy):**
```vue
<!-- Line 67 -->
<view class="ct-action-btn edit-btn" @tap="openEdit(ct)">
<text class="ct-action-text">编辑</text>
</view>
<!-- Line 73 -->
<view class="ct-action-btn toggle-btn" @tap="toggleActive(ct)">
...
</view>
<!-- Line 77 -->
<view class="ct-action-btn delete-btn" @tap="confirmDelete(ct)">
...
</view>
<!-- Line 85 - Modal mask -->
<view v-if="showModal" class="modal-mask" @tap.self="closeModal">
...
</view>
```
## Solution Applied
Added the `.stop` modifier to all action button tap handlers to **prevent event propagation** to parent elements:
```vue
<!-- Line 67 - FIXED -->
<view class="ct-action-btn edit-btn" @tap.stop="openEdit(ct)">
<text class="ct-action-text">编辑</text>
</view>
<!-- Line 73 - FIXED -->
<view class="ct-action-btn toggle-btn" @tap.stop="toggleActive(ct)">
...
</view>
<!-- Line 77 - FIXED -->
<view class="ct-action-btn delete-btn" @tap.stop="confirmDelete(ct)">
...
</view>
```
## Why This Works
The `.stop` modifier is equivalent to calling `event.stopPropagation()`. It prevents the tap event from bubbling up the DOM tree, so:
1. User taps edit button → `@tap.stop="openEdit(ct)"` fires
2. Event propagation is **stopped** - event does NOT bubble to modal-mask
3. `openEdit()` sets `showModal.value = true`
4. Modal renders and stays open ✓
## Technical Details
### Vue Event Modifiers Used
- **`.stop`** - Calls `event.stopPropagation()` to prevent event bubbling
### Affected Operations
Three actions were fixed:
1. **Edit** (编辑) - Opens form to edit selected card type
2. **Toggle** (上架/下架) - Toggles active status (on/off shelf)
3. **Delete** (删除) - Opens confirmation dialog for deletion
## Testing Instructions
To verify the fix works:
1. Navigate to Admin → Card Types Management
2. Click the **[编辑]** button on any card
3. Verify the edit modal opens and **stays open**
4. Edit form fields and confirm the changes save correctly
5. Test the toggle button (上架/下架) - should toggle without closing modal
6. Test the delete button - should show confirmation dialog
## Code Changes Summary
| File | Line | Change | Type |
|------|------|--------|------|
| card-types.vue | 67 | `@tap="openEdit(ct)"``@tap.stop="openEdit(ct)"` | Fix |
| card-types.vue | 73 | `@tap="toggleActive(ct)"``@tap.stop="toggleActive(ct)"` | Fix |
| card-types.vue | 77 | `@tap="confirmDelete(ct)"``@tap.stop="confirmDelete(ct)"` | Fix |
Total changes: **3 lines modified**
## Impact Assessment
- **Severity**: High - Feature completely broken, users cannot edit card types
- **Risk**: Very Low - Simple modifier addition, no logic changes
- **Testing**: Quick manual test needed
- **Performance**: No impact
- **Breaking Changes**: None
- **Backward Compatibility**: Fully compatible
## Related Documentation
See the following files for comprehensive feature documentation:
- `CARD_TYPES_ANALYSIS.md` - Deep dive into the feature
- `CARD_TYPES_QUICK_REFERENCE.md` - Quick lookup guide
- `EXPLORATION_SUMMARY.md` - Full system overview
- `CARD_TYPES_INDEX.md` - Master index with all references
## Next Steps
1. ✅ Apply the fix (COMPLETED)
2. Test the feature manually
3. Verify all three action buttons work correctly
4. Consider adding automated E2E tests for card type management
5. Review other modals for similar event propagation issues

View File

@@ -1,228 +0,0 @@
╔═══════════════════════════════════════════════════════════════════════════════╗
║ CARD TYPES MANAGEMENT - COMPLETE FLOW DIAGRAM ║
╚═══════════════════════════════════════════════════════════════════════════════╝
┌─────────────────────────────────────────────────────────────────────────────┐
│ DATABASE TIER (Prisma/MySQL) │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────┐ ┌──────────────────────────┐ │
│ │ CardType Model │ │ CardTypeCategory Enum │ │
│ ├─────────────────────────┤ ├──────────────────────────┤ │
│ │ id (UUID) │ │ TIMES (classes) │ │
│ │ name (String) │ │ DURATION (months) │ │
│ │ type (Enum) ───────────────┐ │ TRIAL (trial) │ │
│ │ totalTimes (Int?) │ │ └──────────────────────────┘ │
│ │ durationDays (Int) │ │ │
│ │ price (Decimal) │ └─────────────────────────────────────────┤
│ │ originalPrice (Decimal?)│ │
│ │ description (String?) │ ┌──────────────────────┐ │
│ │ isActive (Boolean) │────→│ Soft Delete Strategy │ │
│ │ sortOrder (Int) │ │ DELETE = isActive=false │
│ │ createdAt/updatedAt │ └──────────────────────┘ │
│ └─────────────────────────┘ │
│ │
│ Relationships: ← Membership (many), Order (many) │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ API TIER (NestJS Backend) - packages/server/src/membership/ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ MembershipController MembershipService │
│ ┌────────────────────────┐ ┌──────────────────────────┐ │
│ │ GET /membership/... │ │ getActiveCardTypes() │ │
│ │ GET /admin/card-types │──────────→ │ getAllCardTypes() │ │
│ │ POST /admin/... │ │ createCardType(dto) │ │
│ │ PUT /admin/.../id │────────┐ │ updateCardType(id, dto) │ │
│ │ DELETE /admin/.../id │ │ │ deleteCardType(id) │ │
│ └────────────────────────┘ │ └──────────────────────────┘ │
│ ↓ │ ↓ │
│ Validators: └→ PrismaService (DB calls) │
│ - JwtAuthGuard (token required) │
│ - RolesGuard (ADMIN role only) │
│ │
│ Request DTOs: Response Types: │
│ ┌─CreateCardTypeDto───┐ ┌──CardType────────┐ │
│ │ name ✓ │ │ id │ │
│ │ type ✓ │ │ name │ │
│ │ durationDays ✓ │ │ type │ │
│ │ price ✓ │ ─────────→ │ totalTimes │ │
│ │ totalTimes? │ │ durationDays │ │
│ │ originalPrice? │ │ price │ │
│ │ description? │ │ originalPrice │ │
│ │ sortOrder? │ │ isActive │ │
│ └─────────────────────┘ │ sortOrder │ │
│ └──────────────────┘ │
│ ┌─UpdateCardTypeDto───┐ │
│ │ (all fields optional) Includes isActive toggle! │
│ │ name? │
│ │ type? │
│ │ price? │
│ │ isActive? ──────────────────────→ 上架/下架 functionality │
│ │ ... etc ... │
│ └─────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ SHARED TYPES TIER - packages/shared/src/types/ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ TypeScript Interfaces & Enums │
│ ├── CardType (read-only interface) │
│ ├── CreateCardTypeDto │
│ ├── UpdateCardTypeDto │
│ └── CardTypeCategory Enum: TIMES | DURATION | TRIAL │
│ │
│ Shared across Frontend & Backend │
│ ✓ Type safety │
│ ✓ Request/Response validation │
│ ✓ Documentation │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ FRONTEND TIER (Vue 3 + Uni-app) - packages/app/src/ │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────────┐ │
│ │ card-types.vue - Admin Management Page │ │
│ ├───────────────────────────────────────────────────────────────┤ │
│ │ │ │
│ │ ┌─── Toolbar ───────────────────────────┐ │ │
│ │ │ "共 X 个卡种" [ 新增卡种] │ │ │
│ │ │ │ │ │
│ │ │ ↓ tap │ │ │
│ │ │ openAdd() ────────────────────┐ │ │ │
│ │ └───────────────────────────────────┼───┘ │ │
│ │ │ │ │
│ │ ┌─── Card List ──────────────────────┼────┐ │ │
│ │ │ for each cardType: │ │ │ │
│ │ │ ┌────────────────────────────────┐ │ │ │ │
│ │ │ │ [Header band - colored by type]│ │ │ │ │
│ │ │ │ Card Name, ¥Price │ │ │ │ │
│ │ │ │ Duration, Times, Description │ │ │ │ │
│ │ │ ├────────────────────────────────┤ │ │ │ │
│ │ │ │ [编辑] [下架] [删除] │ │ │ │ │
│ │ │ │ ↓ ↓ ↓ │ │ │ │ │
│ │ │ │ open toggle delete │ │ │ │ │
│ │ │ │ Edit() Active() Confirm() │ │ │ │ │
│ │ │ └────────────────────────────────┘ │ │ │ │
│ │ └────────────────────────────────────┼────┘ │ │
│ │ │ │ │
│ │ ┌─── Modal/Popup ────────────────────┼────┐ │ │
│ │ │ @tap.self="closeModal" on mask │ │ │ │
│ │ │ v-if="showModal" │ │ │ │
│ │ │ ┌────────────────────────────────┐ │ │ │ │
│ │ │ │ 新增卡种 / 编辑卡种 │ │ │ │ │
│ │ │ ├────────────────────────────────┤ │ │ │ │
│ │ │ │ 卡种名称 [input] │ │ │ │ │
│ │ │ │ 类型 [picker] │ │ │ │ │
│ │ │ │ 现价 [digit] │ │ │ │ │
│ │ │ │ 原价 [digit] │ │ │ │ │
│ │ │ │ 次数 [number] │ │ │ │ │
│ │ │ │ 有效天数 [number] │ │ │ │ │
│ │ │ │ 排序值 [number] │ │ │ │ │
│ │ │ │ 描述 [textarea] │ │ │ │ │
│ │ │ ├────────────────────────────────┤ │ │ │ │
│ │ │ │ [取消] [确认] │ │ │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ │ ↓ tap │ │ │ │ │
│ │ │ │ submitForm() ────┐ │ │ │ │ │
│ │ │ │ closeModal() │ │ │ │ │ │
│ │ │ │ editTarget = null│ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ └───────────────────┼───────────┘ │ │ │ │
│ │ └─────────────────────┼──────────────┘ │ │ │
│ │ │ │ │ │
│ │ Reactive State: │ │ │ │
│ │ ├─ cardTypes: [] │ │ │ │
│ │ ├─ showModal: false │ │ │ │
│ │ ├─ editTarget: null │ │ │ │
│ │ ├─ form: { │ │ │ │
│ │ │ name, typeIdx, │ │ │ │
│ │ │ priceStr, ... │ │ │ │
│ │ │ } │ │ │ │
│ │ └─ submitting: false │ │ │ │
│ │ │ │ │ │
│ └───────────────────────┼───────────────────┘ │ │
│ │ │ │
│ ┌──────────────────────────────────────┐ │ │
│ │ admin.ts (Pinia Store) │ │ │
│ ├──────────────────────────────────────┤ │ │
│ │ cardTypes: CardType[] │ │ │
│ │ │ │ │
│ │ fetchCardTypes() │ │ │
│ │ ├─ GET /admin/card-types ────────────┼────────────────────┘ │
│ │ ├─ return sorted list │ │
│ │ └─ update state │ │
│ │ │ │
│ │ createCardType(dto) │ │
│ │ ├─ POST /admin/card-types ─────→ Backend │
│ │ └─ refetch list │ │
│ │ │ │
│ │ updateCardType(id, dto) ─────────┐ │ │
│ │ ├─ PUT /admin/card-types/:id │ │ │
│ │ └─ refetch list │ │ │
│ │ │ │ │
│ │ deleteCardType(id) │ │ │
│ │ ├─ DELETE /admin/card-types/:id │ │ │
│ │ └─ refetch list │ │ │
│ └──────────────────────────────────┘ │ │
│ │ │
│ utils/request.ts │ │
│ ├─ get() │ │
│ ├─ post() │ │
│ ├─ put() │ │
│ └─ del() │ │
│ All with JWT Bearer token │ │
└─────────────────────────────────────────────────────────────────────┘
╔══════════════════════════════════════════════════════════════════════════════╗
║ CRITICAL BUG: Edit Popup Closes Immediately ║
╠══════════════════════════════════════════════════════════════════════════════╣
║ ║
║ SYMPTOM: When tapping [编辑], modal appears then instantly closes ║
║ ║
║ ROOT CAUSE: Event propagation issue ║
║ 1. User taps [编辑] button ║
║ 2. openEdit() sets showModal = true ║
║ 3. Modal renders with @tap.self="closeModal" ║
║ 4. Tap event might propagate to modal-mask in same tick ║
║ 5. closeModal() fires immediately ║
║ 6. Modal closes ║
║ ║
║ SOLUTIONS: ║
║ ║
║ Option 1: Stop propagation (RECOMMENDED - SIMPLE) ║
║ @tap.stop="openEdit(ct)" <!-- Add .stop modifier --> ║
║ ║
║ Option 2: Use nextTick() for modal rendering ║
║ function openEdit(ct: CardType) { ║
║ editTarget.value = ct ║
║ form.value = { ... } ║
║ nextTick(() => { ║
║ showModal.value = true // Defer to next frame ║
║ }) ║
║ } ║
║ ║
║ Option 3: State guard with timeout ║
║ const modalJustOpened = ref(false) ║
║ ║
║ function openEdit(ct: CardType) { ║
║ editTarget.value = ct ║
║ form.value = { ... } ║
║ showModal.value = true ║
║ modalJustOpened.value = true ║
║ setTimeout(() => { modalJustOpened.value = false }, 100) ║
║ } ║
║ ║
║ function closeModal() { ║
║ if (!modalJustOpened.value) { ║
║ showModal.value = false ║
║ editTarget.value = null ║
║ } ║
║ } ║
║ ║
╚══════════════════════════════════════════════════════════════════════════════╝

View File

@@ -1,244 +0,0 @@
# 卡种管理 (Card Types Management) - Documentation Index
**Exploration Date**: April 5, 2026
**Total Files Analyzed**: 13 source files (~1,800 lines)
**Documentation Created**: 4 comprehensive guides (1,546 lines)
---
## 📖 Documentation Files
### 1. **EXPLORATION_SUMMARY.md** ⭐ START HERE
**Best for**: Quick overview of the entire system and key findings
- What was explored (13 files, 1,800 lines)
- Documentation generated
- Key findings summary
- File inventory
- Complete workflows
- Bug identification
- Next steps
- Statistics
**Read time**: 15-20 minutes
**Size**: 12 KB, 428 lines
---
### 2. **CARD_TYPES_QUICK_REFERENCE.md** 📋 FOR LOOKUP
**Best for**: Quick lookup when working on the code
- File quick links with line numbers
- Key data model (CardType entity)
- API endpoints
- DTOs & validation rules
- UI components structure
- Form fields list
- Operations guide (Add, Edit, Toggle, Delete)
- React refs & state
- Admin store methods
- **Bug explanation with 3 solutions** ⚡
- Price handling notes
- Testing checklist
- Card type categories
**Read time**: 10 minutes
**Size**: 10 KB, 342 lines
---
### 3. **CARD_TYPES_ANALYSIS.md** 📚 FOR DEEP DIVE
**Best for**: Understanding every detail of the system
**11 Sections**:
1. Project structure
2. Database schema (Prisma)
3. Shared types & DTOs
4. Server-side implementation
5. Frontend admin page
6. Admin store (Pinia)
7. Workflow flows
8. API communication
9. Price handling
10. Card type categories
11. **Detailed bug analysis** with root cause
**Read time**: 30-40 minutes
**Size**: 16 KB, 548 lines
---
### 4. **CARD_TYPES_FLOW_DIAGRAM.txt** 🎨 FOR VISUALIZATION
**Best for**: Understanding data flow and architecture visually
- Database tier diagram
- API tier diagram
- Shared types tier
- Frontend tier (page structure, store, state)
- Complete operation flows (Add, Edit, Toggle, Delete)
- **Bug analysis with solutions**
**Read time**: 20 minutes
**Size**: 24 KB, 228 lines (ASCII art)
---
## 🎯 How to Use This Documentation
### Scenario 1: "I need to understand the whole system"
1. Start with **EXPLORATION_SUMMARY.md** (overview)
2. Look at **CARD_TYPES_FLOW_DIAGRAM.txt** (visual)
3. Dive into **CARD_TYPES_ANALYSIS.md** (details)
### Scenario 2: "I need to find something specific"
→ Use **CARD_TYPES_QUICK_REFERENCE.md** (index & lookup)
### Scenario 3: "I need to fix the edit modal bug"
→ Jump to **CARD_TYPES_QUICK_REFERENCE.md** → Section "THE BUG" or
→ Read **CARD_TYPES_ANALYSIS.md** → Section 11 "Detailed bug analysis"
### Scenario 4: "I need to see how data flows"
→ Check **CARD_TYPES_FLOW_DIAGRAM.txt**
### Scenario 5: "I'm new to this project"
→ Read in order:
1. EXPLORATION_SUMMARY.md
2. CARD_TYPES_FLOW_DIAGRAM.txt
3. CARD_TYPES_QUICK_REFERENCE.md (bookmark for later)
4. CARD_TYPES_ANALYSIS.md (as needed for details)
---
## 🔍 Quick File Locations
### Frontend
- Admin page: `packages/app/src/pages/admin/card-types.vue` (607 lines)
- Pinia store: `packages/app/src/stores/admin.ts` (198 lines)
### Backend
- Controller: `packages/server/src/membership/membership.controller.ts` (68 lines)
- Service: `packages/server/src/membership/membership.service.ts` (173 lines)
- Create DTO: `packages/server/src/membership/dto/create-card-type.dto.ts` (45 lines)
- Update DTO: `packages/server/src/membership/dto/update-card-type.dto.ts` (49 lines)
### Database
- Prisma schema: `packages/server/prisma/schema.prisma` (205 lines)
### Shared Types
- Card types: `packages/shared/src/types/card-type.ts` (39 lines)
- Enums: `packages/shared/src/enums.ts` (47 lines)
---
## ⚡ The Critical Bug
**What**: Edit modal closes immediately when user taps [编辑] button
**Why**: Event propagation issue - tap event bubbles to modal-mask's @tap.self
**Where to Fix**: Line 67 of `packages/app/src/pages/admin/card-types.vue`
**Simple Fix**: Change `@tap="openEdit(ct)"` to `@tap.stop="openEdit(ct)"`
**See Also**:
- CARD_TYPES_QUICK_REFERENCE.md → "THE BUG" section
- CARD_TYPES_ANALYSIS.md → Section 11
- CARD_TYPES_FLOW_DIAGRAM.txt → Bottom (3 solutions shown)
---
## 📊 Key Statistics
| Aspect | Count |
|--------|-------|
| Source files analyzed | 13 |
| Total lines of code | ~1,800 |
| API endpoints | 5 |
| Card type categories | 3 (TIMES, DURATION, TRIAL) |
| Core operations | 4 (Create, Read, Update, Delete) |
| Documentation files | 4 |
| Documentation lines | 1,546 |
| Bugs identified | 1 |
| Bug severity | High (UX-breaking) |
---
## 🎨 Card Type Categories
1. **次卡 (TIMES)**: Class count-based (e.g., 10 classes) - Dark blue
2. **月卡 (DURATION)**: Time period-based (e.g., 30 days) - Purple
3. **体验卡 (TRIAL)**: Trial cards - Gold/tan
---
## 🔐 Auth & Security
- Admin endpoints require JWT Bearer token
- Admin endpoints require ADMIN role
- Public endpoint (GET /membership/card-types) returns only active cards
---
## 💾 Database Details
**CardType Model**:
- Soft delete (set isActive=false, not removed from DB)
- Relationships: Membership (many), Order (many)
- Indexed on: isActive, sortOrder
---
## 📝 API Endpoints
| Method | Endpoint | Auth | Purpose |
|--------|----------|------|---------|
| GET | /membership/card-types | None | Get active cards (public) |
| GET | /admin/card-types | JWT+Admin | Get all cards (admin) |
| POST | /admin/card-types | JWT+Admin | Create card |
| PUT | /admin/card-types/:id | JWT+Admin | Update card (can toggle isActive) |
| DELETE | /admin/card-types/:id | JWT+Admin | Soft delete card |
---
## 🧪 Testing Checklist
- [ ] Create new card with all types
- [ ] Edit existing card
- [ ] Toggle card status (上架/下架)
- [ ] Delete card (soft delete works)
- [ ] List updates after each operation
- [ ] Modal closes after submit
- [ ] **FIX**: Edit modal stays open (not closes immediately)
---
## 🚀 Next Steps
1. **Quick start**: Read EXPLORATION_SUMMARY.md (15 min)
2. **Deep dive**: Read CARD_TYPES_ANALYSIS.md (30 min)
3. **Reference**: Bookmark CARD_TYPES_QUICK_REFERENCE.md
4. **Implement bug fix** (5 min)
5. **Test thoroughly** (15 min)
---
## 💡 Price Handling
**Critical**: Prices are stored as integers (cents)
- ¥980 = 98000 cents
- Display: formatPrice(98000) = "980.00"
---
## 📚 Related Documentation
- `ADMIN_SCHEDULING_EXPLORATION.md` - Scheduling feature
- `BOOKING_ARCHITECTURE_DIAGRAM.md` - Booking system
- `BOOKING_PAGE_ANALYSIS.md` - Booking pages
- `SCHEDULING_QUICK_REFERENCE.md` - Scheduling reference
---
**Generated**: 2026-04-05
**Ready to**: Implement features, fix bugs, deploy updates

View File

@@ -1,342 +0,0 @@
# Card Types Management - Quick Reference Guide
## 📁 File Quick Links
| Purpose | File Path | Lines |
|---------|-----------|-------|
| **Frontend** | | |
| Admin page | `packages/app/src/pages/admin/card-types.vue` | 607 |
| Store (Pinia) | `packages/app/src/stores/admin.ts` | 198 |
| Request utils | `packages/app/src/utils/request.ts` | 80 |
| Format utils | `packages/app/src/utils/format.ts` | 46 |
| **Backend** | | |
| Controller | `packages/server/src/membership/membership.controller.ts` | 68 |
| Service | `packages/server/src/membership/membership.service.ts` | 173 |
| Create DTO | `packages/server/src/membership/dto/create-card-type.dto.ts` | 45 |
| Update DTO | `packages/server/src/membership/dto/update-card-type.dto.ts` | 49 |
| **Database** | | |
| Prisma schema | `packages/server/prisma/schema.prisma` | 205 |
| **Shared** | | |
| Card types | `packages/shared/src/types/card-type.ts` | 39 |
| Enums | `packages/shared/src/enums.ts` | 47 |
| API types | `packages/shared/src/types/api.ts` | 20 |
| Membership types | `packages/shared/src/types/membership.ts` | 19 |
---
## 🎯 Key Data Model
### CardType Entity
```typescript
{
id: string (UUID)
name: string // e.g., "10次课套餐"
type: 'TIMES' | 'DURATION' | 'TRIAL'
totalTimes: number | null // For TIMES/TRIAL cards
durationDays: number // How many days valid
price: number (cents) // ¥980 = 98000
originalPrice: number | null // Strikethrough price
description: string | null
isActive: boolean // 上架(true) / 下架(false)
sortOrder: number // Display order (ascending)
createdAt: DateTime
updatedAt: DateTime
}
```
---
## 🔄 API Endpoints
### Public (No Auth)
```
GET /membership/card-types Returns active cards only
```
### Admin Only (JWT + ADMIN Role)
```
GET /admin/card-types Get all cards (including inactive)
POST /admin/card-types Create new card
PUT /admin/card-types/:id Update card (can toggle isActive)
DELETE /admin/card-types/:id Soft delete (sets isActive=false)
```
---
## 📝 DTOs & Validation
### CreateCardTypeDto
| Field | Required | Type | Validation |
|-------|----------|------|-----------|
| name | ✓ | string | Must be non-empty |
| type | ✓ | enum | TIMES \| DURATION \| TRIAL |
| durationDays | ✓ | int | Min: 1 |
| price | ✓ | number | Min: 0 |
| totalTimes | - | int | Min: 1 (optional) |
| originalPrice | - | number | Min: 0 (optional) |
| description | - | string | Max: 200 (optional) |
| sortOrder | - | int | Min: 0 (optional, default: 0) |
### UpdateCardTypeDto
- All fields optional (partial update)
- Can toggle `isActive` for 上架/下架
---
## 🎨 UI Components
### Page Structure
```
┌─────────────────────────────────────────┐
│ Toolbar: "共 X 个卡种" [ 新增卡种] │
├─────────────────────────────────────────┤
│ Card List │
│ ┌───────────────────────────────────────┐ │
│ │ [Colored Header Band] │ │
│ │ Card Name, ¥Price, Duration, etc │ │
│ │ [编辑] [上架/下架] [删除] │ │
│ └───────────────────────────────────────┘ │
│ ... more cards ... │
├─────────────────────────────────────────┤
│ Modal (Add/Edit Form) │
│ - Title: 新增卡种 / 编辑卡种 │
│ - Input fields │
│ - [取消] [确认] buttons │
└─────────────────────────────────────────┘
```
### Header Colors by Type
- **次卡 (TIMES)**: Dark blue `linear-gradient(90deg, #1a1a2e, #2d2d5e)`
- **月卡 (DURATION)**: Purple `linear-gradient(90deg, #6c3483, #9b59b6)`
- **体验卡 (TRIAL)**: Gold/tan `linear-gradient(90deg, #7d6608, #c9a87c)`
---
## 📋 Form Fields in Modal
```
卡种名称 text input
类型 picker (次卡, 月卡, 体验卡)
现价(元) digit input
原价(元) digit input (optional)
次数 number input (optional)
有效天数 number input (required, default: 90)
排序值 number input (default: 0)
描述 textarea (optional)
```
---
## 🔄 Operations
### ADD New Card Type
1. Tap [ 新增卡种]
2. Modal opens with empty form
3. Fill fields (name, type, price, duration required)
4. Tap [确认]
5. Backend creates card (isActive=true by default)
6. Modal closes, list updates
### EDIT Card Type
1. Tap [编辑] on a card
2. Modal opens with prefilled form
3. Modify desired fields
4. Tap [确认]
5. Backend updates card
6. Modal closes, list updates
### TOGGLE Status (上架/下架)
1. Tap [上架] or [下架]
2. Backend updates `isActive` toggle
3. List re-renders
- Card becomes transparent if `isActive=false`
- Status tag and button text change
### DELETE Card Type
1. Tap [删除]
2. Confirmation dialog appears
3. If confirmed: backend soft-deletes (isActive=false)
4. List updates
---
## ⚙️ React Refs & State
```typescript
const cardTypes = ref<CardType[]>([]) // Current list
const loading = ref(false) // Loading spinner
const showModal = ref(false) // Modal visibility
const submitting = ref(false) // Form submission state
const editTarget = ref<CardType | null>(null) // Card being edited (null=add)
const form = ref({
name: '',
typeIdx: 0, // Index into typeOptions array
priceStr: '', // String (parsed to number on submit)
originalPriceStr: '',
totalTimesStr: '',
durationDaysStr: '90', // Default 90 days
sortOrderStr: '0', // Default 0
description: '',
})
```
---
## 💾 Admin Store Methods
```typescript
// Fetch all cards (including inactive)
await adminStore.fetchCardTypes(): Promise<CardType[]>
// Create new card
await adminStore.createCardType(dto: CreateCardTypeDto): Promise<CardType>
// Update card (all fields optional)
// Can toggle isActive, change price, name, etc.
await adminStore.updateCardType(id: string, dto: UpdateCardTypeDto): Promise<CardType>
// Delete card (soft delete: sets isActive=false)
await adminStore.deleteCardType(id: string): Promise<void>
```
**Note**: All mutations refetch the list automatically
---
## 🐛 THE BUG: Edit Modal Closes Immediately
### Symptom
When user taps [编辑], the edit modal opens then immediately closes.
### Root Cause
Event propagation issue:
1. User taps [编辑] button
2. `openEdit()` runs and sets `showModal = true`
3. Modal renders in same event tick
4. Tap event propagates to `modal-mask` which has `@tap.self="closeModal"`
5. Modal closes instantly
### Current Code (Buggy)
```vue
<view class="ct-action-btn edit-btn" @tap="openEdit(ct)">
<text class="ct-action-text">编辑</text>
</view>
<!-- Modal -->
<view v-if="showModal" class="modal-mask" @tap.self="closeModal">
<!-- ... form ... -->
</view>
```
### Solutions (Pick One)
**Option 1: Stop Propagation (RECOMMENDED)**
```vue
<view class="ct-action-btn edit-btn" @tap.stop="openEdit(ct)">
<!-- Add .stop modifier to prevent bubbling -->
</view>
```
**Option 2: Use nextTick()**
```typescript
import { nextTick } from 'vue'
function openEdit(ct: CardType) {
editTarget.value = ct
form.value = { ... populate ... }
nextTick(() => {
showModal.value = true // Render in next frame
})
}
```
**Option 3: Guard with State**
```typescript
const modalJustOpened = ref(false)
function openEdit(ct: CardType) {
editTarget.value = ct
form.value = { ... }
showModal.value = true
modalJustOpened.value = true
setTimeout(() => { modalJustOpened.value = false }, 100)
}
function closeModal() {
if (!modalJustOpened.value) { // Ignore if just opened
showModal.value = false
editTarget.value = null
}
}
```
**Recommendation**: Use **Option 1** (@tap.stop) - it's simplest and most idiomatic.
---
## 💡 Price Handling
**Important**: Prices are stored as **integers (cents)** in DB and API
- Frontend sends: `{ price: 98000 }` for ¥980
- Display: `formatPrice(98000)``"980.00"`
```typescript
// Utility function
export function formatPrice(cents: number): string {
return (cents / 100).toFixed(2)
}
// Usage in template
¥{{ formatPrice(ct.price) }}
```
---
## 🧪 Testing Checklist
- [ ] Can create new card with all field types
- [ ] Can edit existing card and see changes
- [ ] Can toggle card status (上架/下架)
- [ ] Card becomes transparent when inactive
- [ ] Can delete card (shows confirmation)
- [ ] List updates after each operation
- [ ] Price displayed with 2 decimal places
- [ ] Modal closes after successful submit
- [ ] Modal can be closed by tapping outside (on mask)
- [ ] Modal can be closed by tapping Cancel button
- [ ] **BUG FIX**: Edit modal stays open and doesn't close immediately
---
## 📊 Card Type Categories
| Type | Chinese | Use Case | Example | Color | Required Fields |
|------|---------|----------|---------|-------|-----------------|
| TIMES | 次卡 | Classes count | 10次课套餐 | Dark blue | totalTimes |
| DURATION | 月卡 | Time period | 30天卡 | Purple | durationDays |
| TRIAL | 体验卡 | Trial | 体验卡 | Gold/tan | durationDays |
---
## 🔗 Related Features
### Memberships (User Side)
- User can purchase cards (creates Order)
- Payment successful creates Membership record
- Membership tracks remaining times or expiry date
- Used when user books a class
### Public Card Display
- Users see only `isActive=true` cards on shop page
- Sorted by `sortOrder`
- Can purchase cards
---
## 📚 Documentation Files
- `CARD_TYPES_ANALYSIS.md` - Complete technical analysis
- `CARD_TYPES_FLOW_DIAGRAM.txt` - Visual flow diagrams
- `CARD_TYPES_QUICK_REFERENCE.md` - This file (quick lookup)

222
CLAUDE.md
View File

@@ -1,150 +1,122 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
本文档为 Claude Code (claude.ai/code) 在本项目中工作时提供指导。
## 项目概述
普拉提工作室预约与会员管理的微信小程序。TypeScript monorepo包含三个包:
这是一个普拉提预约微信小程序项目,后端采用 NestJS 框架。项目使用 pnpm monorepo 结构,包含 3 个包:
- **packages/server** — NestJS 后端REST API、Prisma ORM、PostgreSQL
- **packages/app** — Vue 3 + Pinia 前端,基于 Uni-app目标平台 mp-weixin
- **packages/shared** — 前后端共用的 TypeScript 类型、枚举常量
- **packages/app** - Vue 3 + uni-app微信小程序前端
- **packages/server** - NestJS后端 API 服务
- **packages/shared** - TypeScript 类型定义、枚举常量(前后端共用)
## 常用命令
### 开发
```bash
pnpm dev:server # NestJS watch 模式 (localhost:3000)
pnpm dev:app # 微信小程序开发服务器
pnpm build:shared # 必须先构建 shared再构建 server/app
```
# 开发
pnpm dev:server # 启动 NestJS 后端(热重载)
pnpm dev:app # 构建 uni-app 为微信小程序
### 测试(仅 server
```bash
# 构建
pnpm build:shared # 编译共享类型
pnpm build:server # 构建 NestJS 后端
pnpm build:app # 构建微信小程序
# 测试与代码检查
pnpm test # 运行所有测试(仅 server
pnpm lint # 运行 ESLint仅 server
# 数据库相关(位于 packages/server 目录)
cd packages/server
pnpm test # 运行全部测试
pnpm test -- auth.service.spec # 运行单个测试文件
pnpm test:watch # watch 模式
pnpm test:cov # 覆盖率报告
pnpm prisma:generate # 生成 Prisma 客户端
pnpm prisma:migrate # 执行数据库迁移
pnpm prisma:seed # 填充测试数据
pnpm test:watch # 监听模式运行测试
# 部署
pnpm deploy:server # 部署后端到生产环境
```
Jest 配置内联在 `packages/server/package.json`。测试文件位于 `__tests__/` 子目录(如 `src/auth/__tests__/auth.service.spec.ts`),匹配模式:`*.spec.ts`
## 架构说明
### 前端 (packages/app)
- 基于 Vue 3 + uni-app 框架,主攻微信小程序平台
- 页面目录:`src/pages/`(包含 home、booking、card、profile、admin 等模块)
- 组件目录:`src/components/`
- 状态管理Pinia
- 样式SCSS
### 后端 (packages/server)
- 框架NestJS + Prisma ORM
- 核心模块auth认证、user用户、booking预约、membership会员卡、payment支付、studio场馆、time-slot时段、scheduler定时任务、admin管理
- 认证JWT + 微信登录
- 定时任务:@nestjs/schedule
- 数据库SQLite开发/ MySQL生产
### 共享包 (packages/shared)
- TypeScript 接口和类型定义
- 枚举值定义
- 前后端共用的 DTO 类型
### API 结构
- 所有接口统一前缀:`/api`
- RESTful 风格接口
- 全局拦截器:日志记录、响应包装
- 全局过滤器:异常处理
### 数据库
```bash
cd packages/server
pnpm prisma:generate # schema 变更后重新生成 Prisma Client
pnpm prisma:migrate # 运行迁移(交互式)
pnpm prisma:seed # 填充种子数据
```
- Prisma schema 位于 `packages/server/prisma/schema.prisma`
- 核心数据模型User、Studio、TimeSlot、Booking、Membership、CardType、Order
- 注意查询会员列表时booking 统计通过 `groupBy` 批量获取,避免 N+1 查询
### 代码检查
```bash
pnpm lint # 所有包的 ESLint 检查
```
### 卡类型枚举
- `CardTypeCategory` (TIMES/DURATION/TRIAL) 定义在 `packages/shared/src/enums.ts`
- 会员管理筛选使用特殊值 `ACTIVE` 表示持有 ACTIVE 状态会员卡的会员用户(页面默认),`NONE` 表示无卡/无有效会员(两者不在卡种枚举中)
- 前端选项硬编码在 `src/pages/admin/members.vue``cardTypeOptions`,需与枚举保持同步
## 架构
### 管理后台 API 模式
- `/admin/members` 支持 `page`, `limit`, `search`, `cardType` 参数
- `cardType=ACTIVE` → 持有任意 ACTIVE 状态会员卡;`cardType=NONE` → 无 ACTIVE 状态会员卡;省略参数查看全部用户;其他值对应 `CardTypeCategory`
- 预约统计total/completed/cancelled通过 `groupBy` 批量查询
### 数据流
```
微信小程序 → Uni-app (Vue 3) → REST API (NestJS) → Prisma → PostgreSQL
↕ ↕
Pinia stores @nestjs/schedule (定时任务)
```
### 筛选组件模式
- picker 筛选使用 300ms debounce 再触发加载,避免频繁请求
- 列表分页使用 `onReachBottom` + `hasMore` 标志位实现无限滚动
### 后端模块结构
每个功能是一个 NestJS 模块,遵循 controller → service → Prisma 模式。核心模块:
- **auth** — 微信 OAuth 登录code2Session、JWT 令牌、手机号绑定
- **booking** — 创建/取消预约,含会员卡验证和容量检查
- **time-slot** — 课程时段管理;`SlotGeneratorService` 根据 `WeekTemplate` 自动生成
- **membership** — 基于卡的会员制TIMES 次卡、DURATION 时效卡、TRIAL 体验卡)
- **payment** — 微信支付集成,用于购卡
- **scheduler** — 定时任务02:00 自动生成时段02:30 清理过期时段
### Admin Store (`src/stores/admin.ts`)
- 聚合所有管理端 API 调用weekTemplates、cardTypes、studioConfig、members、bookings、orders、stats 等
- 遵循不可变更新原则:`data` 赋值使用展开运算符 `[...newData]`
### 历史课程补录
- `LessonSupplement` 独立记录历史累计课时,归属 user 模块DTO 放 `user/dto`,测试放 `user/__tests__`,前端入口为 `pages/admin/member-supplement.vue`
- 补录不创建预约或时段;只增加累计已完成节数,不推测上课日期、天数、时长,不参与月度统计、活跃网格或邀请奖励。
- 可选择从本人有限次会员卡扣次;补录与扣次必须事务提交,保存实际扣次快照,撤销只返还实际扣次。请求标识用于幂等重试。
- Prisma 迁移按 `YYYYMMDDHHmmss_description/migration.sql` 存放;补录表采用增量迁移,回退说明维护在 `docs/lesson-supplement.md`,不删除审计记录。
### 前端结构
- **pages/** — 按路由组织的页面home、booking、card、profile、admin
- **stores/** — Pinia 状态管理user、booking、studio、admin
- **utils/request.ts** — 封装 `uni.request` 的 HTTP 客户端,自动携带 JWT
- **utils/auth.ts** — 微信登录流程uni.login → 服务端 /auth/login → 存储 token
### 月度教学统计
- 统计归属 admin 模块,服务放 `admin/teaching-analytics.service.ts`,测试放 `admin/__tests__`;共享契约放 `shared/src/types/teaching-analytics.ts`,页面为 `pages/admin/analytics.vue`
- 按 TimeSlot.date 所属自然月查询,不按预约创建或核销日期;日期列以 UTC 日历值读取,中国时间用于判断课程结束。
- 当前无老师归属字段统计范围是工作室operatorId 不是授课老师。COMPLETED 是系统完成状态,不代表签到。
- 已上课程按时段去重,时长按已完成时段累加;上课人次按 COMPLETED 预约计数,学员按 userId 去重。取消、未出席、待确认、已确认独立计数。无日期补录不参与。
- 月历、学员排行和会员卡分布统计已完成记录;明细可组合日期、学员、状态筛选。新增测试目录只放该服务的 *.spec.ts。
### Shared
所有 API 类型、DTO、枚举和业务常量定义在 `packages/shared/src/`,前后端通过 `@mp-pilates/shared` 引用。路径别名配置在 `tsconfig.base.json` 和 Jest 的 `moduleNameMapper`
### 个人中心会员卡
- 个人中心资料区域以单行展示持有卡种和张数,下方每张卡以单行浅色进度槽承载卡名和用量文字,不使用大卡片或轮播;点击进入我的会员卡。`OwnedMembershipCard.vue` 在我的会员卡页面展示余额、已用进度和到期日
- 累计上课、本月上课、剩余课时集中在我的会员卡页面,个人资料卡不重复展示汇总。
- 次数限制以 remainingTimes 是否为 null 判断,不能按卡种推断。次数进度表示已用占总次数,已用包括预约占用;不限次卡不伪造耗课数。
- 会员卡加载失败显示重试,不当作无卡;会话变化时丢弃旧请求结果。
### 数据库 Schema
Prisma schema 位于 `packages/server/prisma/schema.prisma`,关键约定:
- Model 用 PascalCase表名用 snake_case`@@map`
- 字段用 camelCase列名用 snake_case`@map`
- 所有 ID 为 UUID
- 金额字段使用 `Decimal(10, 0)`
- 关键唯一约束:`TimeSlot``@@unique([date, startTime, endTime])``Booking``@@unique([userId, timeSlotId])`
### 课后评价与成长档案
- 评价归属 booking 模块,档案归属 user 模块;共享契约放 shared/src/types/member-care.ts页面沿用 booking/profile/admin 目录,不新增顶层业务目录。
- COMPLETED 后立即可评价,无 24 小时截止;完成后 24 小时仅提醒未评价预约。唯一 bookingId 防重复,提醒状态保存在 Booking 上,定时任务原子领取,未知发送结果不自动重发。
- 星级均分与 NPS 分开NPS 仅使用可选 010 推荐意愿910 推荐者、06 贬损者),按中国自然月聚合并展示样本数。
- 教练私密笔记必须在服务端过滤;课程批注必须属于该学员的已完成预约。体测允许缺项,不以缺项当 0累计课时包含有效补录里程碑为 10/30/50 节。
- 照片仅用于学员与馆主之间的档案展示,不能用于公开宣传。学员本人按照片授权/撤回,馆主不能代授权。与馆图共用 COS 桶,对象前缀 `progress/`,上传为私有 ACL读取用短时签名禁止落库公共链接上传凭证绑定学员及照片记录。
- 新增迁移目录只放 migration.sql测试沿用各模块 __tests__;部署配置与验收清单放 docs/member-care.md。
### 核心业务规则
- 预约需要有效的会员卡(剩余次数或有效期内)
- 取消预约需在课程开始前 `cancelHoursLimit` 小时(默认 2 小时,可在 StudioConfig 中配置)
- 时段根据 WeekTemplate 自动生成未来 14 天的课程
- 默认时段容量为 1私教课
- 成长档案的两端共用 `components/MemberProgress.vue`,仅此跨端组件直接请求 progress API避免主包引用 admin 分包 Store馆主评价页面仍通过 admin Store 访问。
## 环境配置
需要 Node 20+.nvmrc、pnpm 8+、PostgreSQL。复制 `packages/server/.env.example``.env.local`,需配置 DATABASE_URL、JWT_SECRET 及微信相关凭证APPID、SECRET、MCH_ID、MCH_KEY、证书路径
## 开发约定
- **API 前缀**:所有路由在 `/api`setGlobalPrefix
- **参数校验**:全局 ValidationPipe启用 whitelist + forbidNonWhitelisted + transform
- **鉴权守卫**:受保护路由使用 `@UseGuards(JwtAuthGuard)`,通过 `@Req()` 从 JWT 载荷提取用户
- **角色**MEMBER 和 ADMIN管理员路由使用自定义角色守卫
- **异常处理**:使用 NestJS 内置异常BadRequestException、NotFoundException 等)
- **分页**:统一使用 `PaginatedResponse<T>`,包含 data、total、page、limit
- **pnpm**:使用 `shamefully-hoist=true`.npmrc为 Uni-app 兼容所需
## 前端样式规范
### 主题色变量(必用)
所有色值必须使用 `packages/app/src/uni.scss` 中定义的 SCSS 变量,禁止在 Vue/Scss 文件中硬编码色值。
**主题色系:**
```scss
$primary-color: #a9bfcc; /* 主色-柔雾蓝灰 */
$primary-dark: #7ba5be; /* 主色-深蓝灰 */
$primary-light: #c8d8e4; /* 主色-浅蓝灰 */
$primary-bg: #f0f6f9; /* 页面背景-冷白蓝 */
$primary-border: #d8eaf4; /* 边框-淡蓝灰 */
$primary-selected-bg: #EFF6F9; /* 选中态背景 */
```
**通用语义变量(已同步主题色):**
| 变量 | 值 | 用途 |
|------|----|------|
| `$accent-color` | `#7ba5be` | 强调色 |
| `$warning-color` | `#e8a87c` | 警告色 |
| `$brand-light` | `#c8d8e4` | 品牌浅色 |
| `$border-color` | `rgba(180,160,130,0.2)` | 边框(中性) |
| `$text-primary` | `#4A4035` | 主文字(深棕灰) |
| `$text-secondary` | `#7A6A5A` | 次文字 |
| `$text-hint` | `#A09080` | 弱提示文字 |
### 变量替换规则
| 旧硬编码 | 替换为 |
|---------|--------|
| `#c9a87c`(旧暖棕金) | `$primary-dark` |
| `#d4b896`(旧浅棕金) | `$primary-color` |
| `#C4956A`(旧警告橙棕) | `$warning-color` |
| `#B08050`(旧深棕) | `$accent-color` |
| `#7d6608`(旧深暖绿) | `#5a7a8a`(冷青灰) |
| `#e8c88a``#b49868`(旧暖渐变) | `$primary-color` / `$primary-dark` |
### CSS 变量规范
组件内部的多处共用颜色(如阴影、遮罩)若无法用 SCSS 变量,需用 `rgba($primary-dark, 0.x)` 形式动态构造,不可直接写死十六进制值。
### 新增页面/组件
新增页面或组件时:
1. 优先查阅 `uni.scss` 已有变量
2. 若需要新增语义化变量,先更新 `uni.scss`,再在组件中引用
3. 禁止在 `<style>` 块内直接写十六进制颜色值(背景色、文字色、边框、阴影均需走变量)
### 个人身体画像
- 线上获客归属独立 `body-portrait` 模块,不是成长档案的一个页面。共享契约在 `packages/shared/src/types/body-portrait.ts`,规格在 `docs/body-portrait.md`
- 评分只在服务端规则引擎计算;匿名测评用访问令牌哈希,不用可枚举 ID 做权限
- 安全分流不计分。完整报告需登录认领,体验预约需手机号。现有 TRIAL 体验卡承接转化。
- 馆主「今日经营助手」只展示待办,不做成通用 CRM。主包不得引用 admin store。

View File

@@ -1,359 +0,0 @@
# Component & Data Flow Hierarchy
## 🏗️ Component Tree
```
pages/booking/index.vue (Main Page)
├── DateSelector.vue
│ └── Emits: @select (date string)
│ Props: v-model (current date)
├── TimePeriodFilter.vue
│ └── Emits: @change (period key)
│ Props: v-model (current period)
├── SlotCard.vue (Multiple, v-for)
│ ├── Props: slot (TimeSlotWithBookingStatus)
│ ├── Emits: @book (slot) / @cancel (slot)
│ └── Computed: capacityLabel, capacityClass
└── BookingConfirmPopup.vue (Modal)
├── Props: visible, slot, memberships
├── Emits: @confirm ({timeSlotId, membershipId})
├── Emits: @cancel
└── State: selectedMembershipId
```
---
## 🔄 State Management Flow
```
Pinia Store (stores/booking.ts)
├── State:
│ ├── slots: TimeSlotWithBookingStatus[]
│ ├── myBookings: BookingWithDetails[]
│ ├── upcomingBookings: BookingWithDetails[]
│ ├── loadingSlots: boolean
│ └── loadingBookings: boolean
└── Actions:
├── fetchSlots(date) → GET /time-slot/available?date=
├── createBooking({...}) → POST /booking
├── cancelBooking(bookingId) → PUT /booking/:id/cancel
├── fetchMyBookings(status?) → GET /booking/my
└── fetchUpcomingBookings() → GET /booking/my/upcoming
Pinia Store (stores/user.ts)
├── State:
│ ├── user: UserProfileResponse | null
│ ├── memberships: MembershipWithCardType[]
│ ├── token: string
│ └── stats: UserStatsResponse | null
├── Computed:
│ ├── loggedIn: boolean
│ ├── hasValidMembership: boolean
│ └── activeMemberships: MembershipWithCardType[]
└── Actions:
├── login() → WX login + token
├── fetchMemberships() → GET /membership/my
├── fetchProfile() → GET /user/profile
└── logout()
```
---
## 📡 API Calls Sequence
```
INITIAL LOAD
├─ POST /auth/wxLogin
│ └─ Returns: { token, user }
├─ GET /membership/my (if logged in)
│ └─ Returns: MembershipWithCardType[]
└─ GET /time-slot/available?date=TODAY
└─ Returns: TimeSlotWithBookingStatus[]
DATE CHANGE
└─ GET /time-slot/available?date=SELECTED_DATE
└─ Returns: TimeSlotWithBookingStatus[]
BOOKING CREATION
├─ POST /booking
│ ├─ Body: { timeSlotId, membershipId }
│ └─ Returns: BookingWithDetails
└─ GET /time-slot/available?date=SELECTED_DATE (refresh)
└─ Returns: Updated slots with isBookedByMe: true
BOOKING CANCELLATION
├─ PUT /booking/:bookingId/cancel
│ └─ Returns: Updated BookingWithDetails
└─ GET /time-slot/available?date=SELECTED_DATE (refresh)
└─ Returns: Updated slots with isBookedByMe: false
```
---
## 🎭 Slot Card State Machine
```
TimeSlotWithBookingStatus {
status: 'OPEN' | 'FULL' | 'CLOSED'
isBookedByMe: boolean
}
STATE COMBINATIONS:
┌─────────────────────────────────────┐
│ status: OPEN, isBookedByMe: false │
├─────────────────────────────────────┤
│ Button: "可预约" (Tan) │
│ Color: #c9a87c │
│ Action: onBookTap() → Popup │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ status: OPEN, isBookedByMe: true │
├─────────────────────────────────────┤
│ Badge: "已预约" │
│ Link: "取消" (Red underline) │
│ Indicator: Tan bar on left │
│ Action: onCancelTap() → Confirm │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ status: FULL │
├─────────────────────────────────────┤
│ Button: "已约满" (Gray) │
│ Color: #f0f0f0 │
│ Action: Disabled (no-op) │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ status: CLOSED │
├─────────────────────────────────────┤
│ Button: "已关闭" (Gray) │
│ Color: #f0f0f0 │
│ Action: Disabled (no-op) │
└─────────────────────────────────────┘
```
---
## 📊 Capacity Label Colors
```
Condition Label Background Text
─────────────────────────────────────────────────────────────────
status === CLOSED "已关闭" #f5f5f5 #999
status === FULL "0/1 人" #fef0f0 #ef4444
bookedCount >= 80% "0/1 人" #fff8ed #f59e0b
bookedCount < 80% "0/1 人" #f0faf3 #4caf50
```
---
## 🌐 Time Period Filters
```
Key Label Start End Range
──────────────────────────────────────────────────────
null (all) "全部" - - All times
'MORNING' "上午" 06:00 12:00 6am-12pm
'AFTERNOON' "下午" 12:00 18:00 12pm-6pm
'EVENING' "晚上" 18:00 22:00 6pm-10pm
Filtering Logic:
slot.startTime >= period.start && slot.startTime < period.end
```
---
## 📱 UI Layout Breakdown
```
┌─────────────────────────────────┐
│ 📱 Booking Page (750rpx) │
├─────────────────────────────────┤
│ │
│ ┌─────────────────────────────┐│
│ │ 🎫 STICKY HEADER (z-index:100)
│ │ ┌───────────────────────────┐│
│ │ │ DateSelector (horizontal) ││
│ │ │ 今天 5月 4月 3月... ││
│ │ └───────────────────────────┘│
│ │ ┌───────────────────────────┐│
│ │ │ TimePeriodFilter (tabs) ││
│ │ │ 全部 | 上午 | 下午 | 晚上││
│ │ └───────────────────────────┘│
│ └─────────────────────────────┘│
│ │
│ ┌─────────────────────────────┐│
│ │ 📜 SCROLL AREA ││
│ │ ││
│ │ OR [Loading skeleton] ×4 ││
│ │ OR [Empty state] ││
│ │ ││
│ │ [SlotCard 1] ┌──────────┐ ││
│ │ 09:00-10:00 │ 0/1 人 │ ││
│ │ │ [可预约] │ ││
│ │ ┌──────────┘ └─────────┘ ││
│ │ [SlotCard 2] ┌──────────┐ ││
│ │ 10:00-11:00 │ 1/1 人 │ ││
│ │ ✓已预约 [取消]└─────────┘ ││
│ │ [SlotCard 3] ... ││
│ │ ││
│ │ [Spacer 48rpx] ││
│ └─────────────────────────────┘│
│ │
│ ┌──────────────────────────────┐│
│ │ [BookingConfirmPopup] (Modal)││
│ │ ┌────────────────────────────┐│
│ │ │ ✕ 确认预约 ││
│ │ │ ││
│ │ │ 日期: 2026-04-05 ││
│ │ │ 时间: 09:00 - 10:00 ││
│ │ │ 剩余: 1 个名额 ││
│ │ │ ───────────────────── ││
│ │ │ 💳 私教课程 ││
│ │ │ 剩余 10 次 ✓ ││
│ │ │ 确认后扣除 1 次课时 ││
│ │ │ ││
│ │ │ [取消] [确认预约] ││
│ │ └────────────────────────────┘│
│ └──────────────────────────────┘│
└─────────────────────────────────┘
```
---
## 🔐 Authentication Flow
```
PAGE LOAD
├─ Check: userStore.loggedIn?
├─ YES
│ ├─ Check: userStore.activeMemberships.length > 0?
│ │ ├─ NO: await fetchMemberships()
│ │ └─ YES: (already loaded)
│ │
│ └─ Load today's slots
└─ NO (not logged in)
└─ Page loads but booking disabled
(onBookTap shows login modal)
USER TAPS "可预约"
├─ Check: userStore.loggedIn?
│ ├─ NO: Show login modal
│ │ ├─ User confirms → wxLogin()
│ │ ├─ Retry booking flow
│ │ └─ Success: Load memberships, show popup
│ │
│ └─ YES: Continue
├─ Check: userStore.hasValidMembership?
│ ├─ NO: Show purchase modal
│ │ └─ User navigates to /pages/store/index
│ │
│ └─ YES: Continue
└─ Show BookingConfirmPopup
```
---
## ⚙️ Error Handling (Current)
```
fetchSlots() Error:
├─ console.error('Fetch slots failed:', err)
├─ slots.value = []
└─ UI shows: "当日暂无可约时段" (empty state)
❌ User can't distinguish network error from no slots
createBooking() Error:
├─ uni.showToast({ title: message, icon: 'none' })
└─ UI shows: Error toast (Good ✓)
cancelBooking() Error:
├─ uni.showToast({ title: message, icon: 'none' })
└─ UI shows: Error toast (Good ✓)
```
---
## 🧮 Computed Values & Reactivity
```
PAGE LEVEL:
scrollHeight = computed(() => {
// Recalc when window size changes
// = windowHeight - headerHeight - tabbarHeight
})
filteredSlots = computed(() => {
// Depends on: slots, selectedPeriod
// Recalc when either changes
// Filters by TIME_PERIODS[selectedPeriod].start/end
})
COMPONENT LEVEL:
SlotCard.capacityLabel = computed(() => {
// Depends on: slot.status, slot.bookedCount, slot.capacity
// Returns: "已关闭" | "X/Y 人"
})
SlotCard.capacityClass = computed(() => {
// Depends on: slot.status, slot.bookedCount, slot.capacity
// Returns: "cap-open" | "cap-almost" | "cap-full" | "cap-closed"
})
BookingConfirmPopup.selectedMembership = computed(() => {
// Depends on: selectedMembershipId, memberships
// Returns: Found membership or null
})
```
---
## 🎯 Key Data Transformations
```
Raw API Response
└─ TimeSlot {
date: "2026-04-05",
startTime: "09:00",
endTime: "10:00",
...
}
STORE (bookingStore.slots)
└─ TimeSlotWithBookingStatus extends TimeSlot {
isBookedByMe: boolean,
myBookingId: string | null
}
DISPLAY (SlotCard)
├─ capacityLabel: "0/1 人" | "已关闭"
├─ capacityClass: "cap-open" | "cap-almost" | "cap-full" | "cap-closed"
├─ Button state: "可预约" | "已预约" | "已约满" | "已关闭"
└─ Time display: "09:00 - 10:00" (slice first 5 chars)
BOOKING CREATION
├─ Selected Slot ID
├─ Selected Membership ID
└─ POST /booking
└─ Success: Slot updated with isBookedByMe: true
```

View File

@@ -1,428 +0,0 @@
# 卡种管理 (Card Types Management) - Complete Exploration Summary
**Date**: 2026-04-05
**Project**: MP-Pilates (WeChat Mini-Program for Pilates Studio Booking)
**Focus**: Card types (卡种) admin feature
---
## 📦 What Was Explored
A comprehensive exploration of the **card types management system** across all three tiers of the application:
- Frontend (Vue 3 + Uni-app)
- Backend (NestJS)
- Database (Prisma/MySQL)
- Shared Types
### Total Files Analyzed: **13 files, ~1,800 lines of code**
---
## 📚 Documentation Generated
Three comprehensive documentation files have been created in the project root:
### 1. **CARD_TYPES_ANALYSIS.md** (Complete Technical Guide)
- **Sections**: 11 major sections
- **Content**:
- Database schema details
- Shared types and DTOs
- Server-side implementation (controller, service, DTOs)
- Frontend admin page structure
- Admin store (Pinia) implementation
- Complete workflow flows
- API communication details
- Price handling
- Card type categories
- Field requirements & validation table
- **Detailed bug analysis**: Edit popup closes immediately
### 2. **CARD_TYPES_FLOW_DIAGRAM.txt** (Visual Architecture)
- **Content**:
- Database tier diagram (CardType model, enums, soft delete)
- API tier diagram (endpoints, validators, DTOs)
- Shared types tier
- Frontend tier (page structure, store, components)
- Complete operation flows (Add, Edit, Toggle, Delete)
- **Bug analysis with solutions** (3 solution options)
### 3. **CARD_TYPES_QUICK_REFERENCE.md** (Quick Lookup)
- **Sections**: 13 quick-reference sections
- **Content**:
- File quick links with line numbers
- Key data model
- API endpoints
- DTOs & validation rules
- UI components
- Form fields
- Operations guide
- React refs & state
- Admin store methods
- Bug explanation and solutions
- Price handling notes
- Testing checklist
- Card type categories
---
## 🎯 Key Findings
### Data Structure
```
CardType
├── id (UUID)
├── name (卡种名称)
├── type (TIMES | DURATION | TRIAL)
├── totalTimes (次卡的次数)
├── durationDays (有效天数)
├── price (现价,单位:分)
├── originalPrice (原价,可选)
├── description (描述)
├── isActive (上架状态)
├── sortOrder (显示顺序)
└── timestamps
```
### Three Card Type Categories
1. **次卡 (TIMES)**: Class count-based (e.g., 10 classes)
2. **月卡 (DURATION)**: Time period-based (e.g., 30 days)
3. **体验卡 (TRIAL)**: Trial cards
### Core Operations
-**Create**: Add new card types
-**Read**: View all cards (admin) or active cards (public)
-**Update**: Edit card details or toggle status
-**Delete**: Soft delete (sets isActive=false)
### API Endpoints
```
GET /membership/card-types (public)
GET /admin/card-types (admin only)
POST /admin/card-types (admin only)
PUT /admin/card-types/:id (admin only)
DELETE /admin/card-types/:id (admin only)
```
---
## 🐛 Critical Bug Identified
### **Edit Modal Closes Immediately on Tap**
**Symptom**: When user taps the [编辑] button, the edit form modal appears and then instantly closes.
**Root Cause**: Event propagation issue
- User taps [编辑] button
- `openEdit()` sets `showModal = true`
- Modal renders in the same event tick
- Tap event propagates to `modal-mask` element
- `@tap.self="closeModal"` fires immediately
- Modal closes
**Current Code (Buggy)**:
```vue
<view class="ct-action-btn edit-btn" @tap="openEdit(ct)">
<text>编辑</text>
</view>
<view v-if="showModal" class="modal-mask" @tap.self="closeModal">
<!-- form -->
</view>
```
**Recommended Fix (Option 1 - Simplest)**:
```vue
<view class="ct-action-btn edit-btn" @tap.stop="openEdit(ct)">
<!-- Add .stop modifier to stop event propagation -->
</view>
```
**Alternative Fixes**: See CARD_TYPES_QUICK_REFERENCE.md for 2 additional solutions using nextTick() or state guards.
---
## 📂 File Inventory
### Frontend Files
| File | Purpose | Lines |
|------|---------|-------|
| `packages/app/src/pages/admin/card-types.vue` | Admin page (ADD, EDIT, DELETE, TOGGLE) | 607 |
| `packages/app/src/stores/admin.ts` | Pinia store (state + API calls) | 198 |
| `packages/app/src/utils/request.ts` | HTTP request utilities | 80 |
| `packages/app/src/utils/format.ts` | Price & date formatting | 46 |
### Backend Files
| File | Purpose | Lines |
|------|---------|-------|
| `packages/server/src/membership/membership.controller.ts` | API endpoints | 68 |
| `packages/server/src/membership/membership.service.ts` | Business logic | 173 |
| `packages/server/src/membership/dto/create-card-type.dto.ts` | Create validation | 45 |
| `packages/server/src/membership/dto/update-card-type.dto.ts` | Update validation | 49 |
### Database Files
| File | Purpose | Lines |
|------|---------|-------|
| `packages/server/prisma/schema.prisma` | DB schema definition | 205 |
### Shared/Types Files
| File | Purpose | Lines |
|------|---------|-------|
| `packages/shared/src/types/card-type.ts` | CardType, CreateCardTypeDto, UpdateCardTypeDto | 39 |
| `packages/shared/src/enums.ts` | CardTypeCategory enum | 47 |
| `packages/shared/src/types/api.ts` | API response types | 20 |
| `packages/shared/src/types/membership.ts` | Membership types | 19 |
**Total**: 13 files, ~1,800 lines analyzed
---
## 🔄 Complete Workflow
### Adding a New Card Type
```
User → [ 新增卡种] → openAdd()
Modal appears with empty form
User fills: name, type, price, durationDays
[确认] → submitForm()
Validate inputs → Build payload → adminStore.createCardType()
POST /admin/card-types → Backend creates card
Refetch list → Modal closes → Page updates
```
### Editing a Card Type
```
User → [编辑] on card → openEdit(card)
Modal appears with card data
User edifies fields
[确认] → submitForm()
Validate inputs → Build payload → adminStore.updateCardType(id, payload)
PUT /admin/card-types/:id → Backend updates card
Refetch list → Modal closes → Page updates
```
### Toggling Status (上架/下架)
```
User → [上架/下架] button → toggleActive(card)
adminStore.updateCardType(id, { isActive: !current })
PUT /admin/card-types/:id → Backend toggles isActive
Refetch list → Card UI updates (opacity, status tag, button text)
```
### Deleting a Card Type
```
User → [删除] button → confirmDelete(card)
Confirmation dialog appears
User confirms
adminStore.deleteCardType(id)
DELETE /admin/card-types/:id → Backend soft-deletes (isActive=false)
Refetch list → Page updates
```
---
## 💾 Database Details
### CardType Model
- **Storage**: MySQL table `card_types`
- **Primary Key**: UUID
- **Important Field**: `isActive` (boolean, default: true)
- **Delete Strategy**: Soft delete (set isActive=false, not actually removed)
- **Relationships**:
- One-to-many with Membership
- One-to-many with Order
### Indexes
- `isActive` (for filtering active cards)
- `sortOrder` (for ordering)
---
## 🎨 UI/UX Details
### Page Layout
```
┌─ Toolbar ─────────────┐
│ Count + Add button │
├──────────────────────┤
│ Loading skeleton │ (while loading)
├──────────────────────┤
│ Card List │
├──────────────────────┤
│ Modal (Add/Edit) │ (if showModal=true)
└──────────────────────┘
```
### Card Display
- **Header**: Colored band (type-specific gradient)
- **Status tag**: "销售中" or "已下架"
- **Content**: Name, price, description, meta info
- **Actions**: 3 buttons (编辑, 上架/下架, 删除)
- **Inactive styling**: opacity: 0.6 when isActive=false
### Modal Form
```
Title: 新增卡种 / 编辑卡种
Fields:
- 卡种名称 (text input)
- 类型 (picker)
- 现价 (digit)
- 原价 (digit, optional)
- 次数 (number, optional)
- 有效天数 (number, default: 90)
- 排序值 (number, default: 0)
- 描述 (textarea, optional)
Buttons: [取消] [确认/保存中...]
```
---
## 🔐 Security & Auth
### Authentication
- All admin endpoints require JWT Bearer token
- Token stored in localStorage and included in all requests
### Authorization
- Admin endpoints require `UserRole.ADMIN`
- Enforced via RolesGuard on backend
### Public Endpoints
- GET /membership/card-types (no auth needed)
- Returns only `isActive=true` cards
---
## 📊 Validation Rules
### On Create
| Field | Required | Validation |
|-------|----------|-----------|
| name | ✓ | Non-empty string |
| type | ✓ | One of: TIMES, DURATION, TRIAL |
| durationDays | ✓ | Int, Min: 1 |
| price | ✓ | Number, Min: 0 |
| totalTimes | - | Int, Min: 1 (optional) |
| originalPrice | - | Number, Min: 0 (optional) |
| description | - | String, Max: 200 (optional) |
| sortOrder | - | Int, Min: 0 (optional, default: 0) |
### On Update
- All fields optional (partial update)
- Can include `isActive` for toggling status
---
## 💡 Price Handling
**Critical**: Prices are stored as **integers (cents)**, not floats
- In DB: `98000` (cents)
- In API: `{ price: 98000 }`
- Display: `¥980.00` (using formatPrice utility)
**Conversion**:
```typescript
// Display
formatPrice(cents: number): string {
return (cents / 100).toFixed(2)
}
// Store (frontend → backend)
// User inputs: "980"
// Send as: 98000 (no need to convert, prices are already in cents in the UI)
```
---
## 🧪 Testing Recommendations
### Unit Tests Needed
- [ ] CardType service methods (create, update, delete)
- [ ] Card type validation (DTO validation)
- [ ] Price formatting utilities
### Integration Tests Needed
- [ ] Admin endpoints require ADMIN role
- [ ] Public endpoint returns only active cards
- [ ] Soft delete sets isActive=false
### E2E Tests Needed (Frontend)
- [ ] Create card flow
- [ ] Edit card flow (including bug fix)
- [ ] Toggle status flow
- [ ] Delete card flow
- [ ] Modal closes properly on submit
- [ ] Modal closes on outside tap
- [ ] Modal closes on cancel button
---
## 🚀 Next Steps (If Implementing Bug Fix)
1. **Locate file**: `packages/app/src/pages/admin/card-types.vue`
2. **Find**: Line 67 with `<view class="ct-action-btn edit-btn" @tap="openEdit(ct)">`
3. **Change**: `@tap="openEdit(ct)"``@tap.stop="openEdit(ct)"`
4. **Also check**: Lines 6 and 77 (other buttons that might have same issue)
5. **Test**: Try editing a card - modal should stay open
---
## 📖 How to Use This Documentation
1. **Quick lookup**: Start with `CARD_TYPES_QUICK_REFERENCE.md`
2. **Understanding architecture**: Read `CARD_TYPES_FLOW_DIAGRAM.txt`
3. **Deep dive**: Consult `CARD_TYPES_ANALYSIS.md` for detailed information
4. **Bug fix**: Find solution in Quick Reference "THE BUG" section
---
## 📝 Summary Statistics
| Metric | Value |
|--------|-------|
| Files Analyzed | 13 |
| Total Lines of Code | ~1,800 |
| Endpoints | 5 |
| Card Type Categories | 3 |
| Core Operations | 4 (CRUD) |
| Bugs Identified | 1 |
| Bug Severity | High (UX-breaking) |
| Documentation Pages | 3 |
| Recommended Solution | @tap.stop modifier |
---
## ✅ Exploration Complete
All files related to the card types management feature have been thoroughly reviewed, analyzed, and documented.
**Key Achievement**: Identified and documented the root cause of the edit popup bug, along with three solution approaches.
**Ready to**:
- Implement bug fix
- Build additional features
- Optimize performance
- Add tests
- Deploy updates
---
**Generated**: 2026-04-05
**Location**: `/Users/richard/Documents/code/pilates/mp-pilates/`

View File

@@ -1,167 +0,0 @@
# Modal Event Handling Audit
## Overview
This document provides a security and event-handling audit of all modals in the application to identify and prevent event propagation issues similar to the card-types bug.
## Audit Results
### ✅ FIXED: packages/app/src/pages/admin/card-types.vue
**Status**: FIXED in commit a85270e
**Issue**: Action buttons inside a list card were closing the modal immediately when clicked due to event propagation to parent modal-mask.
**Solution**: Added `.stop` modifier to all three action button tap handlers:
- Edit button: `@tap.stop="openEdit(ct)"`
- Toggle button: `@tap.stop="toggleActive(ct)"`
- Delete button: `@tap.stop="confirmDelete(ct)"`
**Root Cause Pattern**:
- List items contain action buttons
- Action buttons are inside list cards
- Modal-mask has `@tap.self="closeModal"`
- Event from action button bubbles up through list card to modal-mask
---
### ✅ SAFE: packages/app/src/pages/admin/week-template.vue
**Status**: NO ACTION NEEDED
**Structure**:
- Template list (lines 30-56) - separate from modal
- Modal (lines 65+) - below the list
- Event handlers on template action buttons cannot reach modal-mask
**Reasoning**: The action buttons for edit/delete/toggle are on items in the template list, which is spatially separated from the modal-mask. The events cannot propagate upward to reach the modal-mask since the modal is rendered separately below the list.
---
### ✅ SAFE: packages/app/src/pages/admin/members.vue
**Status**: NO ACTION NEEDED
**Structure**:
- Members list uses `@tap="openDetail(m)"` on entire row element
- Modal is triggered with delay to handle event properly
- List items are separate from modal-mask
**Reasoning**: The entire member row has a single tap handler. The modal is opened as a detail view, not as an overlay that interferes with list item events. The architecture prevents event propagation issues.
---
### ✅ SAFE: components/BookingConfirmPopup.vue
**Status**: NO ACTION NEEDED (Special-case popup component)
**Structure**: Dedicated popup component with internal button handlers
---
## Event Propagation Risk Pattern
🚨 **RISK PATTERN** - High risk of event propagation issues:
```vue
<!-- List of items with action buttons -->
<view class="item-list">
<view v-for="item in items" :key="item.id" class="item-card">
<view class="item-actions">
<view @tap="handleAction1(item)">Action 1</view>
<view @tap="handleAction2(item)">Action 2</view>
</view>
</view>
</view>
<!-- Modal that appears on top -->
<view v-if="showModal" class="modal-mask" @tap.self="closeModal">
<view class="modal">...</view>
</view>
```
When an action button is tapped, the event bubbles: action button → item card → item-list → modal-mask
**SOLUTION**: Add `.stop` modifier to prevent bubbling:
```vue
<view @tap.stop="handleAction1(item)">Action 1</view>
```
---
## Preventive Measures
### 1. Code Review Checklist
When implementing modals with action buttons in lists:
- [ ] List items contain action buttons/clickable elements
- [ ] Modal-mask has `@tap.self="closeModal"` handler
- [ ] Check if tap events can bubble from buttons → modal-mask
- [ ] Add `.stop` modifier if event propagation risk exists
### 2. Testing Strategy
For any modal with nearby action buttons:
```
Test Scenario:
1. Click/tap action button that opens modal
2. Verify modal opens and stays open
3. Verify you can interact with modal content
4. Verify clicking outside modal (on mask) closes it
5. Verify multiple rapid clicks on action buttons don't cause flicker
```
### 3. Best Practices
```vue
<!-- SAFE: Action button prevents event propagation -->
<view @tap.stop="openModal(item)">Edit</view>
<!-- RISKY: Event can bubble to modal-mask -->
<view @tap="openModal(item)">Edit</view>
<!-- ALTERNATIVE: Use .prevent for links/special handlers -->
<view @tap.prevent="handleSpecial">Special</view>
<!-- ALTERNATIVE: Defer modal opening to next tick -->
<script>
async function openModal(item) {
editTarget.value = item
await nextTick()
showModal.value = true
}
</script>
```
---
## Summary
| File | Issue | Status | Solution |
|------|-------|--------|----------|
| card-types.vue | Event propagation | ✅ FIXED | Added `.stop` to 3 buttons |
| week-template.vue | N/A - Separate structure | ✅ SAFE | No action needed |
| members.vue | N/A - Single tap handler | ✅ SAFE | No action needed |
**Total Affected**: 1 file
**Total Fixed**: 1 file
**Total Safe**: 2 files
---
## Future Enhancements
1. **Automated Testing**: Add E2E tests for modal interactions
2. **ESLint Rule**: Consider adding custom rule to warn about `@tap` handlers on buttons inside modals
3. **Documentation**: Add event handling guidelines to project style guide
4. **Component Library**: Create a reusable `<Modal>` component with proper event handling built-in
---
## References
- Vue Event Handling: https://vuejs.org/guide/essentials/event-handling.html
- Event Modifiers: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers
- Bug Fix Commit: a85270e - fix(admin): prevent edit modal from closing immediately on tap

View File

@@ -1,592 +0,0 @@
# Booking Page - Quick Reference & Code Snippets
## 🚀 Quick Start: Understanding the Flow
### Where Slots Come From
```typescript
// 1. Store calls API
packages/app/src/stores/booking.ts:17-27
async function fetchSlots(date: string) {
loadingSlots.value = true
try {
// GET /time-slot/available?date=2026-04-05
slots.value = await get<TimeSlotWithBookingStatus[]>(
'/time-slot/available',
{ date }
)
} catch (err) {
console.error('Fetch slots failed:', err)
slots.value = [] // ⚠️ Clears on error!
} finally {
loadingSlots.value = false
}
}
```
### Where Time Periods Are Defined
```typescript
// packages/shared/src/constants.ts:11-15
export const TIME_PERIODS = {
MORNING: { label: '上午', start: '06:00', end: '12:00' },
AFTERNOON: { label: '下午', start: '12:00', end: '18:00' },
EVENING: { label: '晚上', start: '18:00', end: '22:00' },
} as const
```
### Where Filtering Happens
```typescript
// pages/booking/index.vue:94-103
const filteredSlots = computed<TimeSlotWithBookingStatus[]>(() => {
const slots = bookingStore.slots as TimeSlotWithBookingStatus[]
if (!selectedPeriod.value) return [...slots]
const period = TIME_PERIODS[selectedPeriod.value]
return slots.filter((slot) => {
const t = slot.startTime // "09:00", "10:00", etc
return t >= period.start && t < period.end
})
})
```
### Slot Rendering
```vue
<!-- pages/booking/index.vue:34-42 -->
<view v-else class="slot-list">
<SlotCard
v-for="slot in filteredSlots"
:key="slot.id"
:slot="slot"
@book="onBookTap"
@cancel="onCancelTap"
/>
</view>
```
---
## 🔍 Finding Specific Things
### Q: Where do the time slot types come from?
**A:** `packages/shared/src/types/time-slot.ts`
```typescript
interface TimeSlotWithBookingStatus extends TimeSlot {
readonly isBookedByMe: boolean // true if user booked it
readonly myBookingId: string | null // needed for cancellation
}
interface TimeSlot {
readonly id: string // UUID
readonly date: string // "2026-04-05"
readonly startTime: string // "09:00"
readonly endTime: string // "10:00"
readonly capacity: number // 1 (for private lessons)
readonly bookedCount: number // 0 or 1
readonly status: TimeSlotStatus // OPEN|FULL|CLOSED
readonly source: TimeSlotSource // TEMPLATE|MANUAL
readonly templateId: string | null
readonly createdAt: string
readonly updatedAt: string
}
```
### Q: Where is the membership selection happening?
**A:** `components/BookingConfirmPopup.vue:136-147`
```typescript
const selectedMembershipId = ref<string>('')
watch(
[() => props.visible, () => props.memberships],
([visible, memberships]) => {
if (visible && memberships.length > 0) {
selectedMembershipId.value = memberships[0].id // Auto-select first
}
},
{ immediate: true },
)
```
### Q: Where are the button states determined?
**A:** `components/SlotCard.vue:15-45`
```vue
<!-- OPEN + not booked by me -->
<template v-if="slot.status === TimeSlotStatus.OPEN && !slot.isBookedByMe">
<view class="btn btn-book" @tap.stop="emit('book', slot)">
<text class="btn-text">可预约</text>
</view>
</template>
<!-- OPEN + booked by me -->
<template v-else-if="slot.status === TimeSlotStatus.OPEN && slot.isBookedByMe">
<view class="booked-row">
<view class="badge-booked">
<text class="badge-text">已预约</text>
</view>
<view class="btn-cancel" @tap.stop="emit('cancel', slot)">
<text class="btn-cancel-text">取消</text>
</view>
</view>
</template>
<!-- FULL or CLOSED -->
<template v-else>
<view class="btn btn-disabled">
<text class="btn-text">
{{ slot.status === TimeSlotStatus.FULL ? '已约满' : '已关闭' }}
</text>
</view>
</template>
```
### Q: Where is the API request actually made?
**A:** `utils/request.ts:22-59`
```typescript
export function request<T>(options: RequestOptions): Promise<T> {
return new Promise((resolve, reject) => {
const token = uni.getStorageSync('token') as string
uni.request({
url: `${BASE_URL}${options.url}`, // BASE_URL = http://localhost:3000/api
method: options.method || 'GET',
data: options.data,
header: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options.header,
},
success: (res) => {
if (res.statusCode === 401) {
uni.removeStorageSync('token')
uni.showToast({ title: '请重新登录', icon: 'none' })
reject(new Error('Unauthorized'))
return
}
if (res.statusCode >= 400) {
const body = res.data as ApiResponse<unknown>
reject(new Error(body?.message || `请求失败 (${res.statusCode})`))
return
}
const body = res.data as ApiResponse<T>
if (body.success) {
resolve(body.data as T) // ← Extract data from ApiResponse
} else {
reject(new Error(body.message || '请求失败'))
}
},
fail: (err) => {
reject(new Error(err.errMsg || '网络请求失败'))
},
})
})
}
```
---
## 🐛 Debugging Tips
### Tip 1: Check what's in the store
```typescript
// In browser console while in booking page:
console.log('Slots:', JSON.stringify(uni.$u.pinia.state.value.booking.slots, null, 2))
console.log('Selected period:', uni.$u.pinia.state.value.booking.selectedPeriod)
```
### Tip 2: Log slot filtering
```typescript
// Add to pages/booking/index.vue filteredSlots computed:
const filteredSlots = computed<TimeSlotWithBookingStatus[]>(() => {
const slots = bookingStore.slots as TimeSlotWithBookingStatus[]
if (!selectedPeriod.value) {
console.log('No period filter, showing all slots:', slots.length)
return [...slots]
}
const period = TIME_PERIODS[selectedPeriod.value]
console.log(`Filtering by ${selectedPeriod.value}:`, period)
console.log('All slot times:', slots.map(s => s.startTime))
const filtered = slots.filter((slot) => {
const t = slot.startTime
const matches = t >= period.start && t < period.end
if (!matches) console.log(`${t} not in [${period.start}, ${period.end})`)
return matches
})
console.log('Filtered result:', filtered.length)
return filtered
})
```
### Tip 3: Verify API response
```typescript
// In stores/booking.ts fetchSlots():
async function fetchSlots(date: string) {
loadingSlots.value = true
try {
console.log('Fetching slots for date:', date)
slots.value = await get<TimeSlotWithBookingStatus[]>(
'/time-slot/available',
{ date }
)
console.log('Received slots:', slots.value)
console.log('Slot count:', slots.value.length)
if (slots.value.length > 0) {
console.log('First slot:', JSON.stringify(slots.value[0], null, 2))
}
} catch (err) {
console.error('Fetch slots failed:', err)
slots.value = []
} finally {
loadingSlots.value = false
}
}
```
### Tip 4: Check network requests
```typescript
// Open WeChat DevTools → Network tab
// Look for GET request to /time-slot/available
// Check:
// ✓ URL has ?date=YYYY-MM-DD
// ✓ Authorization header exists
// ✓ Response status 200
// ✓ Response body has "success": true
```
---
## ❌ Common Issues & Solutions
### Issue 1: Slots not loading
**Symptoms:**
- Page shows "当日暂无可约时段" (no slots)
- No error message
**Check list:**
```typescript
// 1. Is API endpoint correct?
// Check: /time-slot/available?date=2026-04-05
// Should return TimeSlotWithBookingStatus[]
// 2. Is date format correct?
// Page sends: formatDate(new Date()) → "2026-04-05"
// API expects: "YYYY-MM-DD"
console.log(formatDate(new Date())) // Should output: "2026-04-05"
// 3. Is authentication working?
console.log('Token:', uni.getStorageSync('token'))
// 4. Check for errors in console
// If fetchSlots fails, slots.value becomes []
```
**Solution:**
```typescript
// In bookingStore.fetchSlots(), add error state:
const error = ref<string | null>(null)
async function fetchSlots(date: string) {
loadingSlots.value = true
error.value = null // Clear previous error
try {
slots.value = await get<TimeSlotWithBookingStatus[]>(
'/time-slot/available',
{ date }
)
} catch (err) {
console.error('Fetch slots failed:', err)
error.value = err instanceof Error ? err.message : '加载失败'
slots.value = []
} finally {
loadingSlots.value = false
}
}
// Then in page template:
<view v-if="error" class="error-wrap">
<text>{{ error }}</text>
<view @tap="loadSlots(selectedDate)"></view>
</view>
```
### Issue 2: Time period filtering not working
**Symptoms:**
- Select "上午" (morning) but all slots still show
- Or vice versa
**Check:**
```typescript
// 1. Verify TIME_PERIODS constant
console.log('TIME_PERIODS:', TIME_PERIODS)
// 2. Check selectedPeriod value
console.log('Selected period:', selectedPeriod.value)
// 3. Verify slot.startTime format
// Should be "HH:MM" like "09:00", not "09:00:00"
bookingStore.slots.forEach(slot => {
console.log('Slot time:', slot.startTime, 'format ok?', /^\d{2}:\d{2}$/.test(slot.startTime))
})
// 4. Test filtering manually
const slot = bookingStore.slots[0]
const period = TIME_PERIODS.MORNING
console.log(`${slot.startTime} >= ${period.start}?`, slot.startTime >= period.start)
console.log(`${slot.startTime} < ${period.end}?`, slot.startTime < period.end)
```
**Solution:**
```typescript
// If time format is "09:00:00", slice it:
const filteredSlots = computed<TimeSlotWithBookingStatus[]>(() => {
const slots = bookingStore.slots as TimeSlotWithBookingStatus[]
if (!selectedPeriod.value) return [...slots]
const period = TIME_PERIODS[selectedPeriod.value]
return slots.filter((slot) => {
// Ensure HH:MM format
const t = slot.startTime.slice(0, 5) // "09:00:00" → "09:00"
return t >= period.start && t < period.end
})
})
```
### Issue 3: Booking button not responding
**Symptoms:**
- Click "可预约" but nothing happens
- No modal appears
**Check:**
```typescript
// 1. Is slot.status correct?
console.log('Slot status:', slot.status)
// Should be "OPEN" to show book button
// 2. Is isBookedByMe false?
console.log('Is booked by me?', slot.isBookedByMe)
// Should be false to show book button
// 3. Is onBookTap being called?
// Add to pages/booking/index.vue:
async function onBookTap(slot: TimeSlotWithBookingStatus) {
console.log('Book tapped for slot:', slot) // ← Should log
// Rest of code...
}
// 4. Is userStore.loggedIn true?
console.log('Logged in?', userStore.loggedIn)
```
### Issue 4: Membership not showing in popup
**Symptoms:**
- Booking popup appears but no membership card shown
- "暂无可用会员卡" displayed
**Check:**
```typescript
// 1. Are memberships loaded?
console.log('Memberships:', userStore.memberships)
// 2. Are any memberships ACTIVE?
console.log('Active memberships:', userStore.activeMemberships)
console.log('Has valid membership?', userStore.hasValidMembership)
// 3. Are memberships passed to popup?
// In pages/booking/index.vue:
<BookingConfirmPopup
:memberships="userStore.activeMemberships as MembershipWithCardType[]"
...
/>
console.log('Popup passed memberships:', userStore.activeMemberships)
```
**Solution:**
```typescript
// In onMounted:
onMounted(async () => {
if (userStore.loggedIn && userStore.activeMemberships.length === 0) {
console.log('Fetching memberships...')
try {
await userStore.fetchMemberships()
console.log('Memberships loaded:', userStore.activeMemberships)
} catch (err) {
console.error('Failed to fetch memberships:', err)
uni.showToast({ title: '加载会员卡失败', icon: 'none' })
}
}
await loadSlots(selectedDate.value)
})
```
---
## 📊 Capacity Display Logic
### How Capacity Color is Determined
```typescript
// components/SlotCard.vue:69-81
const capacityLabel = computed(() => {
const { bookedCount, capacity, status } = props.slot
if (status === TimeSlotStatus.CLOSED) return '已关闭'
return `${bookedCount}/${capacity}`
})
const capacityClass = computed(() => {
const { bookedCount, capacity, status } = props.slot
if (status === TimeSlotStatus.CLOSED) return 'cap-closed'
if (status === TimeSlotStatus.FULL) return 'cap-full'
if (bookedCount >= capacity * 0.8) return 'cap-almost'
return 'cap-open'
})
// Color mapping in styles:
// cap-open: #f0faf3 bg, #4caf50 text (green) - <80% booked
// cap-almost: #fff8ed bg, #f59e0b text (orange) - ≥80% booked
// cap-full: #fef0f0 bg, #ef4444 text (red) - status: FULL
// cap-closed: #f5f5f5 bg, #999 text (gray) - status: CLOSED
```
### Example Calculations
```typescript
// Slot 1: capacity=1, bookedCount=0, status=OPEN
// 0/1 人 in green badge (0% booked)
// Slot 2: capacity=1, bookedCount=1, status=OPEN
// 1/1 人 in red badge (100% booked ≥ 80%)
// Slot 3: capacity=5, bookedCount=4, status=OPEN
// 4/5 人 in orange badge (80% booked ≥ 80%)
// Slot 4: capacity=5, bookedCount=3, status=OPEN
// 3/5 人 in green badge (60% booked < 80%)
```
---
## 🔗 API Contract Summary
### GET /time-slot/available
**Request:**
```
GET /api/time-slot/available?date=2026-04-05
Authorization: Bearer <token>
```
**Response (200 OK):**
```json
{
"success": true,
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"date": "2026-04-05",
"startTime": "09:00",
"endTime": "10:00",
"capacity": 1,
"bookedCount": 0,
"status": "OPEN",
"source": "MANUAL",
"templateId": null,
"createdAt": "2026-04-01T10:00:00Z",
"updatedAt": "2026-04-05T09:00:00Z",
"isBookedByMe": false,
"myBookingId": null
}
],
"message": null
}
```
**Error (400):**
```json
{
"success": false,
"data": null,
"message": "Invalid date format"
}
```
### POST /booking
**Request:**
```json
POST /api/booking
{
"timeSlotId": "550e8400-e29b-41d4-a716-446655440000",
"membershipId": "220e8400-e29b-41d4-a716-446655440111"
}
```
**Response (201):**
```json
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440222",
"userId": "user-123",
"timeSlotId": "550e8400-e29b-41d4-a716-446655440000",
"membershipId": "220e8400-e29b-41d4-a716-446655440111",
"status": "CONFIRMED",
"bookedAt": "2026-04-05T10:30:00Z",
"courseDate": "2026-04-05",
"courseTime": "09:00",
"instructorName": "instructor name",
"isCompleted": false
},
"message": null
}
```
### PUT /booking/:id/cancel
**Request:**
```
PUT /api/booking/550e8400-e29b-41d4-a716-446655440222/cancel
```
**Response (200):**
```json
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440222",
"status": "CANCELLED",
"cancelledAt": "2026-04-05T10:35:00Z"
},
"message": null
}
```
---
## 🎯 Next Steps for Debugging
1. **Verify API Endpoint**
- Open DevTools → Network
- Check `/time-slot/available?date=...` request
- Confirm response has `"success": true`
- Confirm data array is not empty
2. **Check Store State**
- Add console.logs to bookingStore.fetchSlots()
- Verify slots are set correctly
- Check loadingSlots toggle
3. **Verify Computed Properties**
- Log filteredSlots in component
- Check if filtering logic works
- Verify slot.startTime format
4. **Test User Interaction**
- Click date item → verify onDateSelect fires
- Click period tab → verify onPeriodChange fires
- Click book button → verify onBookTap fires
- Check modals appear
5. **Check Mobile-Specific Issues**
- Test in WeChat DevTools
- Check rpx calculations
- Verify touch events work

View File

@@ -1,244 +0,0 @@
# WeChat Mini-Program Admin Scheduling - Documentation Index
**Created**: 2026-04-05
**Project**: mp-pilates (Pilates Studio Booking System)
---
## 📚 Documentation Files
This exploration contains **3 comprehensive documents** about the admin scheduling/排课设置 system:
### 1. **ADMIN_SCHEDULING_EXPLORATION.md** (24 KB, 803 lines)
**Purpose**: Complete deep-dive into the scheduling system
**Sections**:
- Executive Summary
- File Structure (frontend, backend, shared)
- 4 Key Components (Admin Dashboard, Week Templates, Slot Adjustment, Admin Store)
- Backend Architecture (Controllers, Services, Slot Generator)
- Data Flow & User Journey
- Constants & Utilities
- Permission Model
- Implementation Status
- Edge Cases
- UI Design Patterns
- Deployment & Configuration
**Best for**: Understanding the complete architecture and how everything connects
---
### 2. **SCHEDULING_FLOW_DIAGRAM.md** (13 KB, 271 lines)
**Purpose**: Visual flowcharts and architecture diagrams
**Sections**:
- Component Architecture (visual tree)
- Data Flow: Template → Slots (visual flowchart)
- State Management breakdown
- API Endpoints Summary
- Entity Relationships (ER diagram)
- Weekday Mapping (ISO vs JS conversion)
- Timeline Example (realistic scenario)
**Best for**: Quick visual understanding of the flow and architecture
---
### 3. **SCHEDULING_QUICK_REFERENCE.md** (7.9 KB, 296 lines)
**Purpose**: Quick lookup guide for developers
**Sections**:
- Quick Links to Key Files (with line numbers)
- The Flow in 30 Seconds
- Core Entities (WeekTemplate, TimeSlot)
- API Endpoints (with JSON examples)
- UI State Management
- Permissions & Auth
- Important Constants
- Common Gotchas (5 key points)
- Usage Example (step-by-step)
- Related Components
- Scalability Notes
**Best for**: Developers jumping into the code for the first time
---
## 🎯 Choose Your Path
### If you want to...
**Understand the big picture**
→ Read: `SCHEDULING_FLOW_DIAGRAM.md`
→ Then: `ADMIN_SCHEDULING_EXPLORATION.md` (section 2)
**Start coding immediately**
→ Read: `SCHEDULING_QUICK_REFERENCE.md`
→ Then: Jump to specific file links
**Debug a specific issue**
→ Read: `SCHEDULING_QUICK_REFERENCE.md` (Common Gotchas)
→ Then: Search in `ADMIN_SCHEDULING_EXPLORATION.md`
**Understand data flow**
→ Read: `SCHEDULING_FLOW_DIAGRAM.md` (Data Flow section)
→ Then: `ADMIN_SCHEDULING_EXPLORATION.md` (section 7: Data Flow)
---
## 🔑 Key Files by Role
### Frontend Developer
**Must Read**:
- `SCHEDULING_QUICK_REFERENCE.md` → UI State Management
- `packages/app/src/pages/admin/week-template.vue` (500 lines)
- `packages/app/src/pages/admin/slot-adjust.vue` (428 lines)
- `packages/app/src/stores/admin.ts` (171 lines)
### Backend Developer
**Must Read**:
- `SCHEDULING_QUICK_REFERENCE.md` → API Endpoints
- `packages/server/src/time-slot/time-slot.controller.ts`
- `packages/server/src/time-slot/slot-generator.service.ts`
- `packages/server/src/time-slot/time-slot.service.ts`
### Full-Stack Developer
**Must Read**: All documentation files in order:
1. `SCHEDULING_QUICK_REFERENCE.md` (5 min)
2. `SCHEDULING_FLOW_DIAGRAM.md` (10 min)
3. `ADMIN_SCHEDULING_EXPLORATION.md` (20 min)
---
## 🎓 Learning Timeline
### Day 1: Orientation (30 minutes)
- Read: `SCHEDULING_QUICK_REFERENCE.md` section "The Flow: In 30 Seconds"
- Skim: `SCHEDULING_FLOW_DIAGRAM.md`
### Day 2: Deep Dive (1-2 hours)
- Read: `SCHEDULING_FLOW_DIAGRAM.md` (entire)
- Read: `ADMIN_SCHEDULING_EXPLORATION.md` (sections 1-3)
### Day 3: Implementation (ongoing)
- Refer to: `SCHEDULING_QUICK_REFERENCE.md` as needed
- Cross-reference: `ADMIN_SCHEDULING_EXPLORATION.md` sections 4-8
- Check: Backend/Frontend specific sections
---
## 🔗 File Paths: Quick Lookup
| Component | Path | Lines |
|-----------|------|-------|
| Admin Dashboard | `packages/app/src/pages/admin/index.vue` | 177 |
| **Week Templates** | `packages/app/src/pages/admin/week-template.vue` | 500 ⭐ |
| Slot Adjustment | `packages/app/src/pages/admin/slot-adjust.vue` | 428 |
| Admin Store | `packages/app/src/stores/admin.ts` | 171 |
| API Controller | `packages/server/src/time-slot/time-slot.controller.ts` | 92 |
| API Service | `packages/server/src/time-slot/time-slot.service.ts` | 142 |
| Slot Generator | `packages/server/src/time-slot/slot-generator.service.ts` | 172 |
| Types: Templates | `packages/shared/src/types/week-template.ts` | 19 |
| Types: Slots | `packages/shared/src/types/time-slot.ts` | 30 |
| Constants | `packages/shared/src/constants.ts` | 22 |
| Utilities | `packages/app/src/utils/format.ts` | 47 |
⭐ = Main scheduling component (排课设置)
---
## 📊 System Overview
```
┌─────────────────────────────────────────────────────────┐
│ ADMIN SCHEDULING SYSTEM │
├─────────────────────────────────────────────────────────┤
│ │
│ Frontend (Vue 3 + TypeScript) │
│ ├─ week-template.vue (templates CRUD) │
│ ├─ slot-adjust.vue (manual operations) │
│ └─ admin.ts (Pinia store) │
│ │
│ Backend (NestJS + Prisma) │
│ ├─ time-slot.controller.ts (API routes) │
│ ├─ time-slot.service.ts (business logic) │
│ └─ slot-generator.service.ts (auto-generation) │
│ │
│ Database (PostgreSQL/MySQL) │
│ ├─ WeekTemplate (recurring schedule rules) │
│ ├─ TimeSlot (actual bookable slots) │
│ └─ Booking (user reservations) │
│ │
└─────────────────────────────────────────────────────────┘
```
---
## 🚀 Quick Start Checklist
- [ ] Read `SCHEDULING_QUICK_REFERENCE.md` (5 min)
- [ ] Skim `SCHEDULING_FLOW_DIAGRAM.md` (5 min)
- [ ] Open `packages/app/src/pages/admin/week-template.vue`
- [ ] Open `packages/server/src/time-slot/slot-generator.service.ts`
- [ ] Bookmark this index file for reference
- [ ] Ask questions about specific sections in the docs
---
## 📝 Terms & Definitions
| Term | Definition |
|------|-----------|
| **WeekTemplate** | Recurring schedule rule (e.g., "every Monday 9-10 AM") |
| **TimeSlot** | Actual bookable time (e.g., "Monday, April 6, 9-10 AM") |
| **排课设置** | Schedule setup (admin template management) |
| **临时调整** | Temporary adjustments (manual slot operations) |
| **isDirty** | Flag indicating unsaved changes |
| **Atomic** | All-or-nothing database transaction |
| **skipDuplicates** | Prisma option to ignore duplicate records on batch insert |
| **ISO Weekday** | 1=Monday, 2=Tuesday, ..., 7=Sunday |
---
## 🆘 Getting Help
### Question Type → Documentation
**"How does admin add a new class?"**
`SCHEDULING_QUICK_REFERENCE.md` → Usage Example
**"What API endpoints exist?"**
`SCHEDULING_QUICK_REFERENCE.md` → API Endpoints
→ OR `ADMIN_SCHEDULING_EXPLORATION.md` → Backend Architecture
**"How do templates become slots?"**
`SCHEDULING_FLOW_DIAGRAM.md` → Data Flow section
**"What database schema?"**
`SCHEDULING_QUICK_REFERENCE.md` → Core Entities
→ OR `SCHEDULING_FLOW_DIAGRAM.md` → Entity Relationships
**"Where does X file?"**
`SCHEDULING_QUICK_REFERENCE.md` → File Paths lookup table
---
## ✅ Verification Checklist
- [x] All 3 documentation files created
- [x] 803 + 271 + 296 = 1,370 lines of documentation
- [x] Complete file paths documented
- [x] API endpoints listed with examples
- [x] Data flow diagrams included
- [x] Common gotchas documented
- [x] Usage examples provided
- [x] Scalability notes included
- [x] Permission model explained
- [x] Timezone handling noted
---
**Last Updated**: 2026-04-05
**Status**: Complete and ready for reference

View File

@@ -1,271 +0,0 @@
# Admin Scheduling Flow Diagram
## Component Architecture
```
┌─────────────────────────────────────────────────────────┐
│ Admin Dashboard │
│ (pages/admin/index.vue) │
│ │
│ 📅 排课设置 🔧 临时调整 👥 会员 📋 订单 💳 卡 🏢 工作室
└─────────────────────────────────────────────────────────┘
└─► 📅 排课设置 (Week Template)
└─────────────────────────────────────────┐
│ pages/admin/week-template.vue │
│ ================================ │
│ │
│ 1. Fetch Templates (onMounted) │
│ └─ GET /admin/week-template │
│ │
│ 2. Display grouped by day (Mon-Sun) │
│ │
│ 3. Add/Edit/Delete/Toggle locally │
│ └─ isDirty flag = true │
│ │
│ 4. Save All Changes (bottom bar) │
│ └─ PUT /admin/week-template │
│ (Full template array) │
│ │
│ 5. Backend transaction: │
│ - DELETE all templates │
│ - CREATE new templates │
└────────────────────────────────────────┘
└─► 🔧 临时调整 (Slot Adjustment - 3 Tabs)
└─────────────────────────────────────────┐
│ pages/admin/slot-adjust.vue │
│ ================================ │
│ │
│ TAB 0: 新增时段 (Add Manual Slot) │
│ ├─ Date picker │
│ ├─ Time pickers │
│ ├─ Capacity input │
│ └─ POST /admin/time-slot/manual │
│ └─ Creates slot with source=MANUAL │
│ │
│ TAB 1: 关闭时段 (Close Slots) │
│ ├─ Date picker │
│ ├─ Fetch slots for date │
│ │ └─ GET /admin/time-slots?date=XXX │
│ ├─ Display with status badges │
│ │ (OPEN/FULL/CLOSED) │
│ └─ PUT /admin/time-slot/:id/close │
│ │
│ TAB 2: 批量生成 (Batch Generate) │
│ ├─ Start/end date pickers │
│ ├─ POST /admin/generate-slots │
│ └─ Backend: │
│ 1. Fetch active WeekTemplates │
│ 2. For each day in range: │
│ - Get ISO weekday (1-7) │
│ - Find matching templates │
│ - Create TimeSlot records │
│ 3. Returns { count: N } │
└────────────────────────────────────────┘
```
## Data Flow: Template → Slots
```
┌──────────────────────────────────────────────────────────────────┐
│ ADMIN TEMPLATE SETUP │
│ (weeks/admin/week-template.vue) │
└──────────────────────────────────────────────────────────────────┘
┌───────────────────────────────────┐
│ Admin configures templates: │
│ │
│ 周一: 09:00-10:00 (10 ppl) │
│ 周一: 18:00-19:00 (8 ppl) │
│ 周三: 10:00-11:00 (12 ppl) │
│ 周五: 18:00-20:00 (15 ppl) │
└───────────────────────────────────┘
┌───────────────────────────────────┐
│ PUT /admin/week-template │
│ (All templates replaced) │
└───────────────────────────────────┘
┌────────────────────────────────────────────┐
│ Backend: Delete all, Create new (atomic) │
└────────────────────────────────────────────┘
┌────────────────────────────────────────────┐
│ Scheduler (nightly cron or manual trigger)│
│ POST /admin/generate-slots (14 days) │
└────────────────────────────────────────────┘
┌────────────────────────────────────────────┐
│ SlotGeneratorService.generateSlots() │
│ │
│ For each active template: │
│ For date in next 14 days: │
│ If template.dayOfWeek == date.dayOfWeek:
│ CREATE TimeSlot { │
│ date, startTime, endTime, │
│ capacity, source=TEMPLATE, │
│ templateId │
│ } │
└────────────────────────────────────────────┘
┌────────────────────────────────────────────┐
│ GENERATED TIME SLOTS │
│ │
│ 2026-04-06 (Mon): │
│ 09:00-10:00 (10 ppl, OPEN) │
│ 18:00-19:00 (8 ppl, OPEN) │
│ │
│ 2026-04-08 (Wed): │
│ 10:00-11:00 (12 ppl, OPEN) │
│ │
│ 2026-04-11 (Fri): │
│ 18:00-20:00 (15 ppl, OPEN) │
│ ... (more dates) │
└────────────────────────────────────────────┘
┌────────────────────────────────────────────┐
│ Members can book available slots │
│ GET /time-slot/available?date=YYYY-MM-DD
└────────────────────────────────────────────┘
```
## State Management
### Component State (week-template.vue)
```typescript
templates: LocalTemplate[] Main data array
loading: boolean Fetch state
saving: boolean Save state
isDirty: boolean "Save bar" trigger
showModal: boolean Modal visibility
editTarget: LocalTemplate | null Which template is being edited
form: { Modal form data
dayIdx: number
startTime: string
endTime: string
capacityStr: string
}
grouped: Computed<Record<number, LocalTemplate[]>> Grouped by dayOfWeek
```
### Store State (stores/admin.ts)
```typescript
weekTemplates: WeekTemplate[] Cached from server
cardTypes: CardType[]
studioConfig: StudioConfig | null
// ...other admin state
```
## API Endpoints Summary
### Week Templates
```
GET /admin/week-template Fetch all templates
PUT /admin/week-template Replace all templates
```
### Time Slots
```
GET /admin/time-slots?date=YYYY-MM-DD Fetch slots for date
POST /admin/time-slot/manual Create manual slot
PUT /admin/time-slot/:id/close Close a slot
POST /admin/generate-slots Generate slots from templates
```
### Public Endpoints
```
GET /time-slot/available?date=YYYY-MM-DD For members
GET /time-slot/:id For members
```
## Entity Relationships
```
┌─────────────────────┐
│ WeekTemplate │
├─────────────────────┤
│ id │
│ dayOfWeek (1-7) │
│ startTime │
│ endTime │
│ capacity │
│ isActive │
└─────────────────────┘
│ (1:N)
┌─────────────────────┐ ┌──────────────────┐
│ TimeSlot │ │ Booking (M:1) │
├─────────────────────┤ ├──────────────────┤
│ id │◄─────│ timeSlotId │
│ date │ │ userId │
│ startTime │ │ status │
│ endTime │ └──────────────────┘
│ capacity │
│ bookedCount │
│ status │
│ source (TEMPLATE/ │
│ MANUAL) │
│ templateId (FK) │
└─────────────────────┘
```
## Weekday Mapping
### Frontend Picker (dayOptions)
```
Index 0: 周一 (Monday) ──► dayOfWeek = 1
Index 1: 周二 (Tuesday) ──► dayOfWeek = 2
Index 2: 周三 (Wednesday) ──► dayOfWeek = 3
Index 3: 周四 (Thursday) ──► dayOfWeek = 4
Index 4: 周五 (Friday) ──► dayOfWeek = 5
Index 5: 周六 (Saturday) ──► dayOfWeek = 6
Index 6: 周日 (Sunday) ──► dayOfWeek = 7
```
### Backend Conversion (slot-generator.service.ts)
```typescript
JS getDay(): 0=Sun, 1=Mon, 2=Tue, ..., 6=Sat
toIsoWeekday()
ISO weekday: 1=Mon, 2=Tue, ..., 7=Sun
```
## Timeline Example
```
TODAY: 2026-04-05 (Sunday)
Admin actions:
1. Sets up weekly templates for Mon-Fri
2. Taps "保存全部更改"
3. PUT /admin/week-template sent
Backend scheduler (daily at midnight):
4. Runs generateSlots(14)
5. Tomorrow is 2026-04-06 (Monday)
6. Generates slots for Apr 6-19 (next 14 days)
7. Creates TimeSlots based on active templates:
Generated slots:
2026-04-06 (Mon): 09:00-10:00, 18:00-19:00
2026-04-07 (Tue): (none if no templates)
2026-04-08 (Wed): 10:00-11:00
2026-04-09 (Thu): (none if no templates)
2026-04-10 (Fri): 18:00-20:00
2026-04-11 (Sat): (none - weekend)
2026-04-12 (Sun): (none - weekend)
...repeats until 2026-04-19
Members can book from Apr 6 onwards
```

View File

@@ -1,296 +0,0 @@
# Admin Scheduling - Quick Reference Guide
## 🎯 Quick Links to Key Files
### Frontend Components
| File | Lines | Purpose |
|------|-------|---------|
| `packages/app/src/pages/admin/index.vue` | 1-177 | Admin dashboard, 6 nav items |
| `packages/app/src/pages/admin/week-template.vue` | 1-500 | **MAIN: Schedule template management** |
| `packages/app/src/pages/admin/slot-adjust.vue` | 1-428 | 3 tabs: add/close/generate slots |
| `packages/app/src/stores/admin.ts` | 1-171 | API calls (Pinia store) |
### Backend Services
| File | Purpose |
|------|---------|
| `packages/server/src/time-slot/time-slot.controller.ts` | API endpoints (/admin/*) |
| `packages/server/src/time-slot/time-slot.service.ts` | Template & slot logic |
| `packages/server/src/time-slot/slot-generator.service.ts` | Auto-generate slots from templates |
| `packages/server/src/time-slot/dto/week-template.dto.ts` | Input validation |
### Shared Types & Constants
| File | Exports |
|------|---------|
| `packages/shared/src/types/week-template.ts` | `WeekTemplate`, `WeekTemplateInput` |
| `packages/shared/src/types/time-slot.ts` | `TimeSlot`, `CreateManualSlotDto` |
| `packages/shared/src/constants.ts` | `WEEKDAY_LABELS`, `SLOT_GENERATION_DAYS`, etc. |
---
## 🔄 The Flow: In 30 Seconds
```
Admin edits templates
isDirty = true → Save bar appears
Admin taps "保存全部更改"
PUT /admin/week-template (full array)
Backend: DELETE all, CREATE new (atomic)
Scheduler triggers (nightly or manual)
POST /admin/generate-slots
SlotGeneratorService fetches active templates
For each day (next 14 days):
Match templates by ISO weekday
Create TimeSlot records (source=TEMPLATE)
Members see slots and can book
```
---
## 📊 Core Entities
### WeekTemplate (Database)
```typescript
id: string // UUID
dayOfWeek: number // 1=Mon, 2=Tue, ..., 7=Sun
startTime: string // "09:00"
endTime: string // "10:00"
capacity: number // Max bookings
isActive: boolean // Enabled/disabled
createdAt: string
updatedAt: string
```
### TimeSlot (Database)
```typescript
id: string
date: string // YYYY-MM-DD
startTime: string
endTime: string
capacity: number
bookedCount: number // How many booked
status: "OPEN" | "FULL" | "CLOSED"
source: "TEMPLATE" | "MANUAL"
templateId: string | null // Links to WeekTemplate
createdAt: string
updatedAt: string
```
---
## 🌐 API Endpoints
### GET /admin/week-template
Returns all templates (ordered by dayOfWeek ASC, startTime ASC)
```json
[
{
"id": "uuid1",
"dayOfWeek": 1,
"startTime": "09:00",
"endTime": "10:00",
"capacity": 10,
"isActive": true,
"createdAt": "2026-04-05T00:00:00Z",
"updatedAt": "2026-04-05T00:00:00Z"
}
]
```
### PUT /admin/week-template
Replace all templates (atomic transaction)
```json
{
"templates": [
{ "dayOfWeek": 1, "startTime": "09:00", "endTime": "10:00", "capacity": 10, "isActive": true },
{ "dayOfWeek": 1, "startTime": "18:00", "endTime": "19:00", "capacity": 8, "isActive": true },
{ "dayOfWeek": 3, "startTime": "10:00", "endTime": "11:00", "capacity": 12, "isActive": false }
]
}
```
### POST /admin/time-slot/manual
Create a one-off slot
```json
{
"date": "2026-04-15",
"startTime": "14:00",
"endTime": "15:00",
"capacity": 10
}
```
### PUT /admin/time-slot/:id/close
Close a slot (changes status to CLOSED)
### POST /admin/generate-slots
Generate slots for next 14 days from active templates
Response: `{ "count": 28 }`
---
## 🎨 UI State Management
### week-template.vue Local State
```typescript
// Main data
templates: LocalTemplate[] // All templates
grouped: Computed<Record<number, LocalTemplate[]>> // By dayOfWeek
// UI states
loading: boolean // Initial fetch
saving: boolean // Save in progress
isDirty: boolean // Show save bar?
showModal: boolean // Show add/edit modal?
editTarget: LocalTemplate | null // Editing which template?
// Modal form
form: {
dayIdx: number // 0-6 (picker index)
startTime: string // "09:00"
endTime: string // "10:00"
capacityStr: string // User input as string
}
```
### Key Computed
```typescript
const grouped = computed(() => {
// Groups templates by dayOfWeek for rendering
// Sorts by day number ascending (1-7)
// Returns: { 1: [...], 3: [...], 5: [...], ... }
})
```
---
## 🔐 Permissions & Auth
All `/admin/*` endpoints require:
1. Valid JWT token in `Authorization: Bearer <token>` header
2. User role must be `UserRole.ADMIN`
3. Guards: `@UseGuards(JwtAuthGuard, RolesGuard)`
---
## 🧮 Important Constants
From `packages/shared/src/constants.ts`:
```typescript
SLOT_GENERATION_DAYS = 14 // Generate 14 days ahead
DEFAULT_SLOT_CAPACITY = 1 // Private lesson default
DEFAULT_CANCEL_HOURS_LIMIT = 2 // Cancel up to 2 hours before
WEEKDAY_LABELS = [
'', // index 0 (unused)
'周一', // index 1 → dayOfWeek 1 (Monday)
'周二', // index 2 → dayOfWeek 2
'周三', // ... etc
'周四',
'周五',
'周六',
'周日' // index 7 → dayOfWeek 7 (Sunday)
]
```
---
## 🐛 Common Gotchas
### 1. dayOfWeek vs JS getDay()
- **Frontend uses**: ISO weekday (1=Mon, 7=Sun)
- **JS Date.getDay()**: 0=Sun, 6=Sat
- **Backend converts**: `toIsoWeekday()` in slot-generator.service.ts
### 2. Template Replace (Not Merge)
- `PUT /admin/week-template` **deletes all** and creates new
- NOT a merge/patch operation
- Frontend must send complete array
### 3. isDirty Flag
- Tracks **any** change locally (add/edit/delete/toggle)
- Used to show/hide save bar
- Cleared after successful save
### 4. Timezone
- All dates stored as UTC midnight: `setUTCHours(0,0,0,0)`
- Frontend displays as local YYYY-MM-DD strings
- May cause off-by-one on day boundaries
### 5. Slot Generation
- Uses `skipDuplicates: true` in Prisma
- Safe to re-run without creating duplicates
- Assumes `date + startTime + endTime` is unique
---
## 💡 Usage Example: Add a Monday 9AM Class
**Frontend (week-template.vue)**:
```typescript
// User clicks "+ 新增时段"
openAdd()
form.value = { dayIdx: 0, startTime: '09:00', endTime: '10:00', capacityStr: '10' }
showModal.value = true
// User confirms in modal
submitForm()
templates.value.push({
_key: String(Date.now()),
dayOfWeek: 1, // dayOptions[0].value = Monday
startTime: '09:00',
endTime: '10:00',
capacity: 10,
isActive: true
})
isDirty.value = true // ← Save bar appears
// User taps "保存全部更改"
handleSave()
payload = templates.value.map(t => ({...}))
await adminStore.saveWeekTemplates(payload)
// Backend creates transaction:
// DELETE FROM week_template
// INSERT INTO week_template (day_of_week, start_time, end_time, capacity, is_active)
// VALUES (1, '09:00', '10:00', 10, true)
// ... (all other templates)
// Frontend refetches and displays
```
---
## 🔗 Related Components
- **Admin Members** (`pages/admin/members.vue`): Shows member list
- **Admin Orders** (`pages/admin/orders.vue`): Shows order history
- **Admin Card Types** (`pages/admin/card-types.vue`): Manage membership cards
- **Admin Studio** (`pages/admin/studio.vue`): Studio info settings
---
## 📈 Scalability Notes
### Current Approach
- Templates: Small dataset (typically < 50 records)
- Slots: Generated in batches (14 days at a time)
- Uses `skipDuplicates` to handle reruns safely
### Bottlenecks
- Template replacement deletes ALL and creates NEW (atomic but slow with 1000s)
- Slot generation is serial (could be parallelized)
- No pagination for templates (assumes all fit in memory)
### Future Improvements
- Batch template updates (don't replace all)
- Pagination if templates > 100
- Incremental slot generation (detect last generated date)

View File

@@ -117,6 +117,7 @@ echo_info "文件上传完成"
# 6. 服务器端安装依赖并重启
echo_info "服务器部署操作..."
ssh ${SERVER_USER}@${SERVER_HOST} "bash -l" << 'ENDSSH'
set -e
export PATH="$HOME/.nvm/versions/node/v22.17.1/bin:$PATH"
SERVER_PATH="/usr/local/web/mp-pilates-server"
PM2_APP_NAME="mp-pilates-server"

338
docs/STUDIO_COS_SETUP.md Normal file
View File

@@ -0,0 +1,338 @@
# 工作室画廊 COS 接入配置说明
本文档对应当前仓库当前实现。
现在已经不再使用 STS `AssumeRole`
当前方案改为:
- 服务端使用长期密钥直接签发 COS POST Policy
- 管理中心小程序拿到表单签名后直传 COS
- 工作室配置中的 `logo``bannerUrl``photos` 保存最终可访问 URL
当前实现代码入口:
- `packages/server/src/studio/studio-upload.service.ts`
- `packages/server/src/studio/studio.controller.ts`
- `packages/app/src/utils/studio-upload.ts`
- `packages/app/src/pages/admin/studio.vue`
## 一、整体链路
1. 管理中心点击上传图片。
2. 小程序请求服务端 `POST /api/admin/studio/upload-credentials`
3. 服务端用 `COS_SECRET_ID``COS_SECRET_KEY` 直接生成一组 POST Policy 表单字段。
4. 服务端把 `uploadUrl``key``formData``fileUrl``expiresAt` 返回给小程序。
5. 小程序使用 `uni.uploadFile` 直接上传到 COS。
6. 上传成功后,把 URL 保存到工作室配置,再调用 `PUT /api/admin/studio/info` 落库。
这个方案没有临时密钥,也没有角色扮演。
安全边界来自两层:
- 服务端只为单个对象 key 签发一次表单策略
- 表单策略有明确过期时间,过期后自动失效
## 二、这个方案的本质
你现在选的是“服务端代签名”的直传方案。
它和 STS 的差别是:
- STS给前端一段时间内可用的短期密钥
- 当前方案:不给前端密钥,只给前端一个短时有效的上传表单签名
所以结论很直接:
- 仍然有有效期
- 但有效期作用在 POST Policy 上,不是作用在临时密钥上
当前代码里默认有效期是 `1800` 秒。
环境变量:
- `COS_UPLOAD_DURATION_SECONDS`
当前实现限制范围:
- 最短 `300`
- 最长 `7200`
## 三、你现在真正需要准备的东西
先确认下面几个信息:
- COS Bucket 名称,例如 `plates-1251306435`
- COS 所在地域,例如 `ap-guangzhou`
- 服务端使用的 COS 长期密钥 `SecretId` / `SecretKey`
- 图片上传前缀,例如 `mp/studio`
- 图片访问域名
建议约定:
- Bucket`plates-1251306435`
- Region`ap-guangzhou`
- Prefix`mp/studio`
## 四、COS 控制台配置
### 1. 创建或确认 Bucket
控制台路径:`对象存储 COS`
建议:
- 地域选 `广州` 或你当前实际地域
- 存储类型标准存储即可
- Bucket 名称和环境变量保持完全一致
### 2. 图片访问方式
当前实现保存的是直接图片 URL。
所以图片必须能被小程序和前台直接访问。
你有两种方式:
1. 直接使用 COS 源站并允许读
2. 配 CDN / 自定义域名并让这个域名可直接访问图片
如果你什么都不配,上传成功后图片可能打不开。
最直接做法:
- 让这个图片 Bucket 对外可读
更稳妥做法:
- 单独图片 Bucket
- 用 CDN 域名做 `COS_PUBLIC_BASE_URL`
### 3. 微信小程序合法域名
微信公众平台需要补白名单:
- `request 合法域名`:你的后端 API 域名
- `uploadFile 合法域名``https://<bucket>.cos.<region>.myqcloud.com`
- `downloadFile 合法域名`:图片访问域名
如果图片访问也走 COS 源站,那么 `downloadFile 合法域名` 同样加:
- `https://<bucket>.cos.<region>.myqcloud.com`
例如:
- `https://focus.richarjiang.com`
- `https://plates-1251306435.cos.ap-guangzhou.myqcloud.com`
## 五、服务端账号需要什么权限
现在已经不需要:
- STS
- CAM 角色
- `AssumeRole`
- 角色信任策略
- `COS_UPLOAD_ROLE_ARN`
现在服务端只需要一对可以给目标 Bucket 生成上传签名的长期密钥。
最简单的做法是:
- 用你的主账号密钥
但生产上更合理的是:
- 建一个专用 CAM 用户,只给这个 Bucket 上传相关权限
### 推荐 CAM 用户权限策略
如果你要建专用 CAM 用户,给它绑定下面这类策略即可。
把下面真实值替换成你的实际资源:
- 地域:`ap-guangzhou`
- AppId`1251306435`
- Bucket`plates-1251306435`
- Prefix`mp/studio`
```json
{
"version": "2.0",
"statement": [
{
"effect": "allow",
"action": [
"name/cos:PutObject",
"name/cos:PostObject"
],
"resource": [
"qcs::cos:ap-guangzhou:uid/1251306435:plates-1251306435/mp/studio/*"
]
}
]
}
```
如果你后续还要服务端删除对象,再补:
- `name/cos:DeleteObject`
当前仓库实现不需要删除对象,所以先不要额外放大权限。
## 六、服务端环境变量
把下面变量配置到 `packages/server/.env` 或线上环境:
```env
COS_SECRET_ID=your-cos-secret-id
COS_SECRET_KEY=your-cos-secret-key
COS_BUCKET=plates-1251306435
COS_REGION=ap-guangzhou
COS_PUBLIC_BASE_URL=https://plates-1251306435.cos.ap-guangzhou.myqcloud.com
COS_UPLOAD_PREFIX=mp/studio
COS_UPLOAD_DURATION_SECONDS=1800
```
各字段含义:
- `COS_SECRET_ID`:用于签发 POST Policy 的长期密钥 ID
- `COS_SECRET_KEY`:用于签发 POST Policy 的长期密钥 Key
- `COS_BUCKET`:上传目标 Bucket
- `COS_REGION`Bucket 地域
- `COS_PUBLIC_BASE_URL`:最终展示图片的访问域名
- `COS_UPLOAD_PREFIX`:统一对象前缀
- `COS_UPLOAD_DURATION_SECONDS`Policy 有效期秒数
现在可以删除或忽略这些旧配置:
- `COS_UPLOAD_ROLE_ARN`
- `COS_APP_ID`
- `COS_UPLOAD_ROLE_SESSION_NAME`
它们对当前实现已经没用。
## 七、控制台操作清单
按这个顺序做:
1. 确认 COS Bucket 已存在。
2. 确认图片访问域名对外可读。
3. 在微信公众平台加好 `request` / `uploadFile` / `downloadFile` 合法域名。
4. 准备一对 COS 长期密钥。
5.`COS_SECRET_ID``COS_SECRET_KEY``COS_BUCKET``COS_REGION``COS_PUBLIC_BASE_URL``COS_UPLOAD_PREFIX` 配到服务端。
6. 重启服务端。
7. 在管理中心上传一张图片测试。
## 八、接口返回内容说明
请求:
```http
POST /api/admin/studio/upload-credentials
Content-Type: application/json
Authorization: Bearer <admin-token>
{
"fileName": "demo.jpg",
"contentType": "image/jpeg",
"assetType": "gallery"
}
```
正常返回会包含:
- `uploadUrl`
- `fileUrl`
- `key`
- `assetType`
- `expiresAt`
- `formData`
`formData` 里会有这些字段:
- `key`
- `policy`
- `success_action_status`
- `Content-Type`
- `q-sign-algorithm`
- `q-ak`
- `q-key-time`
- `q-sign-time`
- `q-signature`
这就是小程序直传需要的全部内容。
## 九、怎么验证是否配置正确
### 1. 接口层验证
调用 `POST /api/admin/studio/upload-credentials`
如果成功,说明:
- 服务端长期密钥有效
- 服务端已经能正确签发 policy
### 2. 上传层验证
在管理中心上传一张图,检查:
1. COS Bucket 下是否出现对象
2. 返回的 `fileUrl` 浏览器是否能直接访问
3. 保存工作室设置后首页是否显示该图
### 3. 失败时怎么定位
如果 `upload-credentials` 接口失败,优先检查:
- `COS_SECRET_ID` / `COS_SECRET_KEY` 是否正确
- `COS_BUCKET` / `COS_REGION` 是否正确
- 服务端是否已经加载最新环境变量
如果接口成功但上传失败,优先检查:
- 小程序 `uploadFile 合法域名` 是否正确
- Bucket 权限策略是否允许当前长期密钥上传到该前缀
- `Content-Type` 是否被策略条件限制住
如果上传成功但图片打不开,优先检查:
- Bucket 或图片域名是否可公网访问
- `COS_PUBLIC_BASE_URL` 是否正确
- 小程序 `downloadFile 合法域名` 是否正确
## 十、当前实现的边界
当前仓库实现边界如下:
- 只支持 `jpg``jpeg``png``webp``heic``heif`
- 单次上传大小上限 `10MB`
- 只支持普通表单直传,不支持分片上传
- 删除工作室图片时,只会从数据库配置里移除 URL不会删除 COS 历史对象
最后一条是故意保守设计。
原因很简单:
- 先保证配置删除安全
- 避免误删真实文件
如果以后要做“删配置时同步删对象”,那时再单独加 `DeleteObject` 权限。
## 十一、初始化工作室画廊
如果你要把现在手工写死的图片 URL 一次性写入数据库,执行:
```bash
pnpm --filter @mp-pilates/server studio:seed-gallery
```
脚本文件:
- `packages/server/prisma/update-studio-gallery.ts`
## 十二、建议的生产做法
如果你后面要长期维护,建议:
1. 图片单独放一个 Bucket。
2. 长期密钥不要直接用主账号,换成专用 CAM 用户。
3. 对专用 CAM 用户只给 `mp/studio/*` 前缀上传权限。
4. 用 CDN 域名作为 `COS_PUBLIC_BASE_URL`
这样后面扩展、迁移、审计都会更稳。

118
docs/body-portrait.md Normal file
View File

@@ -0,0 +1,118 @@
# 个人身体画像增长系统
入口小程序「3 分钟身体状态评估」、报告页、体验预约,以及管理中心「今日经营助手」。线上获客归属独立 `body-portrait` 模块;线下专业评估与改善计划复用成长档案口径,不把问卷结果写成医疗诊断。
## 产品口径
- 对外名称:**3 分钟身体状态评估 / 个人身体画像**。只使用「关注度、可能表现、建议进一步评估」。禁止「诊断、疾病检测、患病风险、准确率」。
- 分数 0100 只表示**问卷关注度**,不表示身体能力、疼痛程度或患病概率。
- 陌生用户可匿名完成问卷。完成后先看摘要;微信登录并认领后看完整报告。点击体验预约时必须授权手机号。
- 安全分流不计分。命中持续明显疼痛、近期受伤、手脚明显麻木、医生限制运动或医疗恢复期时,不展示动作建议和强销售 CTA。
- 评分只在服务端用版本化规则引擎计算。客户端不得提交分数、画像类型或线索阶段。LLM 不决定结论。
- 现有 `TRIAL` 体验卡就是「评估 + 普拉提体验」。画像只补来源关联,不新增商品类型。
- 成长照片沿用私有 COS、短时签名和学员授权。馆主可见不等于可公开分享。
## 免责声明
各入口固定文案:
> 本评估不是医疗诊断或体态疾病检测,仅用于运动训练参考。若你正处于明显疼痛、伤病或医生限制运动的阶段,请先由医生或相应专业人士确认运动条件。
保存说明:匿名未认领草稿默认 30 天后清理。认领后的健康相关数据仅用于训练评估与跟进;学员可申请删除,审计事件保留必要边界。
## 问卷版本 `portrait-q-v1`
每屏一个决策,可多选的题目明确标注。不询问「骨盆前倾」等专业病名。
| 步骤 | ID | 题干 | 类型 |
| --- | --- | --- | --- |
| 1 | `concerns` | 最近身体哪里最困扰你? | 人体图多选 |
| 2 | `goal` | 如果训练有效果,你最希望看到什么变化? | 单选 |
| 3 | `sittingHours` | 每天坐多久? | 单选 |
| 4 | `exerciseFreq` | 平时运动频率? | 单选 |
| 5 | `workPosture` | 工作时最常见状态? | 单选 |
| 6 | `endOfDayFatigue` | 一天结束后,身体哪里最累? | 人体图多选 |
| 7 | `afterSitting` | 长时间坐着后,你会出现? | 多选 |
| 8 | `standingNotice` | 自然站立时,你有没有注意过? | 多选 |
| 9 | `safety` | 最近是否存在以下情况? | 多选,不计分 |
部位:头颈 `neck`、肩 `shoulder`、上背 `upperBack`、腰 `lowBack`、骨盆 `pelvis`、髋 `hip`、膝 `knee`、腿 `leg`
目标:看起来更挺拔 `posture`、肩颈没那么累 `neckRelief`、久坐更舒服 `backComfort`、腹部更有力量 `core`、身体线条更好 `shaping`、腿型/髋部状态改善 `hipLeg`、动作更稳定 `stability`、我有自己的目标 `other`
## 五维与关注度
维度:肩颈状态 `cervicalShoulder`、脊柱活动 `spinalMobility`、核心控制 `coreControl`、髋骨盆状态 `hipPelvis`、下肢稳定 `lowerLimb`
| 分数 | 关注度 |
| ---: | --- |
| 030 | 低关注 |
| 3150 | 轻度关注 |
| 5170 | 中度关注 |
| 7185 | 高关注 |
| 86100 | 重点关注 |
规则版本 `portrait-r-v1`:先按答案累加,再把每一维 clamp 到 0100。安全选项不加分。
## 画像模板8 种)
主类型 1 个,次类型最多 1 个。
| ID | 标签 |
| --- | --- |
| `sedentaryNeckTension` | 久坐肩颈紧张型 |
| `sedentaryCoreWeak` | 久坐核心弱化型 |
| `neckCompensation` | 肩颈代偿型 |
| `hipTight` | 髋部紧张型 |
| `upperLowerCross` | 上下交叉混合型 |
| `lowerLimbUnstable` | 下肢稳定不足型 |
| `mixedFatigue` | 全身疲劳累积型 |
| `lowOverallConcern` | 整体关注度较低型 |
## 报告结构
1. 一句话结论 + 主/次类型 + 问卷依据(充分/一般,不是准确率)
2. 最多 3 个优先关注点,必须引用用户原话/选项
3. 问题之间的关联(例如久坐 → 胸椎活动减少 → 肩颈承担更多)
4. 三条日常建议;安全分流不下发动作。动作建议含停止条件
5. 线上局限 → 到店评估项目 → 现有体验卡
匹配度只展示「问卷依据:充分 / 一般」,由有效回答数和证据条数计算。
## 漏斗事件
服务端事实:`assessment_started` `assessment_completed` `assessment_claimed` `phone_bound` `trial_purchased` `trial_booked` `trial_attended` `plan_purchased`
客户端可报但需幂等:`report_viewed` `advice_viewed` `trial_clicked` `report_shared`
`trial_attended` 只由体验卡预约被核销COMPLETED产生不等于自动完成也不含补录。
渠道:`xhs` `wechat` `dianping` `member_share` `organic` `other`。分享链接只用邀请码/活动码,不暴露内部用户 ID。
## 线索阶段
只允许前进:`VISIT``STARTED``COMPLETED``CLAIMED``PHONE_BOUND``TRIAL_PURCHASED``TRIAL_BOOKED``TRIAL_ATTENDED``PLAN_PURCHASED``TRAINING``RENEWAL_DUE``RENEWED`。馆主可记跟进备注,不能把阶段任意倒退覆盖历史。
## 线下评估与改善计划V2
到店 60 分钟:沟通目标 → 静态体态 → 活动度 → 动作控制 → 普拉提体验 → 解释结果。协议版本 `offline-v1`。operatorId 不是授课老师。
12 周计划三阶段14 重新建立控制58 改善活动能力912 整合身体动作。卖的是改善计划不是「20 节课」。
## 复测与分享V3
默认可在第 4 / 8 / 12 节生成复测待办。对比必须同协议、同观察项。成长卡片默认不含照片;公开导出需学员单次确认。分享落地进入 `source=member_share` 的新测评。
## 部署
新增表见 `packages/server/prisma/migrations/20260911180000_body_portrait/migration.sql`。发布顺序:`prisma migrate deploy` → 后端 → 小程序。回退先回退应用,表可保留。
## 验收清单
- 匿名可完成、可续填;登录后同一会话只能认领一次。
- 完整报告需登录;体验预约需手机号。
- 安全分流不计分、无动作建议、无强销售。
- 分数与画像只来自服务端快照。
- 馆主今日待办能看到「测完未约 / 体验后未购 / 待复测」。
- 漏斗按渠道聚合;补录不进入获客转化。
- 照片与分享遵守成长档案隐私规则。

View File

@@ -0,0 +1,41 @@
# 移除秒杀功能
按业务调整下线限时秒杀活动。前后端代码、共享类型、Prisma schema 与迁移均已同步清理。
## 清理范围
| 层 | 内容 |
| --- | --- |
| 后端模块 | `packages/server/src/flash-sale/`(service、controller、admin controller、dto、测试) |
| 调度任务 | `SchedulerService.handleExpireFlashSaleReservations` 及其依赖注入 |
| 支付流程 | `PaymentService``flashSaleOrder` 标记为 PAID 的分支 |
| 前端页面 | `pages/flash-sale/detail.vue``pages/admin/flash-sales.vue` |
| 前端组件 | `components/FlashSaleSection.vue` |
| 前端状态 | `stores/flash-sale.ts` |
| 前端入口 | `pages/admin/index.vue` 秒杀管理菜单与对应样式 |
| 首页 | `pages/home/index.vue``FlashSaleSection` 引用 |
| 共享类型 | `shared/src/types/flash-sale.ts`,`enums.ts``FlashSaleStatus``FlashSaleOrderStatus`,以及 `index.ts` 的 re-export |
| 数据库 | Prisma 删除 `FlashSale``FlashSaleOrder` 模型、相关枚举与 `Order.flash_sale_id` 字段 |
## 数据库迁移
新增 `packages/server/prisma/migrations/20260910030338_drop_flash_sale/migration.sql`
执行 `pnpm prisma migrate deploy` 后以下内容会被移除:
- `flash_sales``flash_sale_orders` 两张表
- `orders.flash_sale_id` 列与外键
- `FlashSaleStatus``FlashSaleOrderStatus` 枚举
迁移以 MySQL 方言编写;SQLite 开发环境由 Prisma shadow database 自动重建。
## 验证
```bash
pnpm build:shared
pnpm build:server
pnpm test # 包含 payment / scheduler 套件
```
## 回退说明
回退需要还原 schema 与源码,本项目不保留 git 自动恢复外的额外兜底。如需重新启用秒杀,按 git 历史恢复即可,并运行 `pnpm prisma migrate reset` 重新初始化数据库。

32
docs/invite-marketing.md Normal file
View File

@@ -0,0 +1,32 @@
# 邀请好友领课时
个人中心为所有登录用户展示 6 位邀请码;首次访问 `/invite/code` 时惰性生成,字符避开 0、1、I、O。数据库唯一索引保证唯一条件更新和冲突重试保证并发安全无需回填存量用户。
分享入口使用微信 `button open-type="share"`,分享落地为 `/pages/card/detail?showAll=1&inviteCode=XXXXXX`。落地弹窗自动填码,未领取的列表价格标注「领取后 95 折」。用户确认后绑定一次,禁止自邀和更换邀请人;绑定后体验卡、次卡、期限卡及限时购卡均按当前售价享 95 折,按分四舍五入,后续购买自动享受。订单金额只由服务端计算。
每位好友首次支付非体验卡后,邀请人获得独立的 1 次赠课会员卡365 天有效;邀请人无需先持有会员卡。赠课卡隐藏于商品列表,可从「我的会员卡」预约。体验卡购买与上课均不发奖。每人只奖励一次,续购不重复奖励。
订单记录下单时的邀请人和卡片类别。支付到账、购卡权益、邀请资格更新、赠课及奖励记录处于同一数据库事务。条件更新防止并发回调、同一好友多笔订单重复发奖。历史无归因快照的订单不补发奖励;历史已 QUALIFIED 的邀请保留原资格,不重复奖励。
## 发布
先备份数据库,并在服务端运行 `pnpm exec prisma migrate deploy`,应用 `20260908000000_invite_codes`。该迁移新增可空邀请码、唯一索引、订单归因字段及隐藏赠课卡类型,不更新用户历史数据。
然后运行 `pnpm prisma:generate`,从仓库根目录运行 `pnpm build:shared``pnpm build:server``pnpm build:app`。先发布服务端,再发布小程序。无需新增环境变量。已于 2026-09-08 22:29北京时间执行生产迁移并发布后台小程序尚未发布。
## 真机验收
用两个微信账号验证:个人中心复制和好友分享;分享卡片落地列表与自动填码;未登录确认领取;重启后保留服务端优惠;原价和 95 折金额一致;体验卡支付不赠课;次卡/期限卡首次支付赠课到账;后续购买不再赠课;赠课可预约。还应验证支付失败、取消和重复回调。微信分享与真实微信支付仍需在部署后进行真机验证。
## 验证限制
邀请、支付和限时购卡价格测试通过。已在 390 × 844 的 H5 预览中检查个人中心入口和自动填码落地弹窗H5 预览不代替微信真机验收。全量测试中的旧 SchedulerService 测试缺少 FlashSaleService mock8 项失败,与本次修改无关。`pnpm lint` 因仓库未安装 ESLint 无法运行。
## 本次后台发布记录
- 目标:`129.204.155.94`,目录 `/usr/local/web/mp-pilates-server`PM2 服务 `mp-pilates-server`,端口 3008。
- 使用服务器现有 Node 22.16.0 和 Prisma 5.22.0;现有部署脚本中的 Node 22.17.1 路径不适用于当前服务器,因此按步骤发布构建,未修改线上环境配置及证书。
- 数据库迁移状态正常,新增 3 个字段及独立隐藏赠课卡核验通过。
- 公网 `/api/health``/api/membership/card-types` 返回 200商品列表不包含赠课卡未登录访问 `/api/invite/code` 返回预期的 401。
- 旧构建和 Prisma schema 已归档在服务器 `/usr/local/web/releases/mp-pilates-invite-20260908/previous-build.tgz`,新构建归档为同目录 `release.tgz`
- 本次只进行发布及只读核验,未制造测试用户、邀请关系或支付订单。微信真机分享与支付仍待小程序发布后联调。

29
docs/lesson-supplement.md Normal file
View File

@@ -0,0 +1,29 @@
# 历史课程补录
入口:会员档案 → 上课情况 → 补录上课。一次填写 1999 节,可备注,默认仅补记录,也可选择本人有限次会员卡扣次(含已过期卡)。不限次卡无需扣次;余额不足阻止提交。
一批补录展示为「系统补录 · N 节」,不是 N 个虚拟预约。累计已上课次数(个人中心、会员档案、会员列表已完成)增加 N累计预约、月度节数/天数/时长、最近 30 天网格、邀请奖励保持正常预约口径,因为补录没有真实上课日期。记录时间明确为补录时间。
老师与管理员共用 ADMIN 权限;成员只能读取自己的生效记录。事务保存记录与扣次快照,请求标识唯一,网络重试不重复扣次。撤销软删除,保留操作人与时间,只返还当时实际扣次,过期卡不重新激活。若原卡已转为不限次,撤销阻止并要求先核对卡状态。
## 迁移与发布
新增 `lesson_supplements` 表及关联索引,不修改既有预约数据。按仓库发布流程先执行 `prisma migrate deploy` 并重新生成 Prisma Client、发布后端再发布小程序。开发检查不自动触及生产数据库。
回退:先回退应用代码,保留新增表即可,旧代码不读取该表。若一定要移除表,须先导出审计数据并核对已扣会员卡余额;仅在未写入任何补录的环境可执行 `DROP TABLE lesson_supplements;`。MySQL DDL 不能靠事务回滚,不在生产自动执行删除。
## 本次验证
- 补录与用户统计相关 62 项测试通过,覆盖权限、数量校验、仅补记录、扣次、余额不足、过期卡、重复提交、并发冲突、撤销和统计口径。
- 共享包与后端构建、小程序构建、vue-tsc、Prisma schema 校验通过。
- 使用真实 Vue 页面与示例接口检查 375/320 宽度布局、十节补录、撤销、余额不足及学员历史记录;不替代微信真机与真实数据库联调。
- 全量测试存在原有 SchedulerService 测试依赖缺失:未提供 FlashSaleService8 项失败;其余已执行用例通过。
- 2026-09-08 已经用户授权执行生产迁移及后端发布;小程序仍需单独发布。
## 生产发布记录2026-09-08
- 执行 `pnpm deploy:server`,迁移 `20260908090000_add_lesson_supplements` 成功,全部 4 个迁移处于最新状态。
- 发布前数据库及后端备份保存在服务器 `/usr/local/web/mp-pilates-backups/20260908-145852/`
- 新表读取成功,验收时为 0 条记录;未创建测试补录或修改学员余额。
- 内网及公网 `https://focus.richarjiang.com/api/health` 均返回 `success: true``status: ok`PM2 `mp-pilates-server` 为 online重启计数为 0。
- 部署脚本增加远端 `set -e`,使依赖安装或迁移失败时停止发布。

41
docs/member-care.md Normal file
View File

@@ -0,0 +1,41 @@
# 课后评价与成长档案
入口:预约详情评价、个人中心「我的成长档案」、管理中心「课后评价」与会员档案「成长档案」。评价归属 booking 模块,档案归属 user 模块。共享契约在 `packages/shared/src/types/member-care.ts`
## 产品口径
- 课程变为 COMPLETED 后即可评价,没有 24 小时截止。完成后 24 小时只提醒仍未评价的预约。
- 同一预约只能评价一次。提醒状态写在 Booking 上,定时任务原子领取;发送结果未知或失败不自动重发。
- 星级均分与 NPS 分开。NPS 只用可选的 010 推荐意愿910 推荐者、06 贬损者),按中国自然月聚合并展示样本数。
- 教练私密笔记只在服务端过滤。课程批注必须属于该学员的已完成预约。
- 体测允许缺项,缺项不按 0 计算。累计课时含有效补录,里程碑为 10 / 30 / 50 节。
- 成长照片仅用于学员与馆主之间的档案,不用于公开宣传。学员本人授权或撤回,馆主不能代授权。误传或学员主动删除会同时删除数据库记录和 COS 对象。
## 部署配置
新增环境变量(见 `packages/server/.env.example`
| 变量 | 作用 |
| --- | --- |
| `WX_SUBSCRIBE_TEMPLATE_CLASS_REVIEW` | 课后评价订阅消息模板 ID |
成长照片与馆图共用 `COS_BUCKET``COS_SECRET_ID``COS_SECRET_KEY``COS_REGION`。对象写在 `progress/{userId}/` 下,上传带私有 ACL读取用约 60 秒签名 URL不落库公共链接。小程序合法域名沿用现有 COS 域名即可。
评价提醒模板字段由服务端按预约填充:`thing1` 课程名称(工作室名)、`thing2` 课程教练Iris`time3` 课程时间、`thing4` 温馨提示。未配置模板 ID 时定时任务不领取预约。
回退:先回退应用代码。新增表可保留;`progress/` 下对象不会被旧代码读取。不要在生产直接 `DROP TABLE`
## 迁移
目录 `packages/server/prisma/migrations/20260909120000_member_care/migration.sql`。发布时先 `prisma migrate deploy`,再发布后端,最后发布小程序。
## 验收清单
- 学员在 CONFIRMED 或 COMPLETED 且未评价时都可以订阅提醒;核销后仍能订阅。
- 完成后可立即评价;重复提交返回已评价。
- 首页匿名均分不含评论文案管理端趋势按中国自然月NPS 与星级分开展示。
- 私密笔记学员不可见;馆主在学员授权前不能读取照片,授权后可看,撤回后不能再签发。
- 误传照片可删除,删除后档案和 COS 对象都不再保留。
- 体测可只填一项,柔韧度允许负值;累计课时含未撤销补录。
- 未配置评价模板时,定时任务不领取预约。
- 小程序真机确认可上传、可用签名链接预览成长照片。

View File

@@ -0,0 +1,47 @@
# 月度教学统计
入口:管理中心 → 统计分析。页面为 `packages/app/src/pages/admin/analytics.vue`,接口为 `GET /api/admin/teaching-analytics?month=YYYY-MM`
## 统计口径
| 指标 | 定义 |
| --- | --- |
| 已上课程 | COMPLETED 预约关联的时段数,同一时段只计一次 |
| 已完成上课人次 | COMPLETED 预约数 |
| 本月上课学员 | 已完成预约的 userId 去重,不按姓名合并 |
| 授课小时 | 已完成时段的排课分钟数之和除以 60同一时段不重复累计 |
| 上课天数 | 已完成课程日期去重 |
| 人均上课次数 | 上课人次除以上课学员数,无学员时显示横线 |
| 上月参考 | 上一个完整自然月的已上课程节数;当月未结束时明确提示,不给误导性环比 |
| 待核对 | 已过中国时间课程结束时刻、仍待确认或已确认的预约 |
月份以 TimeSlot.date 的日历日期为准,查询使用月初包含、下月初不包含的区间。预约创建时间、完成时间和取消时间不影响月份归属。取消、未出席、待确认和已确认不计入已上课程。
当前模型没有老师归属、课程名称或课程类别,因此统计范围明确为工作室;不能把 operatorId 当作授课老师。用卡分布代表预约所用会员卡的当前卡种名称,不代表课程类别、实际消课收入或老师课酬。同名卡种合并显示。
系统存在自动完成预约任务COMPLETED 不等于现场签到,不提供签到率。没有课程日期的历史累计补录不计入本报告。
## 页面与交互
- 米白底、松绿色总览、宋体标题与衬线数字,延续原有课表风格。
- 月份选择器、前后月切换、回到本月、手动刷新与下拉刷新;支持 2000—2099 年。
- 月历显示每天已完成课程节数,点击日期定位明细,再次点击解除日期条件。
- 学员排行支持姓名搜索,显示上课次数、天数与最近上课日期;点击查看该学员全月已完成明细。
- 明细支持日期、学员、预约状态组合筛选;每个状态显示当前日期/学员条件内的记录数。清除筛选恢复全月全部记录。
- 明细显示课程日期、起止时间、学员、用卡与状态,点击姓名进入会员详情。
- 排行每次增加 10 人、明细每次增加 20 条,避免一次渲染过多节点。接口返回当月完整记录,不以列表显示上限截断统计。
- 切月清空旧数据和筛选,请求序号防止慢响应覆盖新月份。错误提示与空月独立显示,失败不伪装成零数据。
## 实现边界与验证
接口继承管理中心的 JWT 和 ADMIN 权限保护。一次查询读取当月及上月必要关联字段,无逐学员查询;只向前端返回当月明细与两个月的汇总。未新增数据库表或迁移。
服务测试覆盖课程去重、同名不同学员、状态排除、空月、跨年、闰年、月会员管理 页面中,默认是查看全部用户,这个查看效率太低了,我希望默认看到的是会员用户增加这么一个筛选, 至于新用户,我可以选择筛选无卡用户就行了,这样的体验会更加好一些参数验证、中国时间结束判断以及接口权限元数据。
验证通过:共享包构建、后端构建、前端类型检查、微信小程序构建;新增统计测试 12 项通过。全量测试 231 项通过,原有 scheduler 测试 8 项因缺少 FlashSaleService mock 失败。
使用真实 Vue 页面与 SCSS、模拟数据进行了 390px 手机宽度预览,验证学员钻取、日期筛选、快速切月、空月和错误状态。浏览器预览仅模拟小程序容器;微信真机、原生月份选择器以及线上数据联调仍需发布前验收。
设计参考:[TeamUp 出勤报表](https://support.goteamup.com/en/articles/9327465-reports-class-attendances-all-attendances),借鉴按学员、日期和状态追溯出勤记录的交互,不复制其产品界面。
上线需要部署后端并发布小程序,本次仅实现与本地验证,未执行生产部署。

View File

@@ -0,0 +1,946 @@
# 会员卡编辑功能实现计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 在管理后台会员列表中,点击会员弹出详情/编辑弹窗,支持编辑卡种、有效期、次数,以及清空会员卡
**Architecture:** 后端在 `UserController` 新增三个 admin 接口GET/PUT/DELETE `/admin/members/:userId/membership`),前端将现有详情弹窗改造为 Tab 模式store 新增三个 action
**Tech Stack:** NestJS (后端) + Vue 3 + uni-app + Pinia (前端)
---
## 文件结构
```
Backend:
- packages/server/src/user/user.controller.ts (新增3个接口)
- packages/server/src/user/user.service.ts (新增3个 service 方法)
- packages/server/src/user/dto/update-user-membership.dto.ts (新建)
Frontend:
- packages/app/src/stores/admin.ts (新增3个 action)
- packages/app/src/pages/admin/members.vue (改造详情弹窗为 Tab 模式)
```
---
## Phase 1: 后端接口
### Task 1: 创建 UpdateUserMembershipDto
**Files:**
- Create: `packages/server/src/user/dto/update-user-membership.dto.ts`
```typescript
import { IsDateString, IsInt, IsOptional, IsUUID, Min } from 'class-validator'
export class UpdateUserMembershipDto {
@IsUUID()
cardTypeId: string
@IsOptional()
@IsInt()
@Min(0)
remainingTimes?: number | null
@IsDateString()
startDate: string
@IsDateString()
expireDate: string
}
```
- [ ] **Step 1: 创建目录并写入文件**
```bash
mkdir -p /Users/richard/Documents/code/pilates/mp-pilates/packages/server/src/user/dto
```
写入 `packages/server/src/user/dto/update-user-membership.dto.ts`
---
### Task 2: UserService 新增会员卡管理方法
**Files:**
- Modify: `packages/server/src/user/user.service.ts` — 在文件末尾添加 3 个新方法
需要添加的方法:
1. `getUserMembership(userId: string)` — 返回 `Membership & { cardType: CardType } | null`
2. `updateUserMembership(userId: string, dto: UpdateUserMembershipDto)` — 创建或更新 membershipstatus 自动计算
3. `deleteUserMembership(userId: string)` — 软删除status → EXPIRED
关键业务逻辑:
- `updateUserMembership` 中 status 计算规则:
- `expireDate < now``EXPIRED`
- `remainingTimes === 0``USED_UP`
- 否则 → `ACTIVE`
- 如果用户已有 membership → 更新;无 → 创建新的
- 需要同时 import `CardTypeCategory``MembershipStatus`
```typescript
// 在 user.service.ts 顶部已有 import追加方法
import { CardTypeCategory, MembershipStatus } from '@mp-pilates/shared'
import { UpdateUserMembershipDto } from './dto/update-user-membership.dto'
import { Membership, CardType, Prisma } from '@prisma/client'
import { PrismaService } from '../prisma/prisma.service'
// 在 class 末尾添加:
async getUserMembership(userId: string): Promise<(Membership & { cardType: CardType }) | null> {
// userId 无唯一约束,取第一条
const membership = await this.prisma.membership.findFirst({
where: { userId },
include: { cardType: true },
})
return membership ? { ...membership, cardType: { ...membership.cardType } } : null
}
async updateUserMembership(
userId: string,
dto: UpdateUserMembershipDto,
): Promise<Membership & { cardType: CardType }> {
// 计算 status
const now = new Date()
const expireDate = new Date(dto.expireDate)
const remainingTimes = dto.remainingTimes ?? null
const isTimeBased = remainingTimes !== null
let status: MembershipStatus = MembershipStatus.ACTIVE
if (expireDate < now) {
status = MembershipStatus.EXPIRED
} else if (isTimeBased && remainingTimes <= 0) {
status = MembershipStatus.USED_UP
}
// 由于 userId 无唯一约束,先查是否存在,取第一条
const existing = await this.prisma.membership.findFirst({ where: { userId } })
let membership: Membership & { cardType: CardType }
if (existing) {
// 已有 membership → 更新
const updated = await this.prisma.membership.update({
where: { id: existing.id },
data: {
cardTypeId: dto.cardTypeId,
remainingTimes: dto.remainingTimes ?? null,
startDate: new Date(dto.startDate),
expireDate: new Date(dto.expireDate),
status,
},
include: { cardType: true },
})
membership = { ...updated, cardType: { ...updated.cardType } }
} else {
// 无 membership → 创建新的
const created = await this.prisma.membership.create({
data: {
userId,
cardTypeId: dto.cardTypeId,
remainingTimes: dto.remainingTimes ?? null,
startDate: new Date(dto.startDate),
expireDate: new Date(dto.expireDate),
status,
},
include: { cardType: true },
})
membership = { ...created, cardType: { ...created.cardType } }
}
return membership
}
async deleteUserMembership(userId: string): Promise<void> {
await this.prisma.membership.updateMany({
where: { userId },
data: { status: MembershipStatus.EXPIRED },
})
}
```
注意:`Membership` 表的 `userId` 暂无唯一约束,实现阶段如有需要可加。`findFirst` + `update` 的方案在只有一张卡时工作正常。
---
### Task 3: UserController 新增 3 个 admin 接口
**Files:**
- Modify: `packages/server/src/user/user.controller.ts`
在文件顶部添加 `@Param` import然后在 `Admin: Member Management` 区块后添加新接口:
```typescript
import {
Controller,
Get,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
} from '@nestjs/common'
// ... existing imports ...
import { UpdateUserMembershipDto } from './dto/update-user-membership.dto'
// 在 getMembers 之后添加:
@Get('admin/members/:userId/membership')
@UseGuards(RolesGuard)
@Roles(UserRole.ADMIN)
getUserMembership(@Param('userId') userId: string) {
return this.userService.getUserMembership(userId)
}
@Put('admin/members/:userId/membership')
@UseGuards(RolesGuard)
@Roles(UserRole.ADMIN)
updateUserMembership(
@Param('userId') userId: string,
@Body() dto: UpdateUserMembershipDto,
) {
return this.userService.updateUserMembership(userId, dto)
}
@Delete('admin/members/:userId/membership')
@UseGuards(RolesGuard)
@Roles(UserRole.ADMIN)
deleteUserMembership(@Param('userId') userId: string) {
return this.userService.deleteUserMembership(userId)
}
```
---
## Phase 2: 前端 Store
### Task 4: Admin Store 新增 3 个 action
**Files:**
- Modify: `packages/app/src/stores/admin.ts`
`MemberSummary` 类型后添加 `UserMembership` 类型(放在 fetchMembers 附近):
```typescript
export interface UserMembership {
userId: string
membership: {
id: string
cardTypeId: string
remainingTimes: number | null
startDate: string
expireDate: string
status: string
cardType: {
id: string
name: string
type: string
totalTimes: number | null
durationDays: number
}
} | null
}
```
`fetchMembers` action 后添加:
```typescript
async function getUserMembership(userId: string): Promise<UserMembership> {
return get<UserMembership>(`/admin/members/${userId}/membership`)
}
async function updateUserMembership(
userId: string,
dto: {
cardTypeId: string
remainingTimes?: number | null
startDate: string
expireDate: string
},
): Promise<any> {
return put<any>(`/admin/members/${userId}/membership`, dto)
}
async function deleteUserMembership(userId: string): Promise<void> {
return del<void>(`/admin/members/${userId}/membership`)
}
```
`return` 对象中导出这三个函数。
---
## Phase 3: 前端 UI详情弹窗改造
### Task 5: members.vue 弹窗改造 — 结构变更
**Files:**
- Modify: `packages/app/src/pages/admin/members.vue`
将现有的详情弹窗(`detail-modal`)从单一视图改造为 Tab 模式。
#### 5.1 模板改动
**原有弹窗代码:**
```vue
<!-- Detail modal -->
<view v-if="showDetail && detailMember" class="modal-mask" @tap.self="showDetail = false">
<view class="modal">
<!-- 详情内容 -->
</view>
</view>
```
**替换为:**
```vue
<!-- Detail / Edit modal -->
<view v-if="showDetail && detailMember" class="modal-mask" @tap.self="closeModal">
<view class="modal">
<!-- Header with close -->
<view class="modal-header">
<text class="modal-title">会员详情</text>
<text class="modal-close-btn" @tap="closeModal">×</text>
</view>
<!-- Tab bar -->
<view class="tab-bar">
<view
class="tab-item"
:class="{ 'tab-item--active': activeTab === 'detail' }"
@tap="switchTab('detail')"
>
<text class="tab-text">详情</text>
</view>
<view
class="tab-item"
:class="{ 'tab-item--active': activeTab === 'edit' }"
@tap="switchTab('edit')"
>
<text class="tab-text">编辑</text>
</view>
</view>
<!-- Tab: 详情 -->
<view v-if="activeTab === 'detail'" class="tab-content">
<!-- 头像区 -->
<view class="detail-header">
<view class="detail-avatar">
<image v-if="detailMember.avatarUrl" class="avatar-img" :src="detailMember.avatarUrl" mode="aspectFill" />
<view v-else class="avatar-placeholder avatar-placeholder--lg">
<text class="avatar-text avatar-text--lg">{{ (detailMember.nickname || '?').slice(0, 1) }}</text>
</view>
</view>
<text class="detail-name">{{ detailMember.nickname || '未知用户' }}</text>
<text class="detail-openid" @tap="copyOpenid(detailMember.openid)">{{ detailMember.openid }}</text>
<text class="detail-phone">{{ detailMember.phone || '未绑定手机' }}</text>
</view>
<!-- 会员卡信息有卡时 -->
<view v-if="detailMembership" class="membership-card">
<view class="membership-card-header">
<text class="membership-card-name">{{ detailMembership.cardType.name }}</text>
<text class="membership-card-badge" :class="'badge--' + detailMembership.status">
{{ statusLabel(detailMembership.status) }}
</text>
</view>
<view class="membership-card-info">
<text class="membership-info-item">有效期{{ formatDate(detailMembership.startDate) }} - {{ formatDate(detailMembership.expireDate) }}</text>
<text v-if="detailMembership.remainingTimes != null" class="membership-info-item">
剩余{{ detailMembership.remainingTimes }}
</text>
</view>
</view>
<!-- 无卡时 -->
<view v-else class="no-membership">
<text class="no-membership-text">暂无会员卡</text>
<view class="no-membership-btn" @tap="goEdit">
<text class="no-membership-btn-text">去开卡</text>
</view>
</view>
<!-- 预约统计 -->
<view class="detail-stats">
<view class="detail-stat">
<text class="detail-stat-value">{{ detailMember.totalBookings }}</text>
<text class="detail-stat-label">总预约</text>
</view>
<view class="detail-stat">
<text class="detail-stat-value">{{ detailMember.completedBookings }}</text>
<text class="detail-stat-label">已完成</text>
</view>
<view class="detail-stat">
<text class="detail-stat-value">{{ detailMember.cancelledBookings }}</text>
<text class="detail-stat-label">已取消</text>
</view>
</view>
<!-- 清空卡按钮有卡时 -->
<view v-if="detailMembership" class="danger-zone">
<view class="danger-btn" @tap="onClearMembership">
<text class="danger-btn-text">解除会员卡</text>
</view>
</view>
</view>
<!-- Tab: 编辑 -->
<view v-if="activeTab === 'edit'" class="tab-content">
<!-- 加载中 -->
<view v-if="editLoading" class="edit-loading">
<text class="edit-loading-text">加载中...</text>
</view>
<!-- 编辑表单 -->
<view v-else class="edit-form">
<!-- 卡种选择 -->
<view class="form-item">
<text class="form-label">卡种</text>
<picker
class="form-picker"
mode="selector"
:value="editForm.cardTypeIndex"
:range="editCardTypes"
range-key="name"
@change="onCardTypeChange"
>
<view class="form-picker-inner">
<text class="form-picker-text">{{ editCardTypes[editForm.cardTypeIndex]?.name || '请选择' }}</text>
<text class="form-picker-arrow"></text>
</view>
</picker>
</view>
<!-- 剩余次数TIMES/TRIAL -->
<view v-if="isTimeBasedCard" class="form-item">
<text class="form-label">剩余次数</text>
<input
class="form-input"
type="number"
v-model="editForm.remainingTimes"
placeholder="请输入剩余次数"
/>
</view>
<!-- 生效日期 -->
<view class="form-item">
<text class="form-label">生效日期</text>
<picker
class="form-picker"
mode="date"
:value="editForm.startDate"
@change="(e) => onStartDateChange(e)"
>
<view class="form-picker-inner">
<text class="form-picker-text">{{ editForm.startDate }}</text>
</view>
</picker>
</view>
<!-- 有效期至 -->
<view class="form-item">
<text class="form-label">有效期至</text>
<picker
class="form-picker"
mode="date"
:value="editForm.expireDate"
@change="(e) => onExpireDateChange(e)"
>
<view class="form-picker-inner">
<text class="form-picker-text">{{ editForm.expireDate }}</text>
</view>
</picker>
</view>
<!-- 保存按钮 -->
<view class="edit-submit">
<view
class="submit-btn"
:class="{ 'submit-btn--disabled': editSubmitting }"
@tap="onSaveMembership"
>
<text class="submit-btn-text">{{ editSubmitting ? '保存中...' : '保存' }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
```
#### 5.2 Script 改动
新增以下状态:
> 注意:在 `import { ref, onMounted, onUnmounted }` 后添加 `computed`
> `import { ref, computed, onMounted, onUnmounted } from 'vue'`
```typescript
const activeTab = ref<'detail' | 'edit'>('detail')
const detailMembership = ref<any>(null) // 当前会员卡数据
const editLoading = ref(false)
const editSubmitting = ref(false)
const editCardTypes = ref<any[]>([]) // 卡种列表(去获取)
const editForm = ref({
cardTypeIndex: 0,
cardTypeId: '',
remainingTimes: null as number | null,
startDate: '',
expireDate: '',
manuallyEditedExpire: false, // 用户手动修改过 expireDate 时为 true
})
// 是否为次数卡TIMES / TRIAL依赖 cardTypeIndex
const isTimeBasedCard = computed(() => {
const card = editCardTypes.value[editForm.value.cardTypeIndex]
return card && (card.type === 'TIMES' || card.type === 'TRIAL')
})
// 工具函数
function formatDate(dateStr: string): string {
if (!dateStr) return '-'
return dateStr.slice(0, 10)
}
function statusLabel(status: string): string {
const map: Record<string, string> = {
ACTIVE: '有效',
EXPIRED: '已过期',
USED_UP: '已用完',
}
return map[status] || status
}
// 懒加载会员卡数据
async function loadDetailMembership(userId: string) {
detailMembership.value = null
try {
const result = await adminStore.getUserMembership(userId)
detailMembership.value = result.membership
} catch {}
}
function switchTab(tab: 'detail' | 'edit') {
activeTab.value = tab
if (tab === 'edit') {
// 切换到编辑 Tab 时加载会员卡数据和卡种列表
if (!editCardTypes.value.length) {
adminStore.fetchCardTypes().then((types) => {
editCardTypes.value = types
})
}
// 如果还没加载 membership先加载
if (!detailMembership.value) {
loadDetailMembership(detailMember.value!.userId).then(() => {
initEditForm()
})
} else {
initEditForm()
}
}
}
function initEditForm() {
const m = detailMembership.value
const types = editCardTypes.value
if (m) {
// 有卡:预填充
const idx = types.findIndex((t) => t.id === m.cardTypeId)
editForm.value = {
cardTypeIndex: idx >= 0 ? idx : 0,
cardTypeId: m.cardTypeId,
remainingTimes: m.remainingTimes,
startDate: m.startDate.slice(0, 10),
expireDate: m.expireDate.slice(0, 10),
manuallyEditedExpire: false,
}
} else {
// 无卡:默认选中第一个卡种
editForm.value = {
cardTypeIndex: 0,
cardTypeId: types[0]?.id || '',
remainingTimes: types[0]?.totalTimes ?? null,
startDate: formatDate2(new Date()),
expireDate: calculateExpireDate(formatDate2(new Date()), types[0]?.durationDays ?? 30),
manuallyEditedExpire: false,
}
}
}
function formatDate2(date: Date): string {
const y = date.getFullYear()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
return `${y}-${m}-${d}`
}
function calculateExpireDate(startDate: string, durationDays: number): string {
const d = new Date(startDate)
d.setDate(d.getDate() + durationDays)
return formatDate2(d)
}
function onCardTypeChange(e: { detail: { value: number } }) {
const idx = e.detail.value
const cardType = editCardTypes.value[idx]
editForm.value.cardTypeIndex = idx
editForm.value.cardTypeId = cardType.id
// 自动填充次数和有效期(仅当用户未手动修改过有效期时)
if (cardType.totalTimes != null) {
editForm.value.remainingTimes = cardType.totalTimes
}
if (!editForm.value.manuallyEditedExpire) {
editForm.value.startDate = formatDate2(new Date())
editForm.value.expireDate = calculateExpireDate(
formatDate2(new Date()),
cardType.durationDays,
)
}
}
function onStartDateChange(e: { detail: { value: string } }) {
editForm.value.startDate = e.detail.value
if (!editForm.value.manuallyEditedExpire) {
const cardType = editCardTypes.value[editForm.value.cardTypeIndex]
if (cardType) {
editForm.value.expireDate = calculateExpireDate(e.detail.value, cardType.durationDays)
}
}
}
function onExpireDateChange(e: { detail: { value: string } }) {
editForm.value.expireDate = e.detail.value
editForm.value.manuallyEditedExpire = true
}
function goEdit() {
switchTab('edit')
}
async function onSaveMembership() {
if (editSubmitting.value) return
const userId = detailMember.value?.userId
if (!userId) return
editSubmitting.value = true
try {
await adminStore.updateUserMembership(userId, {
cardTypeId: editForm.value.cardTypeId,
remainingTimes: editForm.value.remainingTimes,
startDate: editForm.value.startDate,
expireDate: editForm.value.expireDate,
})
uni.showToast({ title: '保存成功', icon: 'success' })
activeTab.value = 'detail'
await loadDetailMembership(userId)
// 刷新列表
loadMembers(false)
} catch {
uni.showToast({ title: '保存失败', icon: 'none' })
} finally {
editSubmitting.value = false
}
}
async function onClearMembership() {
const userId = detailMember.value?.userId
if (!userId) return
uni.showModal({
title: '确认解除',
content: '确定要解除该用户的会员卡吗?',
confirmColor: '#e64329',
success: async (res) => {
if (!res.confirm) return
try {
await adminStore.deleteUserMembership(userId)
uni.showToast({ title: '已解除', icon: 'success' })
showDetail.value = false
loadMembers(false)
} catch {
uni.showToast({ title: '操作失败', icon: 'none' })
}
},
})
}
function closeModal() {
showDetail.value = false
activeTab.value = 'detail'
detailMembership.value = null
}
// 修改 openDetail
function openDetail(m: MemberSummary) {
detailMember.value = m
showDetail.value = true
detailMembership.value = null // 重置,懒加载
activeTab.value = 'detail'
// 预加载 membership详情 Tab 需要显示)
loadDetailMembership(m.userId)
}
```
#### 5.3 样式改动
`<style>` 末尾添加以下样式:
```scss
/* ── Modal header ─────────────────────────── */
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 0 32rpx 0;
}
.modal-title {
font-size: 32rpx;
font-weight: 700;
color: $brand-color;
}
.modal-close-btn {
font-size: 48rpx;
color: $text-hint;
line-height: 1;
}
/* ── Tab bar ───────────────────────────────── */
.tab-bar {
display: flex;
border-bottom: 1rpx solid $border-color;
margin-bottom: 32rpx;
}
.tab-item {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding-bottom: 16rpx;
position: relative;
}
.tab-item--active::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 48rpx;
height: 4rpx;
background: $accent-color;
border-radius: 2rpx;
}
.tab-text {
font-size: 28rpx;
color: $text-hint;
}
.tab-item--active .tab-text {
color: $accent-color;
font-weight: 600;
}
.tab-content {
min-height: 400rpx;
}
/* ── Membership card ────────────────────────── */
.membership-card {
background: linear-gradient(135deg, rgba($brand-color, 0.08), rgba($accent-color, 0.08));
border: 1rpx solid rgba($brand-color, 0.15);
border-radius: $radius-md;
padding: 24rpx;
margin-bottom: 24rpx;
}
.membership-card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16rpx;
}
.membership-card-name {
font-size: 30rpx;
font-weight: 700;
color: $brand-color;
}
.membership-card-badge {
font-size: 20rpx;
padding: 4rpx 12rpx;
border-radius: 8rpx;
}
.badge--ACTIVE { background: rgba(#52c41a, 0.12); color: #52c41a; }
.badge--EXPIRED { background: rgba($text-hint, 0.12); color: $text-hint; }
.badge--USED_UP { background: rgba(#faad14, 0.12); color: #faad14; }
.membership-card-info {
display: flex;
flex-direction: column;
gap: 8rpx;
}
.membership-info-item {
font-size: 24rpx;
color: $text-secondary;
}
/* ── No membership ──────────────────────────── */
.no-membership {
display: flex;
flex-direction: column;
align-items: center;
padding: 48rpx 0;
gap: 24rpx;
}
.no-membership-text {
font-size: 28rpx;
color: $text-hint;
}
.no-membership-btn {
background: $brand-color;
border-radius: 36rpx;
padding: 16rpx 48rpx;
}
.no-membership-btn-text {
font-size: 26rpx;
font-weight: 600;
color: $accent-color;
}
/* ── Danger zone ───────────────────────────── */
.danger-zone {
margin-top: 24rpx;
padding-top: 24rpx;
border-top: 1rpx solid $border-color;
}
.danger-btn {
width: 100%;
height: 80rpx;
background: rgba(230, 67, 41, 0.08);
border-radius: 40rpx;
display: flex;
align-items: center;
justify-content: center;
}
.danger-btn-text {
font-size: 26rpx;
color: #e64329;
}
/* ── Edit form ─────────────────────────────── */
.edit-loading {
display: flex;
align-items: center;
justify-content: center;
padding: 80rpx 0;
}
.edit-loading-text {
font-size: 26rpx;
color: $text-hint;
}
.edit-form {
display: flex;
flex-direction: column;
gap: 24rpx;
}
.form-item {
display: flex;
align-items: center;
gap: 20rpx;
}
.form-label {
font-size: 26rpx;
color: $text-secondary;
width: 140rpx;
flex-shrink: 0;
}
.form-input {
flex: 1;
height: 72rpx;
background: $bg-page;
border-radius: $radius-sm;
padding: 0 20rpx;
font-size: 26rpx;
color: $text-primary;
}
.form-picker {
flex: 1;
height: 72rpx;
background: $bg-page;
border-radius: $radius-sm;
display: flex;
align-items: center;
}
.form-picker-inner {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20rpx;
}
.form-picker-text {
font-size: 26rpx;
color: $text-primary;
}
.form-picker-arrow {
font-size: 20rpx;
color: $text-hint;
}
.edit-submit {
margin-top: 16rpx;
}
.submit-btn {
width: 100%;
height: 88rpx;
background: $brand-color;
border-radius: 44rpx;
display: flex;
align-items: center;
justify-content: center;
}
.submit-btn--disabled {
opacity: 0.5;
}
.submit-btn-text {
font-size: 28rpx;
font-weight: 600;
color: $accent-color;
}
```
---
## 自检清单
- [ ] 后端接口路径正确:`/admin/members/:userId/membership`(不是 `/admin/membership/...`
- [ ] `UpdateUserMembershipDto` 字段与前端 `editForm` 一致
- [ ] `isTimeBasedCard` 计算逻辑:`cardType.type === 'TIMES' || cardType.type === 'TRIAL'`
- [ ] `detailMembership``openDetail` 时懒加载,不阻塞弹窗打开
- [ ] `deleteUserMembership` 是软删除status → EXPIRED不是物理删除
- [ ] `switchTab('edit')` 时 initEditForm 使用 `detailMembership.value`(可能为 null
- [ ] 卡种 picker 变化时,`remainingTimes` 只对 TIMES/TRIAL 类型生效

View File

@@ -0,0 +1,186 @@
# 会员卡编辑功能设计
**日期:** 2026-04-07
**状态:** 已批准
---
## 1. 概述
在管理后台会员列表中,点击会员 item 时弹出的详情弹窗增加"编辑"能力。管理员可编辑指定用户的卡种、卡有效期、剩余次数,也可清空/解除会员卡。
**前置约束:**
- 一个用户只能拥有一张会员卡
- 支持清空卡(解除会员资格)
---
## 2. 交互设计
### 2.1 弹窗结构
```
┌─────────────────────────────────┐
│ 会员详情 [×] │
├──────────┬──────────────────────┤
│ 详情 │ 编辑 │ ← Tab 切换
├──────────┴──────────────────────┤
│ 头像 / 昵称 / OpenID / 手机号 │
│ ───────────────────────────── │
│ 会员卡信息区(根据 Tab 显示) │
│ 预约统计(总/完成/取消) │
│ ───────────────────────────── │
│ [关闭] │
└─────────────────────────────────┘
```
### 2.2 无卡用户交互
- 详情 Tab 显示"暂无会员卡"提示
- 显示"去开卡"按钮,点击切换到编辑 Tab
- 编辑 Tab 中卡种 picker 默认选中列表第一项,有效期自动计算
### 2.3 状态说明
| 场景 | Tab 初始显示 | 编辑表单状态 |
|------|-------------|-------------|
| 有卡用户 | 详情 Tab | 预填充当前数据 |
| 无卡用户 | 详情 Tab提示无卡 | 空白表单,卡种默认选中第一项 |
---
## 3. 表单字段
| 字段 | 组件 | 条件 | 说明 |
|------|------|------|------|
| 卡种 | picker | 必填 | 从 `CardType` 表读取,按 sortOrder 排序 |
| 剩余次数 | input (number) | TIMES / TRIAL 类型 | 默认填充卡种的 totalTimes |
| 生效日期 | date picker | 必填 | 默认当天 |
| 有效期至 | date picker | 必填 | 自动计算,支持手动调整 |
### 3.1 卡种切换逻辑
切换卡种时:
1. `remainingTimes` 自动填充新卡种的 `totalTimes`TIMES/TRIAL 类型)
2. `expireDate` 按新卡种 `durationDays` 重新计算起始日期
3. 编辑器内手动修改过 `expireDate` 时,不再自动覆盖
---
## 4. API 设计
### 4.1 获取用户会员卡
```
GET /admin/members/:userId/membership
```
**响应:**
```json
{
"userId": "uuid",
"membership": {
"id": "uuid",
"cardTypeId": "uuid",
"remainingTimes": 10,
"startDate": "2026-01-01",
"expireDate": "2026-04-01",
"status": "ACTIVE",
"cardType": { ... }
} | null
}
```
### 4.2 创建或更新会员卡
```
PUT /admin/members/:userId/membership
```
**请求体:**
```json
{
"cardTypeId": "uuid",
"remainingTimes": 10,
"startDate": "2026-04-07",
"expireDate": "2026-07-07"
}
```
**业务逻辑:**
- 若该用户已有 membership → 更新
- 若该用户无 membership → 创建新的
- `status` 由后端根据 expireDate 和 remainingTimes 自动计算
### 4.3 解除会员卡
```
DELETE /admin/members/:userId/membership
```
**业务逻辑:**
- 将 membership 的 `status` 标记为 `EXPIRED`(软删除,便于审计)
- 不物理删除记录
---
## 5. 数据模型
### 5.1 会员卡状态自动计算规则
```
if (expireDate < now) → EXPIRED
else if (remainingTimes === 0) → USED_UP
else → ACTIVE
```
### 5.2 变更日志
通过现有的 `BookingStatusHistory` 表记录操作tbd: 是否需要独立 `MembershipChangeLog` 表,待实现时确认)。
---
## 6. 错误处理
| 场景 | 处理 |
|------|------|
| 卡种不存在 | 后端返回 404前端提示"卡种不存在" |
| 有效期早于生效日期 | 前端表单校验失败,提示"有效期不能早于生效日期" |
| 次数为负数 | 前端表单校验失败,提示"次数不能为负数" |
| 网络错误 | Toast 提示"网络错误,请重试" |
| 清空卡确认 | 弹出确认对话框,提示"确定要解除该用户的会员卡吗?" |
---
## 7. 涉及改动
### 后端
- `packages/server/src/membership/membership.controller.ts` — 新增三个 admin 接口
- `packages/server/src/membership/membership.service.ts` — 新增 `getUserMembership` / `updateUserMembership` / `deleteUserMembership`
- `packages/server/src/user/user.controller.ts` — 无改动(列表接口保持不变)
### 前端
- `packages/app/src/stores/admin.ts` — 新增三个 store action
- `packages/app/src/pages/admin/members.vue` — 将详情弹窗改造为 Tab 模式,新增编辑表单
---
## 8. UI 细节
### 8.1 Tab 切换
- 详情/编辑 Tab 横向排列,激活态有下划线指示
- 无卡用户点击"去开卡"后,自动切到编辑 Tab
### 8.2 编辑表单提交
- 保存成功后 Toast 提示"保存成功"
- 自动切回详情 Tab 并刷新数据
- 保存按钮点击后置灰,防止重复提交
### 8.3 清空卡
- 需二次确认
- 成功后弹窗关闭,列表自动刷新

View File

@@ -22,5 +22,6 @@
"@prisma/engines",
"prisma"
]
}
},
"version": "0.0.2"
}

View File

@@ -0,0 +1,84 @@
<template>
<view class="about-section">
<view class="section-header">
<view>
<text class="section-title">老师介绍</text>
</view>
<text class="section-more" @tap="goToDetail">查看详情</text>
</view>
<view class="teacher-card" @tap="goToDetail">
<view class="teacher-main">
<view class="cover-wrap">
<image class="teacher-cover" :src="teacher.avatar" mode="aspectFill" />
</view>
<view class="teacher-content">
<view class="teacher-heading">
<view>
<view class="name-row">
<text class="teacher-name">{{ teacher.name }}</text>
</view>
<text class="teacher-title">{{ teacher.title }}</text>
</view>
</view>
<view class="specialty-row">
<text class="specialty-text">{{ teacher.specialties.join(' · ') }}</text>
</view>
<text class="teacher-intro">{{ teacher.intro }}</text>
</view>
</view>
<view class="action-row">
<view class="secondary-btn" @tap.stop="goToDetail">
<text class="secondary-btn-text">查看详情</text>
</view>
<view class="primary-btn" @tap.stop="goToBooking">
<text class="primary-btn-text">立即预约</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { irisProfile } from '../utils/teacher'
const teacher = irisProfile
function goToDetail() {
uni.navigateTo({ url: `/pages/teacher/detail?id=${teacher.id}` })
}
function goToBooking() {
uni.switchTab({ url: '/pages/booking/index' })
}
</script>
<style lang="scss" scoped>
.about-section { margin: 36rpx 32rpx 0; }
.section-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20rpx; }
.section-title { font-size: 30rpx; font-weight: 500; color: #514943; }
.section-more { font-size: 23rpx; color: #8b817b; padding: 8rpx 0; }
.teacher-card { padding: 26rpx; background: #f2ebe5; border-radius: 28rpx; }
.teacher-main { display: flex; align-items: flex-start; gap: 24rpx; }
.cover-wrap { width: 164rpx; height: 230rpx; border-radius: 18rpx; overflow: hidden; background: #e1d4c8; flex-shrink: 0; }
.teacher-cover { width: 100%; height: 100%; }
.teacher-content { flex: 1; min-width: 0; }
.name-row { margin-bottom: 8rpx; }
.teacher-name { font-size: 34rpx; font-weight: 500; color: #514943; }
.teacher-title { font-size: 22rpx; color: #8b817b; line-height: 1.5; }
.specialty-row { margin: 14rpx 0 10rpx; }
.specialty-text { font-size: 21rpx; color: #617d73; line-height: 1.6; }
.teacher-intro { font-size: 22rpx; line-height: 1.7; color: #786b61; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.action-row { display: flex; gap: 16rpx; margin-top: 24rpx; }
.secondary-btn, .primary-btn { flex: 1; height: 68rpx; border-radius: 999rpx; display: flex; align-items: center; justify-content: center; }
.secondary-btn { background: #fbf7f3; }
.primary-btn { background: #6b8276; }
.secondary-btn-text { font-size: 24rpx; color: #78675c; }
.primary-btn-text { font-size: 24rpx; font-weight: 400; color: #fff; }
</style>

View File

@@ -0,0 +1,45 @@
<template>
<view class="sil">
<text class="hint">点选身体区域可多选</text>
<view class="figure">
<view class="head zone" :class="{ on: selected.includes(BodyRegion.NECK) }" @tap="toggle(BodyRegion.NECK)">头颈</view>
<view class="row">
<view class="shoulder zone" :class="{ on: selected.includes(BodyRegion.SHOULDER) }" @tap="toggle(BodyRegion.SHOULDER)"></view>
</view>
<view class="torso zone" :class="{ on: selected.includes(BodyRegion.UPPER_BACK) }" @tap="toggle(BodyRegion.UPPER_BACK)">上背</view>
<view class="waist zone" :class="{ on: selected.includes(BodyRegion.LOW_BACK) }" @tap="toggle(BodyRegion.LOW_BACK)"></view>
<view class="pelvis zone" :class="{ on: selected.includes(BodyRegion.PELVIS) }" @tap="toggle(BodyRegion.PELVIS)">骨盆</view>
<view class="row">
<view class="hip zone" :class="{ on: selected.includes(BodyRegion.HIP) }" @tap="toggle(BodyRegion.HIP)"></view>
</view>
<view class="row">
<view class="knee zone" :class="{ on: selected.includes(BodyRegion.KNEE) }" @tap="toggle(BodyRegion.KNEE)"></view>
</view>
<view class="leg zone" :class="{ on: selected.includes(BodyRegion.LEG) }" @tap="toggle(BodyRegion.LEG)"></view>
</view>
</view>
</template>
<script setup lang="ts">
import { BodyRegion } from '@mp-pilates/shared'
const props = defineProps<{ selected: readonly string[] }>()
const emit = defineEmits<{ (e: 'change', value: BodyRegion[]): void }>()
function toggle(region: BodyRegion) {
const current = new Set(props.selected)
if (current.has(region)) current.delete(region)
else current.add(region)
emit('change', [...current] as BodyRegion[])
}
</script>
<style lang="scss" scoped>
.sil { padding: 12rpx 0 8rpx; }
.hint { display: block; text-align: center; color: #8a7b6e; font-size: 22rpx; margin-bottom: 16rpx; }
.figure { display: flex; flex-direction: column; align-items: center; gap: 10rpx; }
.zone { min-width: 160rpx; padding: 16rpx 28rpx; border-radius: 999rpx; background: #f3eee8; color: #6b5c50; font-size: 24rpx; text-align: center; }
.zone.on { background: #6b8276; color: #fff; }
.head { min-width: 120rpx; }
.row { display: flex; gap: 12rpx; }
</style>

View File

@@ -36,15 +36,12 @@
<!-- Membership card selection -->
<view class="card-section">
<view class="section-label-row">
<text class="section-label">选择扣课会员卡</text>
<text class="section-label">选择会员卡</text>
</view>
<!-- Single membership -->
<view v-if="memberships.length === 1" class="card-single">
<view class="card-item selected">
<view class="card-icon-wrap">
<text class="card-icon">💳</text>
</view>
<view class="card-info">
<text class="card-name">{{ memberships[0].cardType.name }}</text>
<text class="card-remain" v-if="memberships[0].remainingTimes !== null">
@@ -61,7 +58,7 @@
</view>
<!-- Multiple memberships picker -->
<view v-else-if="memberships.length > 1" class="card-picker-wrap">
<scroll-view v-else-if="memberships.length > 1" class="card-picker-wrap" scroll-y>
<view
v-for="m in memberships"
:key="m.id"
@@ -69,9 +66,6 @@
:class="{ selected: selectedMembershipId === m.id }"
@tap="selectedMembershipId = m.id"
>
<view class="card-icon-wrap">
<text class="card-icon">💳</text>
</view>
<view class="card-info">
<text class="card-name">{{ m.cardType.name }}</text>
<text class="card-remain" v-if="m.remainingTimes !== null">
@@ -85,7 +79,7 @@
<text class="check-icon"></text>
</view>
</view>
</view>
</scroll-view>
<!-- No memberships fallback (should not normally appear) -->
<view v-else class="no-card-tip">
@@ -96,22 +90,31 @@
<!-- Deduction tip -->
<view class="deduction-tip" v-if="selectedMembership">
<text class="deduction-text">
确认后将从{{ selectedMembership.cardType.name }}扣除 1 次课时
{{ selectedMembership.remainingTimes === null
? `${selectedMembership.cardType.name}」有效期内不限次`
: `确认后将从「${selectedMembership.cardType.name}」扣除 1 次课时` }}
</text>
</view>
<!-- Subscribe note -->
<view class="subscribe-tip">
<text class="subscribe-tip-text">🔔 确认预约将同步订阅约课结果课前1小时提醒与取消通知</text>
</view>
<!-- Action buttons -->
<view class="action-row">
<view class="btn-outline" @tap="handleCancel">
<text class="btn-outline-text">取消</text>
</view>
<view
<button
class="btn-confirm"
:class="{ disabled: !selectedMembershipId }"
:disabled="!selectedMembershipId || requestingSubscribe"
:loading="requestingSubscribe"
@tap="handleConfirm"
>
<text class="btn-confirm-text">确认预约</text>
</view>
</button>
</view>
</view>
</view>
@@ -120,6 +123,7 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { TimeSlotWithBookingStatus, MembershipWithCardType } from '@mp-pilates/shared'
import { requestBookingCreatedSubscriptionMessage } from '../utils/wechat-subscription'
const props = defineProps<{
visible: boolean
@@ -134,13 +138,14 @@ const emit = defineEmits<{
}>()
const selectedMembershipId = ref<string>('')
const requestingSubscribe = ref(false)
// Auto-select the first membership when popup opens or memberships list changes
watch(
[() => props.visible, () => props.memberships],
([visible, memberships]) => {
if (visible && memberships.length > 0) {
selectedMembershipId.value = memberships[0].id
if (visible) {
selectedMembershipId.value = memberships[0]?.id ?? ''
}
},
{ immediate: true },
@@ -150,8 +155,20 @@ const selectedMembership = computed(() =>
props.memberships.find((m) => m.id === selectedMembershipId.value) ?? null,
)
function handleConfirm() {
async function handleConfirm() {
if (!props.timeSlot || !selectedMembershipId.value) return
if (requestingSubscribe.value) return
requestingSubscribe.value = true
try {
await requestBookingCreatedSubscriptionMessage()
} catch (err: unknown) {
console.warn('[subscribe] booking confirm failed', err)
} finally {
requestingSubscribe.value = false
}
emit('confirm', {
timeSlotId: props.timeSlot.id,
membershipId: selectedMembershipId.value,
@@ -169,261 +186,47 @@ function handleMaskTap() {
</script>
<style lang="scss" scoped>
.popup-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.45);
z-index: 1000;
display: flex;
align-items: flex-end;
justify-content: center;
}
.popup-panel {
width: 100%;
background: #fff;
border-radius: 32rpx 32rpx 0 0;
padding: 32rpx 32rpx calc(32rpx + env(safe-area-inset-bottom));
display: flex;
flex-direction: column;
gap: 0;
}
.popup-header {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
margin-bottom: 32rpx;
}
.popup-title {
font-size: 34rpx;
font-weight: 700;
color: #1a1a1a;
}
.close-btn {
width: 56rpx;
height: 56rpx;
display: flex;
align-items: center;
justify-content: center;
background: $primary-selected-bg;
border-radius: 50%;
}
.close-icon {
font-size: 24rpx;
color: #999;
}
/* Info rows */
.info-section {
display: flex;
flex-direction: column;
gap: 20rpx;
margin-bottom: 28rpx;
}
.info-row {
display: flex;
flex-direction: row;
align-items: center;
}
.info-label {
font-size: 28rpx;
color: #999;
width: 80rpx;
flex-shrink: 0;
}
.info-value {
font-size: 28rpx;
color: #222;
font-weight: 500;
}
.divider {
height: 1rpx;
background: $primary-border;
margin: 8rpx 0 28rpx;
}
/* Card selection */
.card-section {
display: flex;
flex-direction: column;
gap: 16rpx;
margin-bottom: 24rpx;
}
.section-label-row {
margin-bottom: 8rpx;
}
.section-label {
font-size: 28rpx;
color: #666;
font-weight: 500;
}
.card-single,
.card-picker-wrap {
display: flex;
flex-direction: column;
gap: 16rpx;
}
.popup-mask { position: fixed; inset: 0; background: rgba(56, 48, 42, 0.32); z-index: 1000; display: flex; align-items: flex-end; justify-content: center; }
.popup-panel { width: 100%; box-sizing: border-box; background: #fbf9f6; border-radius: 36rpx 36rpx 0 0; padding: 28rpx 32rpx calc(24rpx + env(safe-area-inset-bottom)); }
.popup-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24rpx; }
.popup-title { font-size: 32rpx; font-weight: 500; color: #514943; }
.close-btn { width: 60rpx; height: 60rpx; display: flex; align-items: center; justify-content: center; }
.close-icon { font-size: 26rpx; color: #8b817b; }
.info-section { padding: 24rpx; background: #f1e8e1; border-radius: 24rpx; display: flex; flex-direction: column; gap: 14rpx; }
.info-row { display: flex; align-items: center; gap: 20rpx; }
.info-label { font-size: 24rpx; color: #8b7b70; width: 64rpx; flex-shrink: 0; }
.info-value { font-size: 26rpx; color: #6f5c50; font-weight: 400; }
.divider { height: 24rpx; }
.card-section { display: flex; flex-direction: column; gap: 16rpx; }
.section-label { font-size: 26rpx; color: #514943; font-weight: 500; }
.card-picker-wrap { height: 250rpx; }
.card-item {
display: flex;
flex-direction: row;
align-items: center;
padding: 24rpx 20rpx;
border-radius: 16rpx;
border: 2rpx solid $primary-border;
background: $primary-bg;
gap: 20rpx;
transition: border-color 0.15s, background 0.15s;
&.selected {
border-color: $primary-dark;
background: $primary-selected-bg;
}
display: flex; align-items: center; padding: 22rpx 24rpx; border-radius: 24rpx;
border: 2rpx solid #eee8e3; background: #fff; gap: 20rpx; box-sizing: border-box;
&.selected { border-color: #a5b8ab; background: #f0f4ee; }
}
.card-icon-wrap {
width: 60rpx;
height: 60rpx;
border-radius: 14rpx;
background: linear-gradient(135deg, $primary-color, $primary-dark);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.card-icon {
font-size: 32rpx;
}
.card-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 6rpx;
}
.card-name {
font-size: 28rpx;
font-weight: 600;
color: #222;
}
.card-remain {
font-size: 22rpx;
color: #999;
}
.check-mark {
width: 44rpx;
height: 44rpx;
border-radius: 50%;
background: $primary-dark;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.check-icon {
font-size: 24rpx;
color: #fff;
font-weight: 700;
}
.no-card-tip {
padding: 24rpx;
text-align: center;
}
.no-card-text {
font-size: 26rpx;
color: #bbb;
}
/* Deduction tip */
.deduction-tip {
background: $primary-selected-bg;
border-radius: 12rpx;
padding: 16rpx 20rpx;
margin-bottom: 28rpx;
}
.deduction-text {
font-size: 24rpx;
color: $primary-dark;
line-height: 1.5;
}
/* Action buttons */
.action-row {
display: flex;
flex-direction: row;
gap: 20rpx;
margin-top: 8rpx;
}
.btn-outline {
flex: 1;
height: 88rpx;
border-radius: 44rpx;
border: 2rpx solid $primary-border;
display: flex;
align-items: center;
justify-content: center;
&:active {
background: #f5f5f5;
}
}
.btn-outline-text {
font-size: 30rpx;
color: #666;
font-weight: 500;
}
.card-picker-wrap .card-item { margin-bottom: 12rpx; }
.card-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8rpx; }
.card-name { font-size: 26rpx; font-weight: 400; color: #514943; overflow-wrap: anywhere; }
.card-remain { font-size: 22rpx; color: #8b817b; }
.check-mark { width: 36rpx; height: 36rpx; border-radius: 50%; background: #6b8276; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.check-icon { font-size: 22rpx; color: #fff; }
.no-card-tip { padding: 24rpx; text-align: center; }
.no-card-text { font-size: 24rpx; color: #8b817b; }
.deduction-tip { padding: 18rpx 4rpx; }
.deduction-text { font-size: 22rpx; color: #8b817b; line-height: 1.6; }
.subscribe-tip { padding: 0 4rpx 14rpx; text-align: center; }
.subscribe-tip-text { font-size: 21rpx; color: #7f8a7e; }
.action-row { display: flex; gap: 20rpx; margin-top: 12rpx; }
.btn-outline { flex: 1; height: 88rpx; border-radius: 999rpx; background: #f0eae4; display: flex; align-items: center; justify-content: center; }
.btn-outline-text { font-size: 28rpx; color: #78675c; font-weight: 400; }
.btn-confirm {
flex: 2;
height: 88rpx;
border-radius: 44rpx;
background: linear-gradient(135deg, $primary-color, $primary-dark);
display: flex;
align-items: center;
justify-content: center;
&:active {
opacity: 0.85;
}
&.disabled {
background: $primary-border;
}
}
.btn-confirm-text {
font-size: 30rpx;
color: #fff;
font-weight: 600;
letter-spacing: 1rpx;
.disabled & {
color: #bbb;
}
flex: 2; height: 88rpx; padding: 0; margin: 0; border: none; line-height: 1;
border-radius: 999rpx; background: #6b8276;
display: flex; align-items: center; justify-content: center;
&::after { border: none; }
&:active { background: #597264; }
&.disabled { background: #d9dfd8; }
}
.btn-confirm-text { font-size: 28rpx; color: #fff; font-weight: 500; .disabled & { color: #677467; } }
</style>

View File

@@ -1,51 +1,49 @@
<template>
<view class="brand-banner">
<!-- Background image layer -->
<!-- Background image layer with blur -->
<image
v-if="studioInfo?.bannerUrl"
class="banner-bg"
:src="studioInfo.bannerUrl"
:src="bannerImage"
mode="aspectFill"
/>
<!-- Dark overlay for readability -->
<view class="banner-overlay" />
<!-- Status bar spacer -->
<view class="status-bar" :style="{ height: statusBarHeight + 'px' }" />
<!-- Centered content -->
<view class="banner-content">
<!-- Circular logo -->
<view class="logo-circle">
<image
v-if="studioInfo?.logo"
v-if="logoImage"
class="logo-img"
:src="studioInfo.logo"
mode="aspectFit"
:src="logoImage"
mode="aspectFill"
/>
<text v-else class="logo-placeholder">FC</text>
<view v-else class="logo-placeholder">
<text>{{ studioName.slice(0, 1) || 'F' }}</text>
</view>
</view>
<!-- Studio name -->
<text class="studio-name">{{ studioInfo?.name || 'Focus Core' }}</text>
<text class="studio-name">{{ studioName }}</text>
</view>
</view>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { computed } from 'vue'
import type { StudioConfig } from '@mp-pilates/shared'
import { getSystemLayout } from '../utils/system'
defineProps<{
const props = defineProps<{
studioInfo: StudioConfig | null
}>()
const statusBarHeight = ref(0)
const fallbackBannerImage = 'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/mp/images/bannerBg.jpg'
const fallbackLogoImage = 'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/mp/images/logo.jpg'
onMounted(() => {
statusBarHeight.value = getSystemLayout().statusBarHeight
})
const bannerImage = computed(() => props.studioInfo?.bannerUrl || fallbackBannerImage)
const logoImage = computed(() => props.studioInfo?.logo || fallbackLogoImage)
const studioName = computed(() => props.studioInfo?.name || 'Focus Core')
</script>
<style lang="scss" scoped>
@@ -63,6 +61,8 @@ onMounted(() => {
left: 0;
width: 100%;
height: 100%;
filter: blur(2px);
transform: scale(1.05);
}
.banner-overlay {
@@ -74,11 +74,6 @@ onMounted(() => {
background: rgba($primary-dark, 0.25);
}
.status-bar {
position: relative;
z-index: 2;
}
.banner-content {
position: relative;
z-index: 2;
@@ -86,7 +81,7 @@ onMounted(() => {
flex-direction: column;
align-items: center;
justify-content: center;
padding-top: 40rpx;
padding-top: 120rpx;
}
.logo-circle {
@@ -102,15 +97,22 @@ onMounted(() => {
}
.logo-img {
width: 160rpx;
height: 160rpx;
width: 200rpx;
height: 200rpx;
border-radius: 50%;
}
.logo-placeholder {
width: 200rpx;
height: 200rpx;
border-radius: 50%;
font-size: 64rpx;
font-weight: 800;
color: #333;
letter-spacing: 4rpx;
display: flex;
align-items: center;
justify-content: center;
}
.studio-name {

View File

@@ -3,7 +3,7 @@
<!-- Section header -->
<view class="section-header">
<text class="section-title">会员卡</text>
<text class="section-action" @tap="goToAllCards">全部</text>
<text class="section-action" @tap="goToAllCards">全部 </text>
</view>
<!-- Loading skeleton -->
@@ -13,7 +13,7 @@
:key="i"
class="card-row skeleton-row"
>
<view class="skeleton-thumb" />
<view class="skeleton-card-cover" />
<view class="skeleton-info">
<view class="skeleton-line skeleton-line--title" />
<view class="skeleton-line skeleton-line--sub" />
@@ -30,31 +30,49 @@
class="card-row"
@tap="goToDetail(card.id)"
>
<!-- Thumbnail -->
<view class="card-thumb" :class="thumbClass(card)">
<view class="thumb-fallback">
<text class="thumb-name">{{ truncate(card.name, 8) }}</text>
<text class="thumb-price">¥{{ formatPrice(card.price) }}</text>
</view>
<!-- Card Cover image if available, gradient fallback -->
<view class="card-cover" :class="card.coverUrl ? '' : getCardCoverClass(card.type)">
<image
v-if="card.coverUrl"
class="card-cover-img"
:src="card.coverUrl"
mode="aspectFill"
/>
<template v-else>
<text class="cover-label">{{ card.type === CardTypeCategory.TRIAL ? '体验' : card.type === CardTypeCategory.DURATION ? '期限卡' : '次卡' }}</text>
</template>
</view>
<!-- Card info -->
<!-- Card info aligns with card-cover height -->
<view class="card-info">
<view class="info-top">
<view class="card-name-row">
<text class="card-name">{{ card.name }}</text>
<text class="card-validity">有效期:{{ card.durationDays }} </text>
<text v-if="isRenewable(card)" class="renew-tag"></text>
</view>
<text class="card-validity">有效期 {{ card.durationDays }} </text>
</view>
<view class="info-bottom">
<view v-if="card.totalTimes" class="card-times">
<text class="card-times-value">{{ card.totalTimes }}</text>
<text class="card-times-unit">课时</text>
</view>
<view class="price-row">
<text class="price-label">价格:</text>
<text class="price-symbol">¥</text>
<text class="price-current">{{ formatPrice(card.price) }}</text>
<text class="price-current">¥{{ formatPrice(invite.price(card.price)) }}</text>
<text
v-if="card.originalPrice && card.originalPrice > card.price"
class="price-original"
>
原价:¥{{ formatPrice(card.originalPrice) }}
¥{{ formatPrice(card.originalPrice) }}
</text>
</view>
</view>
</view>
<text v-if="invite.eligible" class="renew-tag">95 </text>
<!-- Arrow -->
<text class="card-arrow"></text>
</view>
</view>
<!-- Empty -->
@@ -65,24 +83,51 @@
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useInviteStore } from '../stores/invite'
import { computed, ref, onMounted } from 'vue'
import type { CardType } from '@mp-pilates/shared'
import { CardTypeCategory } from '@mp-pilates/shared'
import { get } from '../utils/request'
import { formatPrice } from '../utils/format'
import { formatPrice, getCardCoverClass } from '../utils/format'
import { useUserStore } from '../stores/user'
const invite = useInviteStore()
const userStore = useUserStore()
const cardTypes = ref<CardType[]>([])
const loading = ref(false)
const hasLoaded = ref(false)
const renewableCardTypeIds = computed(() => {
const ids = new Set<string>()
for (const membership of userStore.memberships) {
if (membership.cardType.type !== CardTypeCategory.TRIAL) {
ids.add(membership.cardTypeId)
}
}
return ids
})
function isRenewable(card: CardType): boolean {
return card.type !== CardTypeCategory.TRIAL && renewableCardTypeIds.value.has(card.id)
}
async function fetchCardTypes() {
// Stale-While-Revalidate: only show skeleton on first load
// Subsequent refreshes silently update data in background
if (!hasLoaded.value) {
loading.value = true
}
try {
const result = await get<CardType[]>('/membership/card-types')
cardTypes.value = result
.filter((c) => c.isActive)
.sort((a, b) => a.sortOrder - b.sortOrder)
hasLoaded.value = true
} catch {
// Only show error toast on first load; silent fail on background refresh
if (!hasLoaded.value) {
uni.showToast({ title: '加载会员卡失败', icon: 'none' })
}
} finally {
loading.value = false
}
@@ -98,227 +143,41 @@ function goToDetail(id: string) {
}
function goToAllCards() {
// Navigate to all cards page or scroll behavior
uni.navigateTo({ url: '/pages/card/detail?showAll=1' })
}
function thumbClass(card: CardType): string {
if (card.type === CardTypeCategory.TRIAL) return 'thumb--trial'
if (card.type === CardTypeCategory.DURATION) return 'thumb--duration'
return 'thumb--times'
}
function truncate(str: string, maxLen: number): string {
return str.length > maxLen ? str.slice(0, maxLen) + '…' : str
}
</script>
<style lang="scss" scoped>
.card-shop {
background: #ffffff;
margin-top: 16rpx;
padding-bottom: 20rpx;
}
/* ── Section header ── */
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 32rpx 32rpx 20rpx;
}
.section-title {
font-size: 36rpx;
font-weight: 700;
color: #222;
}
.section-action {
font-size: 26rpx;
color: #999;
padding: 8rpx 24rpx;
border: 1rpx solid #ddd;
border-radius: 24rpx;
}
/* ── Card list ── */
.card-list {
padding: 0 32rpx;
}
.card-row {
display: flex;
align-items: center;
gap: 24rpx;
padding: 24rpx 0;
border-bottom: 1rpx solid #f0f0f0;
&:last-child {
border-bottom: none;
}
}
/* ── Thumbnail ── */
.card-thumb {
width: 200rpx;
height: 140rpx;
border-radius: 12rpx;
overflow: hidden;
flex-shrink: 0;
position: relative;
}
.thumb-fallback {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8rpx;
padding: 12rpx;
}
.thumb--times .thumb-fallback {
background: linear-gradient(135deg, #3a3a3a, #555);
}
.thumb--duration .thumb-fallback {
background: linear-gradient(135deg, #6c3483, #9b59b6);
}
.thumb--trial .thumb-fallback {
background: linear-gradient(135deg, #5a7a8a, $primary-dark);
}
.thumb-name {
font-size: 22rpx;
font-weight: 600;
color: #ffffff;
text-align: center;
line-height: 1.3;
word-break: break-all;
}
.thumb-price {
font-size: 24rpx;
font-weight: 700;
color: #ffffff;
}
/* ── Card info ── */
.card-info {
flex: 1;
min-width: 0;
}
.card-name {
display: block;
font-size: 30rpx;
font-weight: 600;
color: #222;
margin-bottom: 8rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-validity {
display: block;
font-size: 24rpx;
color: #999;
margin-bottom: 12rpx;
}
.price-row {
display: flex;
align-items: baseline;
gap: 4rpx;
}
.price-label {
font-size: 24rpx;
color: #e53935;
}
.price-symbol {
font-size: 24rpx;
color: #e53935;
font-weight: 600;
}
.price-current {
font-size: 40rpx;
font-weight: 800;
color: #e53935;
}
.price-original {
font-size: 22rpx;
color: #bbb;
text-decoration: line-through;
margin-left: 12rpx;
}
/* ── Skeleton ── */
.skeleton-row {
display: flex;
align-items: center;
gap: 24rpx;
padding: 24rpx 0;
border-bottom: 1rpx solid #f0f0f0;
}
.skeleton-thumb {
width: 200rpx;
height: 140rpx;
border-radius: 12rpx;
flex-shrink: 0;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
}
.skeleton-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 16rpx;
}
.skeleton-line {
height: 24rpx;
border-radius: 6rpx;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
&--title {
width: 70%;
height: 30rpx;
}
&--sub {
width: 40%;
}
&--price {
width: 50%;
height: 36rpx;
}
}
/* ── Empty state ── */
.empty-state {
padding: 80rpx;
display: flex;
align-items: center;
justify-content: center;
}
.empty-text {
font-size: 28rpx;
color: #bbb;
}
.card-shop { margin: 36rpx 32rpx 0; }
.section-header { display: flex; align-items: center; justify-content: space-between; gap: 16rpx; margin-bottom: 20rpx; }
.section-title { font-size: 30rpx; font-weight: 500; color: #514943; }
.section-action { font-size: 23rpx; color: #8b817b; padding: 8rpx 0; }
.card-list { padding: 0 24rpx; border-radius: 28rpx; background: #fff; border: 1rpx solid #eee8e3; }
.card-row { display: flex; align-items: center; gap: 20rpx; padding: 26rpx 0; border-bottom: 1rpx solid #f0ebe6; &:last-child { border: none; } }
.card-cover { width: 132rpx; height: 148rpx; border-radius: 16rpx; overflow: hidden; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: #f0e6de; }
.card-cover-img { width: 100%; height: 100%; }
.cover--times { background: #f0e6de; }
.cover--duration { background: #e9ede5; }
.cover--trial { background: #f2e4e0; }
.cover-label { font-family: 'Songti SC', 'STSong', serif; font-size: 28rpx; color: #857062; letter-spacing: 3rpx; }
.card-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 14rpx; }
.info-top { display: flex; flex-direction: column; gap: 8rpx; }
.card-name-row { display: flex; align-items: baseline; gap: 8rpx; }
.card-name { min-width: 0; font-size: 27rpx; font-weight: 400; color: #514943; line-height: 1.5; overflow-wrap: anywhere; }
.renew-tag { flex-shrink: 0; font-size: 18rpx; color: #617d73; background: #edf2ec; padding: 3rpx 8rpx; border-radius: 6rpx; }
.card-validity { font-size: 21rpx; color: #8b817b; }
.info-bottom { display: flex; align-items: baseline; flex-wrap: wrap; gap: 8rpx 16rpx; }
.card-times { display: flex; align-items: baseline; gap: 4rpx; }
.card-times-value { font-size: 24rpx; color: #6f655e; }
.card-times-unit { font-size: 20rpx; color: #8b817b; }
.price-row { display: flex; align-items: baseline; flex-wrap: wrap; gap: 8rpx; }
.price-current { font-size: 30rpx; font-weight: 500; color: #8b6c5b; font-variant-numeric: tabular-nums; }
.price-original { font-size: 20rpx; color: #a59b93; text-decoration: line-through; }
.card-arrow { font-size: 32rpx; color: #b2a79e; flex-shrink: 0; }
.skeleton-card-cover { width: 132rpx; height: 148rpx; border-radius: 16rpx; flex-shrink: 0; }
.skeleton-info { flex: 1; display: flex; flex-direction: column; gap: 16rpx; }
.skeleton-line { height: 24rpx; width: 70%; border-radius: 8rpx; &--sub { width: 50%; } }
.skeleton-line, .skeleton-card-cover { background: linear-gradient(90deg, #f0eae5 25%, #faf7f3 50%, #f0eae5 75%); background-size: 400% 100%; animation: shimmer 1.4s infinite; }
.empty-state { padding: 48rpx 24rpx; border-radius: 24rpx; background: #f3efea; text-align: center; }
.empty-text { font-size: 24rpx; color: #8b817b; }
</style>

View File

@@ -0,0 +1,76 @@
<template>
<view class="review">
<text class="eyebrow">课后 · 留一点感受</text>
<text class="title">这节课感觉怎么样</text>
<text class="hint">文字与标签仅你和馆主可见星级会计入首页匿名均分</text>
<view v-if="loading" class="hint">正在读取评价</view>
<view v-else-if="error" class="hint">{{ error }}<button class="secondary" @tap="load">重新加载</button></view>
<template v-else-if="review">
<text class="saved-stars">{{ '★'.repeat(review.rating) }}{{ '☆'.repeat(5 - review.rating) }}</text>
<view class="tags"><text v-for="tag in review.tags" :key="tag" class="tag selected">{{ tag }}</text></view>
<text class="comment">{{ review.comment || '谢谢你留下这份反馈。' }}</text>
<text class="hint">已评价 · {{ formatChinaDate(review.createdAt) }}</text>
</template>
<template v-else-if="canReview">
<view class="stars"><button v-for="n in 5" :key="n" :aria-label="n + ' 星'" :class="{ chosen: rating >= n }" @tap="rating = n">{{ rating >= n ? '★' : '☆' }}</button></view>
<text class="rating-label">{{ rating ? labels[rating - 1] : '轻触星星,为这节课评分' }}</text>
<view class="tags"><button v-for="tag in REVIEW_TAGS" :key="tag" class="tag" :class="{ selected: tags.includes(tag) }" @tap="toggle(tag)">{{ tag }}</button></view>
<text class="hint">可选最多 3 个标签</text>
<textarea v-model="comment" maxlength="200" placeholder="哪里让你有收获?还有什么可以做得更好?" />
<text class="counter">{{ comment.length }} / 200</text>
<picker :range="recommendations" @change="recommendation = Number($event.detail.value) - 1"><view class="recommend">你有多愿意推荐我们<text>{{ recommendation < 0 ? '选填 ' : recommendation + ' / 10 ' }}</text></view></picker>
<text class="hint">0 表示完全不愿意10 表示非常愿意</text>
<button class="primary" :loading="saving" :disabled="saving || !rating" @tap="submit">提交评价</button>
</template>
<text v-else class="hint">课程完成后即可评价</text>
</view>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { REVIEW_TAGS } from '@mp-pilates/shared'
import type { ClassReview } from '@mp-pilates/shared'
import { get, post } from '../utils/request'
import { formatChinaDate } from '../utils/format'
const props = defineProps<{ bookingId: string }>()
const review = ref<ClassReview | null>(null), canReview = ref(false), loading = ref(false), saving = ref(false), error = ref('')
const rating = ref(0), tags = ref<string[]>([]), comment = ref(''), recommendation = ref(-1)
const labels = ['不太满意', '有待改善', '整体还好', '很满意', '非常满意']
const recommendations = ['暂不填写', ...Array.from({ length: 11 }, (_, n) => String(n))]
let sequence = 0
async function load() {
const seq = ++sequence; loading.value = true; error.value = ''
try { const result = await get<{ review: ClassReview | null; canReview: boolean }>(`/booking/${props.bookingId}/review`); if (seq === sequence) { review.value = result.review; canReview.value = result.canReview } }
catch (e) { if (seq === sequence) error.value = e instanceof Error ? e.message : '评价加载失败' }
finally { if (seq === sequence) loading.value = false }
}
function toggle(tag: string) {
if (tags.value.includes(tag)) tags.value = tags.value.filter(t => t !== tag)
else if (tags.value.length < 3) tags.value = [...tags.value, tag]
else uni.showToast({ title: '最多选择 3 个标签', icon: 'none' })
}
async function submit() {
if (saving.value || !rating.value) return
saving.value = true
try { review.value = await post<ClassReview>(`/booking/${props.bookingId}/review`, { rating: rating.value, tags: tags.value, comment: comment.value, ...(recommendation.value >= 0 ? { recommendation: recommendation.value } : {}) }); uni.showToast({ title: '谢谢你的反馈', icon: 'success' }) }
catch (e) { uni.showToast({ title: e instanceof Error ? e.message : '提交失败,请重试', icon: 'none' }) }
finally { saving.value = false }
}
watch(() => props.bookingId, () => { review.value = null; rating.value = 0; tags.value = []; comment.value = ''; recommendation.value = -1; void load() }, { immediate: true })
</script>
<style lang="scss" scoped>
.review { margin: 28rpx 32rpx; padding: 32rpx; border: 1rpx solid #e7e0d7; border-radius: 28rpx; background: #fffdf9; color: #514943; }
.eyebrow { display:block; color:#8c7867; font-size:22rpx; letter-spacing:3rpx; }
.title { display:block; margin:18rpx 0; font-family:'Songti SC','STSong',serif; font-size:38rpx; }
.hint { display:block; font-size:23rpx; line-height:1.8; color:#82796e; }
.stars { display:flex; justify-content:space-between; margin:24rpx 0 8rpx; }
.stars button { padding:0; margin:0; width:96rpx; height:96rpx; line-height:96rpx; font-size:60rpx; background:transparent; color:#b7ac9c; &::after {border:0;} &.chosen {color:#a5824b;} }
.rating-label {display:block; text-align:center; color:#8c7867; font-size:24rpx; margin-bottom:24rpx;}
.tags {display:flex;flex-wrap:wrap;gap:14rpx;margin:18rpx 0;}
.tag {margin:0;padding:15rpx 20rpx;font-size:24rpx;line-height:1.5;border-radius:16rpx;background:#f4f1eb;color:#72695f;&::after{border:0;} &.selected{background:#e7eee7;color:#4d685c;}}
textarea {margin-top:22rpx;padding:24rpx;width:100%;height:190rpx;box-sizing:border-box;background:#f6f3ed;border-radius:18rpx;font-size:26rpx;line-height:1.7;}
.counter{display:block;text-align:right;color:#8b817b;font-size:21rpx;margin:10rpx 0 20rpx;}
.recommend{display:flex;justify-content:space-between;gap:16rpx;align-items:center;min-height:88rpx;border-top:1rpx solid #eee8e0;font-size:24rpx;}
.primary,.secondary{margin-top:24rpx;min-height:88rpx;line-height:88rpx;border-radius:22rpx;background:#617d70;color:#fff;font-size:27rpx;&::after{border:0;}}
.secondary{background:#eee9df;color:#645c52;}.primary[disabled]{background:#d5dcd2;color:#697365;}
.saved-stars{display:block;font-size:46rpx;color:#a5824b;margin-top:24rpx;}.comment{display:block;line-height:1.8;font-size:27rpx;margin:20rpx 0;white-space:pre-wrap;}
</style>

View File

@@ -39,7 +39,14 @@ onMounted(() => {
})
function handleBack() {
const pages = getCurrentPages()
if (pages.length > 1) {
uni.navigateBack({ delta: 1 })
return
}
uni.switchTab({ url: '/pages/home/index' })
}
</script>

View File

@@ -1,17 +1,20 @@
<template>
<view class="date-selector">
<view class="date-selector" :class="`date-selector--${variant}`">
<scroll-view class="scroll" scroll-x enhanced :show-scrollbar="false">
<view class="track">
<view
v-for="item in dateRange"
:key="item.date"
class="date-item"
:class="{ active: item.date === modelValue, today: item.isToday }"
:class="[
`date-item--${variant}`,
{ active: item.date === modelValue, today: item.isToday },
]"
@tap="handleSelect(item.date)"
>
<text class="weekday">{{ item.isToday ? '今天' : item.weekday }}</text>
<text class="day">{{ getDayNumber(item.date) }}</text>
<text class="month">{{ getMonthNumber(item.date) }}</text>
<text v-if="variant !== 'soft' || getDayNumber(item.date) === '1'" class="month">{{ getMonthNumber(item.date) }}</text>
</view>
</view>
</scroll-view>
@@ -25,6 +28,7 @@ import { getDateRange } from '../utils/format'
interface Props {
modelValue: string
variant?: 'default' | 'booking' | 'soft'
}
const props = defineProps<Props>()
@@ -47,6 +51,8 @@ function handleSelect(date: string) {
emit('update:modelValue', date)
emit('select', date)
}
const variant = computed(() => props.variant ?? 'default')
</script>
<style lang="scss" scoped>
@@ -55,6 +61,11 @@ function handleSelect(date: string) {
padding: 16rpx 0 20rpx;
border-bottom: 1rpx solid $primary-border;
&.date-selector--booking {
background: rgba(252, 250, 248, 0.96);
border-bottom-color: rgba(192, 154, 137, 0.12);
}
.scroll {
width: 100%;
white-space: nowrap;
@@ -121,6 +132,60 @@ function handleSelect(date: string) {
font-weight: 600;
}
}
&.date-item--booking {
background: rgba(247, 242, 238, 0.88);
border: 1rpx solid rgba(192, 154, 137, 0.08);
.weekday {
color: #9d8b83;
}
.day {
color: #3a2e2a;
}
.month {
color: #b7a79f;
}
&.active {
background: linear-gradient(135deg, #d7beb1, #b98f7d);
box-shadow: 0 12rpx 28rpx rgba(143, 103, 89, 0.16);
.weekday,
.day,
.month {
color: #fffaf7;
}
}
&.today:not(.active) {
.weekday {
color: #8f6759;
}
}
}
}
}
.date-selector.date-selector--soft {
padding: 8rpx 0 24rpx;
background: #fbf9f6;
border-bottom: none;
.track { padding: 0 32rpx; gap: 12rpx; }
.date-item {
min-width: 0; width: 86rpx; height: 116rpx; padding: 0;
box-sizing: border-box; border-radius: 24rpx;
background: transparent; gap: 12rpx;
.weekday { font-size: 22rpx; color: #8b817b; }
.day { font-size: 34rpx; font-weight: 400; color: #514943; }
&.active {
background: #eee3dc;
.weekday, .day { color: #705b4f; }
.day { font-weight: 500; }
}
&.today:not(.active) .weekday { color: #617d73; font-weight: 400; }
}
}
</style>

View File

@@ -0,0 +1,71 @@
<template>
<view class="invite-entry">
<button class="invite-heading" :disabled="opening" @tap="open" aria-label="邀请好友查看邀请码与邀请权益">
<view class="entry-copy">
<text class="entry-title">邀请好友领课时</text>
<text class="entry-caption">好友享 95 · {{ user.loggedIn && invite.activity ? `已获 ${invite.activity.rewardedTimes} 节赠课` : '一起练,得赠课' }}</text>
</view>
<view class="invite-count">
<text class="count-number">{{ user.loggedIn && invite.activity ? invite.activity.referrals.length : '—' }}<text v-if="user.loggedIn"> </text></text>
<text class="count-label">{{ user.loggedIn ? '已邀请' : '登录查看' }}</text>
</view>
<text class="entry-arrow"></text>
</button>
<view v-if="visible" class="veil" @tap="visible = false" @touchmove.stop.prevent>
<view class="sheet" @tap.stop>
<button class="close" @tap="visible = false" aria-label="关闭">×</button>
<text class="eyebrow">A LITTLE GIFT, SHARED</text>
<text class="headline">好朋友好好练</text>
<text class="subtitle">把你的练习日常分享给在意的人</text>
<view class="benefits"><view><text class="benefit-num">1<text> </text></text><text>你得免费课</text></view><view><text class="benefit-num">95<text> </text></text><text>好友购卡优惠</text></view></view>
<view class="ticket" @tap="copy"><text>你的专属邀请码 · 点击复制</text><text class="ticket-code">{{ invite.code }}</text></view>
<text class="rules">好友确认邀请码体验卡次卡和期限卡均享 95 每位好友首次成功购买非体验卡你得 1 节免费课购买或完成体验课不触发赠课</text>
<text class="rules">赠课自动存入我的会员卡365 天内可预约每位好友仅绑定一位邀请人</text>
<button class="share" open-type="share" :disabled="!invite.code">分享给微信好友</button>
<text class="footnote">送朋友一份心意也给自己一次练习</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useInviteStore } from '../stores/invite'
import { useUserStore } from '../stores/user'
import { getErrorMessage } from '../utils/auth'
const invite = useInviteStore()
const user = useUserStore()
const visible = ref(false)
const opening = ref(false)
async function open() {
if (opening.value) return
opening.value = true
try {
if (!user.loggedIn) await user.login()
await Promise.all([invite.refresh(), invite.refreshActivity().catch(() => {})])
visible.value = true
} catch (err) { uni.showToast({ title: getErrorMessage(err, '暂时无法获取邀请码,请重试'), icon: 'none' }) }
finally { opening.value = false }
}
function copy() {
if (!invite.code) { open(); return }
uni.setClipboardData({ data: invite.code })
}
</script>
<style scoped lang="scss">
.invite-entry { margin: 16rpx 32rpx; padding: 0; background: #eaf0e7; border: 1rpx solid #d9e3d4; border-radius: 20rpx; color: #435b4c; }
.invite-heading { width: 100%; min-height: 120rpx; box-sizing: border-box; margin: 0; padding: 18rpx 24rpx; background: transparent; border-radius: 20rpx; color: inherit; display: flex; gap: 20rpx; text-align: left; align-items: center; line-height: 1.5; &::after { border: none; } &:active { background: #e2eadf; } }
.entry-copy { flex: 1; min-width: 0; }
.entry-title { display: block; font-size: 28rpx; font-weight: 500; }
.entry-caption { display: block; margin-top: 6rpx; font-size: 21rpx; color: #6b7d65; }
.invite-count { flex-shrink: 0; text-align: right; }
.count-number { display: block; font-family: Georgia, serif; font-size: 34rpx; line-height: 1.2; font-variant-numeric: tabular-nums; text { font-size: 20rpx; } }
.count-label { display: block; margin-top: 5rpx; font-size: 19rpx; color: #6b7d65; }
.entry-arrow { flex-shrink: 0; font-size: 30rpx; color: #87967f; }
.eyebrow { display: block; font-size: 19rpx; letter-spacing: 3rpx; color: #788976; }
.veil { position: fixed; inset: 0; z-index: 400; background: rgba(32,43,35,.48); display: flex; align-items: center; padding: 30rpx; }
.sheet { position: relative; width: 100%; max-height: 85vh; overflow-y: auto; box-sizing: border-box; padding: 48rpx 34rpx 32rpx; border-radius: 32rpx; background: #fcfaf5; }.close { position: absolute; right: 18rpx; top: 12rpx; margin: 0; background: transparent; color: #7b8477; font-size: 36rpx; }.close::after,.share::after { border: none; }
.headline { display: block; margin-top: 20rpx; font-family: 'Songti SC',serif; font-size: 46rpx; }.subtitle { display: block; margin-top: 12rpx; font-size: 23rpx; color: #87907f; }
.benefits { display: flex; margin: 30rpx 0; padding: 25rpx 0; background: #eaf0e5; border-radius: 22rpx; }.benefits>view { flex: 1; text-align: center; font-size: 24rpx; }.benefits>view+view { border-left: 1rpx solid #cbd8c5; }.benefit-num { display: block; font: 66rpx Georgia,serif; margin-bottom: 10rpx; }.benefit-num text { font-size: 26rpx; }
.ticket { padding: 22rpx; text-align: center; border: 1rpx dashed #b7c5af; border-radius: 16rpx; font-size: 21rpx; color: #7a8772; }.ticket-code { display: block; margin-top: 12rpx; font: 42rpx monospace; letter-spacing: 10rpx; color: #435b4c; }
.rules { display: block; margin-top: 18rpx; font-size: 21rpx; line-height: 1.8; color: #7d8076; }.share { margin-top: 26rpx; border-radius: 999rpx; background: #526e58; color: #fff; font-size: 27rpx; line-height: 86rpx; }.footnote { display: block; text-align: center; margin-top: 16rpx; font-size: 19rpx; color: #93978a; }
</style>

View File

@@ -0,0 +1,40 @@
<template>
<view class="supplements">
<view v-for="item in records" :key="item.id" class="record" :class="{ 'record--revoked': item.revokedAt }">
<view class="record-head">
<view class="record-title"><text>系统补录</text><text class="record-sub">{{ item.revokedAt ? '已撤销' : '历史课程' }}</text></view>
<text class="record-quantity">{{ item.quantity }}<text class="record-unit"> </text></text>
</view>
<text class="record-date">{{ formatDateTimeFull(item.createdAt) }} 补录</text>
<text class="record-note">{{ item.deductedTimes ? `${item.cardName} · ${item.revokedAt ? '已返还' : '扣除'} ${item.deductedTimes}` : '仅补记录 · 未扣会员卡' }}</text>
<text v-if="item.remark" class="record-note">{{ item.remark }}</text>
<view v-if="editable" class="record-footer">
<text class="record-operator"> {{ item.operatorName }} 补录</text>
<button v-if="!item.revokedAt" class="revoke" :disabled="busy" @tap="emit('revoke', item)">撤销补录</button>
<text v-else class="record-operator">{{ formatDateTimeFull(item.revokedAt) }} 撤销</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import type { LessonSupplementRecord } from '@mp-pilates/shared'
import { formatDateTimeFull } from '../utils/format'
defineProps<{ records: readonly LessonSupplementRecord[]; editable?: boolean; busy?: boolean }>()
const emit = defineEmits<{ revoke: [record: LessonSupplementRecord] }>()
</script>
<style lang="scss" scoped>
.supplements { display: flex; flex-direction: column; }
.record { padding: 24rpx 0; border-bottom: 1rpx solid #eee8e3; color: #514943; }
.record:last-child { border-bottom: none; }
.record--revoked { color: #8b817b; }
.record-head { display: flex; align-items: center; justify-content: space-between; gap: 20rpx; }
.record-title { display: flex; flex-direction: column; gap: 8rpx; font-size: 28rpx; }
.record-sub { font-size: 20rpx; color: #8b817b; }
.record-quantity { flex-shrink: 0; font-size: 42rpx; font-variant-numeric: tabular-nums; color: #617d73; }
.record-unit { font-size: 22rpx; }
.record-date { display: block; margin-top: 20rpx; color: #8b817b; font-size: 21rpx; }
.record-note { display: block; margin-top: 12rpx; font-size: 23rpx; color: #786b61; line-height: 1.6; overflow-wrap: anywhere; }
.record-footer { margin-top: 20rpx; padding-top: 16rpx; border-top: 1rpx solid #eee8e3; display: flex; align-items: center; justify-content: space-between; gap: 16rpx; flex-wrap: wrap; }
.record-operator { color: #8b817b; font-size: 21rpx; }
.revoke { margin: 0; padding: 8rpx 12rpx; font-size: 22rpx; line-height: 1.5; background: transparent; color: #967561; &::after { border: none; } }
</style>

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,78 @@
<template>
<view class="month-divider">
<!-- 左侧细线 -->
<view class="month-divider__line" />
<!-- 月份主体 -->
<view class="month-divider__body">
<!-- 月份装饰一个小圆点 + 月份名 -->
<view class="month-divider__dot" />
<text class="month-divider__label">{{ label }}</text>
<view class="month-divider__dot" />
</view>
<!-- 右侧细线 -->
<view class="month-divider__line" />
<!-- 副信息节气或描述 -->
<text v-if="hint" class="month-divider__hint">{{ hint }}</text>
</view>
</template>
<script setup lang="ts">
defineProps<{
/** 主标签,例如 "十月" */
label: string
/** 副信息,例如 "共 3 节" */
hint?: string
}>()
</script>
<style lang="scss" scoped>
.month-divider {
display: flex;
align-items: center;
gap: 16rpx;
margin: 48rpx 32rpx 24rpx;
&__line {
flex: 1;
height: 1rpx;
background: linear-gradient(
to right,
transparent 0%,
rgba(155, 138, 117, 0.25) 30%,
rgba(155, 138, 117, 0.45) 100%
);
}
&__body {
display: flex;
align-items: center;
gap: 14rpx;
padding: 0 4rpx;
}
&__dot {
width: 6rpx;
height: 6rpx;
border-radius: 50%;
background: #b09a83;
}
&__label {
font-family: "Songti SC", "STSong", "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 28rpx;
font-weight: 400;
color: #6f645a;
letter-spacing: 8rpx;
}
&__hint {
font-size: 22rpx;
color: #a89d92;
letter-spacing: 1rpx;
font-variant-numeric: tabular-nums;
}
}
</style>

View File

@@ -0,0 +1,382 @@
<template>
<view class="hero" :class="`hero--${tone}`" @tap="handleTap">
<!-- 背景纹理层 -->
<view class="hero__grain" />
<!-- 装饰右上角的弧线暗示月相 -->
<view class="hero__moon" />
<view class="hero__main">
<!-- 左侧大日期块 -->
<view class="hero__date">
<text class="hero__day">{{ dayNumber }}</text>
<text class="hero__month">{{ monthLabel }}</text>
<text class="hero__weekday">{{ weekdayLabel }}</text>
</view>
<!-- 分隔虚线 -->
<view class="hero__divider">
<view v-for="i in 6" :key="i" class="hero__divider-dot" />
</view>
<!-- 右侧课程信息 -->
<view class="hero__info">
<view class="hero__time-row">
<text class="hero__time">{{ startTime }}</text>
<text class="hero__time-end"> {{ endTime }}</text>
</view>
<text class="hero__membership">{{ cardName }}</text>
<view class="hero__status">
<view class="hero__dot" />
<text class="hero__status-text">{{ statusLabel }}</text>
<text v-if="countdownText" class="hero__countdown">· {{ countdownText }}</text>
</view>
</view>
</view>
<!-- 底部诗意一句 -->
<view class="hero__footer">
<text class="hero__poem">{{ poem }}</text>
<view class="hero__cta">
<text class="hero__cta-text">查看详情</text>
<text class="hero__cta-arrow"></text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { BookingWithDetails } from '@mp-pilates/shared'
import { BookingStatus } from '@mp-pilates/shared'
import {
bookingStatusLabel,
bookingStatusBannerClass,
} from '../utils/booking-helpers'
const props = defineProps<{
booking: BookingWithDetails
}>()
const emit = defineEmits<{
tap: [booking: BookingWithDetails]
}>()
const months = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二']
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
function parseDate(dateStr: string): Date {
const normalized = dateStr.slice(0, 10)
const [y, m, d] = normalized.split('-').map(Number)
return new Date(y, m - 1, d)
}
const date = computed(() => parseDate(props.booking.timeSlot.date))
const dayNumber = computed(() => String(date.value.getDate()).padStart(2, '0'))
const monthLabel = computed(() => `${date.value.getMonth() + 1}`)
const weekdayLabel = computed(() => weekdays[date.value.getDay()])
const startTime = computed(() => props.booking.timeSlot.startTime.slice(0, 5))
const endTime = computed(() => props.booking.timeSlot.endTime.slice(0, 5))
const cardName = computed(() => props.booking.membership?.cardType?.name || '会员卡')
const statusLabel = computed(() => bookingStatusLabel(props.booking.status))
const tone = computed(() => bookingStatusBannerClass(props.booking.status))
const today = new Date()
const todayStr = computed(() => {
const d = today
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
})
const tomorrow = new Date(today.getTime() + 86400000)
const tomorrowStr = computed(() => {
const d = tomorrow
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
})
const dateKey = computed(() => {
const d = date.value
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
})
const relativeLabel = computed(() => {
if (dateKey.value === todayStr.value) return '今天'
if (dateKey.value === tomorrowStr.value) return '明天'
return `${months[date.value.getMonth()]}${date.value.getDate()}`
})
const countdownText = computed(() => {
if (props.booking.status !== BookingStatus.CONFIRMED) return ''
if (dateKey.value !== todayStr.value && dateKey.value !== tomorrowStr.value) return ''
const target = new Date(`${dateKey.value}T${props.booking.timeSlot.startTime}:00`).getTime()
const diff = target - Date.now()
if (diff <= 0) return '即将开始'
const hours = Math.floor(diff / 3_600_000)
const mins = Math.floor((diff % 3_600_000) / 60_000)
if (dateKey.value === todayStr.value) {
if (hours <= 0) return `${mins} 分钟后`
return `${hours} 小时 ${mins} 分后`
}
return `${hours} 小时 ${mins}`
})
const poem = computed(() => {
const poems: Record<string, string> = {
today: '让呼吸慢一些,让脊柱回到中央。',
tomorrow: '明天见,记得早些休息。',
upcoming: '你的身体,会记得每一次到达。',
pending: '待确认中,我们会为你预留这朵花。',
}
if (dateKey.value === todayStr.value) return poems.today
if (dateKey.value === tomorrowStr.value) return poems.tomorrow
if (props.booking.status === BookingStatus.PENDING_CONFIRMATION) return poems.pending
return poems.upcoming
})
function handleTap() {
emit('tap', props.booking)
}
</script>
<style lang="scss" scoped>
.hero {
position: relative;
margin: 24rpx 32rpx 0;
padding: 36rpx 32rpx 28rpx;
border-radius: 36rpx;
overflow: hidden;
background: linear-gradient(140deg, #efe5d6 0%, #e6d8c4 100%);
color: #3a322b;
box-shadow:
0 1rpx 0 rgba(122, 99, 84, 0.04),
0 12rpx 32rpx rgba(122, 99, 84, 0.06);
&--pending {
background: linear-gradient(140deg, #ece1cd 0%, #e2d2b8 100%);
}
&--confirmed {
background: linear-gradient(140deg, #e2ebe2 0%, #d4e0d3 100%);
}
&--completed {
background: linear-gradient(140deg, #efe5d6 0%, #e6d8c4 100%);
}
&--cancelled {
background: linear-gradient(140deg, #ede4dc 0%, #e3d6c9 100%);
opacity: 0.85;
}
&--noshow {
background: linear-gradient(140deg, #ede0dc 0%, #e3cfc7 100%);
}
&__grain {
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0.4;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.45 0 0 0 0 0.36 0 0 0 0 0.27 0 0 0 0.18 0'/></filter><rect width='200' height='200' filter='url(%23n)'/></svg>");
mix-blend-mode: multiply;
}
&__moon {
position: absolute;
top: -80rpx;
right: -60rpx;
width: 220rpx;
height: 220rpx;
border-radius: 50%;
background: radial-gradient(circle at 30% 30%, rgba(255, 248, 235, 0.55) 0%, rgba(255, 248, 235, 0) 70%);
pointer-events: none;
}
&__main {
position: relative;
display: flex;
align-items: stretch;
gap: 24rpx;
}
&__date {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2rpx;
width: 132rpx;
flex-shrink: 0;
padding: 8rpx 0;
border-radius: 20rpx;
background: rgba(255, 251, 244, 0.5);
backdrop-filter: blur(8rpx);
}
&__day {
font-family: "Songti SC", "STSong", "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 72rpx;
line-height: 1;
font-weight: 500;
color: #3a322b;
font-variant-numeric: tabular-nums;
}
&__month {
margin-top: 8rpx;
font-size: 22rpx;
color: #6f645a;
letter-spacing: 2rpx;
}
&__weekday {
font-size: 20rpx;
color: #8b7d70;
letter-spacing: 1rpx;
}
&__divider {
display: flex;
flex-direction: column;
justify-content: center;
gap: 6rpx;
flex-shrink: 0;
width: 2rpx;
padding: 8rpx 0;
}
&__divider-dot {
width: 2rpx;
height: 8rpx;
background: #b09a83;
border-radius: 1rpx;
opacity: 0.5;
}
&__info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
gap: 8rpx;
padding: 4rpx 0;
}
&__time-row {
display: flex;
align-items: baseline;
gap: 6rpx;
}
&__time {
font-family: "Songti SC", "STSong", "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 50rpx;
line-height: 1;
font-weight: 500;
color: #2a2520;
font-variant-numeric: tabular-nums;
letter-spacing: -1rpx;
}
&__time-end {
font-size: 24rpx;
color: #6f645a;
font-variant-numeric: tabular-nums;
}
&__membership {
font-size: 24rpx;
color: #6f645a;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__status {
display: flex;
align-items: center;
gap: 8rpx;
margin-top: 4rpx;
}
&__dot {
width: 10rpx;
height: 10rpx;
border-radius: 50%;
background: #6e8b7d;
box-shadow: 0 0 0 4rpx rgba(110, 139, 125, 0.18);
}
&__status-text {
font-size: 22rpx;
color: #6e8b7d;
letter-spacing: 1rpx;
}
&__countdown {
font-size: 22rpx;
color: #8b7d70;
font-variant-numeric: tabular-nums;
}
&__footer {
position: relative;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
margin-top: 28rpx;
padding-top: 20rpx;
border-top: 1rpx dashed rgba(122, 99, 84, 0.22);
}
&__poem {
flex: 1;
font-size: 22rpx;
color: #6f645a;
letter-spacing: 2rpx;
font-style: italic;
line-height: 1.5;
}
&__cta {
flex-shrink: 0;
display: flex;
align-items: center;
gap: 6rpx;
padding: 6rpx 0;
}
&__cta-text {
font-size: 22rpx;
color: #8b7d70;
letter-spacing: 2rpx;
}
&__cta-arrow {
font-size: 22rpx;
color: #8b7d70;
transform: translateY(-1rpx);
transition: transform 0.3s ease;
}
}
.hero:active {
transform: scale(0.99);
transition: transform 0.15s ease;
.hero__cta-arrow {
transform: translate(4rpx, -1rpx);
}
}
</style>

View File

@@ -0,0 +1,54 @@
<template>
<view class="pass" :class="[tone, { 'pass--compact': compact }]">
<view class="pass-heading">
<view class="pass-identity"><text class="pass-kind">{{ getCardTypeLabel(membership.cardType.type) }} · MEMBERSHIP</text><text class="pass-name">{{ membership.cardType.name }}</text></view>
<text class="pass-mark">{{ compact ? '查看 ' : '有效' }}</text>
</view>
<view class="pass-balance">
<text class="balance-label">{{ unlimited ? '有效期内' : '剩余' }}</text>
<text class="balance-number">{{ unlimited ? '不限次' : membership.remainingTimes }}</text>
<text v-if="!unlimited" class="balance-unit"></text>
<text v-if="!unlimited && total !== null" class="usage-label">已用 {{ used }} / {{ total }} </text>
<text v-else-if="unlimited" class="usage-label">{{ days }} 天后到期</text>
</view>
<view v-if="!unlimited && total !== null && total > 0" class="usage-track" :aria-label="`已用${used}次,共${total}次`"><view class="usage-fill" :style="{ width: `${progress}%` }" /></view>
<view v-else class="pass-rule" />
<view class="pass-dates"><text v-if="!compact">{{ membership.startDate.slice(0, 10).replace(/-/g, '.') }} 起</text><text :class="{ 'expiry-soon': days <= 7 }">{{ membership.expireDate.slice(0, 10).replace(/-/g, '.') }} 到期</text></view>
<slot />
</view>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { CardTypeCategory, type MembershipWithCardType } from '@mp-pilates/shared'
import { getCardTypeLabel, getMembershipTotalTimes, getMembershipUsedTimes } from '../utils/format'
const props = defineProps<{ membership: MembershipWithCardType; compact?: boolean; now: number }>()
const unlimited = computed(() => props.membership.remainingTimes === null)
const total = computed(() => getMembershipTotalTimes(props.membership))
const used = computed(() => getMembershipUsedTimes(props.membership))
const progress = computed(() => total.value && total.value > 0 ? Math.min(100, Math.max(0, used.value / total.value * 100)) : 0)
const days = computed(() => Math.max(0, Math.ceil((new Date(props.membership.expireDate).getTime() - props.now) / 86400000)))
const tone = computed(() => props.membership.cardType.type === CardTypeCategory.DURATION ? 'pass--sage' : props.membership.cardType.type === CardTypeCategory.TRIAL ? 'pass--clay' : 'pass--sand')
</script>
<style scoped lang="scss">
.pass { --pass-bg: #f0e6d8; --pass-ink: #655240; --pass-line: #d7c3a9; --pass-track: #e3d4c1; box-sizing: border-box; padding: 30rpx; border-radius: 24rpx; background: var(--pass-bg); color: var(--pass-ink); border: 1rpx solid var(--pass-line); }
.pass--sage { --pass-bg: #e7eee4; --pass-ink: #465f4d; --pass-line: #b8c9b3; --pass-track: #d4dfce; }
.pass--clay { --pass-bg: #f2e5df; --pass-ink: #845c4a; --pass-line: #d9b9aa; --pass-track: #e7d0c4; }
.pass-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 20rpx; }
.pass-identity { min-width: 0; flex: 1; }
.pass-kind { display: block; font-size: 18rpx; letter-spacing: 2rpx; }
.pass-name { display: block; margin-top: 12rpx; font-family: 'Songti SC', 'STSong', serif; font-size: 34rpx; line-height: 1.4; overflow-wrap: anywhere; }
.pass-mark { flex-shrink: 0; font-size: 21rpx; padding-top: 4rpx; }
.pass-balance { display: flex; align-items: baseline; flex-wrap: wrap; gap: 10rpx; margin-top: 30rpx; }
.balance-label, .balance-unit { font-size: 23rpx; }
.balance-number { font-family: 'Baskerville', 'Times New Roman', serif; font-size: 60rpx; line-height: 1.2; font-variant-numeric: tabular-nums; }
.usage-label { font-size: 23rpx; margin-left: auto; }
.usage-track { height: 7rpx; border-radius: 8rpx; background: var(--pass-track); overflow: hidden; margin-top: 22rpx; }
.usage-fill { height: 100%; background: var(--pass-ink); border-radius: 8rpx; }
.pass-rule { height: 1rpx; margin-top: 22rpx; background: var(--pass-line); }
.pass-dates { display: flex; justify-content: space-between; gap: 16rpx; margin-top: 18rpx; font-size: 22rpx; font-variant-numeric: tabular-nums; }
.expiry-soon { font-weight: 600; }
.pass--compact { height: 100%; padding: 24rpx; border-radius: 20rpx; .pass-name { font-size: 30rpx; margin-top: 8rpx; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .pass-balance { margin-top: 18rpx; } .balance-number { font-size: 42rpx; } .usage-label { font-size: 21rpx; } .pass-dates { justify-content: flex-end; font-size: 21rpx; margin-top: 14rpx; } .usage-track, .pass-rule { margin-top: 16rpx; } }
</style>

View File

@@ -0,0 +1,19 @@
<template>
<view class="progress">
<view class="bar"><view class="fill" :style="{ width: `${percent}%` }" /></view>
<text class="label">{{ step }}/{{ total }}</text>
</view>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ step: number; total: number }>()
const percent = computed(() => Math.round((props.step / props.total) * 100))
</script>
<style lang="scss" scoped>
.progress { display: flex; align-items: center; gap: 16rpx; margin: 8rpx 0 24rpx; }
.bar { flex: 1; height: 8rpx; background: #efe8e1; border-radius: 8rpx; overflow: hidden; }
.fill { height: 100%; background: #6b8276; }
.label { font-size: 22rpx; color: #8a7b6e; }
</style>

View File

@@ -0,0 +1,69 @@
<template>
<canvas canvas-id="portraitRadar" class="radar" />
</template>
<script setup lang="ts">
import { getCurrentInstance, onMounted, watch } from 'vue'
import { BODY_DIMENSION_LABELS, type BodyPortraitScores } from '@mp-pilates/shared'
const props = defineProps<{ scores: BodyPortraitScores }>()
const instance = getCurrentInstance()
const labels = ['肩颈', '脊柱', '核心', '髋骨盆', '下肢']
const keys = ['cervicalShoulder', 'spinalMobility', 'coreControl', 'hipPelvis', 'lowerLimb'] as const
function draw() {
const ctx = uni.createCanvasContext('portraitRadar', instance?.proxy)
const w = 280
const h = 280
const cx = w / 2
const cy = h / 2
const radius = 96
ctx.clearRect(0, 0, w, h)
ctx.setStrokeStyle('#d9cfc5')
ctx.setFillStyle('#edf2ec')
for (let ring = 1; ring <= 4; ring++) {
ctx.beginPath()
for (let i = 0; i < 5; i++) {
const angle = -Math.PI / 2 + (Math.PI * 2 * i) / 5
const x = cx + Math.cos(angle) * radius * (ring / 4)
const y = cy + Math.sin(angle) * radius * (ring / 4)
if (i === 0) ctx.moveTo(x, y)
else ctx.lineTo(x, y)
}
ctx.closePath()
ctx.stroke()
}
ctx.setFillStyle('rgba(107,130,118,0.35)')
ctx.setStrokeStyle('#6b8276')
ctx.beginPath()
keys.forEach((key, i) => {
const angle = -Math.PI / 2 + (Math.PI * 2 * i) / 5
const value = Math.max(8, props.scores[key]) / 100
const x = cx + Math.cos(angle) * radius * value
const y = cy + Math.sin(angle) * radius * value
if (i === 0) ctx.moveTo(x, y)
else ctx.lineTo(x, y)
})
ctx.closePath()
ctx.fill()
ctx.stroke()
ctx.setFillStyle('#5d5148')
ctx.setFontSize(11)
ctx.setTextAlign('center')
labels.forEach((label, i) => {
const angle = -Math.PI / 2 + (Math.PI * 2 * i) / 5
const x = cx + Math.cos(angle) * (radius + 22)
const y = cy + Math.sin(angle) * (radius + 22)
ctx.fillText(label, x, y)
})
ctx.draw()
}
onMounted(draw)
watch(() => props.scores, draw, { deep: true })
void BODY_DIMENSION_LABELS
</script>
<style lang="scss" scoped>
.radar { width: 560rpx; height: 560rpx; margin: 0 auto; }
</style>

View File

@@ -0,0 +1,126 @@
<template>
<view class="practice">
<view class="practice__heading">
<view>
<view class="practice__title">练习足迹<text class="practice__period">最近 30 </text></view>
</view>
<view class="practice__summary"><text class="practice__number">{{ activity ? total : '—' }}</text><text>节课</text></view>
</view>
<view v-if="error" class="practice__state">
<text>暂时未能加载练习记录</text>
<button class="practice__retry" @tap="load">重新加载</button>
</view>
<template v-else>
<view class="practice__range">
<text>{{ activity ? formatDate(activity.days[0].date) : '正在读取练习记录' }}</text>
<text>{{ activity ? formatDate(activity.days[29].date) + ' · 今天' : '' }}</text>
</view>
<view class="practice__grid" :class="{ 'practice__grid--loading': !activity }">
<button v-for="(day, index) in cells" :key="day.date || index"
class="practice__cell" :class="[
`practice__cell--${Math.min(day.count, 3)}`,
{ 'practice__cell--selected': selected === day.date && !!activity, 'practice__cell--today': index === 29 },
]"
:disabled="!activity" :aria-label="activity ? `${formatDate(day.date)}已完成 ${day.count} 节课` : '加载中'"
@tap="selected = day.date">
<text>{{ day.date ? Number(day.date.slice(-2)) : '' }}</text>
</button>
</view>
<view class="practice__footer">
<text class="practice__detail">{{ detail }}</text>
<view class="practice__legend">
<text>0</text><view class="practice__swatch practice__cell--0" />
<view class="practice__swatch practice__cell--1" /><view class="practice__swatch practice__cell--2" />
<view class="practice__swatch practice__cell--3" /><text>3+ </text>
</view>
</view>
</template>
</view>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import type { PracticeActivity } from '@mp-pilates/shared'
import { get } from '../utils/request'
const props = defineProps<{ refreshKey: number }>()
const activity = ref<PracticeActivity | null>(null)
const selected = ref('')
const error = ref(false)
let loading = false
let disposed = false
const cells = computed(() => activity.value?.days ?? Array.from({ length: 30 }, () => ({ date: '', count: 0 })))
const total = computed(() => cells.value.reduce((sum, day) => sum + day.count, 0))
const activeDays = computed(() => cells.value.filter(day => day.count > 0).length)
const detail = computed(() => {
if (!activity.value) return '正在整理练习记录'
const day = activity.value.days.find(item => item.date === selected.value)
if (day) return `${formatDate(day.date)} · ${day.count ? `已完成 ${day.count} 节课` : '暂无已完成课程'}`
return total.value ? `已练习 ${activeDays.value} 天 · 点选查看` : '近 30 天暂无已完成课程'
})
function formatDate(date: string) {
return `${Number(date.slice(5, 7))}${Number(date.slice(8, 10))}`
}
async function load() {
if (loading || disposed) return
loading = true
error.value = false
try {
const result = await get<PracticeActivity>('/booking/my/activity')
if (!disposed) {
activity.value = result
if (!result.days.some(day => day.date === selected.value)) selected.value = ''
}
} catch {
if (!disposed) {
activity.value = null
error.value = true
}
} finally {
loading = false
}
}
onMounted(load)
watch(() => props.refreshKey, load)
onUnmounted(() => { disposed = true })
</script>
<style scoped lang="scss">
.practice {
margin: 24rpx 32rpx 0;
padding: 28rpx;
border: 1rpx solid #eee8e3;
border-radius: 28rpx;
background: #fff;
color: #514943;
&__heading, &__range, &__footer, &__legend { display: flex; align-items: center; justify-content: space-between; }
&__title { font-size: 28rpx; font-weight: 500; }
&__period { margin-left: 16rpx; font-size: 21rpx; font-weight: 400; letter-spacing: 0; color: #8b817b; }
&__summary { display: flex; align-items: baseline; gap: 8rpx; font-size: 21rpx; color: #8b817b; }
&__number { font-size: 44rpx; font-weight: 400; line-height: 1; color: #617d73; font-variant-numeric: tabular-nums; }
&__range { margin: 24rpx 0 12rpx; font-size: 20rpx; color: #8b817b; }
&__grid { display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); gap: 9rpx; }
&__cell {
width: 100%; height: 44rpx; min-width: 0; margin: 0; padding: 0;
display: flex; justify-content: center; align-items: center;
border-radius: 8rpx; border: 2rpx solid transparent; box-sizing: border-box;
font-size: 19rpx; line-height: 1; font-variant-numeric: tabular-nums;
&::after { border: none; }
&--0 { background: #edf0e9; color: #7c8676; }
&--1 { background: #ccd9c6; color: #516d50; }
&--2 { background: #9cb594; color: #304b36; }
&--3 { background: #637f5f; color: #ffffff; }
&--today { border-bottom-color: #516d50; }
&--selected { box-shadow: 0 0 0 3rpx #fff, 0 0 0 5rpx #637f5f; }
}
&__grid--loading { opacity: 0.5; }
&__footer { margin-top: 22rpx; gap: 12rpx; flex-wrap: wrap; }
&__detail { font-size: 21rpx; color: #788477; }
&__legend { gap: 5rpx; font-size: 18rpx; color: #8b817b; }
&__swatch { width: 13rpx; height: 13rpx; border-radius: 3rpx; }
&__state { min-height: 200rpx; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 20rpx; font-size: 24rpx; color: #8b817b; }
&__retry { margin: 0; padding: 0 24rpx; line-height: 56rpx; font-size: 24rpx; color: #516d50; background: #edf0e9; border-radius: 28rpx; &::after { border: none; } }
}
</style>

View File

@@ -1,33 +1,18 @@
<template>
<view class="profile-menu">
<template v-for="item in menuItems" :key="item.key">
<!-- Separator -->
<view v-if="item.type === 'separator'" class="profile-menu__separator" />
<slot />
<!-- Menu item -->
<view
v-else
class="profile-menu__item"
:class="{ 'profile-menu__item--admin': item.isAdmin }"
hover-class="profile-menu__item--hover"
hover-stay-time="150"
@tap="handleTap(item)"
>
<view
class="profile-menu__icon-wrap"
:class="[
`profile-menu__icon-wrap--${item.key}`,
{ 'profile-menu__icon-wrap--admin': item.isAdmin },
]"
/>
<text class="profile-menu__title" :class="{ 'profile-menu__title--admin': item.isAdmin }">
{{ item.title }}
</text>
<text v-if="item.badge" class="profile-menu__badge">{{ item.badge }}</text>
<view class="profile-menu__links">
<template v-for="item in menuItems" :key="item.key">
<view v-if="item.type === 'separator'" class="profile-menu__separator" />
<view v-else class="profile-menu__item" :class="{ 'profile-menu__item--admin': item.isAdmin }"
hover-class="profile-menu__item--hover" hover-stay-time="150" @tap="handleTap(item)">
<text class="profile-menu__title">{{ item.title }}</text>
<text class="profile-menu__arrow"></text>
</view>
</template>
</view>
</view>
</template>
<script setup lang="ts">
@@ -39,8 +24,7 @@ interface MenuItem {
title?: string
path?: string
isAdmin?: boolean
badge?: string
action?: 'clear' | 'about'
action?: 'clear' | 'notifications'
requireAuth?: boolean
}
@@ -51,19 +35,24 @@ const props = defineProps<{
const emit = defineEmits<{
(e: 'clear-cache'): void
(e: 'about'): void
(e: 'require-login'): void
(e: 'open-notifications'): void
}>()
const menuItems = computed<MenuItem[]>(() => {
const items: MenuItem[] = [
{
key: 'membership',
type: 'item',
title: '我的会员卡',
path: '/pages/profile/membership',
{ key: 'progress', type: 'item', title: '我的成长档案', path: '/pages/profile/progress', requireAuth: true },
{ key: 'portrait', type: 'item', title: '身体状态评估', path: '/pages/portrait/index' },
{ key: 'plan', type: 'item', title: '我的改善计划', path: '/pages/portrait/plan', requireAuth: true },
...(props.isAdmin
? [{
key: 'teaching-schedule',
type: 'item' as const,
title: '我的课表',
path: '/pages/profile/teaching-schedule',
requireAuth: true,
},
}]
: []),
{
key: 'bookings',
type: 'item',
@@ -78,6 +67,13 @@ const menuItems = computed<MenuItem[]>(() => {
path: '/pages/profile/info',
requireAuth: true,
},
{
key: 'notifications',
type: 'item',
title: '消息提醒设置',
action: 'notifications',
requireAuth: true,
},
{
key: 'sep1',
type: 'separator',
@@ -88,12 +84,6 @@ const menuItems = computed<MenuItem[]>(() => {
title: '清除缓存',
action: 'clear',
},
{
key: 'about',
type: 'item',
title: '关于我们',
action: 'about',
},
]
if (props.isAdmin) {
@@ -118,8 +108,8 @@ function handleTap(item: MenuItem) {
}
if (item.action === 'clear') {
emit('clear-cache')
} else if (item.action === 'about') {
emit('about')
} else if (item.action === 'notifications') {
emit('open-notifications')
} else if (item.path) {
uni.navigateTo({ url: item.path })
}
@@ -128,237 +118,12 @@ function handleTap(item: MenuItem) {
<style lang="scss" scoped>
.profile-menu {
background: $bg-card;
border-radius: $radius-lg;
margin: $spacing-lg $spacing-lg 0;
overflow: hidden;
&__separator {
height: $spacing-sm;
background: $bg-page;
}
&__item {
display: flex;
align-items: center;
padding: $spacing-md $spacing-lg;
border-bottom: 1rpx solid $border-color;
background: $bg-card;
transition: background 0.15s;
&:last-child {
border-bottom: none;
}
&--hover {
background: #f5f5f5;
}
&--admin {
background: rgba($accent-color, 0.04);
}
}
&__icon-wrap {
width: 56rpx;
height: 56rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-right: $spacing-md;
position: relative;
background: rgba($brand-color, 0.06);
// ─── Pure CSS Icons ────────────────────────────────
// 会员卡 — 圆角矩形卡片 + 横线
&--membership {
background: rgba($accent-color, 0.10);
&::before {
content: '';
width: 26rpx;
height: 18rpx;
border: 2.5rpx solid $accent-color;
border-radius: 4rpx;
box-sizing: border-box;
}
&::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, 1rpx);
width: 16rpx;
height: 0;
border-top: 2.5rpx solid $accent-color;
}
}
// 预约 — 日历(矩形 + 顶部两个小竖线)
&--bookings {
background: rgba($brand-color, 0.06);
&::before {
content: '';
width: 24rpx;
height: 22rpx;
border: 2.5rpx solid $brand-color;
border-radius: 4rpx;
border-top-width: 5rpx;
box-sizing: border-box;
}
&::after {
content: '';
position: absolute;
top: 14rpx;
left: 50%;
transform: translateX(-50%);
width: 10rpx;
height: 0;
border-top: 2.5rpx solid $brand-color;
// 用 box-shadow 模拟两个竖线
box-shadow:
-4rpx -7rpx 0 0 $brand-color,
4rpx -7rpx 0 0 $brand-color;
}
}
// 个人信息 — 人形(圆 + 肩弧)
&--info {
background: rgba($brand-color, 0.06);
&::before {
content: '';
width: 12rpx;
height: 12rpx;
border: 2.5rpx solid $brand-color;
border-radius: 50%;
position: absolute;
top: 16rpx;
left: 50%;
transform: translateX(-50%);
box-sizing: border-box;
}
&::after {
content: '';
width: 22rpx;
height: 10rpx;
border: 2.5rpx solid $brand-color;
border-bottom: none;
border-radius: 12rpx 12rpx 0 0;
position: absolute;
bottom: 13rpx;
left: 50%;
transform: translateX(-50%);
box-sizing: border-box;
}
}
// 清除缓存 — 旋转的刷新箭头(圆弧)
&--clear {
background: rgba($text-hint, 0.08);
&::before {
content: '';
width: 20rpx;
height: 20rpx;
border: 2.5rpx solid $text-secondary;
border-radius: 50%;
border-right-color: transparent;
box-sizing: border-box;
}
&::after {
content: '';
position: absolute;
top: 14rpx;
right: 15rpx;
width: 0;
height: 0;
border-left: 5rpx solid $text-secondary;
border-top: 4rpx solid transparent;
border-bottom: 4rpx solid transparent;
}
}
// 关于我们 — 圆形中心一个点 + 竖线info 标记)
&--about {
background: rgba($text-hint, 0.08);
&::before {
content: '';
width: 22rpx;
height: 22rpx;
border: 2.5rpx solid $text-secondary;
border-radius: 50%;
box-sizing: border-box;
}
&::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 2.5rpx;
height: 8rpx;
background: $text-secondary;
border-radius: 1rpx;
box-shadow: 0 -6rpx 0 0 $text-secondary;
}
}
// 管理中心 — 齿轮(圆 + 四个刻度)
&--admin {
background: rgba($accent-color, 0.12);
&::before {
content: '';
width: 14rpx;
height: 14rpx;
border: 2.5rpx solid $accent-color;
border-radius: 50%;
box-sizing: border-box;
}
&::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 24rpx;
height: 24rpx;
transform: translate(-50%, -50%);
// 四条刻度线用 box-shadow 实现
background:
linear-gradient($accent-color, $accent-color) center top / 2.5rpx 5rpx no-repeat,
linear-gradient($accent-color, $accent-color) center bottom / 2.5rpx 5rpx no-repeat,
linear-gradient($accent-color, $accent-color) left center / 5rpx 2.5rpx no-repeat,
linear-gradient($accent-color, $accent-color) right center / 5rpx 2.5rpx no-repeat;
}
}
}
&__title {
flex: 1;
font-size: 30rpx;
color: $text-primary;
&--admin {
color: $accent-color;
font-weight: 500;
}
}
&__badge {
font-size: 22rpx;
color: #ffffff;
background: $error-color;
border-radius: 20rpx;
padding: 2rpx 12rpx;
margin-right: $spacing-sm;
}
&__arrow {
font-size: 36rpx;
color: $text-hint;
line-height: 1;
transform: scaleX(0.6);
transform-origin: center;
}
&__links { margin: 24rpx 32rpx 0; border-radius: 26rpx; background: #fff; overflow: hidden; }
&__item { display: flex; align-items: center; gap: 20rpx; min-height: 96rpx; padding: 0 28rpx; box-sizing: border-box; border-bottom: 1rpx solid #f2ede8; &:last-child { border-bottom: none; } }
&__item--hover { background: #f4f1ec; }
&__item--admin { background: #eff3ed; .profile-menu__title { color: #617d73; } }
&__title { flex: 1; font-size: 27rpx; font-weight: 400; color: #6f655e; }
&__arrow { font-size: 30rpx; color: #b2a79e; line-height: 1; }
&__separator { height: 12rpx; background: #fbf9f6; }
}
</style>

View File

@@ -1,98 +1,38 @@
<template>
<view class="quick-entry">
<!-- Not logged in -->
<view v-if="!userStore.loggedIn" class="entry-card login-card" @tap="handleLogin">
<view class="entry-content">
<view class="entry-left">
<view class="entry-icon-wrap login-icon">
<view class="icon-user" />
</view>
<view class="entry-text">
<text class="entry-title">欢迎来到工作室</text>
<text class="entry-subtitle">登录后即可预约课程</text>
</view>
</view>
<view class="entry-btn login-btn">
<text class="entry-btn-text">微信登录</text>
</view>
<view v-if="!userStore.loggedIn || userStore.memberships.length === 0" class="entry-pill pill-login" @tap="handlePortrait">
<text class="pill-label">3 分钟了解自己的身体状态</text>
<view class="pill-action action-login">
<text class="pill-action-text">开始评估</text>
</view>
</view>
<!-- Logged in, no memberships at all new user -->
<view
v-else-if="userStore.loggedIn && userStore.memberships.length === 0"
class="entry-card trial-card"
@tap="handleTrialEntry"
>
<view class="entry-content">
<view class="entry-left">
<view class="entry-icon-wrap trial-icon">
<view class="icon-star" />
</view>
<view class="entry-text">
<text class="entry-title">初次体验</text>
<text class="entry-subtitle">专属体验课了解普拉提</text>
</view>
</view>
<view class="entry-btn trial-btn">
<text class="entry-btn-text">预约体验课</text>
</view>
</view>
<view class="card-badge trial-badge">新会员专享</view>
</view>
<!-- Has valid active card + running low warning -->
<!-- Has valid active card -->
<template v-else-if="userStore.hasValidMembership">
<view class="entry-card active-card" @tap="handleBooking">
<view class="entry-content">
<view class="entry-left">
<view class="entry-icon-wrap active-icon">
<view class="icon-clock" />
</view>
<view class="entry-text">
<text class="entry-title">一键约课</text>
<text class="entry-subtitle">{{ activeMembershipLabel }}</text>
</view>
</view>
<view class="entry-btn book-btn">
<text class="entry-btn-text">立即预约</text>
</view>
</view>
<!-- Running low badge -->
<view v-if="isRunningLow" class="card-badge low-badge">
仅剩 {{ lowestRemainingTimes }}
<view class="entry-pill pill-active" @tap="handleBooking">
<text class="pill-label pill-label-active">{{ activeMembershipLabel }}</text>
<view class="pill-action action-book">
<text class="pill-action-text">预约课程</text>
</view>
</view>
<!-- Renew reminder if running low -->
<view v-if="isRunningLow" class="renew-tip" @tap="scrollToCardShop">
<view class="renew-tip-icon">
<view class="icon-warning" />
</view>
<text class="renew-tip-text">课次即将用完点击续卡保持练习节奏</text>
<text class="renew-tip-action">续卡 </text>
<!-- Running low: thin accent strip -->
<view v-if="renewStripText" class="renew-strip" @tap="handleRenew">
<text class="renew-strip-text">{{ renewStripText }}</text>
<text class="renew-strip-arrow"></text>
</view>
</template>
<!-- Has memberships but none active buy card -->
<view
v-else
class="entry-card expired-card"
@tap="scrollToCardShop"
class="entry-pill pill-expired"
@tap="handleRenew"
>
<view class="entry-content">
<view class="entry-left">
<view class="entry-icon-wrap expired-icon">
<view class="icon-card" />
</view>
<view class="entry-text">
<text class="entry-title">续费会员卡</text>
<text class="entry-subtitle">您的卡已到期续卡继续练习</text>
</view>
</view>
<view class="entry-btn renew-btn">
<text class="entry-btn-text">购买会员卡</text>
</view>
<text class="pill-label">暂无可用会员卡</text>
<view class="pill-action action-renew">
<text class="pill-action-text">续卡</text>
</view>
</view>
</view>
@@ -101,7 +41,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useUserStore } from '../stores/user'
import { CardTypeCategory } from '@mp-pilates/shared'
import { getErrorMessage } from '../utils/auth'
const emit = defineEmits<{
(e: 'scroll-to-card-shop'): void
@@ -114,19 +54,19 @@ async function handleLogin() {
if (loading.value) return
loading.value = true
try {
await userStore.login()
await userStore.fetchMemberships()
// 登录成功后跳转到个人中心,让用户完善信息
uni.navigateTo({ url: '/pages/profile/info' })
} catch {
uni.showToast({ title: '登录失败,请重试', icon: 'none' })
await userStore.loginWithSetup()
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '登录失败,请重试'), icon: 'none' })
} finally {
loading.value = false
}
}
function handlePortrait() {
uni.navigateTo({ url: '/pages/portrait/index' })
}
function handleTrialEntry() {
// Navigate to the first TRIAL card detail page
uni.navigateTo({ url: '/pages/card/detail?trial=1' })
}
@@ -138,13 +78,21 @@ function scrollToCardShop() {
emit('scroll-to-card-shop')
}
// Computed: label for the active membership
function handleRenew() {
const cardTypeId = userStore.renewalHint?.cardTypeId
if (cardTypeId) {
uni.navigateTo({ url: `/pages/card/detail?id=${cardTypeId}` })
return
}
scrollToCardShop()
}
const activeMembershipLabel = computed(() => {
const active = userStore.activeMemberships
if (!active.length) return ''
const m = active[0]
const cardName = m.cardType.name
if (m.cardType.type === CardTypeCategory.TIMES && m.remainingTimes !== null) {
if (m.remainingTimes !== null) {
return `${cardName} · 剩余 ${m.remainingTimes}`
}
const expire = new Date(m.expireDate)
@@ -153,319 +101,32 @@ const activeMembershipLabel = computed(() => {
return `${cardName} · 剩余 ${daysLeft}`
})
// Check if any TIMES card has ≤ 2 remaining
const isRunningLow = computed(() => {
return userStore.activeMemberships.some(
(m) =>
m.cardType.type === CardTypeCategory.TIMES &&
m.remainingTimes !== null &&
m.remainingTimes <= 2,
)
})
const lowestRemainingTimes = computed(() => {
const timesCards = userStore.activeMemberships.filter(
(m) =>
m.cardType.type === CardTypeCategory.TIMES &&
m.remainingTimes !== null &&
m.remainingTimes <= 2,
)
if (!timesCards.length) return 0
return Math.min(...timesCards.map((m) => m.remainingTimes as number))
const renewStripText = computed(() => {
const hint = userStore.renewalHint
if (!hint || !userStore.hasValidMembership) return ''
if (hint.kind === 'times_low') {
return `仅剩 ${hint.remainingTimes ?? 0} 次 · 续卡保持节奏`
}
if (hint.kind === 'days_low') {
return `还剩 ${hint.daysLeft ?? 0} 天到期 · 续卡不中断`
}
if (hint.kind === 'trial_low') {
return '体验课将尽 · 选购会员卡'
}
return ''
})
</script>
<style lang="scss" scoped>
.quick-entry {
margin: 24rpx 24rpx 0;
}
.entry-card {
position: relative;
border-radius: 16rpx;
padding: 36rpx 32rpx;
box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
overflow: hidden;
}
.login-card {
background: linear-gradient(135deg, #1a1a2e 0%, #2d2d5e 100%);
}
.trial-card {
background: linear-gradient(135deg, #2d2d5e 0%, #4a3f7a 100%);
}
.active-card {
background: linear-gradient(135deg, #2a3a4a 0%, #1a2a3a 100%);
}
.expired-card {
background: linear-gradient(135deg, #4a4a4a 0%, #2a2a2a 100%);
}
.entry-content {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24rpx;
}
.entry-left {
display: flex;
align-items: center;
gap: 28rpx;
flex: 1;
}
.entry-icon-wrap {
width: 88rpx;
height: 88rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
position: relative;
}
.login-icon {
background: rgba(255, 255, 255, 0.12);
}
.trial-icon {
background: rgba(255, 215, 0, 0.2);
}
.active-icon {
background: rgba(168, 196, 206, 0.25);
}
.expired-icon {
background: rgba(255, 255, 255, 0.12);
}
/* ── Icon shapes (pure CSS) ── */
/* User icon: head + shoulders */
.icon-user {
position: relative;
width: 36rpx;
height: 36rpx;
&::before {
content: '';
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 20rpx;
height: 20rpx;
border-radius: 50%;
background: #fff;
}
&::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 28rpx;
height: 14rpx;
border-radius: 14rpx 14rpx 0 0;
background: #fff;
}
}
/* Star icon - diamond shape */
.icon-star {
position: relative;
width: 32rpx;
height: 32rpx;
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(45deg);
width: 24rpx;
height: 24rpx;
background: #ffd700;
}
}
/* Clock icon - circle with dot */
.icon-clock {
position: relative;
width: 36rpx;
height: 36rpx;
border-radius: 50%;
border: 3rpx solid #fff;
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 8rpx;
height: 8rpx;
border-radius: 50%;
background: #fff;
}
}
/* Card icon */
.icon-card {
position: relative;
width: 36rpx;
height: 26rpx;
border-radius: 4rpx;
border: 3rpx solid #fff;
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 12rpx;
height: 6rpx;
border-radius: 2rpx;
background: #fff;
}
}
/* Warning triangle */
.icon-warning {
position: relative;
width: 0;
height: 0;
border-left: 12rpx solid transparent;
border-right: 12rpx solid transparent;
border-bottom: 20rpx solid #e8a87c;
}
.entry-text {
flex: 1;
min-width: 0;
}
.entry-title {
display: block;
font-size: 34rpx;
font-weight: 600;
color: #ffffff;
margin-bottom: 8rpx;
letter-spacing: 1rpx;
}
.entry-subtitle {
display: block;
font-size: 24rpx;
color: rgba(255, 255, 255, 0.6);
line-height: 1.4;
}
.entry-btn {
flex-shrink: 0;
padding: 18rpx 36rpx;
border-radius: 40rpx;
display: flex;
align-items: center;
justify-content: center;
position: relative;
overflow: hidden;
&::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(180deg, rgba(255,255,255,0.2) 0%, transparent 100%);
opacity: 0.5;
}
}
.entry-btn-text {
font-size: 28rpx;
font-weight: 600;
white-space: nowrap;
position: relative;
z-index: 1;
}
.login-btn,
.trial-btn,
.book-btn {
background: $primary-color;
}
.renew-btn {
background: #666;
}
.login-btn .entry-btn-text,
.trial-btn .entry-btn-text,
.book-btn .entry-btn-text,
.renew-btn .entry-btn-text {
color: #1a1a2e;
}
/* Corner badge */
.card-badge {
position: absolute;
top: 0;
right: 0;
padding: 8rpx 20rpx;
font-size: 20rpx;
font-weight: 600;
border-radius: 0 16rpx 0 16rpx;
}
.trial-badge {
background: linear-gradient(135deg, #ffd700, #ffaa00);
color: #1a1a2e;
}
.low-badge {
background: #e74c3c;
color: #ffffff;
}
/* Renew tip bar */
.renew-tip {
display: flex;
align-items: center;
gap: 12rpx;
margin-top: 16rpx;
padding: 20rpx 24rpx;
background: #fff8f0;
border-radius: 12rpx;
border: 1rpx solid rgba(240, 180, 100, 0.3);
}
.renew-tip-icon {
width: 36rpx;
height: 36rpx;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.renew-tip-text {
flex: 1;
font-size: 24rpx;
color: #a0622a;
line-height: 1.4;
}
.renew-tip-action {
font-size: 24rpx;
color: $primary-dark;
font-weight: 600;
flex-shrink: 0;
}
.quick-entry { margin: 24rpx 32rpx 0; }
.entry-pill { display: flex; align-items: center; min-height: 120rpx; box-sizing: border-box; padding: 24rpx; gap: 20rpx; border-radius: 28rpx; background: #f1e8e1; }
.pill-active { background: #edf2ec; }
.pill-expired { background: #f0ece7; }
.pill-label { flex: 1; min-width: 0; font-size: 26rpx; line-height: 1.6; color: #6f5c50; overflow-wrap: anywhere; }
.pill-label-active { color: #526b5d; }
.pill-action { flex-shrink: 0; min-height: 68rpx; padding: 0 24rpx; border-radius: 999rpx; display: flex; align-items: center; justify-content: center; background: #6b8276; }
.pill-action-text { font-size: 24rpx; font-weight: 400; color: #fff; white-space: nowrap; }
.renew-strip { display: flex; align-items: center; justify-content: space-between; gap: 16rpx; padding: 18rpx 12rpx 0; }
.renew-strip-text { font-size: 22rpx; color: #8b817b; line-height: 1.5; }
.renew-strip-arrow { font-size: 28rpx; color: #8b817b; }
</style>

View File

@@ -0,0 +1,9 @@
<template><view v-if="summary && summary.count > 0" class="summary"><view><text class="label">来自真实课后反馈</text><text class="caption">每一次被听见,让练习更贴近你。</text></view><view class="score"><text>{{ summary.average }}<text class="star">★</text></text><text class="count">{{ summary.count }} 份评价</text></view></view></template>
<script setup lang="ts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { get } from '../utils/request'
const summary = ref<{ count: number; average: number | null } | null>(null)
onShow(async () => { try { summary.value = await get('/reviews/summary') } catch { summary.value = null } })
</script>
<style scoped>.summary{margin:24rpx 32rpx;padding:26rpx;display:flex;justify-content:space-between;align-items:center;gap:20rpx;border:1rpx solid #e2e5d9;border-radius:24rpx;background:#f1f3e9;}.label{display:block;font-size:26rpx;color:#65735b;}.caption{display:block;font-size:22rpx;color:#8a8d7c;line-height:1.7;margin-top:10rpx;}.score{flex-shrink:0;text-align:right;font-size:46rpx;color:#6b785c;font-family:'Baskerville',serif;}.star{font-size:27rpx;margin-left:8rpx;color:#a1874b;}.count{display:block;font-size:21rpx;font-family:inherit;line-height:1.8;color:#858874;}</style>

View File

@@ -0,0 +1,16 @@
<template>
<view class="notice">
<text class="title">建议先确认运动条件</text>
<text class="body">{{ message }}</text>
</view>
</template>
<script setup lang="ts">
defineProps<{ message: string }>()
</script>
<style lang="scss" scoped>
.notice { margin: 24rpx 0; padding: 28rpx; border-radius: 20rpx; background: #f7eee8; }
.title { display: block; font-size: 30rpx; color: #7a4e3e; margin-bottom: 12rpx; }
.body { display: block; font-size: 26rpx; line-height: 1.7; color: #8a6458; }
</style>

View File

@@ -0,0 +1,288 @@
<template>
<view
class="session"
:class="[
`session--${tone}`,
{ 'session--muted': muted, 'session--history': history },
]"
@tap="handleTap"
>
<!-- 左侧日期块 -->
<view class="session__date">
<text class="session__day">{{ dayNumber }}</text>
<text class="session__weekday">{{ weekdayLabel }}</text>
</view>
<!-- 中央分隔虚线 -->
<view class="session__rail">
<view class="session__dot" />
<view class="session__line" />
</view>
<!-- 主体信息 -->
<view class="session__body">
<view class="session__top">
<text class="session__time">{{ startTime }}</text>
<text class="session__time-end"> {{ endTime }}</text>
</view>
<text class="session__membership">{{ cardName }}</text>
<view class="session__bottom">
<view class="session__status">
<view class="session__status-dot" />
<text class="session__status-text">{{ statusLabel }}</text>
</view>
<text v-if="!history" class="session__cancel" @tap.stop="handleCancel">取消预约</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { BookingWithDetails } from '@mp-pilates/shared'
import { BookingStatus } from '@mp-pilates/shared'
import {
bookingStatusLabel,
bookingStatusStripeClass,
} from '../utils/booking-helpers'
const props = defineProps<{
booking: BookingWithDetails
/** 历史记录模式(更紧凑,隐藏取消按钮) */
history?: boolean
}>()
const emit = defineEmits<{
tap: [booking: BookingWithDetails]
cancel: [booking: BookingWithDetails]
}>()
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
function parseDate(dateStr: string): Date {
const normalized = dateStr.slice(0, 10)
const [y, m, d] = normalized.split('-').map(Number)
return new Date(y, m - 1, d)
}
const date = computed(() => parseDate(props.booking.timeSlot.date))
const dayNumber = computed(() => {
const d = date.value.getDate()
return d < 10 ? `0${d}` : String(d)
})
const weekdayLabel = computed(() => weekdays[date.value.getDay()])
const startTime = computed(() => props.booking.timeSlot.startTime.slice(0, 5))
const endTime = computed(() => props.booking.timeSlot.endTime.slice(0, 5))
const cardName = computed(() => props.booking.membership?.cardType?.name || '会员卡')
const statusLabel = computed(() => bookingStatusLabel(props.booking.status))
const tone = computed(() => bookingStatusStripeClass(props.booking.status))
const muted = computed(() => {
return props.booking.status === BookingStatus.CANCELLED || props.booking.status === BookingStatus.NO_SHOW
})
function handleTap() {
emit('tap', props.booking)
}
function handleCancel() {
emit('cancel', props.booking)
}
</script>
<style lang="scss" scoped>
.session {
position: relative;
display: flex;
align-items: stretch;
gap: 20rpx;
padding: 28rpx 24rpx;
margin: 0 32rpx 16rpx;
border-radius: 28rpx;
background: #fdfbf7;
border: 1rpx solid #ede5d8;
box-shadow:
0 1rpx 0 rgba(122, 99, 84, 0.02),
0 4rpx 16rpx rgba(122, 99, 84, 0.03);
transition: transform 0.2s ease, box-shadow 0.2s ease;
&__date {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2rpx;
width: 80rpx;
flex-shrink: 0;
padding: 4rpx 0;
}
&__day {
font-family: "Songti SC", "STSong", "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 44rpx;
font-weight: 500;
line-height: 1;
color: #3a322b;
font-variant-numeric: tabular-nums;
}
&__weekday {
font-size: 19rpx;
color: #a89d92;
letter-spacing: 1rpx;
margin-top: 4rpx;
}
&__rail {
display: flex;
flex-direction: column;
align-items: center;
gap: 0;
width: 14rpx;
flex-shrink: 0;
padding: 6rpx 0;
}
&__dot {
width: 10rpx;
height: 10rpx;
border-radius: 50%;
background: #6e8b7d;
flex-shrink: 0;
}
&__line {
width: 1rpx;
flex: 1;
background: linear-gradient(
to bottom,
rgba(155, 138, 117, 0.3) 0%,
rgba(155, 138, 117, 0) 100%
);
}
// 状态颜色
&--stripe--pending &__dot { background: #b8967c; }
&--stripe--confirmed &__dot { background: #6e8b7d; }
&--stripe--completed &__dot { background: #6e8b7d; }
&--stripe--cancelled &__dot { background: #c4a09a; }
&--stripe--noshow &__dot { background: #b89a93; }
&__body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6rpx;
padding: 4rpx 0;
}
&__top {
display: flex;
align-items: baseline;
gap: 6rpx;
}
&__time {
font-family: "Songti SC", "STSong", "Noto Serif SC", "Source Han Serif SC", serif;
font-size: 34rpx;
font-weight: 500;
color: #3a322b;
font-variant-numeric: tabular-nums;
}
&__time-end {
font-size: 22rpx;
color: #a89d92;
font-variant-numeric: tabular-nums;
}
&__membership {
font-size: 22rpx;
color: #786b61;
line-height: 1.5;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12rpx;
margin-top: 6rpx;
}
&__status {
display: flex;
align-items: center;
gap: 8rpx;
}
&__status-dot {
width: 8rpx;
height: 8rpx;
border-radius: 50%;
background: #6e8b7d;
}
&__status-text {
font-size: 21rpx;
color: #786b61;
letter-spacing: 1rpx;
}
&--stripe--pending &__status-text { color: #957c65; }
&--stripe--pending &__status-dot { background: #b8967c; }
&--stripe--cancelled &__status-text { color: #a89d92; }
&--stripe--cancelled &__status-dot { background: #c4a09a; }
&--stripe--noshow &__status-text { color: #9c7a6e; }
&--stripe--noshow &__status-dot { background: #b89a93; }
&__cancel {
font-size: 22rpx;
color: #a89d92;
padding: 6rpx 0 6rpx 16rpx;
letter-spacing: 1rpx;
transition: color 0.2s ease;
}
&__cancel:active {
color: #9c7a6e;
}
// 已取消 / 未出席:弱化
&--muted {
background: #f5f0e8;
border-color: #e8e0d4;
.session__day {
color: #a89d92;
}
.session__time {
color: #a89d92;
}
.session__membership {
color: #a89d92;
}
.session__dot {
opacity: 0.5;
}
}
}
.session:active {
transform: scale(0.99);
box-shadow:
0 1rpx 0 rgba(122, 99, 84, 0.02),
0 2rpx 8rpx rgba(122, 99, 84, 0.04);
}
</style>

View File

@@ -1,64 +1,29 @@
<template>
<view class="slot-card" :class="{ 'slot-card--booked': timeSlot.isBookedByMe }">
<!-- Booked accent bar -->
<view v-if="timeSlot.isBookedByMe" class="booked-bar" />
<view class="slot-main">
<!-- Left: Time column -->
<view class="slot-time-col">
<text class="slot-start">{{ timeSlot.startTime.slice(0, 5) }}</text>
<view class="time-divider" />
<text class="slot-end">{{ timeSlot.endTime.slice(0, 5) }}</text>
<view class="slot-card" :class="`slot-card--${statusClass}`" @tap="emit('cardTap', timeSlot)">
<view class="slot-heading">
<view class="slot-time">
<text class="time-start">{{ startTimeDisplay }}</text>
<text class="time-end"> {{ endTimeDisplay }}</text>
</view>
<!-- Center: Info -->
<view class="slot-info">
<view class="slot-title-row">
<text class="slot-title">普拉提私教</text>
<text class="slot-duration">{{ durationMin }}分钟</text>
<text class="slot-duration">{{ durationMin }} 分钟</text>
</view>
<view class="slot-meta">
<view class="slot-capacity" :class="capacityClass">
<text class="capacity-dot" />
<text class="capacity-text">{{ capacityLabel }}</text>
<view class="slot-body">
<view class="course-info">
<text class="course-name">普拉提私教</text>
<text class="slot-status">{{ capacityLabel }}</text>
</view>
</view>
</view>
<!-- Right: Action -->
<view class="slot-action">
<!-- OPEN + not booked -->
<template v-if="timeSlot.status === TimeSlotStatus.OPEN && !timeSlot.isBookedByMe">
<view class="btn btn-book" @tap.stop="emit('book', timeSlot)">
<text class="btn-text">预约</text>
</view>
</template>
<!-- OPEN + booked by me -->
<template v-else-if="timeSlot.status === TimeSlotStatus.OPEN && timeSlot.isBookedByMe">
<view class="booked-badge-col">
<view class="badge-booked">
<text class="badge-text">已预约</text>
</view>
<view class="btn-cancel" @tap.stop="emit('cancel', timeSlot)">
<text class="btn-cancel-text">取消预约</text>
</view>
</view>
</template>
<!-- FULL -->
<template v-else-if="timeSlot.status === TimeSlotStatus.FULL">
<view class="btn btn-full">
<text class="btn-text">已约满</text>
</view>
</template>
<!-- CLOSED -->
<template v-else>
<view class="btn btn-closed">
<text class="btn-text">已关闭</text>
<view class="action-area">
<template v-if="timeSlot.isBookedByMe">
<text class="booked-label">已预约</text>
<view v-if="timeSlot.status === TimeSlotStatus.OPEN" class="cancel-link" @tap.stop="emit('cancel', timeSlot)">
<text>取消预约</text>
</view>
</template>
<button v-else-if="!isPast && timeSlot.status === TimeSlotStatus.OPEN && timeSlot.bookedCount < timeSlot.capacity"
class="book-button" hover-class="book-button--pressed" @tap.stop="emit('book', timeSlot)">
预约
</button>
<text v-else class="unavailable-label">{{ isPast ? '已结束' : timeSlot.status === TimeSlotStatus.CLOSED ? '未开放' : '已约满' }}</text>
</view>
</view>
</view>
@@ -66,8 +31,9 @@
<script setup lang="ts">
import type { TimeSlotWithBookingStatus } from '@mp-pilates/shared'
import { TimeSlotStatus } from '@mp-pilates/shared'
import { BookingStatus, TimeSlotStatus } from '@mp-pilates/shared'
import { computed } from 'vue'
import { isSlotPast } from '../utils/format'
interface Props {
timeSlot: TimeSlotWithBookingStatus
@@ -77,246 +43,78 @@ const props = defineProps<Props>()
const emit = defineEmits<{
book: [timeSlot: TimeSlotWithBookingStatus]
cancel: [timeSlot: TimeSlotWithBookingStatus]
cardTap: [timeSlot: TimeSlotWithBookingStatus]
}>()
const startTimeDisplay = computed(() => props.timeSlot.startTime.slice(0, 5))
const endTimeDisplay = computed(() => props.timeSlot.endTime.slice(0, 5))
const durationMin = computed(() => {
const [sh, sm] = props.timeSlot.startTime.split(':').map(Number)
const [eh, em] = props.timeSlot.endTime.split(':').map(Number)
return (eh * 60 + em) - (sh * 60 + sm)
})
const myBookingLabel = computed(() => (
props.timeSlot.myBookingStatus === BookingStatus.PENDING_CONFIRMATION
? '待老师确认'
: '已预约'
))
const capacityLabel = computed(() => {
const { bookedCount, capacity, status } = props.timeSlot
if (status === TimeSlotStatus.CLOSED) return '已关闭'
if (status === TimeSlotStatus.FULL) return '已约满'
const remaining = capacity - bookedCount
return `剩余 ${remaining} 个名额`
const { bookedCount, capacity, status, isBookedByMe } = props.timeSlot
if (isBookedByMe) return myBookingLabel.value
if (isPast.value) return '已结束'
if (status === TimeSlotStatus.CLOSED) return '暂未开放'
if (status === TimeSlotStatus.FULL || bookedCount >= capacity) return '名额已满'
return `还可约 ${Math.max(0, capacity - bookedCount)}`
})
const capacityClass = computed(() => {
const { bookedCount, capacity, status } = props.timeSlot
if (status === TimeSlotStatus.CLOSED) return 'cap-closed'
if (status === TimeSlotStatus.FULL) return 'cap-full'
if (bookedCount >= capacity * 0.8) return 'cap-almost'
return 'cap-open'
const statusClass = computed(() => {
if (isPast.value && !props.timeSlot.isBookedByMe) return 'expired'
if (props.timeSlot.isBookedByMe) return 'booked'
if (props.timeSlot.status === TimeSlotStatus.FULL) return 'full'
if (props.timeSlot.status === TimeSlotStatus.CLOSED) return 'closed'
return 'open'
})
const isPast = computed(() => isSlotPast(props.timeSlot.date, props.timeSlot.startTime))
</script>
<style lang="scss" scoped>
.slot-card {
margin: 0 32rpx 20rpx;
padding: 28rpx;
border: 1rpx solid #eee8e3;
border-radius: 28rpx;
background: #fff;
border-radius: 24rpx;
overflow: hidden;
box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.05);
position: relative;
transition: transform 0.15s, box-shadow 0.15s;
&:active {
transform: scale(0.985);
}
&--booked {
background: #f0f7fb;
box-shadow: 0 4rpx 24rpx rgba($primary-dark, 0.12);
}
color: #514943;
}
.booked-bar {
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 8rpx;
background: linear-gradient(180deg, $primary-color, $primary-dark);
border-radius: 24rpx 0 0 24rpx;
.slot-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 16rpx; }
.slot-time { display: flex; align-items: baseline; gap: 12rpx; font-variant-numeric: tabular-nums; }
.time-start { font-size: 40rpx; font-weight: 500; line-height: 1.2; }
.time-end { font-size: 28rpx; color: #8b817b; }
.slot-duration { flex-shrink: 0; font-size: 22rpx; color: #8b817b; }
.slot-body { display: flex; align-items: center; justify-content: space-between; gap: 20rpx; margin-top: 24rpx; }
.course-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8rpx; }
.course-name { font-size: 26rpx; font-weight: 400; }
.slot-status { font-size: 22rpx; color: #617d73; }
.action-area { display: flex; flex-direction: column; align-items: flex-end; gap: 2rpx; flex-shrink: 0; }
.book-button {
display: flex; align-items: center; justify-content: center;
min-width: 136rpx; height: 72rpx; margin: 0; padding: 0 30rpx;
border: none; border-radius: 999rpx; background: #6b8276;
font-size: 26rpx; font-weight: 400; line-height: 1; color: #fff;
&::after { border: none; }
&--pressed { background: #597264; }
}
.slot-main {
display: flex;
flex-direction: row;
align-items: center;
padding: 32rpx 28rpx 32rpx 36rpx;
gap: 24rpx;
}
/* ── Time column ─── */
.slot-time-col {
display: flex;
flex-direction: column;
align-items: center;
min-width: 80rpx;
flex-shrink: 0;
}
.slot-start {
font-size: 34rpx;
font-weight: 700;
color: #1a1a1a;
line-height: 1.2;
}
.time-divider {
width: 2rpx;
height: 16rpx;
background: #e0dcd6;
margin: 6rpx 0;
border-radius: 1rpx;
}
.slot-end {
font-size: 24rpx;
font-weight: 500;
color: #999;
line-height: 1.2;
}
/* ── Info ─── */
.slot-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 10rpx;
min-width: 0;
}
.slot-title-row {
display: flex;
flex-direction: row;
align-items: baseline;
gap: 12rpx;
}
.slot-title {
font-size: 30rpx;
font-weight: 600;
color: #1a1a1a;
}
.slot-duration {
font-size: 22rpx;
color: #bbb;
font-weight: 400;
}
.slot-meta {
display: flex;
flex-direction: row;
align-items: center;
gap: 12rpx;
}
.slot-capacity {
display: inline-flex;
align-items: center;
gap: 8rpx;
.capacity-dot {
width: 10rpx;
height: 10rpx;
border-radius: 50%;
}
.capacity-text {
font-size: 22rpx;
font-weight: 500;
}
&.cap-open {
.capacity-dot { background: #4caf50; }
.capacity-text { color: #4caf50; }
}
&.cap-almost {
.capacity-dot { background: #f59e0b; }
.capacity-text { color: #f59e0b; }
}
&.cap-full {
.capacity-dot { background: #ef4444; }
.capacity-text { color: #ef4444; }
}
&.cap-closed {
.capacity-dot { background: #ccc; }
.capacity-text { color: #999; }
}
}
/* ── Action ─── */
.slot-action {
flex-shrink: 0;
}
.btn {
min-width: 140rpx;
height: 72rpx;
border-radius: 36rpx;
display: flex;
align-items: center;
justify-content: center;
padding: 0 32rpx;
.btn-text {
font-size: 26rpx;
font-weight: 600;
}
&.btn-book {
background: linear-gradient(135deg, $primary-color, $primary-dark);
box-shadow: 0 4rpx 16rpx rgba($primary-dark, 0.3);
.btn-text { color: #fff; }
&:active {
opacity: 0.85;
}
}
&.btn-full {
background: #fef0f0;
.btn-text { color: #ef4444; }
}
&.btn-closed {
background: #f5f5f5;
.btn-text { color: #bbb; }
}
}
.booked-badge-col {
display: flex;
flex-direction: column;
align-items: center;
gap: 8rpx;
}
.badge-booked {
height: 52rpx;
padding: 0 24rpx;
background: linear-gradient(135deg, $primary-selected-bg, $primary-border);
border-radius: 26rpx;
display: flex;
align-items: center;
justify-content: center;
.badge-text {
font-size: 24rpx;
color: $primary-dark;
font-weight: 600;
}
}
.btn-cancel {
padding: 4rpx 8rpx;
display: flex;
align-items: center;
.btn-cancel-text {
font-size: 22rpx;
color: #ef4444;
font-weight: 400;
}
.booked-label { font-size: 24rpx; color: #617d73; }
.cancel-link { padding: 12rpx 0 8rpx 20rpx; font-size: 21rpx; color: #8b817b; }
.unavailable-label { padding: 14rpx 24rpx; border-radius: 999rpx; background: #f3f0ed; color: #8b817b; font-size: 23rpx; }
.slot-card--booked { background: #f2f5f0; border-color: #e2e9df; }
.slot-card--expired, .slot-card--closed, .slot-card--full {
background: #f7f5f2;
.time-start, .course-name { color: #8b817b; }
.slot-status { color: #948a82; }
}
</style>

View File

@@ -1,61 +1,77 @@
<template>
<view class="studio-info">
<!-- Horizontal photo strip -->
<scroll-view v-if="studioInfo?.photos?.length" scroll-x class="photo-strip" :show-scrollbar="false">
<view class="photo-strip-inner">
<image v-for="(photo, idx) in studioInfo.photos" :key="idx" class="strip-photo" :src="photo" mode="aspectFill"
@tap="previewPhoto(idx)" />
</view>
</scroll-view>
<!-- Address + Phone row -->
<text class="section-title">来工作室坐坐</text>
<!-- Address + Chat row -->
<view class="location-row">
<view class="location-left" @tap="handleAddressTap">
<text class="location-icon">📍</text>
<view class="location-content">
<text class="location-label">场馆地址</text>
<text class="location-text">
{{ studioInfo?.address || '深圳市宝安区西乡街道财富港 D 座 1203D' }}
</text>
</view>
<view class="phone-btn" @tap="handlePhoneTap">
<text class="phone-icon">📞</text>
</view>
<button class="chat-btn" open-type="contact">
<text>联系老师</text>
</button>
</view>
<!-- Horizontal gallery -->
<view class="gallery-block">
<scroll-view scroll-x class="gallery-scroll" :show-scrollbar="false" enhanced>
<view class="gallery-track">
<view
v-for="(photo, idx) in galleryPhotos"
:key="photo"
class="gallery-item"
@tap="previewPhoto(idx)"
>
<image class="gallery-image" :src="photo" mode="aspectFill" />
</view>
</view>
</scroll-view>
</view>
</view>
</template>
<script setup lang="ts">
import type { StudioConfig } from '@mp-pilates/shared'
import { computed } from 'vue'
import {
DEFAULT_STUDIO_GALLERY_PHOTOS,
type StudioConfig,
} from '@mp-pilates/shared'
const props = defineProps<{
studioInfo: StudioConfig | null
}>()
const galleryPhotos = computed(() => {
const photos = props.studioInfo?.photos?.filter(Boolean) ?? []
return photos.length ? photos : [...DEFAULT_STUDIO_GALLERY_PHOTOS]
})
function previewPhoto(index: number) {
if (!props.studioInfo?.photos?.length) return
uni.previewImage({
current: index,
urls: props.studioInfo.photos,
urls: galleryPhotos.value,
})
}
function handleAddressTap() {
if (!props.studioInfo) return
const latitude = props.studioInfo?.latitude ?? 22.567048
const longitude = props.studioInfo?.longitude ?? 113.867227
const address = props.studioInfo?.address || '深圳市宝安区西乡街道财富港 D 座 1203D'
const name = props.studioInfo?.name || 'Focus Core'
const { latitude, longitude, address, name } = props.studioInfo
if (latitude && longitude) {
uni.openLocation({
latitude,
longitude,
name: name || 'Focus Core',
name,
address,
fail() {
copyAddress()
},
})
} else {
copyAddress()
}
}
function copyAddress() {
@@ -68,87 +84,18 @@ function copyAddress() {
},
})
}
function handlePhoneTap() {
const phone = props.studioInfo?.phone
if (!phone) return
uni.makePhoneCall({
phoneNumber: phone,
fail() {
uni.showToast({ title: '拨号失败', icon: 'none' })
},
})
}
</script>
<style lang="scss" scoped>
.studio-info {
background: #ffffff;
}
/* ── Photo strip ── */
.photo-strip {
width: 100%;
padding: 24rpx 0;
}
.photo-strip-inner {
display: flex;
flex-direction: row;
gap: 16rpx;
padding: 0 24rpx;
width: max-content;
}
.strip-photo {
width: 240rpx;
height: 160rpx;
border-radius: 12rpx;
flex-shrink: 0;
}
/* ── Location row ── */
.location-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24rpx 32rpx 28rpx;
gap: 24rpx;
}
.location-left {
display: flex;
align-items: center;
gap: 12rpx;
flex: 1;
min-width: 0;
}
.location-icon {
font-size: 28rpx;
flex-shrink: 0;
}
.location-text {
font-size: 26rpx;
color: #666;
line-height: 1.5;
word-break: break-all;
}
.phone-btn {
width: 72rpx;
height: 72rpx;
border-radius: 50%;
background: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.phone-icon {
font-size: 36rpx;
color: #4CAF50;
}
.studio-info { margin: 36rpx 32rpx 0; }
.section-title { display: block; margin-bottom: 20rpx; font-size: 30rpx; font-weight: 500; color: #514943; }
.location-row { display: flex; align-items: center; justify-content: space-between; gap: 20rpx; margin-bottom: 20rpx; }
.location-left, .location-content { flex: 1; min-width: 0; }
.location-label { display: block; font-size: 21rpx; color: #8b817b; margin-bottom: 6rpx; }
.location-text { font-size: 24rpx; color: #6f655e; line-height: 1.7; overflow-wrap: anywhere; }
.chat-btn { flex-shrink: 0; margin: 0; padding: 0 20rpx; line-height: 64rpx; font-size: 23rpx; border: none; border-radius: 999rpx; background: #f0eae4; color: #78675c; &::after { border: none; } }
.gallery-scroll { width: 100%; }
.gallery-track { display: inline-flex; gap: 16rpx; }
.gallery-item { width: 264rpx; height: 180rpx; border-radius: 20rpx; overflow: hidden; flex-shrink: 0; background: #e9e1d8; }
.gallery-image { width: 100%; height: 100%; }
</style>

View File

@@ -0,0 +1,376 @@
<template>
<view v-if="visible" class="modal-mask" @tap="handleClose">
<view class="modal-panel" @tap.stop>
<view class="modal-header">
<text class="modal-title">微信消息提醒设置</text>
<view class="close-btn" @tap="handleClose">
<text class="close-icon"></text>
</view>
</view>
<view class="notice-box">
<text class="notice-title">💡 为什么需要增加订阅次数</text>
<text class="notice-desc">
微信订阅消息每授权 1 次可接收 1 条通知建议点击下方按钮并在弹出的微信授权窗中勾选<text class="notice-highlight">总是保持以上选择</text>即可永久无感自动接收课程变动与上课提醒
</text>
</view>
<view class="quota-list">
<view v-if="loading" class="loading-wrap">
<text class="loading-text">加载提醒状态中...</text>
</view>
<view v-else-if="quotas.length === 0" class="empty-wrap">
<text class="empty-text">未检测到可用提醒模板配置</text>
</view>
<view v-else v-for="item in quotas" :key="item.scene" class="quota-item">
<view class="quota-info">
<view class="quota-title-row">
<text class="quota-icon">{{ getSceneIcon(item.scene) }}</text>
<text class="quota-name">{{ getSceneName(item.scene) }}</text>
</view>
<text class="quota-desc">{{ item.description }}</text>
</view>
<view class="quota-badge" :class="getBadgeClass(item.remainingQuota)">
<text class="badge-text">
{{ item.remainingQuota > 0 ? `${item.remainingQuota}` : '待补充' }}
</text>
</view>
</view>
</view>
<view class="modal-actions">
<button
class="btn-primary"
:loading="subscribing"
:disabled="subscribing"
@tap="handleTopUp"
>
一键补充全部提醒次数 (+3)
</button>
<view class="btn-secondary" @tap="handleOpenSettings">
<text class="btn-secondary-text">微信权限与通知设置</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { SubscriptionMessageScene } from '@mp-pilates/shared'
import type { SubscriptionQuotaItem } from '@mp-pilates/shared'
import {
fetchUserSubscriptionQuotas,
requestBookingBundleSubscriptionMessage,
openSubscribeSettings,
} from '../utils/wechat-subscription'
const props = defineProps<{
visible: boolean
}>()
const emit = defineEmits<{
(e: 'update:visible', val: boolean): void
}>()
const quotas = ref<SubscriptionQuotaItem[]>([])
const loading = ref(false)
const subscribing = ref(false)
async function loadQuotas() {
loading.value = true
try {
quotas.value = await fetchUserSubscriptionQuotas()
} finally {
loading.value = false
}
}
watch(
() => props.visible,
(val) => {
if (val) {
void loadQuotas()
}
},
{ immediate: true },
)
function handleClose() {
emit('update:visible', false)
}
function getSceneIcon(scene: SubscriptionMessageScene): string {
switch (scene) {
case SubscriptionMessageScene.BOOKING_CREATED:
return '📅'
case SubscriptionMessageScene.CLASS_REMINDER:
return '⏰'
case SubscriptionMessageScene.BOOKING_CANCELLED:
return '📋'
case SubscriptionMessageScene.CLASS_REVIEW:
return '⭐'
default:
return '🔔'
}
}
function getSceneName(scene: SubscriptionMessageScene): string {
switch (scene) {
case SubscriptionMessageScene.BOOKING_CREATED:
return '约课成功通知'
case SubscriptionMessageScene.CLASS_REMINDER:
return '上课前 1 小时提醒'
case SubscriptionMessageScene.BOOKING_CANCELLED:
return '约课取消通知'
case SubscriptionMessageScene.CLASS_REVIEW:
return '课后评价提醒'
default:
return '课程服务通知'
}
}
function getBadgeClass(quota: number): string {
if (quota >= 3) return 'badge--healthy'
if (quota > 0) return 'badge--warning'
return 'badge--danger'
}
async function handleTopUp() {
if (subscribing.value) return
subscribing.value = true
try {
const results = await requestBookingBundleSubscriptionMessage()
const acceptedCount = results.filter((r) => r.result === 'accept').length
if (acceptedCount > 0) {
uni.showToast({ title: `已成功补充 ${acceptedCount} 项提醒额度`, icon: 'success' })
await loadQuotas()
} else {
uni.showToast({ title: '未增加额度,可再次点击尝试', icon: 'none' })
}
} catch (error) {
console.warn('[subscribe] top-up failed', error)
uni.showToast({ title: '授权未完成,可进入微信设置检查', icon: 'none' })
} finally {
subscribing.value = false
}
}
async function handleOpenSettings() {
await openSubscribeSettings()
await loadQuotas()
}
</script>
<style lang="scss" scoped>
.modal-mask {
position: fixed;
inset: 0;
background: rgba(56, 48, 42, 0.45);
z-index: 1000;
display: flex;
align-items: flex-end;
justify-content: center;
}
.modal-panel {
width: 100%;
box-sizing: border-box;
background: #fbf9f6;
border-radius: 36rpx 36rpx 0 0;
padding: 32rpx 32rpx calc(32rpx + env(safe-area-inset-bottom));
max-height: 85vh;
display: flex;
flex-direction: column;
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 24rpx;
}
.modal-title {
font-size: 32rpx;
font-weight: 500;
color: #514943;
}
.close-btn {
width: 60rpx;
height: 60rpx;
display: flex;
align-items: center;
justify-content: center;
}
.close-icon {
font-size: 28rpx;
color: #8b817b;
}
.notice-box {
background: #f0f4ee;
border-radius: 20rpx;
padding: 20rpx 24rpx;
margin-bottom: 24rpx;
display: flex;
flex-direction: column;
gap: 8rpx;
}
.notice-title {
font-size: 24rpx;
font-weight: 500;
color: #476d54;
}
.notice-desc {
font-size: 22rpx;
color: #657568;
line-height: 1.6;
}
.notice-highlight {
font-weight: 600;
color: #3b5a45;
}
.quota-list {
display: flex;
flex-direction: column;
gap: 16rpx;
margin-bottom: 28rpx;
max-height: 480rpx;
overflow-y: auto;
}
.loading-wrap,
.empty-wrap {
padding: 40rpx 0;
text-align: center;
}
.loading-text,
.empty-text {
font-size: 24rpx;
color: #8b817b;
}
.quota-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 24rpx;
background: #fff;
border: 2rpx solid #eee8e3;
border-radius: 20rpx;
gap: 16rpx;
}
.quota-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6rpx;
}
.quota-title-row {
display: flex;
align-items: center;
gap: 12rpx;
}
.quota-icon {
font-size: 26rpx;
}
.quota-name {
font-size: 26rpx;
font-weight: 500;
color: #514943;
}
.quota-desc {
font-size: 21rpx;
color: #8b817b;
}
.quota-badge {
padding: 6rpx 16rpx;
border-radius: 999rpx;
flex-shrink: 0;
}
.badge-text {
font-size: 22rpx;
font-weight: 500;
}
.badge--healthy {
background: #edf5eb;
.badge-text {
color: #4f7957;
}
}
.badge--warning {
background: #fdf5ea;
.badge-text {
color: #b07d39;
}
}
.badge--danger {
background: #fbeee9;
.badge-text {
color: #bc5e4c;
}
}
.modal-actions {
display: flex;
flex-direction: column;
gap: 16rpx;
}
.btn-primary {
width: 100%;
height: 88rpx;
border-radius: 999rpx;
background: #6b8276;
color: #fff;
font-size: 28rpx;
font-weight: 500;
display: flex;
align-items: center;
justify-content: center;
border: none;
line-height: 1;
&::after {
border: none;
}
&:active {
background: #597264;
}
}
.btn-secondary {
height: 72rpx;
display: flex;
align-items: center;
justify-content: center;
}
.btn-secondary-text {
font-size: 25rpx;
color: #7b8974;
}
</style>

View File

@@ -1,10 +1,10 @@
<template>
<view class="time-period-filter">
<view class="time-period-filter" :class="`time-period-filter--${variant}`">
<view
v-for="tab in tabs"
:key="tab.key ?? 'all'"
class="tab-item"
:class="{ active: modelValue === tab.key }"
:class="[`tab-item--${variant}`, { active: modelValue === tab.key }]"
@tap="handleChange(tab.key)"
>
<text class="tab-label">{{ tab.label }}</text>
@@ -25,14 +25,17 @@ interface Tab {
interface Props {
modelValue: PeriodKey
variant?: 'default' | 'booking' | 'soft'
}
defineProps<Props>()
const props = defineProps<Props>()
const emit = defineEmits<{
change: [period: PeriodKey]
'update:modelValue': [period: PeriodKey]
}>()
const variant = computed(() => props.variant ?? 'default')
const tabs = computed<Tab[]>(() => [
{ key: null, label: '全部' },
...Object.entries(TIME_PERIODS).map(([key, val]) => ({
@@ -55,6 +58,11 @@ function handleChange(key: PeriodKey) {
padding: 0 24rpx;
border-bottom: 1rpx solid $primary-border;
&.time-period-filter--booking {
background: rgba(252, 250, 248, 0.96);
border-bottom-color: rgba(192, 154, 137, 0.12);
}
.tab-item {
flex: 1;
display: flex;
@@ -87,6 +95,40 @@ function handleChange(key: PeriodKey) {
border-radius: 2rpx;
}
}
&.tab-item--booking {
.tab-label {
color: #9d8b83;
}
&.active {
.tab-label {
color: #8f6759;
}
&::after {
width: 48rpx;
height: 5rpx;
background: linear-gradient(90deg, #c8a899, #a87d6c);
border-radius: 999rpx;
box-shadow: 0 4rpx 10rpx rgba(168, 125, 108, 0.18);
}
}
}
}
}
.time-period-filter.time-period-filter--soft {
margin: 0 32rpx 24rpx; padding: 6rpx;
border: none; border-radius: 999rpx; background: #f0ece7;
.tab-item {
padding: 14rpx 0; border-radius: 999rpx;
.tab-label { font-size: 24rpx; color: #8b817b; }
&.active {
background: #fff;
.tab-label { color: #617d73; font-weight: 500; }
&::after { display: none; }
}
}
}
</style>

View File

@@ -9,6 +9,7 @@
v-for="booking in displayedBookings"
:key="booking.id"
class="booking-card"
@tap="goToBookingDetail(booking.id)"
>
<!-- Date column -->
<view class="date-col">
@@ -24,7 +25,6 @@
<view class="details-col">
<text class="card-name">{{ booking.membership.cardType.name }}</text>
<view class="time-row">
<text class="time-icon">🕐</text>
<text class="time-text">
{{ formatTime(booking.timeSlot.startTime) }} {{ formatTime(booking.timeSlot.endTime) }}
</text>
@@ -72,6 +72,7 @@ function formatTime(timeStr: string): string {
function statusLabel(status: BookingStatus): string {
const map: Record<BookingStatus, string> = {
[BookingStatus.PENDING_CONFIRMATION]: '待确认',
[BookingStatus.CONFIRMED]: '已确认',
[BookingStatus.CANCELLED]: '已取消',
[BookingStatus.COMPLETED]: '已完成',
@@ -81,6 +82,7 @@ function statusLabel(status: BookingStatus): string {
}
function statusDotClass(status: BookingStatus): string {
if (status === BookingStatus.PENDING_CONFIRMATION) return 'dot--pending'
if (status === BookingStatus.CONFIRMED) return 'dot--confirmed'
if (status === BookingStatus.COMPLETED) return 'dot--completed'
if (status === BookingStatus.CANCELLED) return 'dot--cancelled'
@@ -88,6 +90,7 @@ function statusDotClass(status: BookingStatus): string {
}
function statusTextClass(status: BookingStatus): string {
if (status === BookingStatus.PENDING_CONFIRMATION) return 'text--pending'
if (status === BookingStatus.CONFIRMED) return 'text--confirmed'
if (status === BookingStatus.COMPLETED) return 'text--completed'
if (status === BookingStatus.CANCELLED) return 'text--cancelled'
@@ -97,133 +100,32 @@ function statusTextClass(status: BookingStatus): string {
function goToBookings() {
uni.navigateTo({ url: '/pages/profile/bookings' })
}
function goToBookingDetail(id: string) {
uni.navigateTo({ url: `/pages/booking/detail?id=${id}` })
}
</script>
<style lang="scss" scoped>
.upcoming-section {
margin: 24rpx 24rpx 0;
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16rpx;
}
.section-title {
font-size: 32rpx;
font-weight: 700;
color: #1a1a2e;
}
.section-more {
font-size: 26rpx;
color: $primary-dark;
}
.booking-card {
background: #ffffff;
border-radius: 16rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
padding: 28rpx 28rpx;
display: flex;
align-items: center;
gap: 24rpx;
margin-bottom: 16rpx;
}
.date-col {
display: flex;
flex-direction: column;
align-items: center;
flex-shrink: 0;
width: 88rpx;
}
.date-day {
font-size: 52rpx;
font-weight: 800;
color: #1a1a2e;
line-height: 1;
}
.date-month {
font-size: 22rpx;
color: $primary-dark;
margin-top: 4rpx;
}
.date-weekday {
font-size: 22rpx;
color: #999;
margin-top: 4rpx;
}
.booking-divider {
width: 2rpx;
height: 80rpx;
background: #f0f0f0;
flex-shrink: 0;
}
.details-col {
flex: 1;
}
.card-name {
display: block;
font-size: 30rpx;
font-weight: 600;
color: #1a1a2e;
margin-bottom: 10rpx;
}
.time-row {
display: flex;
align-items: center;
gap: 8rpx;
margin-bottom: 10rpx;
}
.time-icon {
font-size: 24rpx;
}
.time-text {
font-size: 26rpx;
color: #555;
}
.status-row {
display: flex;
align-items: center;
gap: 8rpx;
}
.status-dot {
width: 12rpx;
height: 12rpx;
border-radius: 50%;
}
.dot--confirmed { background: #27ae60; }
.dot--completed { background: #3498db; }
.dot--cancelled { background: #e74c3c; }
.dot--default { background: #999; }
.status-text {
font-size: 24rpx;
color: #999;
}
.text--confirmed { color: #27ae60; }
.text--completed { color: #3498db; }
.text--cancelled { color: #e74c3c; }
.booking-arrow {
font-size: 36rpx;
color: #ccc;
flex-shrink: 0;
}
.upcoming-section { margin: 36rpx 32rpx 0; }
.section-header { display: flex; align-items: center; justify-content: space-between; gap: 16rpx; margin-bottom: 20rpx; }
.section-title { font-size: 30rpx; font-weight: 500; color: #514943; }
.section-more { font-size: 23rpx; color: #8b817b; padding: 8rpx 0; }
.booking-card { display: flex; align-items: center; gap: 24rpx; margin-bottom: 16rpx; padding: 26rpx; border-radius: 28rpx; background: #fff; border: 1rpx solid #eee8e3; }
.date-col { display: flex; flex-direction: column; align-items: center; gap: 4rpx; width: 72rpx; flex-shrink: 0; }
.date-day { font-size: 44rpx; font-weight: 400; line-height: 1.1; color: #617d73; }
.date-month, .date-weekday { font-size: 20rpx; color: #8b817b; }
.booking-divider { width: 1rpx; height: 80rpx; background: #eee8e3; flex-shrink: 0; }
.details-col { flex: 1; min-width: 0; }
.card-name { display: block; font-size: 26rpx; color: #514943; font-weight: 400; line-height: 1.5; margin-bottom: 8rpx; overflow-wrap: anywhere; }
.time-row { margin-bottom: 8rpx; }
.time-text { font-size: 24rpx; color: #6f655e; font-variant-numeric: tabular-nums; }
.status-row { display: flex; align-items: center; gap: 8rpx; }
.status-dot { width: 8rpx; height: 8rpx; border-radius: 50%; background: #a5b8ab; }
.status-text { font-size: 21rpx; color: #617d73; }
.dot--pending { background: #b8a18b; }
.text--pending { color: #957c65; }
.dot--cancelled { background: #b69589; }
.text--cancelled { color: #9c7a6e; }
.booking-arrow { font-size: 32rpx; color: #b2a79e; flex-shrink: 0; }
</style>

View File

@@ -1,15 +1,14 @@
<template>
<view class="user-card">
<!-- Header: gradient background, padded to sit below nav bar -->
<view class="user-card__header" :style="{ paddingTop: (navBarHeight ?? 0) + 'px' }">
<view class="user-card__header">
<!-- Not logged in state -->
<view v-if="!loggedIn" class="user-card__guest">
<view class="user-card__avatar-wrap">
<image class="user-card__avatar-img" src="/static/default-avatar.jpg" mode="aspectFill" />
</view>
<view class="user-card__guest-info">
<text class="user-card__guest-title">Hi欢迎来到普拉提</text>
<text class="user-card__guest-sub">登录后查看个人数据</text>
<text class="user-card__guest-title">欢迎来到工作室</text>
<text class="user-card__guest-sub">登录后查看会员卡与练习记录</text>
</view>
<button class="user-card__login-btn" :loading="loading" @tap="handleLogin">
微信登录
@@ -17,7 +16,7 @@
</view>
<!-- Logged in + profile loaded -->
<view v-else-if="loggedIn && hasProfile" class="user-card__user">
<view v-else-if="loggedIn && hasProfile" class="user-card__user" @tap="emit('edit')">
<view class="user-card__avatar-wrap">
<image
class="user-card__avatar-img"
@@ -25,17 +24,15 @@
mode="aspectFill"
@error="onAvatarError"
/>
<!-- VIP badge hidden for now -->
<!-- <view class="user-card__vip-badge" v-if="vipLevel">
<text class="user-card__vip-text">{{ vipLevel }}</text>
</view> -->
</view>
<view class="user-card__info">
<view class="user-card__name-row">
<text class="user-card__nickname">{{ user!.nickname }}</text>
<text v-if="hasMembership" class="user-card__member-label">会员</text>
</view>
<text v-if="maskedPhone" class="user-card__phone">{{ maskedPhone }}</text>
<text class="user-card__phone">{{ maskedPhone || '完善个人资料' }}</text>
</view>
<text class="user-card__edit">资料 </text>
</view>
<!-- Logged in but profile still loading -->
@@ -52,44 +49,43 @@
</view>
</view>
<!-- Stats row: shown only when profile is loaded -->
<view v-if="loggedIn && hasProfile" class="user-card__stats">
<view class="user-card__stat-item">
<text class="user-card__stat-value">{{ stats?.totalBookings ?? 0 }}</text>
<text class="user-card__stat-label">总训练()</text>
</view>
<view class="user-card__stat-divider" />
<view class="user-card__stat-item">
<text class="user-card__stat-value">{{ stats?.monthBookings ?? 0 }}</text>
<text class="user-card__stat-label">本月()</text>
</view>
<view class="user-card__stat-divider" />
<view class="user-card__stat-item">
<text class="user-card__stat-value">{{ remainingSessions }}</text>
<text class="user-card__stat-label">剩余课时()</text>
</view>
<button v-if="loggedIn && hasProfile" class="membership-row" @tap="handleMembershipTap">
<text class="membership-row__label">会员卡</text>
<text class="membership-row__value">{{ membershipLabel }}</text>
<text v-if="!membershipsError && membershipsLoaded && activeMemberships.length > 1" class="membership-row__count">{{ activeMemberships.length }} </text>
<text class="membership-row__arrow"></text>
</button>
<view v-if="loggedIn && hasProfile && membershipsLoaded && !membershipsError && activeMemberships.length" class="mini-progress-list">
<button v-for="item in cardProgress" :key="item.id" class="mini-progress" :aria-label="`${item.name}${item.label}`" @tap="handleMembershipTap">
<view v-if="item.percent !== null" class="mini-progress__fill" :style="{ width: `${item.percent}%` }" />
<view class="mini-progress__heading"><text class="mini-progress__name">{{ item.name }}</text><text class="mini-progress__usage">{{ item.label }}</text></view>
</button>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { UserProfileResponse, UserStatsResponse, MembershipWithCardType } from '@mp-pilates/shared'
import type { UserProfileResponse, MembershipWithCardType } from '@mp-pilates/shared'
import { MembershipStatus } from '@mp-pilates/shared'
import { getCardTypeLabel, getMembershipTotalTimes, getMembershipUsedTimes } from '../utils/format'
const props = defineProps<{
loggedIn: boolean
hasProfile: boolean
user: UserProfileResponse | null
stats: UserStatsResponse | null
now: number
membershipsLoading?: boolean
membershipsLoaded?: boolean
membershipsError?: boolean
memberships?: readonly MembershipWithCardType[]
loading?: boolean
/** Height of the custom nav bar in px, so header content starts below it */
navBarHeight?: number
}>()
const emit = defineEmits<{
(e: 'login'): void
(e: 'edit'): void
(e: 'refresh-memberships'): void
}>()
const avatarFailed = ref(false)
@@ -117,26 +113,43 @@ const maskedPhone = computed(() => {
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
})
// Derive VIP level from active memberships count
const activeMemberships = computed(() =>
props.memberships?.filter((m) => m.status === MembershipStatus.ACTIVE) ?? [],
)
const vipLevel = computed(() => {
const count = activeMemberships.value.length
if (count >= 3) return 'VIP3'
if (count >= 2) return 'VIP2'
if (count >= 1) return 'VIP1'
return null
})
// Sum remaining sessions from all active time-based memberships
const remainingSessions = computed(() =>
activeMemberships.value
.filter((m) => m.cardType.type === 'TIMES')
.reduce((sum, m) => sum + m.remainingCount, 0),
const activeMembershipCount = computed(
() => props.user?.activeMembershipCount ?? activeMemberships.value.length,
)
const hasMembership = computed(() => activeMembershipCount.value > 0)
const membershipLabel = computed(() => {
if (props.membershipsError) return '暂未更新,点击重试'
if (!props.membershipsLoaded) return '加载中…'
if (!activeMemberships.value.length) return '暂无有效卡'
return [...new Set(activeMemberships.value.map(m => getCardTypeLabel(m.cardType.type)))].join(' · ')
})
const cardProgress = computed(() => activeMemberships.value.map(m => {
const total = getMembershipTotalTimes(m)
if (m.remainingTimes !== null) {
const used = getMembershipUsedTimes(m)
return { id: m.id, name: m.cardType.name,
label: total && total > 0 ? `已用 ${used}/${total} 次 · 余 ${m.remainingTimes}` : `剩余 ${m.remainingTimes}`,
percent: total && total > 0 ? Math.max(0, Math.min(100, used / total * 100)) : null }
}
const start = new Date(m.startDate).getTime()
const end = new Date(m.expireDate).getTime()
const remainingDays = Math.max(0, Math.ceil((end - props.now) / 86400000))
return { id: m.id, name: m.cardType.name,
label: `不限次 · 有效期剩 ${remainingDays}`,
percent: end > start ? Math.max(0, Math.min(100, (end - props.now) / (end - start) * 100)) : null }
}))
function handleMembershipTap() {
if (props.membershipsError) { emit('refresh-memberships'); return }
uni.navigateTo({ url: '/pages/profile/membership' })
}
function onAvatarError() {
avatarFailed.value = true
}
@@ -148,186 +161,34 @@ function handleLogin() {
<style lang="scss" scoped>
.user-card {
background: linear-gradient(160deg, #E1F4FA 0%, $primary-color 50%, $primary-dark 100%);
border-radius: 0 0 40rpx 40rpx;
overflow: hidden;
&__header {
padding: $spacing-lg $spacing-lg $spacing-lg;
}
// ── Guest state ──
&__guest {
display: flex;
align-items: center;
gap: $spacing-md;
}
&__guest-info {
flex: 1;
display: flex;
flex-direction: column;
gap: $spacing-xs;
}
&__guest-title {
font-size: 32rpx;
font-weight: 600;
color: #ffffff;
}
&__guest-sub {
font-size: 24rpx;
color: rgba(255, 255, 255, 0.65);
}
&__login-btn {
flex-shrink: 0;
background: rgba(255, 255, 255, 0.2);
color: #ffffff;
font-size: 26rpx;
font-weight: 500;
border: none;
border-radius: $radius-lg;
padding: 0 $spacing-md;
height: 64rpx;
line-height: 64rpx;
min-width: 160rpx;
&::after {
border: none;
}
}
// ── Logged-in user ──
&__user {
display: flex;
align-items: center;
gap: $spacing-md;
}
&__avatar-wrap {
position: relative;
flex-shrink: 0;
width: 120rpx;
height: 120rpx;
}
&__avatar-img {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
border: 4rpx solid rgba(255, 255, 255, 0.4);
}
&__vip-badge {
position: absolute;
bottom: -6rpx;
left: 50%;
transform: translateX(-50%);
background: linear-gradient(135deg, #fbbf24, #f59e0b);
border-radius: 20rpx;
padding: 2rpx 12rpx;
border: 2rpx solid #ffffff;
}
&__vip-text {
font-size: 18rpx;
font-weight: 700;
color: #7c2d12;
line-height: 1;
}
&__info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8rpx;
}
&__name-row {
display: flex;
align-items: center;
gap: $spacing-sm;
}
&__nickname {
font-size: 36rpx;
font-weight: 600;
color: #ffffff;
}
&__phone {
font-size: 26rpx;
color: rgba(255, 255, 255, 0.75);
}
// ── Loading state ──
&__loading {
display: flex;
align-items: center;
gap: $spacing-md;
}
&__avatar-skeleton {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
background: rgba(255, 255, 255, 0.3);
}
&__nickname-skeleton {
width: 160rpx;
height: 36rpx;
border-radius: $radius-sm;
background: rgba(255, 255, 255, 0.3);
}
&__phone-skeleton {
width: 120rpx;
height: 26rpx;
border-radius: $radius-sm;
background: rgba(255, 255, 255, 0.2);
margin-top: 8rpx;
}
// ── Stats row ──
&__stats {
display: flex;
align-items: stretch;
background: rgba(255, 255, 255, 0.15);
margin: 0 $spacing-lg $spacing-lg;
border-radius: $radius-lg;
padding: $spacing-md 0;
backdrop-filter: blur(10rpx);
}
&__stat-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: $spacing-xs 0;
}
&__stat-divider {
width: 1rpx;
background: rgba(255, 255, 255, 0.3);
margin: $spacing-xs 0;
}
&__stat-value {
font-size: 44rpx;
font-weight: 700;
color: #ffffff;
line-height: 1;
}
&__stat-label {
font-size: 22rpx;
color: rgba(255, 255, 255, 0.8);
margin-top: 6rpx;
}
margin: 20rpx 32rpx 0; padding: 28rpx; background: #f2e9e3; border-radius: 32rpx;
&__user, &__loading { display: flex; align-items: center; gap: 20rpx; }
&__avatar-wrap { width: 108rpx; height: 108rpx; flex-shrink: 0; }
&__avatar-img { width: 100%; height: 100%; box-sizing: border-box; border-radius: 50%; border: 5rpx solid #fcf8f4; }
&__info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10rpx; }
&__name-row { display: flex; align-items: center; flex-wrap: wrap; gap: 10rpx; }
&__nickname { font-size: 36rpx; font-weight: 500; line-height: 1.4; color: #514943; overflow-wrap: anywhere; }
&__member-label { flex-shrink: 0; font-size: 19rpx; color: #8b6c5b; background: #fbf5ef; padding: 4rpx 12rpx; border-radius: 999rpx; }
&__phone { font-size: 24rpx; color: #8b7b70; }
&__edit { flex-shrink: 0; font-size: 22rpx; color: #8b7b70; padding: 16rpx 0 16rpx 8rpx; }
&__guest { display: flex; align-items: center; flex-wrap: wrap; gap: 20rpx; }
&__guest-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10rpx; }
&__guest-title { font-size: 32rpx; font-weight: 500; color: #514943; }
&__guest-sub { font-size: 23rpx; color: #8b7b70; line-height: 1.6; }
&__login-btn { width: 100%; height: 76rpx; line-height: 76rpx; margin: 4rpx 0 0; padding: 0; border: none; border-radius: 999rpx; background: #6b8276; color: #fff; font-size: 26rpx; font-weight: 400; &::after { border: none; } }
&__avatar-skeleton { width: 108rpx; height: 108rpx; border-radius: 50%; background: #e6d9ce; }
&__nickname-skeleton { width: 150rpx; height: 32rpx; border-radius: 8rpx; background: #e6d9ce; }
&__phone-skeleton { width: 180rpx; height: 22rpx; border-radius: 6rpx; background: #e6d9ce; }
}
.membership-row { display: flex; align-items: center; gap: 12rpx; width: 100%; margin: 20rpx 0 0; padding: 18rpx 0 0; min-height: 62rpx; border-radius: 0; border-top: 1rpx solid #e3d7ce; background: transparent; text-align: left; line-height: 1.5; font-size: 23rpx; color: #796759; &::after { border: none; } }
.membership-row__label { flex-shrink: 0; color: #8b7b70; }
.membership-row__value { flex: 1; min-width: 0; text-align: right; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.membership-row__count { flex-shrink: 0; font-size: 21rpx; color: #8b7b70; }
.membership-row__arrow { flex-shrink: 0; font-size: 28rpx; color: #8b7b70; }
.mini-progress-list { margin-top: 12rpx; display: flex; flex-direction: column; gap: 8rpx; }
.mini-progress { position: relative; display: block; width: 100%; height: 48rpx; margin: 0; padding: 0 16rpx; overflow: hidden; border: 1rpx solid #d6d9ca; border-radius: 10rpx; background: #eeece4; text-align: left; line-height: 46rpx; &::after { border: none; } &:active { opacity: .8; } }
.mini-progress__heading { position: relative; z-index: 1; display: flex; align-items: center; gap: 12rpx; height: 100%; font-size: 20rpx; color: #46513f; }
.mini-progress__name { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.mini-progress__usage { flex-shrink: 0; font-variant-numeric: tabular-nums; }
.mini-progress__fill { position: absolute; inset: 0 auto 0 0; background: linear-gradient(90deg, #dce3d3, #c9d7bf); border-right: 1rpx solid rgba(109, 135, 91, .16); }
</style>

View File

@@ -1,18 +1,22 @@
{
"name": "普拉提约课",
"appid": "",
"appid": "wx3e7a133d2305fa2c",
"description": "普拉提工作室约课小程序",
"versionName": "0.1.0",
"versionCode": "100",
"transformPx": false,
"mp-weixin": {
"appid": "",
"appid": "wx3e7a133d2305fa2c",
"setting": {
"urlCheck": false,
"es6": true,
"minified": true
},
"usingComponents": true,
"lazyCodeLoading": "requiredComponents",
"optimization": {
"subPackages": true
},
"permission": {
"scope.userLocation": {
"desc": "用于获取工作室位置导航"

View File

@@ -12,13 +12,19 @@
{
"path": "pages/booking/index",
"style": {
"navigationStyle": "custom"
"navigationStyle": "custom",
"componentPlaceholder": {
"booking-confirm-popup": "view"
}
}
},
{
"path": "pages/booking/detail",
"style": {
"navigationStyle": "custom"
"navigationStyle": "custom",
"componentPlaceholder": {
"booking-confirm-popup": "view"
}
}
},
{
@@ -45,6 +51,12 @@
"navigationStyle": "custom"
}
},
{
"path": "pages/profile/teaching-schedule",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/profile/info",
"style": {
@@ -52,58 +64,191 @@
}
},
{
"path": "pages/admin/index",
"path": "pages/profile/invite",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/bookings",
"path": "pages/teacher/detail",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/schedule",
"path": "pages/profile/progress",
"style": {
"navigationStyle": "custom"
}
}
],
"subPackages": [
{
"root": "pages/admin",
"pages": [
{
"path": "index",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/week-template",
"path": "analytics",
"style": {
"navigationStyle": "custom",
"enablePullDownRefresh": true
}
},
{
"path": "bookings",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/slot-adjust",
"path": "schedule",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/members",
"path": "slot-adjust",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/orders",
"path": "members",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/card-types",
"path": "member-detail",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/admin/studio",
"path": "member-edit",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "member-supplement",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "member-arrange",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "orders",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "card-types",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "studio",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "member-progress",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "reviews",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "portrait-today",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "portrait-leads",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "portrait-lead-detail",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "portrait-assessment",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "portrait-plan",
"style": {
"navigationStyle": "custom"
}
}
]
},
{
"root": "pages/portrait",
"pages": [
{
"path": "index",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "assessment",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "report",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "advice",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "trial",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "plan",
"style": {
"navigationStyle": "custom"
}
}
]
}
],
"globalStyle": {

View File

@@ -0,0 +1,279 @@
<template>
<view class="report" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="统计分析" show-back />
<view class="intro">
<text class="eyebrow">PILATES · MONTHLY REVIEW</text>
<text class="title">每一节课都有迹可循</text>
<text class="muted">工作室月度统计 · 按课程日期归档</text>
</view>
<view class="month-nav">
<button aria-label="上个月" :disabled="month === '2000-01'" @tap="shiftMonth(-1)"></button>
<picker mode="date" fields="month" :value="month" start="2000-01" end="2099-12" @change="changeMonth($event.detail.value)">
<view class="month-label">{{ month.replace('-', ' 年 ') }} </view>
</picker>
<button aria-label="下个月" :disabled="month === '2099-12'" @tap="shiftMonth(1)"></button>
</view>
<view class="toolbar">
<button v-if="month !== currentMonth" @tap="changeMonth(currentMonth)">回到本月</button>
<text v-else>本月持续更新</text>
<button :disabled="loading" @tap="load">刷新数据 </button>
</view>
<view v-if="!loggedIn || !isAdmin" class="empty">仅登录后的管理员可查看教学统计</view>
<view v-else-if="loading" class="empty">正在整理这个月的上课记录</view>
<view v-else-if="error" class="empty"><text>{{ error }}</text><button class="outline" @tap="load">重新加载</button></view>
<template v-else-if="report">
<view class="hero">
<text class="hero-label">已上课程</text>
<view class="hero-number">{{ report.summary.sessions }}<text></text></view>
<text class="hero-note">{{ report.previousMonth }} 全月 {{ report.previous.sessions }} · {{ month === currentMonth ? '本月尚未结束' : '按完整自然月统计' }}</text>
<view class="hero-footer">
<view><text class="metric">{{ hours(report.summary.minutes) }}</text><text>授课小时</text></view>
<view><text class="metric">{{ report.summary.teachingDays }}</text><text>上课天数</text></view>
<view><text class="metric">{{ average }}</text><text>人均上课次数</text></view>
</view>
</view>
<view class="metrics">
<view><text class="metric">{{ report.summary.attendances }}<text class="unit">人次</text></text><text>已完成上课</text></view>
<view><text class="metric">{{ report.summary.students }}<text class="unit"></text></text><text>本月上课学员</text></view>
</view>
<button v-if="reviewCount" class="notice" @tap="showReview"><text>{{ reviewCount }} 条已过结束时间的预约仍待处理</text><text>核对明细 </text></button>
<view v-if="!report.records.length" class="empty compact">这个月暂无预约记录可切换月份查看历史教学情况</view>
<view class="section">
<view class="heading"><text>上课日历</text><text class="muted small">数字为已完成课程节数</text></view>
<view class="calendar">
<text v-for="label in weekdays" :key="label" class="weekday">{{ label }}</text>
<view v-for="n in offset" :key="`blank-${n}`" />
<button v-for="day in days" :key="day.date" class="day" :class="{ taught: day.count > 0, selected: selectedDate === day.date }" :aria-label="`${day.date},已上${day.count}节`" @tap="selectDay(day.date)">
<text>{{ day.day }}</text><text class="day-count">{{ day.count ? `${day.count}` : '·' }}</text>
</button>
</view>
<text class="footnote">点击日期查看当天明细再次点击取消筛选</text>
</view>
<view class="section">
<view class="heading"><text>学员上课排行</text><text class="muted small">已完成 · {{ students.length }} </text></view>
<input v-model="search" class="search" placeholder="搜索学员姓名" :maxlength="60" @input="studentLimit = 10" />
<text v-if="!filteredStudents.length" class="footnote">{{ search ? '没有匹配的上课学员' : '本月还没有已完成的上课记录' }}</text>
<button v-for="(student, index) in filteredStudents.slice(0, studentLimit)" :key="student.id" class="student-row" @tap="selectStudent(student)">
<text class="rank">{{ String(index + 1).padStart(2, '0') }}</text>
<view class="student-main">
<text class="student-name">{{ student.name }}</text>
<view class="track"><view class="fill" :style="{ width: `${student.count / maxCount * 100}%` }" /></view>
<text class="small muted">{{ student.days }} · 最近 {{ student.last.slice(5) }}</text>
</view>
<text class="student-count">{{ student.count }}<text class="small"> </text></text>
</button>
<button v-if="filteredStudents.length > studentLimit" class="more" @tap="studentLimit += 10">查看更多学员</button>
</view>
<view class="section">
<view class="heading"><text>上课用卡分布</text><text class="muted small">已完成人次</text></view>
<view v-for="card in cards" :key="card.name" class="distribution"><text>{{ card.name }}</text><text>{{ card.count }} 人次 · {{ Math.round(card.count / report.summary.attendances * 100) }}%</text></view>
<text v-if="!cards.length" class="footnote">暂无已完成记录</text>
</view>
<view id="lesson-details" class="section">
<view class="heading"><text>上课明细</text><text class="muted small">{{ filteredRecords.length }} </text></view>
<scroll-view scroll-x class="status-scroll"><view class="status-tabs">
<button v-for="item in statuses" :key="item.value" :class="{ active: status === item.value }" @tap="setStatus(item.value)">{{ item.label }} {{ countStatus(item.value) }}</button>
</view></scroll-view>
<view v-if="selectedDate || selectedStudent || reviewOnly" class="filters">
<text>{{ selectedDate || '全月' }}{{ selectedStudent ? ` · ${selectedStudent.name}` : '' }}{{ reviewOnly ? ' · 待核对' : '' }}</text>
<button @tap="clearFilters">清除筛选 ×</button>
</view>
<text v-if="!filteredRecords.length" class="footnote">当前条件下没有上课记录</text>
<view v-for="row in filteredRecords.slice(0, detailLimit)" :key="row.id" class="record">
<view class="record-top"><button class="record-name" @tap="openMember(row.userId)">{{ row.nickname || '未命名学员' }} </button><text class="badge" :class="{ completed: row.status === 'COMPLETED' }">{{ statusName(row.status) }}</text></view>
<text class="record-date">{{ row.date.slice(5).replace('-', '月') }} · {{ row.startTime }}{{ row.endTime }}</text>
<text class="muted small">{{ row.cardName }}{{ row.needsReview ? ' · 已过结束时间,请核对' : '' }}</text>
</view>
<button v-if="filteredRecords.length > detailLimit" class="more" @tap="detailLimit += 20">再显示 20 </button>
<text v-else-if="filteredRecords.length" class="footnote">已显示全部 {{ filteredRecords.length }} 条记录</text>
</view>
<view class="notes">
<text class="notes-title">关于这份月报</text>
<text>统计整个工作室暂不区分老师已上课程按已完成预约的时段去重同一节课多人参加只计 1 节课多人次授课时长按该时段排课时长计算</text>
<text>已完成包含系统自动完成不代表现场签到其他状态不计入已上课程没有日期的历史补录不计入月报用卡分布按当前卡种名称归类</text>
<text>更新于 {{ updatedLabel }} · 下拉可刷新</text>
</view>
</template>
</view>
</template>
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import type { TeachingAnalytics } from '@mp-pilates/shared'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { useAdminStore } from './stores/admin'
import { useUserStore } from '../../stores/user'
import { getSystemLayout } from '../../utils/system'
import { getErrorMessage } from '../../utils/auth'
const navBarHeight = `${getSystemLayout().navBarHeight}px`
const { loggedIn, isAdmin } = storeToRefs(useUserStore())
const store = useAdminStore()
const currentMonth = ref(chinaMonth())
const month = ref(currentMonth.value)
const report = ref<TeachingAnalytics | null>(null)
const loading = ref(false)
const error = ref('')
const selectedDate = ref('')
const selectedStudent = ref<{ id: string; name: string } | null>(null)
const status = ref('ALL')
const reviewOnly = ref(false)
const search = ref('')
const studentLimit = ref(10)
const detailLimit = ref(20)
let requestId = 0
const weekdays = ['一', '二', '三', '四', '五', '六', '日']
const statuses = [
{ value: 'ALL', label: '全部' }, { value: 'COMPLETED', label: '已完成' },
{ value: 'CONFIRMED', label: '已确认' }, { value: 'PENDING_CONFIRMATION', label: '待确认' },
{ value: 'CANCELLED', label: '已取消' }, { value: 'NO_SHOW', label: '未出席' },
]
const rows = computed(() => report.value?.records ?? [])
const completed = computed(() => rows.value.filter(row => row.status === 'COMPLETED'))
const average = computed(() => report.value?.summary.students ? (report.value.summary.attendances / report.value.summary.students).toFixed(1) : '—')
const reviewCount = computed(() => rows.value.filter(row => row.needsReview).length)
const offset = computed(() => (new Date(`${month.value}-01T00:00:00Z`).getUTCDay() + 6) % 7)
const days = computed(() => {
const [year, number] = month.value.split('-').map(Number)
const counts = new Map<string, Set<string>>()
completed.value.forEach(row => {
if (!counts.has(row.date)) counts.set(row.date, new Set())
counts.get(row.date)!.add(row.slotId)
})
return Array.from({ length: new Date(Date.UTC(year, number, 0)).getUTCDate() }, (_, i) => {
const date = `${month.value}-${String(i + 1).padStart(2, '0')}`
return { date, day: i + 1, count: counts.get(date)?.size ?? 0 }
})
})
const students = computed(() => {
const map = new Map<string, { id: string; name: string; count: number; dates: Set<string>; last: string }>()
completed.value.forEach(row => {
const student = map.get(row.userId) ?? { id: row.userId, name: row.nickname || '未命名学员', count: 0, dates: new Set<string>(), last: row.date }
student.count++
student.dates.add(row.date)
if (row.date > student.last) student.last = row.date
map.set(row.userId, student)
})
return [...map.values()].map(({ dates, ...student }) => ({ ...student, days: dates.size }))
.sort((a, b) => b.count - a.count || a.id.localeCompare(b.id))
})
const filteredStudents = computed(() => students.value.filter(student => student.name.toLowerCase().includes(search.value.trim().toLowerCase())))
const maxCount = computed(() => students.value[0]?.count || 1)
const cards = computed(() => {
const map = new Map<string, number>()
completed.value.forEach(row => map.set(row.cardName, (map.get(row.cardName) ?? 0) + 1))
return [...map].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count)
})
const scopedRecords = computed(() => rows.value.filter(row =>
(!selectedDate.value || row.date === selectedDate.value) &&
(!selectedStudent.value || row.userId === selectedStudent.value.id) &&
(!reviewOnly.value || row.needsReview)))
const filteredRecords = computed(() => scopedRecords.value.filter(row => status.value === 'ALL' || row.status === status.value).slice().reverse())
const updatedLabel = computed(() => report.value ? new Date(new Date(report.value.generatedAt).getTime() + 8 * 3600000).toISOString().slice(0, 16).replace('T', ' ') : '')
function chinaMonth() { return new Date(Date.now() + 8 * 3600000).toISOString().slice(0, 7) }
function hours(minutes: number) { return Number((minutes / 60).toFixed(1)) }
function countStatus(value: string) { return scopedRecords.value.filter(row => value === 'ALL' || row.status === value).length }
function statusName(value: string) { return statuses.find(item => item.value === value)?.label ?? value }
function clearFilters() {
selectedDate.value = ''; selectedStudent.value = null; reviewOnly.value = false
status.value = 'ALL'; detailLimit.value = 20
}
function setStatus(value: string) { status.value = value; detailLimit.value = 20 }
async function scrollDetails() {
await nextTick()
uni.pageScrollTo({ selector: '#lesson-details', offsetTop: -getSystemLayout().navBarHeight - 12, duration: 250 })
}
function selectDay(date: string) {
selectedDate.value = selectedDate.value === date ? '' : date
reviewOnly.value = false; detailLimit.value = 20; scrollDetails()
}
function selectStudent(student: { id: string; name: string }) {
selectedStudent.value = { id: student.id, name: student.name }
selectedDate.value = ''; reviewOnly.value = false; setStatus('COMPLETED'); scrollDetails()
}
function showReview() { clearFilters(); reviewOnly.value = true; scrollDetails() }
function openMember(id: string) { uni.navigateTo({ url: `/pages/admin/member-detail?userId=${encodeURIComponent(id)}` }) }
function shiftMonth(amount: number) {
const [year, number] = month.value.split('-').map(Number)
changeMonth(new Date(Date.UTC(year, number - 1 + amount, 1)).toISOString().slice(0, 7))
}
function changeMonth(value: string) {
if (value === month.value || value < '2000-01' || value > '2099-12') return
month.value = value; clearFilters(); search.value = ''; studentLimit.value = 10; load()
}
async function load() {
const id = ++requestId
report.value = null; error.value = ''; loading.value = false
if (!loggedIn.value || !isAdmin.value) return
loading.value = true
try {
const data = await store.fetchTeachingAnalytics(month.value)
if (id === requestId) report.value = data
} catch (err) {
if (id === requestId) error.value = getErrorMessage(err, '统计暂时无法加载,请重试')
} finally {
if (id === requestId) loading.value = false
}
}
onShow(() => { currentMonth.value = chinaMonth(); load() })
onPullDownRefresh(async () => { try { await load() } finally { uni.stopPullDownRefresh() } })
</script>
<style scoped lang="scss">
.report { min-height: 100vh; box-sizing: border-box; background: #f7f5ef; color: #35483e; padding: 0 30rpx calc(48rpx + env(safe-area-inset-bottom)); }
button { margin: 0; padding: 0; background: transparent; border-radius: 0; font-size: inherit; color: inherit; line-height: 1.5; &::after { border: 0; } &:active { opacity: .65; } }
.intro { padding: 40rpx 4rpx 28rpx; display: flex; flex-direction: column; gap: 14rpx; }
.eyebrow { font-size: 18rpx; letter-spacing: 4rpx; color: #687d6e; }
.title { font-family: 'Songti SC', 'STSong', serif; font-size: 40rpx; line-height: 1.6; }
.muted { color: #73796f; font-size: 23rpx; }
.small { font-size: 22rpx; }
.month-nav { display: flex; justify-content: space-between; align-items: center; border-top: 1rpx solid #d9ddd2; border-bottom: 1rpx solid #d9ddd2; button { width: 80rpx; line-height: 88rpx; font-size: 40rpx; } }
.month-label { padding: 20rpx; font-size: 33rpx; font-family: 'Songti SC', 'STSong', serif; }
.toolbar { display: flex; justify-content: space-between; align-items: center; font-size: 22rpx; color: #677765; min-height: 76rpx; button { padding: 16rpx 0; } }
.hero { background: #344f42; color: #faf7e9; border-radius: 12rpx 12rpx 48rpx 12rpx; padding: 36rpx; }
.hero-label { font-size: 25rpx; letter-spacing: 3rpx; }
.hero-number { font-family: 'Baskerville', 'Times New Roman', serif; font-size: 116rpx; line-height: 1.25; text { font-size: 26rpx; padding-left: 18rpx; } }
.hero-note { font-size: 21rpx; color: #d1dbc9; }
.hero-footer { display: flex; margin-top: 30rpx; padding-top: 26rpx; border-top: 1rpx solid #6d8070; gap: 18rpx; > view { flex: 1; display: flex; flex-direction: column; font-size: 21rpx; gap: 8rpx; } }
.metric { font-size: 40rpx; font-family: 'Baskerville', 'Times New Roman', serif; font-variant-numeric: tabular-nums; }
.unit { font-size: 22rpx; margin-left: 14rpx; }
.metrics { display: flex; padding: 30rpx 0; border-bottom: 1rpx solid #d9ddd2; > view { flex: 1; display: flex; flex-direction: column; gap: 12rpx; font-size: 24rpx; padding-left: 30rpx; &:last-child { border-left: 1rpx solid #d9ddd2; } } }
.notice { width: 100%; text-align: left; margin-top: 26rpx; padding: 24rpx; display: flex; flex-direction: column; gap: 12rpx; background: #f0e5d2; color: #805c30; font-size: 23rpx; border-radius: 12rpx; }
.section { margin-top: 28rpx; background: #fffefa; border: 1rpx solid #e3e5da; border-radius: 16rpx; padding: 28rpx; }
.heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 12rpx; margin-bottom: 24rpx; font-size: 30rpx; }
.heading > text:first-child { font-family: 'Songti SC', 'STSong', serif; }
.calendar { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 8rpx; }
.weekday { text-align: center; font-size: 21rpx; color: #73796f; padding-bottom: 14rpx; }
.day { display: flex; flex-direction: column; justify-content: center; align-items: center; min-height: 92rpx; border-radius: 10rpx; font-size: 25rpx; border: 2rpx solid transparent; }
.day-count { font-size: 18rpx; margin-top: 7rpx; color: #66785f; }
.taught { background: #e8eee2; }
.selected { border-color: #344f42; background: #344f42; color: #fff; .day-count { color: #fff; } }
.footnote { display: block; color: #73796f; font-size: 22rpx; line-height: 1.8; padding-top: 24rpx; }
.search { background: #f2f3ec; border-radius: 10rpx; padding: 20rpx; font-size: 25rpx; margin-bottom: 14rpx; }
.student-row { display: flex; align-items: center; gap: 20rpx; width: 100%; padding: 24rpx 0; text-align: left; border-bottom: 1rpx solid #eeeee5; }
.rank { color: #77836e; font-family: 'Baskerville', serif; font-size: 26rpx; }
.student-main { flex: 1; min-width: 0; }
.student-name { display: block; font-size: 28rpx; word-break: break-all; }
.track { height: 5rpx; background: #eef0e6; margin: 14rpx 0 8rpx; }
.fill { height: 100%; background: #91a180; }
.student-count { flex-shrink: 0; font-size: 34rpx; }
.more { padding: 24rpx 0 0; width: 100%; font-size: 24rpx; color: #52714e; }
.distribution { display: flex; justify-content: space-between; gap: 20rpx; padding: 20rpx 0; border-bottom: 1rpx solid #eeeee5; font-size: 24rpx; > text:first-child { flex: 1; word-break: break-all; } }
.status-scroll { width: 100%; }
.status-tabs { display: flex; gap: 12rpx; padding-bottom: 12rpx; white-space: nowrap; button { flex-shrink: 0; padding: 16rpx 20rpx; border-radius: 8rpx; background: #f1f2eb; font-size: 22rpx; } .active { color: white; background: #344f42; } }
.filters { margin-top: 16rpx; font-size: 22rpx; color: #647b58; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; button { padding: 16rpx 0; } }
.record { display: flex; flex-direction: column; gap: 12rpx; border-bottom: 1rpx solid #e9ebdf; padding: 24rpx 0; }
.record-top { display: flex; align-items: center; justify-content: space-between; gap: 16rpx; }
.record-name { font-size: 28rpx; text-align: left; word-break: break-all; }
.badge { flex-shrink: 0; font-size: 20rpx; color: #867257; background: #f3eee4; padding: 6rpx 12rpx; border-radius: 6rpx; }
.completed { color: #53704b; background: #eaf0e2; }
.record-date { font-size: 25rpx; }
.notes { padding: 32rpx 8rpx; display: flex; flex-direction: column; gap: 16rpx; font-size: 22rpx; line-height: 1.9; color: #73796f; }
.notes-title { color: #455d49; font-size: 25rpx; }
.empty { padding: 80rpx 28rpx; text-align: center; font-size: 26rpx; line-height: 1.8; color: #737e70; }
.compact { padding: 36rpx 20rpx 0; }
.outline { padding: 20rpx; margin-top: 24rpx; border: 1rpx solid #b2bfaa; border-radius: 12rpx; }
</style>

File diff suppressed because it is too large Load Diff

View File

@@ -150,7 +150,7 @@
class="modal-input"
type="number"
v-model="form.totalTimesStr"
placeholder="次卡必填月卡留空"
placeholder="次卡必填月卡可填写次数"
placeholder-style="color:#bbb"
/>
</view>
@@ -188,6 +188,32 @@
auto-height
/>
</view>
<!-- Cover image upload -->
<view class="modal-field modal-field--cover">
<text class="modal-label">封面图</text>
<view class="cover-upload-area">
<view v-if="form.coverUrl" class="cover-preview-wrap">
<image class="cover-preview-img" :src="form.coverUrl" mode="aspectFill" />
<view class="cover-remove-btn" @tap="clearCover">
<text class="cover-remove-icon"></text>
</view>
</view>
<view
v-else
class="cover-upload-btn"
:class="{ 'cover-upload-btn--loading': uploadingCover }"
@tap="uploadCover"
>
<text v-if="uploadingCover" class="cover-upload-hint">上传中...</text>
<template v-else>
<text class="cover-upload-plus"></text>
<text class="cover-upload-hint">上传封面</text>
</template>
</view>
<text class="cover-upload-tip">可选建议 3:2 比例</text>
</view>
</view>
</view>
<!-- Action buttons -->
@@ -213,8 +239,9 @@
import { ref, onMounted } from 'vue'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import { useAdminStore } from './stores/admin'
import { formatPrice } from '../../utils/format'
import { uploadStudioAsset } from './utils/studio-upload'
import { CardTypeCategory } from '@mp-pilates/shared'
import type { CardType } from '@mp-pilates/shared'
@@ -229,6 +256,7 @@ const cardTypes = ref<CardType[]>([])
const loading = ref(false)
const showModal = ref(false)
const submitting = ref(false)
const uploadingCover = ref(false)
const editTarget = ref<CardType | null>(null)
const typeOptions = [
@@ -246,6 +274,7 @@ const defaultForm = () => ({
durationDaysStr: '90',
sortOrderStr: '0',
description: '',
coverUrl: '',
})
const form = ref(defaultForm())
@@ -282,6 +311,7 @@ function openEdit(ct: CardType) {
durationDaysStr: String(ct.durationDays),
sortOrderStr: String(ct.sortOrder),
description: ct.description ?? '',
coverUrl: ct.coverUrl ?? '',
}
showModal.value = true
}
@@ -349,6 +379,9 @@ async function submitForm() {
if (form.value.description.trim()) {
payload.description = form.value.description.trim()
}
if (form.value.coverUrl) {
payload.coverUrl = form.value.coverUrl
}
submitting.value = true
try {
@@ -431,6 +464,85 @@ function confirmDelete(ct: CardType) {
})
}
// ─── Cover image upload ─────────────────────────────
async function uploadCover() {
if (uploadingCover.value) return
try {
const file = await chooseSingleImage()
if (!file) return
uploadingCover.value = true
const url = await uploadStudioAsset({
adminStore,
filePath: file.path,
fileName: file.name,
assetType: 'card-cover',
})
form.value.coverUrl = url
uni.showToast({ title: '上传成功', icon: 'success' })
} catch (error: unknown) {
const message = error instanceof Error ? error.message : '上传失败'
uni.showToast({ title: message, icon: 'none' })
} finally {
uploadingCover.value = false
}
}
function clearCover() {
form.value.coverUrl = ''
}
interface PickedImage {
readonly path: string
readonly name: string
}
function extractFileName(filePath: string): string {
return filePath.split('/').pop() || `image_${Date.now()}.jpg`
}
function chooseSingleImage(): Promise<PickedImage | null> {
return new Promise((resolve, reject) => {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (result) => {
const tempFilePaths = Array.isArray(result.tempFilePaths)
? result.tempFilePaths
: typeof result.tempFilePaths === 'string'
? [result.tempFilePaths]
: []
const path = tempFilePaths[0]
if (!path) {
resolve(null)
return
}
const tempFiles = Array.isArray(result.tempFiles)
? result.tempFiles
: result.tempFiles
? [result.tempFiles]
: []
const file = tempFiles[0] as { path?: string; tempFilePath?: string; name?: string } | undefined
resolve({
path,
name: file?.name || extractFileName(file?.path || file?.tempFilePath || path),
})
},
fail: (error) => {
if ((error.errMsg || '').includes('cancel')) {
resolve(null)
return
}
reject(new Error(error.errMsg || '选择图片失败'))
},
})
})
}
// ─── Helpers ─────────────────────────────────────────
function typeLabel(ct: CardType): string {
@@ -522,16 +634,16 @@ onMounted(fetchCardTypes)
justify-content: space-between;
}
.header--times { background: linear-gradient(90deg, #1a1a2e, #2d2d5e); }
.header--duration { background: linear-gradient(90deg, #6c3483, #9b59b6); }
.header--trial { background: linear-gradient(90deg, #5a7a8a, $primary-dark); }
.header--times { background: linear-gradient(90deg, #E8D5C4, #D4BFA8); }
.header--duration { background: linear-gradient(90deg, #D8C8DC, #C4AECB); }
.header--trial { background: linear-gradient(90deg, #C8D8D2, #A9C4BC); }
.ct-type-label { font-size: 22rpx; font-weight: 600; color: #ffffff; letter-spacing: 2rpx; }
.ct-type-label { font-size: 22rpx; font-weight: 600; color: $brand-color; letter-spacing: 2rpx; }
.ct-status-tag { border-radius: 20rpx; padding: 4rpx 16rpx; }
.tag--on { background: rgba(255,255,255,0.2); }
.tag--off { background: rgba(0,0,0,0.2); }
.ct-status-text { font-size: 20rpx; color: #ffffff; }
.tag--on { background: rgba(74, 64, 53, 0.1); }
.tag--off { background: rgba(74, 64, 53, 0.08); }
.ct-status-text { font-size: 20rpx; color: $brand-color; }
.ct-body { padding: 24rpx; }
@@ -721,4 +833,82 @@ onMounted(fetchCardTypes)
}
.modal-confirm-text { font-size: 28rpx; font-weight: 700; color: $primary-dark; }
/* ── Cover upload ───────────────────────── */
.modal-field--cover {
flex-direction: column;
align-items: flex-start;
gap: 16rpx;
border-bottom: none;
}
.cover-upload-area {
width: 100%;
display: flex;
flex-direction: column;
gap: 12rpx;
}
.cover-preview-wrap {
position: relative;
width: 300rpx;
height: 200rpx;
border-radius: 12rpx;
overflow: hidden;
}
.cover-preview-img {
width: 100%;
height: 100%;
}
.cover-remove-btn {
position: absolute;
top: 8rpx;
right: 8rpx;
width: 44rpx;
height: 44rpx;
background: rgba(0, 0, 0, 0.5);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.cover-remove-icon {
font-size: 20rpx;
color: #ffffff;
}
.cover-upload-btn {
width: 300rpx;
height: 200rpx;
border: 2rpx dashed #ddd;
border-radius: 12rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8rpx;
background: #fafafa;
&:active { background: #f0f0f0; }
&--loading { opacity: 0.6; pointer-events: none; }
}
.cover-upload-plus {
font-size: 48rpx;
color: #bbb;
line-height: 1;
}
.cover-upload-hint {
font-size: 22rpx;
color: #999;
}
.cover-upload-tip {
font-size: 20rpx;
color: #bbb;
}
</style>

View File

@@ -2,157 +2,83 @@
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="管理中心" show-back />
<!-- Stats summary card -->
<view class="stats-card-wrap">
<view class="stats-card">
<view v-if="statsLoading" class="stats-loading">
<view v-for="i in 3" :key="i" class="stat-skeleton" />
</view>
<template v-else>
<view class="stat-block">
<text class="stat-num">{{ stats.todayBookings }}</text>
<text class="stat-sub">今日预约</text>
</view>
<view class="stat-sep" />
<view class="stat-block">
<text class="stat-num">{{ stats.totalOrders }}</text>
<text class="stat-sub">总订单</text>
</view>
<view class="stat-sep" />
<view class="stat-block">
<text class="stat-num">{{ stats.totalBookings }}</text>
<text class="stat-sub">总预约</text>
</view>
</template>
</view>
</view>
<!-- Section header: 课程管理 -->
<!-- Section: 课务运营 -->
<view class="section-header">
<text class="section-title">课程管理</text>
<text class="section-title">今日经营</text>
</view>
<!-- List: schedule -->
<view class="list">
<view class="list-item" @tap="navigate('/pages/admin/bookings')">
<view class="item-left">
<view class="item-icon-wrap icon--bookings">
<text class="item-icon-text"></text>
<view class="list-item" @tap="navigate('/pages/admin/portrait-today')">
<text class="item-title">今日经营助手</text>
<text class="arrow-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">预约管理</text>
<text class="item-desc">查看/确认/核销学员预约</text>
</view>
</view>
<view class="item-arrow">
<view class="list-item" @tap="navigate('/pages/admin/portrait-leads')">
<text class="item-title">身体画像线索</text>
<text class="arrow-text"></text>
</view>
</view>
<!-- Section: 课务运营 -->
<view class="section-header">
<text class="section-title">课务运营</text>
</view>
<view class="list">
<view class="list-item" @tap="navigate('/pages/admin/schedule')">
<view class="item-left">
<view class="item-icon-wrap icon--schedule">
<text class="item-icon-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">排课管理</text>
<text class="item-desc">管理每周课程时段</text>
<text class="arrow-text"></text>
</view>
</view>
<view class="item-arrow">
<view class="list-item" @tap="navigate('/pages/admin/bookings')">
<text class="item-title">预约管理</text>
<text class="arrow-text"></text>
</view>
</view>
<view class="list-item" @tap="navigate('/pages/admin/week-template')">
<view class="item-left">
<view class="item-icon-wrap icon--template">
<text class="item-icon-text"></text>
<!-- Section: 教学复盘 -->
<view class="section-header">
<text class="section-title">教学复盘</text>
</view>
<view class="item-text-group">
<text class="item-title">排课模板</text>
<text class="item-desc">设置每周课程模板</text>
<view class="list">
<view class="list-item" @tap="navigate('/pages/admin/analytics')">
<text class="item-title">统计分析</text>
<text class="arrow-text"></text>
</view>
</view>
<view class="item-arrow">
<view class="list-item" @tap="navigate('/pages/admin/reviews')">
<text class="item-title">课后评价</text>
<text class="arrow-text"></text>
</view>
</view>
</view>
<!-- Section header: 会员与订单 -->
<!-- Section: 会员与订单 -->
<view class="section-header">
<text class="section-title">会员与订单</text>
</view>
<!-- List: members & orders -->
<view class="list">
<view class="list-item" @tap="navigate('/pages/admin/members')">
<view class="item-left">
<view class="item-icon-wrap icon--members">
<text class="item-icon-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">会员管理</text>
<text class="item-desc">查看所有会员信息</text>
</view>
</view>
<view class="item-arrow">
<text class="arrow-text"></text>
</view>
</view>
<view class="list-item" @tap="navigate('/pages/admin/orders')">
<view class="item-left">
<view class="item-icon-wrap icon--orders">
<text class="item-icon-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">订单管理</text>
<text class="item-desc">查看所有订单记录</text>
</view>
</view>
<view class="item-arrow">
<text class="arrow-text"></text>
</view>
</view>
<view class="list-item" @tap="navigate('/pages/admin/card-types')">
<view class="item-left">
<view class="item-icon-wrap icon--card">
<text class="item-icon-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">卡种管理</text>
<text class="item-desc">设置会员卡类型</text>
</view>
</view>
<view class="item-arrow">
<text class="arrow-text"></text>
</view>
</view>
</view>
<!-- Section header: 系统 -->
<!-- Section: 系统设置 -->
<view class="section-header">
<text class="section-title">系统</text>
<text class="section-title">系统设置</text>
</view>
<!-- List: settings -->
<view class="list">
<view class="list-item" @tap="navigate('/pages/admin/studio')">
<view class="item-left">
<view class="item-icon-wrap icon--studio">
<text class="item-icon-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">工作室设置</text>
<text class="item-desc">工作室信息与配置</text>
</view>
</view>
<view class="item-arrow">
<view class="list-item" @tap="navigate('/pages/admin/card-types')">
<text class="item-title">卡种管理</text>
<text class="arrow-text"></text>
</view>
<view class="list-item" @tap="navigate('/pages/admin/studio')">
<text class="item-title">工作室设置</text>
<text class="arrow-text"></text>
</view>
<view class="list-item" @tap="handleIncreaseSubscriptionCount">
<text class="item-title">增加订阅次数</text>
<text class="item-extra">剩余 {{ user?.adminBookingSubscriptionCount ?? 0 }} </text>
<text class="arrow-text">{{ adminSubscribeLoading ? '...' : '' }}</text>
</view>
</view>
@@ -162,106 +88,60 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import type { AdminStats } from '../../stores/admin'
import { useUserStore } from '../../stores/user'
import { requestAdminBookingSubscriptionCount } from '../../utils/wechat-subscription'
import { getErrorMessage } from '../../utils/auth'
const navBarHeight = ref('64px')
const adminStore = useAdminStore()
const userStore = useUserStore()
const { user } = storeToRefs(userStore)
const statsLoading = ref(false)
const stats = ref<AdminStats>({ todayBookings: 0, totalOrders: 0, totalBookings: 0 })
const adminSubscribeLoading = ref(false)
function navigate(path: string) {
uni.navigateTo({ url: path })
}
async function loadStats() {
statsLoading.value = true
async function handleIncreaseSubscriptionCount() {
if (adminSubscribeLoading.value) {
return
}
adminSubscribeLoading.value = true
try {
stats.value = await adminStore.fetchDashboardStats()
} catch {
// fail silently — stats are non-critical
const profile = await requestAdminBookingSubscriptionCount()
if (!profile) {
uni.showToast({ title: '已取消本次授权', icon: 'none' })
return
}
userStore.setProfile(profile)
uni.showToast({ title: `订阅次数 +1剩余 ${profile.adminBookingSubscriptionCount}`, icon: 'none' })
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '订阅授权失败'), icon: 'none' })
} finally {
statsLoading.value = false
adminSubscribeLoading.value = false
}
}
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
loadStats()
userStore.fetchProfile()
})
</script>
<style lang="scss" scoped>
/* ── Page ───────────────────────────────────── */
/* ── Page ───────────────────────── */
.page {
min-height: 100vh;
padding-bottom: 40rpx;
}
/* ── Stats card ─────────────────────────────── */
.stats-card-wrap {
padding: 24rpx 24rpx 8rpx;
}
.stats-card {
background: #FFFFFF;
border-radius: 20rpx;
padding: 32rpx 24rpx;
display: flex;
align-items: center;
box-shadow: 0 4rpx 20rpx rgba(180, 160, 130, 0.10);
border: 1rpx solid rgba(180, 160, 130, 0.12);
}
.stats-loading {
width: 100%;
display: flex;
align-items: center;
justify-content: space-around;
}
.stat-skeleton {
width: 100rpx;
height: 64rpx;
border-radius: 12rpx;
background: linear-gradient(90deg, $primary-border 25%, $primary-light 50%, $primary-border 75%);
background-size: 400% 100%;
animation: shimmer 1.6s ease infinite;
}
.stat-block {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 8rpx;
}
.stat-num {
font-size: 44rpx;
font-weight: 700;
color: #4A4035;
line-height: 1;
font-family: 'DIN Alternate', 'Helvetica Neue', Arial, sans-serif;
}
.stat-sub {
font-size: 22rpx;
color: #A09080;
letter-spacing: 0.5rpx;
}
.stat-sep {
width: 1rpx;
height: 56rpx;
background: rgba(180, 160, 130, 0.2);
}
/* ── Section header ─────────────────────────── */
/* ── Section header ───────────────── */
.section-header {
padding: 32rpx 24rpx 12rpx;
}
@@ -274,7 +154,7 @@ onMounted(() => {
text-transform: uppercase;
}
/* ── List ───────────────────────────────────── */
/* ── List ───────────────────────── */
.list {
background: #FFFFFF;
margin: 0 24rpx;
@@ -287,8 +167,8 @@ onMounted(() => {
.list-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 28rpx 24rpx;
gap: 16rpx;
padding: 32rpx 28rpx;
border-bottom: 1rpx solid rgba(180, 160, 130, 0.1);
transition: background 0.15s ease;
@@ -301,62 +181,23 @@ onMounted(() => {
}
}
.item-left {
display: flex;
align-items: center;
gap: 20rpx;
}
.item-icon-wrap {
width: 72rpx;
height: 72rpx;
border-radius: 18rpx;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.item-icon-text {
font-size: 32rpx;
color: #FFFFFF;
line-height: 1;
}
/* Icon variants — warm muted tones */
.icon--bookings { background: linear-gradient(135deg, #C4A87E, #B49868); }
.icon--schedule { background: linear-gradient(135deg, #8B9E7E, #7A8E6E); }
.icon--template { background: linear-gradient(135deg, #A090C0, #9080B0); }
.icon--members { background: linear-gradient(135deg, $primary-color, $primary-dark); }
.icon--orders { background: linear-gradient(135deg, #7E9EC4, #6E8EB4); }
.icon--card { background: linear-gradient(135deg, #C48E7E, #B47E6E); }
.icon--studio { background: linear-gradient(135deg, #9E9E7E, #8E8E6E); }
.item-text-group {
display: flex;
flex-direction: column;
gap: 4rpx;
}
.item-title {
flex: 1;
font-size: 30rpx;
font-weight: 600;
font-weight: 500;
color: #4A4035;
letter-spacing: 0.5rpx;
}
.item-desc {
.item-extra {
font-size: 24rpx;
color: #A09080;
}
.item-arrow {
flex-shrink: 0;
padding-left: 16rpx;
}
.arrow-text {
font-size: 40rpx;
flex-shrink: 0;
font-size: 36rpx;
color: rgba(180, 160, 130, 0.5);
font-weight: 300;
line-height: 1;

View File

@@ -0,0 +1,574 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="安排课程" show-back />
<view v-if="detail" class="who-bar">
<view class="who-avatar">
<image v-if="detail.user.avatarUrl" class="avatar-img" :src="detail.user.avatarUrl" mode="aspectFill" />
<view v-else class="avatar-fallback">
<text class="avatar-letter">{{ (detail.user.nickname || '?').slice(0, 1) }}</text>
</view>
</view>
<view class="who-copy">
<text class="who-kicker">为学员安排</text>
<text class="who-name">{{ detail.user.nickname || '未知用户' }}</text>
</view>
</view>
<view v-if="usableMemberships.length" class="card-switch">
<scroll-view scroll-x class="card-scroll" :show-scrollbar="false">
<view class="card-track">
<view
v-for="card in usableMemberships"
:key="card.id"
class="card-pill"
:class="{ 'card-pill--on': selectedMembershipId === card.id }"
@tap="selectedMembershipId = card.id"
>
<text class="card-pill-name">{{ card.cardType.name }}</text>
<text class="card-pill-meta">
{{ card.remainingTimes === null ? '有效期内不限次' : `${card.remainingTimes}` }}
</text>
</view>
</view>
</scroll-view>
</view>
<view v-else class="ban-banner">
<text class="ban-text">该会员没有可扣课的有效卡请先开卡</text>
</view>
<DateSelector v-model="selectedDate" variant="booking" @select="onDateSelect" />
<TimePeriodFilter v-model="selectedPeriod" variant="booking" />
<view v-if="slotsLoading" class="slot-skeleton">
<view v-for="i in 4" :key="i" class="slot-skel" />
</view>
<view v-else-if="filteredSlots.length === 0" class="empty-slots">
<text class="empty-title">这天还没有可安排的课表</text>
<text class="empty-sub">请先去排课管理发布时段</text>
<view class="ghost-link" @tap="goSchedule">
<text class="ghost-link-text">前往排课管理</text>
</view>
</view>
<view v-else class="slot-list">
<view
v-for="slot in filteredSlots"
:key="slot.id"
class="slot-row"
:class="{ 'slot-row--disabled': !canPickSlot(slot) }"
@tap="onPickSlot(slot)"
>
<view class="slot-time-col">
<text class="slot-time">{{ slot.startTime.slice(0, 5) }}</text>
<text class="slot-end">{{ slot.endTime.slice(0, 5) }}</text>
</view>
<view class="slot-body">
<text class="slot-title">{{ slotLabel(slot) }}</text>
<text class="slot-cap">{{ slot.bookedCount }}/{{ slot.capacity }} </text>
</view>
<text class="slot-action">{{ slotActionLabel(slot) }}</text>
</view>
</view>
<view v-if="confirmVisible && pendingSlot" class="mask" @tap="confirmVisible = false">
<view class="sheet" @tap.stop>
<text class="sheet-kicker">立即确认</text>
<text class="sheet-title">安排给 {{ detail?.user.nickname || '该会员' }}</text>
<view class="sheet-lines">
<view class="sheet-line">
<text class="sheet-label">时间</text>
<text class="sheet-value">{{ pendingSlot.date }} {{ pendingSlot.startTime.slice(0, 5) }}{{ pendingSlot.endTime.slice(0, 5) }}</text>
</view>
<view class="sheet-line">
<text class="sheet-label">扣卡</text>
<text class="sheet-value">{{ selectedMembership?.cardType.name }}</text>
</view>
</view>
<text class="sheet-note">{{ deductHint }}</text>
<view class="sheet-actions">
<view class="sheet-cancel" @tap="confirmVisible = false">
<text class="sheet-cancel-text">取消</text>
</view>
<view class="sheet-ok" :class="{ 'sheet-ok--disabled': arranging }" @tap="confirmArrange">
<text class="sheet-ok-text">{{ arranging ? '安排中...' : '确认安排' }}</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type {
AdminMemberDetail,
ScheduleSlotPreview,
} from '@mp-pilates/shared'
import { MembershipStatus, TIME_PERIODS, TimeSlotStatus } from '@mp-pilates/shared'
import CustomNavBar from '../../components/CustomNavBar.vue'
import DateSelector from '../../components/DateSelector.vue'
import TimePeriodFilter from '../../components/TimePeriodFilter.vue'
import { getSystemLayout } from '../../utils/system'
import { formatDate, isSlotPast } from '../../utils/format'
import { getErrorMessage } from '../../utils/auth'
import { useAdminStore } from './stores/admin'
type PeriodKey = keyof typeof TIME_PERIODS | null
const adminStore = useAdminStore()
const navBarHeight = ref('64px')
const userId = ref('')
const detail = ref<AdminMemberDetail | null>(null)
const selectedMembershipId = ref('')
const selectedDate = ref(formatDate(new Date()))
const selectedPeriod = ref<PeriodKey>(null)
const slots = ref<ScheduleSlotPreview[]>([])
const slotsLoading = ref(false)
const confirmVisible = ref(false)
const pendingSlot = ref<ScheduleSlotPreview | null>(null)
const arranging = ref(false)
const usableMemberships = computed(() =>
(detail.value?.memberships ?? []).filter((item) =>
item.status === MembershipStatus.ACTIVE
&& (item.remainingTimes === null || item.remainingTimes > 0)
&& new Date(item.expireDate) > new Date(),
),
)
const selectedMembership = computed(
() => usableMemberships.value.find((item) => item.id === selectedMembershipId.value) ?? null,
)
const canArrange = computed(() => Boolean(selectedMembership.value))
const isCountLimited = computed(() => selectedMembership.value?.remainingTimes !== null)
const deductHint = computed(() => {
if (!isCountLimited.value) {
return '将立即确认该课,会员卡不限次,会员无需再确认。'
}
return '将立即确认该课并扣除 1 次,会员无需再确认。'
})
const publishedSlots = computed(() =>
slots.value.filter((slot): slot is ScheduleSlotPreview & { id: string } =>
Boolean(slot.isPublished && slot.id),
),
)
const filteredSlots = computed(() => {
if (!selectedPeriod.value) return publishedSlots.value
const period = TIME_PERIODS[selectedPeriod.value]
return publishedSlots.value.filter((slot) => slot.startTime >= period.start && slot.startTime < period.end)
})
function canPickSlot(slot: ScheduleSlotPreview): boolean {
if (!canArrange.value) return false
if (isSlotPast(slot.date, slot.startTime)) return false
if (slot.status === TimeSlotStatus.CLOSED) return false
if (slot.status === TimeSlotStatus.FULL || slot.bookedCount >= slot.capacity) return false
return true
}
function slotLabel(slot: ScheduleSlotPreview): string {
if (slot.status === TimeSlotStatus.CLOSED) return '已关闭'
if (slot.status === TimeSlotStatus.FULL || slot.bookedCount >= slot.capacity) return '已满员'
if (isSlotPast(slot.date, slot.startTime)) return '已过点'
return '可安排'
}
function slotActionLabel(slot: ScheduleSlotPreview): string {
if (!canPickSlot(slot)) return '—'
return '安排'
}
async function loadSlots(date: string) {
slotsLoading.value = true
try {
slots.value = await adminStore.previewScheduleByDate(date)
} catch (err: unknown) {
slots.value = []
uni.showToast({ title: getErrorMessage(err, '课表加载失败'), icon: 'none' })
} finally {
slotsLoading.value = false
}
}
async function loadPage() {
detail.value = await adminStore.fetchMemberDetail(userId.value)
const first = usableMemberships.value[0]
selectedMembershipId.value = first?.id ?? ''
await loadSlots(selectedDate.value)
}
function onDateSelect(date: string) {
selectedDate.value = date
loadSlots(date)
}
function goSchedule() {
uni.navigateTo({ url: '/pages/admin/schedule' })
}
function onPickSlot(slot: ScheduleSlotPreview) {
if (!canPickSlot(slot) || !slot.id) return
pendingSlot.value = slot
confirmVisible.value = true
}
async function confirmArrange() {
const slot = pendingSlot.value
const membership = selectedMembership.value
if (!slot?.id || !membership || arranging.value) return
arranging.value = true
try {
await adminStore.arrangeMemberBooking({
userId: userId.value,
membershipId: membership.id,
timeSlotId: slot.id,
})
confirmVisible.value = false
uni.showToast({ title: '已安排并确认', icon: 'success' })
setTimeout(() => uni.navigateBack(), 500)
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '安排失败'), icon: 'none' })
} finally {
arranging.value = false
}
}
onLoad((query) => {
userId.value = String(query?.userId || '')
})
onMounted(async () => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
try {
await loadPage()
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '加载失败'), icon: 'none' })
}
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background: $bg-page;
padding-bottom: 80rpx;
}
.who-bar {
margin: 16rpx 24rpx 0;
padding: 20rpx;
border-radius: 20rpx;
background: linear-gradient(135deg, #3c3228, #5a4a3a);
display: flex;
align-items: center;
gap: 18rpx;
}
.who-avatar {
width: 72rpx;
height: 72rpx;
border-radius: 18rpx;
overflow: hidden;
flex-shrink: 0;
}
.avatar-img { width: 100%; height: 100%; }
.avatar-fallback {
width: 100%;
height: 100%;
background: $accent-color;
display: flex;
align-items: center;
justify-content: center;
}
.avatar-letter {
color: #fff8f0;
font-weight: 700;
}
.who-copy {
display: flex;
flex-direction: column;
gap: 4rpx;
}
.who-kicker {
font-size: 18rpx;
letter-spacing: 3rpx;
color: rgba(255, 248, 240, 0.55);
}
.who-name {
font-size: 32rpx;
font-weight: 700;
color: #fff8f0;
}
.card-switch {
padding: 16rpx 0 4rpx;
}
.card-scroll { white-space: nowrap; }
.card-track {
display: inline-flex;
gap: 12rpx;
padding: 0 24rpx;
}
.card-pill {
padding: 14rpx 22rpx;
border-radius: 16rpx;
background: #fff;
border: 2rpx solid rgba(180, 160, 130, 0.18);
display: flex;
flex-direction: column;
gap: 4rpx;
}
.card-pill--on {
border-color: $brand-color;
background: #3c3228;
}
.card-pill-name {
font-size: 24rpx;
font-weight: 700;
color: $text-primary;
}
.card-pill--on .card-pill-name,
.card-pill--on .card-pill-meta {
color: #fff8f0;
}
.card-pill-meta {
font-size: 20rpx;
color: $text-hint;
}
.ban-banner {
margin: 16rpx 24rpx;
padding: 20rpx;
border-radius: 16rpx;
background: rgba($error-color, 0.1);
}
.ban-text {
font-size: 24rpx;
color: $error-color;
}
.slot-skeleton { padding: 16rpx 24rpx; }
.slot-skel {
height: 112rpx;
border-radius: 18rpx;
margin-bottom: 12rpx;
background: linear-gradient(90deg, #efe8df 25%, #f7f2ea 50%, #efe8df 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
}
.empty-slots {
padding: 48rpx 32rpx;
display: flex;
flex-direction: column;
align-items: center;
gap: 10rpx;
}
.empty-title {
font-size: 28rpx;
font-weight: 700;
color: $text-primary;
}
.empty-sub {
font-size: 24rpx;
color: $text-hint;
text-align: center;
}
.ghost-link {
margin-top: 8rpx;
padding: 10rpx 24rpx;
border-radius: 999rpx;
border: 1rpx solid $brand-color;
}
.ghost-link-text {
font-size: 22rpx;
color: $brand-color;
}
.slot-list {
padding: 16rpx 24rpx 8rpx;
}
.slot-row {
display: flex;
align-items: center;
gap: 20rpx;
background: #fff;
border-radius: 18rpx;
padding: 22rpx 20rpx;
margin-bottom: 12rpx;
border: 1rpx solid rgba(180, 160, 130, 0.12);
}
.slot-row--disabled {
opacity: 0.45;
}
.slot-time-col {
width: 120rpx;
display: flex;
flex-direction: column;
}
.slot-time {
font-size: 34rpx;
font-weight: 800;
color: $text-primary;
font-family: 'DIN Alternate', 'Helvetica Neue', sans-serif;
}
.slot-end {
font-size: 22rpx;
color: $text-hint;
}
.slot-body {
flex: 1;
display: flex;
flex-direction: column;
gap: 4rpx;
}
.slot-title {
font-size: 26rpx;
font-weight: 600;
color: $text-primary;
}
.slot-cap {
font-size: 22rpx;
color: $text-hint;
}
.slot-action {
font-size: 24rpx;
font-weight: 700;
color: $accent-color;
}
.mask {
position: fixed;
inset: 0;
background: rgba(44, 36, 28, 0.45);
display: flex;
align-items: flex-end;
z-index: 20;
}
.sheet {
width: 100%;
background: #fff8f0;
border-radius: 28rpx 28rpx 0 0;
padding: 32rpx 32rpx calc(32rpx + env(safe-area-inset-bottom));
}
.sheet-kicker {
font-size: 20rpx;
letter-spacing: 4rpx;
color: $text-hint;
}
.sheet-title {
display: block;
margin-top: 8rpx;
font-size: 36rpx;
font-weight: 700;
color: $text-primary;
font-family: 'Songti SC', Georgia, serif;
}
.sheet-lines {
margin: 28rpx 0 16rpx;
}
.sheet-line {
display: flex;
justify-content: space-between;
padding: 14rpx 0;
border-bottom: 1rpx solid rgba(180, 160, 130, 0.14);
}
.sheet-label {
font-size: 24rpx;
color: $text-hint;
}
.sheet-value {
font-size: 26rpx;
color: $text-primary;
}
.sheet-note {
display: block;
font-size: 24rpx;
color: $text-secondary;
line-height: 1.5;
}
.sheet-actions {
display: flex;
gap: 16rpx;
margin-top: 28rpx;
}
.sheet-cancel,
.sheet-ok {
flex: 1;
height: 84rpx;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
}
.sheet-cancel {
background: #fff;
border: 2rpx solid $brand-color;
}
.sheet-ok {
background: $brand-color;
}
.sheet-ok--disabled { opacity: 0.5; }
.sheet-cancel-text {
font-size: 28rpx;
font-weight: 700;
color: $brand-color;
}
.sheet-ok-text {
font-size: 28rpx;
font-weight: 700;
color: #fff8f0;
}
</style>

View File

@@ -0,0 +1,419 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="会员档案" show-back />
<view v-if="loading && !detail" class="skeleton-wrap">
<view class="skeleton-hero" />
<view class="skeleton-block" />
<view class="skeleton-block" />
</view>
<template v-else-if="detail">
<view class="hero">
<view class="hero-inner">
<view class="hero-avatar">
<image v-if="detail.user.avatarUrl" class="avatar-img" :src="detail.user.avatarUrl" mode="aspectFill" />
<view v-else class="avatar-fallback">
<text class="avatar-letter">{{ (detail.user.nickname || '?').slice(0, 1) }}</text>
</view>
</view>
<view class="hero-copy">
<text class="hero-name">{{ detail.user.nickname || '未知用户' }}</text>
<text class="hero-phone">{{ detail.user.phone || '未绑定手机' }}</text>
</view>
</view>
<view v-if="detail.user.openid" class="member-id" @tap="copyOpenid">
<text class="member-id-label">微信标识</text>
<text class="member-id-value">{{ detail.user.openid }}</text>
<text class="member-id-copy">复制</text>
</view>
<view class="time-pair">
<view class="time-cell">
<text class="time-label">注册时间</text>
<text class="time-value">{{ formatDateTimeFull(detail.user.createdAt) }}</text>
</view>
<view class="time-rule" />
<view class="time-cell">
<text class="time-label">最近登录</text>
<text class="time-value">{{ detail.user.lastLoginAt ? formatDateTimeFull(detail.user.lastLoginAt) : '暂无登录记录' }}</text>
</view>
</view>
</view>
<view class="member-tabs"><button :class="{ selected: activeTab === 'overview' }" @tap="activeTab = 'overview'">会员概览</button><button :class="{ selected: activeTab === 'progress' }" @tap="activeTab = 'progress'">成长档案</button><button @tap="goReviews">课后评价 </button></view>
<MemberProgress v-if="activeTab === 'progress'" admin :user-id="userId" :refresh-key="progressRefreshKey" />
<template v-if="activeTab === 'overview'">
<view class="section section--practice">
<view class="section-heading">
<text class="section-label">上课情况</text>
<button class="supplement-entry" @tap="goSupplement">补录上课 <text></text></button>
</view>
<view class="stats-strip">
<view class="stat">
<text class="stat-num">{{ detail.stats.totalBookings }}</text>
<text class="stat-name">累计预约</text>
</view>
<view class="stat stat--completed">
<text class="stat-num">{{ detail.stats.completedBookings }}</text>
<text class="stat-name">累计上课</text>
</view>
<view class="stat">
<text class="stat-num">{{ detail.stats.cancelledBookings }}</text>
<text class="stat-name">已取消</text>
</view>
<view class="stat">
<text class="stat-num">{{ detail.stats.noShowBookings }}</text>
<text class="stat-name">未到课</text>
</view>
</view>
</view>
<view class="section">
<view class="section-heading">
<text class="section-label">会员卡</text>
<text class="section-note">{{ detail.memberships.length }} </text>
</view>
<view v-if="detail.memberships.length" class="card-list">
<view
v-for="card in detail.memberships"
:key="card.id"
class="mship"
>
<view class="mship-head">
<view class="mship-titles">
<text class="mship-name">{{ card.cardType.name }}</text>
<text class="mship-type">{{ getCardTypeLabel(card.cardType.type) }}</text>
</view>
<view class="mship-status" :class="'mship-status--' + card.status.toLowerCase()">
<text class="mship-status-text">{{ membershipStatusLabel(card.status) }}</text>
</view>
</view>
<view v-if="card.remainingTimes !== null" class="mship-times">
<text class="mship-times-num">{{ card.remainingTimes }}</text>
<text class="mship-times-unit">次可用</text>
</view>
<view v-else class="mship-duration">
<text class="mship-duration-title">有效期内使用</text>
<text class="mship-times-unit">不限次数</text>
</view>
<view v-if="card.remainingTimes !== null && getMembershipTotalTimes(card)" class="progress">
<view class="progress-bar">
<view class="progress-fill" :style="{ width: getMembershipProgressWidth(card) }" />
</view>
<text class="progress-text">
已用 {{ getMembershipUsedTimes(card) }} / {{ getMembershipTotalTimes(card) }}
</text>
</view>
<view class="mship-dates">
<text>{{ formatDate(card.startDate) }} </text>
<text>{{ formatDate(card.expireDate) }} </text>
</view>
</view>
</view>
<view v-else class="empty-card">
<text class="empty-card-title">尚未开卡</text>
<text class="empty-card-sub">开通体验卡次卡或月卡后即可安排课程</text>
<view class="empty-card-btn" @tap="goEdit">
<text class="empty-card-btn-text">去开卡</text>
</view>
</view>
</view>
<view class="section section--last">
<view class="section-heading">
<text class="section-label">即将上课</text>
<text v-if="detail.upcomingBookings.length" class="section-note">{{ detail.upcomingBookings.length }} 节待上</text>
</view>
<view v-if="detail.upcomingBookings.length" class="upcoming-list">
<view v-for="item in detail.upcomingBookings" :key="item.id" class="upcoming-row">
<view class="upcoming-time">
<text class="upcoming-date">{{ item.date.slice(5, 10).replace('-', ' / ') }}</text>
<text class="upcoming-hour">{{ item.startTime.slice(0, 5) }}{{ item.endTime.slice(0, 5) }}</text>
</view>
<view class="upcoming-meta">
<text class="upcoming-card">{{ item.cardName }}</text>
<text class="upcoming-status">{{ bookingStatusLabel(item.status) }}</text>
</view>
</view>
</view>
<view v-else class="upcoming-empty">
<text class="upcoming-empty-text">近期没有待上的课</text>
</view>
</view>
</template>
</template>
<view v-if="activeTab === 'overview'" class="dock">
<view class="dock-btn dock-btn--ghost" @tap="goEdit">
<text class="dock-btn-text">编辑资料</text>
</view>
<view
class="dock-btn dock-btn--solid"
:class="{ 'dock-btn--disabled': !canArrange }"
@tap="goArrange"
>
<text class="dock-btn-text dock-btn-text--solid">安排课程</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import type { AdminMemberDetail, MembershipWithCardType } from '@mp-pilates/shared'
import { MembershipStatus, BookingStatus } from '@mp-pilates/shared'
import MemberProgress from '../../components/MemberProgress.vue'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import {
formatDateTimeFull,
getCardTypeLabel,
getMembershipProgressWidth,
getMembershipUsedTimes,
getMembershipTotalTimes,
} from '../../utils/format'
import { BOOKING_STATUS_LABELS } from '../../utils/booking-helpers'
import { getErrorMessage } from '../../utils/auth'
import { useAdminStore } from './stores/admin'
const adminStore = useAdminStore()
const navBarHeight = ref('64px')
const userId = ref('')
const loading = ref(false)
const activeTab = ref('overview'), progressRefreshKey = ref(0)
const detail = ref<AdminMemberDetail | null>(null)
const canArrange = computed(() => (detail.value?.memberships ?? []).some(isArrangableMembership))
function isArrangableMembership(membership: MembershipWithCardType): boolean {
if (membership.status !== MembershipStatus.ACTIVE) return false
if (membership.remainingTimes !== null && membership.remainingTimes <= 0) return false
return new Date(membership.expireDate) > new Date()
}
function membershipStatusLabel(status: string): string {
const map: Record<string, string> = {
ACTIVE: '有效',
EXPIRED: '已过期',
USED_UP: '已用完',
}
return map[status] || status
}
function bookingStatusLabel(status: BookingStatus): string {
return BOOKING_STATUS_LABELS[status] || status
}
function formatDate(dateStr: string): string {
return dateStr.slice(0, 10)
}
function copyOpenid() {
const openid = detail.value?.user.openid
if (!openid) return
uni.setClipboardData({
data: openid,
success: () => uni.showToast({ title: '已复制 OpenID', icon: 'success' }),
})
}
async function loadDetail() {
if (!userId.value) return
loading.value = true
try {
detail.value = await adminStore.fetchMemberDetail(userId.value)
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '加载失败'), icon: 'none' })
} finally {
loading.value = false
}
}
function goReviews() { uni.navigateTo({ url: `/pages/admin/reviews?userId=${userId.value}` }) }
function goSupplement() {
if (userId.value) uni.navigateTo({ url: `/pages/admin/member-supplement?userId=${userId.value}` })
}
function goEdit() {
if (!userId.value) return
uni.navigateTo({ url: `/pages/admin/member-edit?userId=${userId.value}` })
}
function goArrange() {
if (!canArrange.value) {
uni.showToast({ title: '请先开通有效会员卡', icon: 'none' })
return
}
uni.navigateTo({ url: `/pages/admin/member-arrange?userId=${userId.value}` })
}
onLoad((query) => {
userId.value = String(query?.userId || '')
})
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
})
onShow(() => {
progressRefreshKey.value++
if (userId.value) {
loadDetail()
}
})
</script>
<style lang="scss" scoped>
.member-tabs {display:flex;margin:28rpx 32rpx 0;border-bottom:1rpx solid #e5dfd6;gap:8rpx;}
.member-tabs button{flex:1;margin:0;padding:0;background:transparent;border-radius:0;line-height:88rpx;font-size:25rpx;color:#8b817b;border-bottom:4rpx solid transparent;&::after{border:0;}&.selected{border-color:#617d73;color:#617d73;}}
.page {
--ink: #514943;
--muted: #8b817b;
--line: #eee8e3;
--sage: #617d73;
min-height: 100vh;
box-sizing: border-box;
background: #fbf9f6;
color: var(--ink);
padding-bottom: calc(152rpx + env(safe-area-inset-bottom));
}
.skeleton-wrap { padding: 28rpx 32rpx; }
.skeleton-hero, .skeleton-block {
border-radius: 28rpx;
background: linear-gradient(90deg, #f0eae5 25%, #faf7f3 50%, #f0eae5 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
}
.skeleton-hero { height: 300rpx; margin-bottom: 28rpx; }
.skeleton-block { height: 180rpx; margin-bottom: 28rpx; }
.hero {
margin: 28rpx 32rpx 0;
padding: 32rpx;
border-radius: 32rpx;
background: #f3eae5;
}
.hero-inner { display: flex; align-items: center; gap: 24rpx; }
.hero-avatar {
width: 112rpx;
height: 112rpx;
border-radius: 50%;
overflow: hidden;
border: 6rpx solid #fcf8f4;
flex-shrink: 0;
}
.avatar-img { width: 100%; height: 100%; }
.avatar-fallback {
width: 100%; height: 100%; background: #e0cec4;
display: flex; align-items: center; justify-content: center;
}
.avatar-letter {
font-family: 'Songti SC', 'STSong', serif;
font-size: 44rpx; font-weight: 400; color: #735e53;
}
.hero-copy { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 12rpx; }
.hero-name { font-size: 38rpx; font-weight: 500; line-height: 1.4; overflow-wrap: anywhere; }
.hero-phone { font-size: 26rpx; color: #84746b; letter-spacing: 1rpx; }
.member-id {
display: flex; align-items: center; gap: 14rpx;
margin-top: 24rpx; min-height: 48rpx;
font-size: 20rpx; color: #88786f;
}
.member-id-label { flex-shrink: 0; }
.member-id-value { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.member-id-copy { flex-shrink: 0; color: #715a4e; padding: 8rpx 0 8rpx 8rpx; }
.time-pair {
display: flex; gap: 20rpx;
margin-top: 20rpx; padding-top: 24rpx;
border-top: 1rpx solid #e4d8d0;
}
.time-cell { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10rpx; }
.time-rule { width: 1rpx; background: #e4d8d0; }
.time-label { font-size: 21rpx; color: #88786f; }
.time-value { font-size: 22rpx; color: #6d5c52; line-height: 1.5; font-variant-numeric: tabular-nums; }
.section { padding: 36rpx 32rpx 0; }
.section--last { padding-bottom: 24rpx; }
.section-label { display: block; font-size: 28rpx; font-weight: 500; margin-bottom: 20rpx; }
.section-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 16rpx; }
.supplement-entry { margin: 0; padding: 8rpx 18rpx; line-height: 1.5; font-size: 23rpx; border-radius: 999rpx; background: #edf2ec; color: #617d73; &::after { border: none; } }
.section-note { font-size: 22rpx; color: var(--muted); }
.stats-strip {
display: flex; padding: 26rpx 0;
border-radius: 24rpx; background: #ffffff;
}
.stat {
flex: 1; min-width: 0; display: flex; flex-direction: column;
align-items: center; gap: 12rpx; border-right: 1rpx solid var(--line);
&:last-child { border-right: none; }
}
.stat-num { font-size: 40rpx; font-weight: 400; line-height: 1.1; font-family: 'DIN Alternate', 'Avenir Next', sans-serif; font-variant-numeric: tabular-nums; }
.stat-name { font-size: 22rpx; color: var(--muted); }
.stat--completed { .stat-num, .stat-name { color: var(--sage); } }
.card-list { display: flex; flex-direction: column; gap: 20rpx; }
.mship { padding: 28rpx; background: #fff; border-radius: 28rpx; border: 1rpx solid var(--line); }
.mship-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 20rpx; }
.mship-titles { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8rpx; }
.mship-name { font-size: 29rpx; font-weight: 500; line-height: 1.5; overflow-wrap: anywhere; }
.mship-type { font-size: 21rpx; color: var(--muted); }
.mship-status {
flex-shrink: 0; padding: 6rpx 16rpx; border-radius: 999rpx;
background: #edf2ee; color: #617d73; line-height: 1.3;
&--expired, &--used_up { background: #f2efec; color: #8b817b; }
}
.mship-status-text { font-size: 21rpx; }
.mship-times { margin-top: 22rpx; display: flex; align-items: baseline; gap: 10rpx; }
.mship-times-num { font-size: 52rpx; font-weight: 400; font-family: 'DIN Alternate', 'Avenir Next', sans-serif; line-height: 1.2; }
.mship-times-unit { font-size: 22rpx; color: var(--muted); }
.mship-duration { display: flex; align-items: baseline; flex-wrap: wrap; gap: 12rpx; margin-top: 24rpx; }
.mship-duration-title { font-size: 28rpx; color: #617d73; }
.progress { margin-top: 18rpx; }
.progress-bar { height: 6rpx; border-radius: 6rpx; background: #f0efea; overflow: hidden; }
.progress-fill { height: 100%; border-radius: 6rpx; background: #a5b8ab; }
.progress-text { display: block; margin-top: 10rpx; font-size: 20rpx; color: var(--muted); }
.mship-dates {
margin-top: 22rpx; padding-top: 18rpx; border-top: 1rpx solid #f3efeb;
display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8rpx 20rpx;
font-size: 21rpx; color: var(--muted); line-height: 1.5;
}
.empty-card {
background: #f4f2ed; border-radius: 28rpx; padding: 36rpx 28rpx;
display: flex; flex-direction: column; align-items: flex-start; gap: 12rpx;
}
.empty-card-title { font-size: 28rpx; font-weight: 500; }
.empty-card-sub { font-size: 23rpx; color: var(--muted); line-height: 1.7; }
.empty-card-btn { margin-top: 10rpx; padding: 14rpx 28rpx; border-radius: 999rpx; background: #e4ebe4; }
.empty-card-btn-text { font-size: 24rpx; color: #526e62; }
.upcoming-list { background: #fff; border-radius: 28rpx; padding: 0 28rpx; }
.upcoming-row {
display: flex; align-items: center; justify-content: space-between; gap: 24rpx;
padding: 26rpx 0; border-bottom: 1rpx solid var(--line);
&:last-child { border-bottom: none; }
}
.upcoming-time { flex-shrink: 0; display: flex; flex-direction: column; gap: 10rpx; }
.upcoming-date { font-size: 28rpx; font-weight: 500; }
.upcoming-hour { font-size: 23rpx; color: var(--muted); font-variant-numeric: tabular-nums; }
.upcoming-meta { min-width: 0; display: flex; flex-direction: column; align-items: flex-end; gap: 10rpx; }
.upcoming-card { font-size: 24rpx; text-align: right; overflow-wrap: anywhere; }
.upcoming-status { font-size: 21rpx; color: var(--sage); }
.upcoming-empty { padding: 32rpx 28rpx; background: #f4f2ed; border-radius: 24rpx; }
.upcoming-empty-text { font-size: 24rpx; color: var(--muted); }
.dock {
position: fixed; z-index: 10; left: 0; right: 0; bottom: 0;
display: flex; gap: 20rpx;
padding: 20rpx 32rpx calc(20rpx + env(safe-area-inset-bottom));
background: #fbf9f6; border-top: 1rpx solid var(--line);
}
.dock-btn { flex: 1; height: 88rpx; border-radius: 999rpx; display: flex; align-items: center; justify-content: center; }
.dock-btn--ghost { background: #f0eae4; }
.dock-btn--solid { flex: 1.35; background: #6b8276; }
.dock-btn--disabled { background: #d9dfd8; .dock-btn-text--solid { color: #677467; } }
.dock-btn-text { font-size: 28rpx; font-weight: 500; color: #78675c; }
.dock-btn-text--solid { color: #fff; }
</style>

View File

@@ -0,0 +1,435 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="编辑资料" show-back />
<view v-if="pageLoading" class="loading-wrap">
<text class="loading-text">加载中...</text>
</view>
<view v-else class="form">
<view class="block">
<text class="block-title">基本信息</text>
<view class="field">
<text class="field-label">昵称</text>
<input class="field-input" v-model="profileForm.nickname" maxlength="32" placeholder="会员昵称" />
</view>
<view class="field">
<text class="field-label">手机号</text>
<input class="field-input" v-model="profileForm.phone" maxlength="20" type="number" placeholder="未绑定可手动填写" />
</view>
</view>
<view class="block">
<text class="block-title">{{ editingMembership ? '会员卡' : '开通会员卡' }}</text>
<view v-if="existingMemberships.length > 1" class="field">
<text class="field-label">选择卡片</text>
<picker
class="field-picker"
mode="selector"
:value="membershipIndex"
:range="membershipPickerLabels"
@change="onMembershipPick"
>
<view class="picker-inner">
<text class="picker-text">{{ membershipPickerLabels[membershipIndex] }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view class="field">
<text class="field-label">卡类型</text>
<picker
class="field-picker"
mode="selector"
:value="editForm.cardTypeIndex"
:range="cardTypes"
range-key="name"
@change="onCardTypeChange"
>
<view class="picker-inner">
<text class="picker-text">{{ cardTypes[editForm.cardTypeIndex]?.name || '请选择' }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view v-if="selectedCardType" class="field">
<text class="field-label">
{{ canLeaveTimesEmpty ? '剩余次数(留空不限次)' : '剩余次数' }}
</text>
<input
class="field-input"
type="number"
v-model="editForm.remainingTimes"
:placeholder="canLeaveTimesEmpty ? '留空表示不限次' : '请输入剩余次数'"
/>
</view>
<view class="field">
<text class="field-label">开始日期</text>
<picker class="field-picker" mode="date" :value="editForm.startDate" @change="onStartDateChange">
<view class="picker-inner">
<text class="picker-text">{{ editForm.startDate || '请选择' }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view class="field">
<text class="field-label">到期日期</text>
<picker class="field-picker" mode="date" :value="editForm.expireDate" @change="onExpireDateChange">
<view class="picker-inner">
<text class="picker-text">{{ editForm.expireDate || '请选择' }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view v-if="editingMembership" class="danger-link" @tap="onClearMembership">
<text class="danger-link-text">解除该会员卡</text>
</view>
</view>
<view
class="save-btn"
:class="{ 'save-btn--disabled': submitting }"
@tap="onSave"
>
<text class="save-btn-text">{{ submitting ? '保存中...' : '保存' }}</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { AdminMemberDetail, CardType, MembershipWithCardType } from '@mp-pilates/shared'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { formatDateLocal } from '../../utils/format'
import { getErrorMessage } from '../../utils/auth'
import { useAdminStore } from './stores/admin'
const adminStore = useAdminStore()
const navBarHeight = ref('64px')
const userId = ref('')
const pageLoading = ref(true)
const submitting = ref(false)
const detail = ref<AdminMemberDetail | null>(null)
const cardTypes = ref<CardType[]>([])
const membershipIndex = ref(0)
const profileForm = ref({
nickname: '',
phone: '',
})
const editForm = ref({
membershipId: '' as string | '',
cardTypeIndex: 0,
cardTypeId: '',
remainingTimes: null as number | string | null,
startDate: '',
expireDate: '',
manuallyEditedExpire: false,
})
const existingMemberships = computed(() => detail.value?.memberships ?? [])
const editingMembership = computed(() => existingMemberships.value[membershipIndex.value] ?? null)
const membershipPickerLabels = computed(() =>
existingMemberships.value.map((item) => `${item.cardType.name} · ${item.status}`),
)
const selectedCardType = computed(() => cardTypes.value[editForm.value.cardTypeIndex] ?? null)
const canLeaveTimesEmpty = computed(() => {
const cardType = selectedCardType.value
const membership = editingMembership.value
if (!cardType || cardType.type !== 'DURATION') return false
return cardType.totalTimes === null || (
membership?.cardTypeId === cardType.id && membership.remainingTimes === null
)
})
function calculateExpireDate(startDate: string, durationDays: number): string {
const d = new Date(startDate)
d.setDate(d.getDate() + durationDays)
return formatDateLocal(d)
}
function applyMembership(membership: MembershipWithCardType | null) {
const types = cardTypes.value
if (membership) {
const idx = types.findIndex((item) => item.id === membership.cardTypeId)
editForm.value = {
membershipId: membership.id,
cardTypeIndex: idx >= 0 ? idx : 0,
cardTypeId: membership.cardTypeId,
remainingTimes: membership.remainingTimes,
startDate: membership.startDate.slice(0, 10),
expireDate: membership.expireDate.slice(0, 10),
manuallyEditedExpire: false,
}
return
}
editForm.value = {
membershipId: '',
cardTypeIndex: 0,
cardTypeId: types[0]?.id || '',
remainingTimes: types[0]?.totalTimes ?? null,
startDate: formatDateLocal(new Date()),
expireDate: calculateExpireDate(formatDateLocal(new Date()), types[0]?.durationDays ?? 30),
manuallyEditedExpire: false,
}
}
function onMembershipPick(e: { detail: { value: number } }) {
membershipIndex.value = Number(e.detail.value)
applyMembership(existingMemberships.value[membershipIndex.value] ?? null)
}
function onCardTypeChange(e: { detail: { value: number } }) {
const idx = Number(e.detail.value)
const cardType = cardTypes.value[idx]
if (!cardType) return
editForm.value.cardTypeIndex = idx
editForm.value.cardTypeId = cardType.id
editForm.value.remainingTimes = cardType.totalTimes
if (!editForm.value.manuallyEditedExpire) {
editForm.value.startDate = formatDateLocal(new Date())
editForm.value.expireDate = calculateExpireDate(formatDateLocal(new Date()), cardType.durationDays)
}
}
function onStartDateChange(e: { detail: { value: string } }) {
editForm.value.startDate = e.detail.value
if (!editForm.value.manuallyEditedExpire) {
const cardType = cardTypes.value[editForm.value.cardTypeIndex]
if (cardType) {
editForm.value.expireDate = calculateExpireDate(e.detail.value, cardType.durationDays)
}
}
}
function onExpireDateChange(e: { detail: { value: string } }) {
editForm.value.expireDate = e.detail.value
editForm.value.manuallyEditedExpire = true
}
function parseRemainingTimes(): number | null | undefined {
const rawValue = editForm.value.remainingTimes
if (rawValue === null || (typeof rawValue === 'string' && rawValue.trim() === '')) {
return null
}
const remainingTimes = Number(rawValue)
if (!Number.isInteger(remainingTimes) || remainingTimes < 0) return undefined
return remainingTimes
}
async function loadPage() {
pageLoading.value = true
try {
const [member, types] = await Promise.all([
adminStore.fetchMemberDetail(userId.value),
cardTypes.value.length ? Promise.resolve(cardTypes.value) : adminStore.fetchCardTypes(),
])
detail.value = member
cardTypes.value = [...types]
profileForm.value = {
nickname: member.user.nickname || '',
phone: member.user.phone || '',
}
membershipIndex.value = 0
applyMembership(member.memberships[0] ?? null)
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '加载失败'), icon: 'none' })
} finally {
pageLoading.value = false
}
}
async function onSave() {
if (submitting.value || !userId.value) return
if (!editForm.value.cardTypeId) {
uni.showToast({ title: '请选择卡类型', icon: 'none' })
return
}
const remainingTimes = parseRemainingTimes()
if (remainingTimes === undefined) {
uni.showToast({ title: '剩余次数需为非负整数', icon: 'none' })
return
}
if (remainingTimes === null && !canLeaveTimesEmpty.value) {
uni.showToast({ title: '请输入剩余次数', icon: 'none' })
return
}
submitting.value = true
try {
await adminStore.updateMemberProfile(userId.value, {
nickname: profileForm.value.nickname.trim(),
phone: profileForm.value.phone.trim(),
})
await adminStore.updateUserMembership(userId.value, {
...(editForm.value.membershipId ? { membershipId: editForm.value.membershipId } : {}),
cardTypeId: editForm.value.cardTypeId,
remainingTimes,
startDate: editForm.value.startDate,
expireDate: editForm.value.expireDate,
})
uni.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => uni.navigateBack(), 400)
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '保存失败'), icon: 'none' })
} finally {
submitting.value = false
}
}
function onClearMembership() {
if (!userId.value) return
uni.showModal({
title: '确认解除',
content: '确定要解除当前这张会员卡吗?其他卡不受影响。',
confirmColor: '#C47A7A',
success: async (res) => {
if (!res.confirm) return
const membershipId = editForm.value.membershipId
if (!membershipId) {
uni.showToast({ title: '没有可解除的会员卡', icon: 'none' })
return
}
try {
await adminStore.deleteUserMembership(userId.value, membershipId)
uni.showToast({ title: '已解除', icon: 'success' })
setTimeout(() => uni.navigateBack(), 400)
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '操作失败'), icon: 'none' })
}
},
})
}
onLoad((query) => {
userId.value = String(query?.userId || '')
})
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
loadPage()
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background: $bg-page;
padding-bottom: 80rpx;
}
.loading-wrap {
padding: 80rpx 0;
text-align: center;
}
.loading-text {
font-size: 26rpx;
color: $text-hint;
}
.form {
padding: 24rpx;
}
.block {
background: $bg-card;
border-radius: 20rpx;
padding: 8rpx 24rpx 16rpx;
margin-bottom: 20rpx;
border: 1rpx solid rgba(180, 160, 130, 0.12);
}
.block-title {
display: block;
padding: 20rpx 0 8rpx;
font-size: 22rpx;
letter-spacing: 3rpx;
color: $text-hint;
}
.field {
padding: 20rpx 0;
border-bottom: 1rpx solid rgba(180, 160, 130, 0.1);
&:last-of-type { border-bottom: none; }
}
.field-label {
display: block;
font-size: 24rpx;
color: $text-hint;
margin-bottom: 12rpx;
}
.field-input {
height: 64rpx;
font-size: 30rpx;
color: $text-primary;
}
.field-picker {
display: block;
}
.picker-inner {
display: flex;
align-items: center;
justify-content: space-between;
height: 64rpx;
}
.picker-text {
font-size: 30rpx;
color: $text-primary;
}
.picker-arrow {
font-size: 24rpx;
color: $text-hint;
}
.danger-link {
padding: 20rpx 0 8rpx;
}
.danger-link-text {
font-size: 24rpx;
color: $error-color;
}
.save-btn {
margin-top: 12rpx;
height: 88rpx;
border-radius: 18rpx;
background: $brand-color;
display: flex;
align-items: center;
justify-content: center;
}
.save-btn--disabled { opacity: 0.5; }
.save-btn-text {
font-size: 30rpx;
font-weight: 700;
color: #fff8f0;
}
</style>

View File

@@ -0,0 +1,12 @@
<template><view class="page" :style="{ paddingTop: navBarHeight + 'px' }"><CustomNavBar title="成长档案" show-back /><MemberProgress admin :user-id="userId" :booking-id="bookingId" /></view></template>
<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import MemberProgress from '../../components/MemberProgress.vue'
import { getSystemLayout } from '../../utils/system'
const navBarHeight = getSystemLayout().navBarHeight
const userId = ref(''), bookingId = ref('')
onLoad(query => { userId.value = String(query?.userId || ''); bookingId.value = String(query?.bookingId || '') })
</script>
<style scoped>.page{min-height:100vh;background:#fbf9f6;box-sizing:border-box;}</style>

View File

@@ -0,0 +1,211 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="补录上课" show-back />
<view v-if="loading && !detail" class="state">正在读取会员资料</view>
<view v-else-if="!detail" class="state"><text>{{ loadError || '暂时无法读取会员资料' }}</text><button @tap="load">重新加载</button></view>
<template v-else>
<view v-if="loadError" class="pending-note">{{ loadError }}<button class="reload" :disabled="loading || busy" @tap="load">刷新资料</button></view>
<view class="intro">
<text class="eyebrow">历史课程</text>
<text class="title">补齐每一节练习</text>
<text class="intro-note"> {{ detail.user.nickname || '这位学员' }} 补录已经上完的课程</text>
<view class="current"><text>累计上课</text><text>{{ detail.stats.completedBookings }} </text></view>
</view>
<view v-if="pending" class="pending-note">有一笔补录正在核对请点击下方重试系统会避免重复计入</view>
<view class="form-card">
<text class="label">补录节数</text>
<view class="quantity-row">
<input v-model="quantity" class="quantity-input" type="number" maxlength="3" placeholder="0" :disabled="busy || !!pending" :cursor-spacing="24" />
<text class="unit">节已上课程</text>
</view>
<view class="quick-values"><button v-for="n in [1, 5, 10, 20]" :key="n" :class="{ selected: Number(quantity) === n }" :disabled="busy || !!pending" @tap="quantity = String(n)">{{ n }} </button></view>
<text class="hint">可填写 1999 无需逐节创建预约</text>
</view>
<view class="form-card">
<text class="label">会员卡次数</text>
<view class="options">
<button class="option" :class="{ chosen: !deduct }" :disabled="busy || !!pending" @tap="deduct = false"><text class="option-title">仅补记录</text><text class="option-note">不改变会员卡余额</text></button>
<button class="option" :class="{ chosen: deduct }" :disabled="busy || !!pending" @tap="deduct = true"><text class="option-title">同时扣次</text><text class="option-note">从指定会员卡扣除</text></button>
</view>
<template v-if="deduct">
<text v-if="!cards.length" class="field-error">暂无可扣次的会员卡请选择仅补记录</text>
<picker v-else :range="cardLabels" :value="cardIndex" :disabled="busy || !!pending" @change="cardIndex = Number($event.detail.value)">
<view class="card-picker"><text>{{ cardLabels[cardIndex] || '请选择会员卡' }}</text><text></text></view>
</picker>
<text v-if="selectedCard && validQuantity" class="balance" :class="{ 'field-error': insufficient }">{{ insufficient ? '余额不足请调整节数或更换会员卡' : `扣除 ${count} 次后剩余 ${selectedCard.remainingTimes! - count} ` }}</text>
<text class="hint">过去已扣过的课程请选择仅补记录不限次卡无需扣次</text>
</template>
</view>
<view class="form-card">
<view class="label-row"><text class="label">备注</text><text class="optional">选填</text></view>
<textarea v-model="remark" class="remark" maxlength="200" placeholder="例如:系统启用前已完成的 10 节私教课" :disabled="busy || !!pending" :cursor-spacing="32" />
<text class="hint">{{ remark.length }} / 200</text>
</view>
<view class="summary">
<text class="summary-title">{{ validQuantity ? `累计上课将增加 ${count}` : '填写已完成的课程节数' }}</text>
<text class="hint">记录显示为系统补录不计入本月上课练习天数与最近 30 天网格</text>
</view>
<view class="submit-wrap"><button class="submit" :disabled="busy || loading || !!loadError || (!pending && !canSubmit)" :loading="busy" @tap="submit">{{ busy ? '正在处理' : pending ? '核对并重试补录' : '确认补录' }}</button><text v-if="submitError" class="field-error">{{ submitError }}</text></view>
<view class="history">
<view class="label-row"><text class="label">补录记录</text><text class="optional">{{ records.length }} </text></view>
<LessonSupplementList v-if="records.length" :records="records" editable :busy="busy || !!pending" @revoke="revoke" />
<text v-else class="empty">还没有补录记录</text>
</view>
</template>
</view>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { AdminMemberDetail, CreateLessonSupplementDto, LessonSupplementRecord } from '@mp-pilates/shared'
import CustomNavBar from '../../components/CustomNavBar.vue'
import LessonSupplementList from '../../components/LessonSupplementList.vue'
import { useAdminStore } from './stores/admin'
import { getSystemLayout } from '../../utils/system'
import { HttpRequestError } from '../../utils/request'
import { getErrorMessage } from '../../utils/auth'
const store = useAdminStore()
const navBarHeight = `${getSystemLayout().navBarHeight}px`
const userId = ref('')
const detail = ref<AdminMemberDetail | null>(null)
const records = ref<LessonSupplementRecord[]>([])
const loading = ref(false)
const busy = ref(false)
const loadError = ref('')
const submitError = ref('')
const quantity = ref('')
const remark = ref('')
const deduct = ref(false)
const cardIndex = ref(0)
const pending = ref<CreateLessonSupplementDto | null>(null)
const storageKey = computed(() => `lesson-supplement-pending:${userId.value}`)
const cards = computed(() => (detail.value?.memberships ?? []).filter(c => c.remainingTimes !== null && c.remainingTimes > 0))
const cardLabels = computed(() => cards.value.map(c => `${c.cardType.name} · 余 ${c.remainingTimes}${new Date(c.expireDate) <= new Date() || c.status === 'EXPIRED' ? ' · 已过期' : ''}`))
const selectedCard = computed(() => cards.value[cardIndex.value])
const count = computed(() => Number(quantity.value))
const validQuantity = computed(() => /^\d{1,3}$/.test(quantity.value) && count.value >= 1 && count.value <= 999)
const insufficient = computed(() => !!selectedCard.value && count.value > selectedCard.value.remainingTimes!)
const canSubmit = computed(() => validQuantity.value && (!deduct.value || (!!selectedCard.value && !insufficient.value)))
function clearPending() {
pending.value = null
uni.removeStorageSync(storageKey.value)
}
async function load() {
if (!userId.value) { loadError.value = '缺少会员信息,请返回会员档案'; return }
loading.value = true
loadError.value = ''
try {
const [member, items] = await Promise.all([store.fetchMemberDetail(userId.value), store.fetchLessonSupplements(userId.value)])
detail.value = member
records.value = items
if (pending.value && items.some(item => item.requestId === pending.value!.requestId)) {
clearPending()
quantity.value = ''
remark.value = ''
submitError.value = ''
}
} catch (err) {
loadError.value = getErrorMessage(err, '加载失败,请重试')
if (detail.value) uni.showToast({ title: loadError.value, icon: 'none' })
} finally { loading.value = false }
}
async function submit() {
if (busy.value || loading.value || loadError.value || (!pending.value && !canSubmit.value)) return
busy.value = true
submitError.value = ''
try {
if (!pending.value) {
const result = await uni.showModal({
title: `补录 ${count.value} 节已上课程`,
content: `学员:${detail.value?.user.nickname || '未命名学员'}${deduct.value ? `从「${selectedCard.value.cardType.name}」扣除 ${count.value} 次,剩余 ${selectedCard.value.remainingTimes! - count.value} 次。` : '仅增加上课记录,不扣会员卡次数。'}`,
confirmText: '确认补录', confirmColor: '#617d73',
})
if (!result.confirm) return
const payload: CreateLessonSupplementDto = {
requestId: `supp_${Date.now()}_${Math.random().toString(36).slice(2)}_${Math.random().toString(36).slice(2)}`,
quantity: count.value, ...(deduct.value ? { membershipId: selectedCard.value.id } : {}),
...(remark.value.trim() ? { remark: remark.value.trim() } : {}),
}
// Retain the exact request across timeouts, navigation and application restarts.
uni.setStorageSync(storageKey.value, payload)
pending.value = payload
}
const record = await store.createLessonSupplement(userId.value, pending.value)
if (!records.value.some(item => item.id === record.id)) records.value = [record, ...records.value]
clearPending()
quantity.value = ''
remark.value = ''
uni.showToast({ title: `已补录 ${record.quantity} 节课`, icon: 'success' })
await load()
} catch (err) {
if (err instanceof HttpRequestError && err.statusCode >= 400 && err.statusCode < 500 && err.statusCode !== 408) clearPending()
submitError.value = getErrorMessage(err, '提交失败,请重试')
if (pending.value) submitError.value = '暂未确认提交结果,请核对并重试,不会重复补录。'
} finally { busy.value = false }
}
async function revoke(item: LessonSupplementRecord) {
if (busy.value || pending.value) return
busy.value = true
try {
const result = await uni.showModal({ title: '撤销这笔补录?', content: `累计上课减少 ${item.quantity} 节。${item.deductedTimes ? `向原会员卡返还 ${item.deductedTimes} 次。` : '会员卡余额不变。'}记录会保留为已撤销。`, confirmText: '确认撤销', confirmColor: '#967561' })
if (!result.confirm) return
await store.revokeLessonSupplement(userId.value, item.id)
uni.showToast({ title: '已撤销补录', icon: 'success' })
await load()
} catch (err) { uni.showToast({ title: getErrorMessage(err, '撤销失败,请重试'), icon: 'none' }) }
finally { busy.value = false }
}
onLoad(query => {
userId.value = String(query?.userId || '')
const saved = uni.getStorageSync(storageKey.value) as CreateLessonSupplementDto | undefined
if (saved?.requestId && Number.isInteger(saved.quantity)) {
pending.value = saved
quantity.value = String(saved.quantity)
remark.value = saved.remark || ''
deduct.value = !!saved.membershipId
}
load().then(() => {
if (pending.value?.membershipId) cardIndex.value = cards.value.findIndex(c => c.id === pending.value!.membershipId)
})
})
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; box-sizing: border-box; background: #fbf9f6; color: #514943; padding-bottom: calc(40rpx + env(safe-area-inset-bottom)); }
.intro { margin: 28rpx 32rpx; padding: 32rpx; border-radius: 30rpx; background: #f2e9e3; }
.eyebrow { display: block; font-size: 21rpx; color: #967c69; }
.title { display: block; margin-top: 14rpx; font-size: 38rpx; font-family: 'Songti SC', 'STSong', serif; }
.intro-note { display: block; margin-top: 16rpx; font-size: 24rpx; line-height: 1.7; color: #87786b; overflow-wrap: anywhere; }
.current { display: flex; justify-content: space-between; gap: 20rpx; margin-top: 26rpx; padding-top: 22rpx; border-top: 1rpx solid #e4d8cf; font-size: 24rpx; color: #78675c; }
.form-card { margin: 24rpx 32rpx; padding: 28rpx; border-radius: 26rpx; border: 1rpx solid #eee8e3; background: #fff; }
.label { font-size: 27rpx; font-weight: 500; }
.label-row { display: flex; align-items: center; justify-content: space-between; gap: 20rpx; margin-bottom: 20rpx; }
.optional { font-size: 21rpx; color: #9a9086; }
.quantity-row { display: flex; align-items: baseline; gap: 20rpx; margin-top: 20rpx; }
.quantity-input { width: 180rpx; min-width: 0; height: 92rpx; font-size: 64rpx; color: #617d73; font-variant-numeric: tabular-nums; }
.unit { font-size: 24rpx; color: #8b817b; }
.quick-values { display: flex; gap: 14rpx; margin-top: 20rpx; button { flex: 1; padding: 0; margin: 0; border-radius: 14rpx; font-size: 24rpx; line-height: 64rpx; background: #f5f3ef; color: #81756b; &::after { border: none; } &.selected { background: #e8efe7; color: #617d73; } } }
.hint { display: block; margin-top: 18rpx; color: #92867b; font-size: 22rpx; line-height: 1.7; }
.options { display: flex; gap: 16rpx; margin-top: 22rpx; }
.option { flex: 1; min-width: 0; margin: 0; padding: 22rpx 12rpx; text-align: left; border-radius: 18rpx; border: 2rpx solid #eee8e3; background: #fff; line-height: 1.5; &::after { border: none; } &.chosen { border-color: #a6b8a9; background: #eff3ed; } }
.option-title { display: block; font-size: 26rpx; color: #617d73; }
.option-note { display: block; margin-top: 8rpx; font-size: 20rpx; color: #8b817b; }
.card-picker { display: flex; align-items: center; justify-content: space-between; gap: 16rpx; margin-top: 22rpx; padding: 20rpx; border-radius: 16rpx; background: #f6f3ef; font-size: 24rpx; line-height: 1.6; }
.balance { display: block; margin-top: 16rpx; font-size: 23rpx; color: #617d73; }
.remark { width: 100%; height: 136rpx; box-sizing: border-box; padding: 18rpx; border-radius: 16rpx; background: #faf8f5; font-size: 25rpx; line-height: 1.6; }
.summary { margin: 28rpx 40rpx; }
.summary-title { font-size: 26rpx; color: #617d73; }
.submit-wrap { margin: 28rpx 32rpx; }
.submit { display: block; width: 100%; padding: 0; margin: 0; line-height: 88rpx; border-radius: 999rpx; background: #6b8276; color: #fff; font-size: 28rpx; &::after { border: none; } &[disabled] { background: #e3e8df; color: #8a9586; } }
.history { margin: 44rpx 32rpx 0; }
.empty { display: block; padding: 36rpx 28rpx; border-radius: 24rpx; background: #f3f0eb; font-size: 24rpx; color: #8b817b; }
.field-error { display: block; margin-top: 18rpx; color: #a36e59; font-size: 23rpx; line-height: 1.6; }
.pending-note { margin: 24rpx 32rpx; padding: 24rpx; background: #f2e9e3; color: #8b7160; border-radius: 20rpx; font-size: 24rpx; line-height: 1.7; }
.reload { margin: 16rpx 0 0; font-size: 24rpx; line-height: 2; background: #e5eade; color: #617d73; &::after { border: none; } }
.state { padding: 60rpx 32rpx; font-size: 26rpx; color: #8b817b; text-align: center; button { margin-top: 24rpx; font-size: 26rpx; } }
</style>

View File

@@ -2,12 +2,12 @@
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="会员管理" show-back />
<!-- Search bar -->
<view class="filter-bar">
<view class="search-field">
<input
class="search-input"
v-model="searchQuery"
placeholder="搜索昵称 OpenID"
placeholder="搜索昵称 / 手机 / OpenID"
placeholder-style="color:#bbb"
@confirm="onSearch"
confirm-type="search"
@@ -15,33 +15,43 @@
<view v-if="searchQuery" class="search-clear" @tap="onClear">
<text class="search-clear-icon">×</text>
</view>
</view>
<picker
class="type-picker"
mode="selector"
:value="cardTypeIndex"
:range="cardTypeOptions"
range-key="label"
@change="onCardTypeChange"
>
<view class="type-picker-inner">
<text class="type-picker-text">{{ cardTypeOptions[cardTypeIndex].label }}</text>
<text class="type-picker-arrow"></text>
</view>
</picker>
<view class="search-btn" @tap="onSearch">
<text class="search-btn-text">搜索</text>
</view>
</view>
<!-- Stats row -->
<view class="stats-row">
<view class="stat-item">
<text class="stat-value">{{ total }}</text>
<text class="stat-label">总会员</text>
<text class="stat-label">位用户</text>
</view>
</view>
<!-- Loading skeleton -->
<view v-if="loading && !members.length" class="skeleton-list">
<view v-for="i in 5" :key="i" class="skeleton-item" />
</view>
<!-- Empty -->
<view v-else-if="!loading && !members.length" class="empty-state">
<view class="empty-icon-wrap">
<view class="empty-icon-person" />
</view>
<text class="empty-text">{{ searchQuery ? '未找到匹配的会员' : '暂无会员数据' }}</text>
<text class="empty-text">{{ searchQuery ? '未找到匹配的用户' : '当前筛选下暂无用户' }}</text>
</view>
<!-- Member list -->
<view v-else class="member-list">
<view
v-for="m in members"
@@ -56,8 +66,20 @@
</view>
</view>
<view class="member-info">
<view class="member-name-row">
<text class="member-name">{{ m.nickname || '未知用户' }}</text>
<text class="member-openid">{{ m.openid }}</text>
<view
v-if="m.activeCard"
class="card-chip"
:class="'card-chip--' + m.activeCard.type.toLowerCase()"
>
<text class="card-chip-text">{{ getCardTypeLabel(m.activeCard.type) }}</text>
</view>
<view v-else class="card-chip card-chip--none">
<text class="card-chip-text">无卡</text>
</view>
</view>
<text class="member-sub">{{ m.phone || m.openid }}</text>
</view>
<view class="member-stats">
<text class="member-stat-value">{{ m.totalBookings }}</text>
@@ -67,93 +89,88 @@
</view>
</view>
<!-- Bottom status -->
<view v-if="members.length" class="list-footer">
<text class="list-footer-text">
{{ loading ? '加载中...' : hasMore ? '上拉加载更多' : '— 已加载全部 —' }}
</text>
</view>
<!-- Detail modal -->
<view v-if="showDetail && detailMember" class="modal-mask" @tap.self="showDetail = false">
<view class="modal">
<view class="detail-header">
<view class="detail-avatar">
<image v-if="detailMember.avatarUrl" class="avatar-img" :src="detailMember.avatarUrl" mode="aspectFill" />
<view v-else class="avatar-placeholder avatar-placeholder--lg">
<text class="avatar-text avatar-text--lg">{{ (detailMember.nickname || '?').slice(0, 1) }}</text>
</view>
</view>
<text class="detail-name">{{ detailMember.nickname || '未知用户' }}</text>
<text class="detail-openid" @tap="copyOpenid(detailMember.openid)">
{{ detailMember.openid }}
</text>
<text class="detail-phone">{{ detailMember.phone || '未绑定手机' }}</text>
</view>
<view class="detail-stats">
<view class="detail-stat">
<text class="detail-stat-value">{{ detailMember.totalBookings }}</text>
<text class="detail-stat-label">总预约</text>
</view>
<view class="detail-stat">
<text class="detail-stat-value">{{ detailMember.completedBookings }}</text>
<text class="detail-stat-label">已完成</text>
</view>
<view class="detail-stat">
<text class="detail-stat-value">{{ detailMember.cancelledBookings }}</text>
<text class="detail-stat-label">已取消</text>
</view>
</view>
<view class="modal-close" @tap="showDetail = false">
<text class="modal-close-text">关闭</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { ref, onMounted, onUnmounted } from 'vue'
import { onReachBottom, onShow } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import type { MemberSummary } from '../../stores/admin'
import { getCardTypeLabel } from '../../utils/format'
import { useAdminStore } from './stores/admin'
import type { MemberSummary } from './stores/admin'
const adminStore = useAdminStore()
const navBarHeight = ref('64px')
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
})
const members = ref<MemberSummary[]>([])
const loading = ref(false)
const searchQuery = ref('')
const page = ref(1)
const total = ref(0)
const hasMore = ref(false)
const showDetail = ref(false)
const detailMember = ref<MemberSummary | null>(null)
const LIMIT = 20
const cardTypeOptions = [
{ label: '会员用户', value: 'ACTIVE' },
{ label: '全部用户', value: '' },
{ label: '体验卡', value: 'TRIAL' },
{ label: '次卡', value: 'TIMES' },
{ label: '月卡', value: 'DURATION' },
{ label: '无卡用户', value: 'NONE' },
]
const cardTypeIndex = ref(0)
let requestId = 0
let cardTypeDebounceTimer: ReturnType<typeof setTimeout> | null = null
function onCardTypeChange(e: { detail: { value: number } }) {
cardTypeIndex.value = Number(e.detail.value)
// Invalidate the old filter immediately, including during the debounce window.
requestId++
loading.value = true
members.value = []
total.value = 0
hasMore.value = false
if (cardTypeDebounceTimer) clearTimeout(cardTypeDebounceTimer)
cardTypeDebounceTimer = setTimeout(() => {
loadMembers(true)
cardTypeDebounceTimer = null
}, 300)
}
onUnmounted(() => {
requestId++
if (cardTypeDebounceTimer) clearTimeout(cardTypeDebounceTimer)
})
async function loadMembers(reset = false) {
if (loading.value) return
if (loading.value && !reset) return
const id = ++requestId
const requestedPage = reset ? 1 : page.value + 1
if (reset) {
page.value = 1
members.value = []
total.value = 0
hasMore.value = false
}
loading.value = true
try {
const search = searchQuery.value.trim()
const cardType = cardTypeOptions[cardTypeIndex.value].value
const result = await adminStore.fetchMembers({
page: page.value,
page: requestedPage,
limit: LIMIT,
...(search ? { search } : {}),
...(cardType ? { cardType } : {}),
})
if (id !== requestId) return
page.value = requestedPage
if (reset) {
members.value = [...result.items]
} else {
@@ -162,9 +179,35 @@ async function loadMembers(reset = false) {
total.value = result.total
hasMore.value = members.value.length < result.total
} catch {
uni.showToast({ title: '加载失败', icon: 'none' })
if (id === requestId) uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
loading.value = false
if (id === requestId) loading.value = false
}
}
async function refreshVisibleMembers() {
if (loading.value) return
const id = ++requestId
loading.value = true
try {
const search = searchQuery.value.trim()
const cardType = cardTypeOptions[cardTypeIndex.value].value
const limit = Math.max(members.value.length, LIMIT)
const result = await adminStore.fetchMembers({
page: 1,
limit,
...(search ? { search } : {}),
...(cardType ? { cardType } : {}),
})
if (id !== requestId) return
members.value = [...result.items]
total.value = result.total
page.value = Math.max(1, Math.ceil(members.value.length / LIMIT) || 1)
hasMore.value = members.value.length < result.total
} catch {
if (id === requestId) uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
if (id === requestId) loading.value = false
}
}
@@ -177,26 +220,29 @@ function onClear() {
loadMembers(true)
}
// Scroll to bottom → load next page
onReachBottom(() => {
if (!hasMore.value || loading.value) return
page.value++
loadMembers(false)
})
function openDetail(m: MemberSummary) {
detailMember.value = m
showDetail.value = true
uni.navigateTo({ url: `/pages/admin/member-detail?userId=${m.userId}` })
}
function copyOpenid(openid: string) {
uni.setClipboardData({
data: openid,
success: () => uni.showToast({ title: '已复制 OpenID', icon: 'success' }),
let hasLoaded = false
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
loadMembers(true).then(() => {
hasLoaded = true
})
}
})
onMounted(() => loadMembers(true))
onShow(() => {
if (hasLoaded) {
refreshVisibleMembers()
}
})
</script>
<style lang="scss" scoped>
@@ -206,7 +252,6 @@ onMounted(() => loadMembers(true))
padding-bottom: 40rpx;
}
/* ── Filter bar ──────────────────────────── */
.filter-bar {
display: flex;
align-items: center;
@@ -217,19 +262,27 @@ onMounted(() => loadMembers(true))
position: relative;
}
.search-field {
flex: 1;
min-width: 0;
position: relative;
}
.search-input {
flex: 1;
min-width: 0;
height: 72rpx;
background: $bg-page;
border-radius: 36rpx;
padding: 0 28rpx;
padding: 0 60rpx 0 24rpx;
font-size: 26rpx;
color: $text-primary;
}
.search-clear {
position: absolute;
right: 168rpx;
right: 12rpx;
top: 14rpx;
width: 44rpx;
height: 44rpx;
display: flex;
@@ -251,7 +304,36 @@ onMounted(() => loadMembers(true))
.search-btn-text { font-size: 26rpx; font-weight: 600; color: $accent-color; }
/* ── Stats row ───────────────────────────── */
.type-picker {
flex-shrink: 0;
background: $bg-page;
border-radius: 36rpx;
padding: 0 20rpx;
height: 72rpx;
display: flex;
align-items: center;
}
.type-picker-inner {
display: flex;
align-items: center;
gap: 8rpx;
}
.type-picker-text {
font-size: 24rpx;
color: $text-secondary;
max-width: 120rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.type-picker-arrow {
font-size: 20rpx;
color: $text-hint;
}
.stats-row {
display: flex;
padding: 24rpx 28rpx 16rpx;
@@ -261,7 +343,6 @@ onMounted(() => loadMembers(true))
.stat-value { font-size: 36rpx; font-weight: 800; color: $accent-color; }
.stat-label { font-size: 24rpx; color: $text-hint; }
/* ── Skeleton ────────────────────────────── */
.skeleton-list { padding: 0 24rpx; }
.skeleton-item {
@@ -273,7 +354,6 @@ onMounted(() => loadMembers(true))
animation: shimmer 1.4s infinite;
}
/* ── Empty ───────────────────────────────── */
.empty-state {
display: flex;
flex-direction: column;
@@ -323,7 +403,6 @@ onMounted(() => loadMembers(true))
.empty-text { font-size: 28rpx; color: $text-hint; }
/* ── Member list ─────────────────────────── */
.member-list { padding: 0 24rpx; padding-top: 8rpx; }
.member-row {
@@ -357,124 +436,95 @@ onMounted(() => loadMembers(true))
justify-content: center;
}
.avatar-placeholder--lg {
width: 120rpx;
height: 120rpx;
}
.avatar-text {
font-size: 32rpx;
font-size: 28rpx;
font-weight: 700;
color: $accent-color;
color: $primary-dark;
}
.avatar-text--lg { font-size: 48rpx; }
.member-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6rpx;
gap: 8rpx;
}
.member-name-row {
display: flex;
align-items: center;
gap: 12rpx;
min-width: 0;
}
.member-name {
font-size: 28rpx;
font-weight: 600;
color: $brand-color;
font-size: 30rpx;
font-weight: 700;
color: $text-primary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 280rpx;
}
.member-openid {
.card-chip {
flex-shrink: 0;
padding: 2rpx 12rpx;
border-radius: 8rpx;
background: rgba($accent-color, 0.16);
&--trial { background: rgba(#C47A7A, 0.14); }
&--times { background: rgba($accent-color, 0.16); }
&--duration { background: rgba(#7A9E7E, 0.16); }
&--none { background: rgba($text-hint, 0.12); }
}
.card-chip-text {
font-size: 20rpx;
color: $text-secondary;
letter-spacing: 1rpx;
}
.member-sub {
font-size: 22rpx;
color: $text-hint;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: Menlo, Monaco, Consolas, monospace;
}
.member-stats { display: flex; flex-direction: column; align-items: flex-end; gap: 4rpx; flex-shrink: 0; }
.member-stat-value { font-size: 32rpx; font-weight: 700; color: $accent-color; }
.member-stat-label { font-size: 20rpx; color: $text-hint; }
.member-arrow { font-size: 36rpx; color: $text-hint; transform: scaleX(0.6); }
/* ── List footer ─────────────────────────── */
.list-footer {
text-align: center;
padding: 28rpx 0 16rpx;
}
.list-footer-text { font-size: 24rpx; color: $text-hint; }
/* ── Detail modal ────────────────────────── */
.modal-mask {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: flex-end;
z-index: 100;
}
.modal {
width: 100%;
background: $bg-card;
border-radius: $radius-lg $radius-lg 0 0;
padding: 48rpx 32rpx 60rpx;
}
.detail-header {
.member-stats {
display: flex;
flex-direction: column;
align-items: center;
gap: 12rpx;
margin-bottom: 40rpx;
align-items: flex-end;
flex-shrink: 0;
}
.detail-avatar {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
overflow: hidden;
margin-bottom: 8rpx;
.member-stat-value {
font-size: 32rpx;
font-weight: 800;
color: $text-primary;
font-family: 'DIN Alternate', 'Helvetica Neue', sans-serif;
}
.detail-name { font-size: 32rpx; font-weight: 700; color: $brand-color; }
.member-stat-label {
font-size: 20rpx;
color: $text-hint;
}
.detail-openid {
.member-arrow {
font-size: 32rpx;
color: $text-hint;
flex-shrink: 0;
}
.list-footer {
padding: 16rpx 0 40rpx;
text-align: center;
}
.list-footer-text {
font-size: 22rpx;
color: $accent-color;
font-family: Menlo, Monaco, Consolas, monospace;
padding: 6rpx 16rpx;
background: rgba($accent-color, 0.08);
border-radius: 8rpx;
color: $text-hint;
}
.detail-phone { font-size: 26rpx; color: $text-secondary; }
.detail-stats {
display: flex;
justify-content: space-around;
background: $bg-page;
border-radius: $radius-md;
padding: 28rpx;
margin-bottom: 32rpx;
}
.detail-stat { display: flex; flex-direction: column; align-items: center; gap: 8rpx; }
.detail-stat-value { font-size: 40rpx; font-weight: 800; color: $accent-color; }
.detail-stat-label { font-size: 22rpx; color: $text-hint; }
.modal-close {
width: 100%;
height: 88rpx;
background: $bg-page;
border-radius: 44rpx;
display: flex;
align-items: center;
justify-content: center;
}
.modal-close-text { font-size: 28rpx; color: $text-secondary; }
</style>

View File

@@ -1,5 +1,5 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<view class="page" :style="{ '--status-bar': statusBarHeight + 'px' }">
<CustomNavBar title="订单管理" show-back />
<!-- Summary stats bar -->
@@ -44,7 +44,9 @@
class="list-scroll"
:refresher-enabled="true"
:refresher-triggered="refreshing"
:lower-threshold="120"
@refresherrefresh="onRefresh"
@scrolltolower="loadMore"
>
<!-- Loading skeleton -->
<view v-if="loading && !orders.length" class="order-list">
@@ -106,21 +108,21 @@
</view>
<view class="info-right">
<text class="info-label">下单时间</text>
<text class="info-value">{{ formatDate(order.createdAt) }}</text>
<text class="info-value">{{ formatDateTime(order.createdAt) }}</text>
</view>
</view>
<!-- Paid time if available -->
<view v-if="order.paidAt && order.status === OrderStatus.PAID" class="info-row">
<text class="info-label">支付时间</text>
<text class="info-value">{{ formatDate(order.paidAt) }}</text>
<text class="info-value">{{ formatDateTime(order.paidAt) }}</text>
</view>
</view>
</view>
</view>
<!-- Load more / no more -->
<view v-if="hasMore" class="load-more" @tap="loadMore">
<view v-if="hasMore" class="load-more">
<text class="load-more-text">{{ loading ? '加载中...' : '加载更多' }}</text>
</view>
<view v-else-if="orders.length > 0" class="no-more">
@@ -135,17 +137,19 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import { formatPrice, formatDate } from '../../utils/format'
import { useAdminStore } from './stores/admin'
import { formatPrice, formatDateTime } from '../../utils/format'
import { OrderStatus } from '@mp-pilates/shared'
import type { OrderWithDetails } from '@mp-pilates/shared'
const adminStore = useAdminStore()
const navBarHeight = ref('64px')
// 动态计算顶部模块高度
const statusBarHeight = ref(0)
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
const windowInfo = uni.getWindowInfo()
statusBarHeight.value = windowInfo.statusBarHeight ?? 20
})
const filters = [
@@ -165,6 +169,21 @@ const totalCount = ref<number | null>(null)
const paidCount = ref<number | null>(null)
const pendingCount = ref<number | null>(null)
// 每个 tab 单独缓存数据
const orderCache: Record<string, { items: OrderWithDetails[]; total: number; page: number; hasMore: boolean }> = {}
function getCacheKey(filter: string): string {
return filter || 'all'
}
function getCachedData(filter: string) {
return orderCache[getCacheKey(filter)]
}
function setCachedData(filter: string, data: { items: OrderWithDetails[]; total: number; page: number; hasMore: boolean }) {
orderCache[getCacheKey(filter)] = data
}
const LIMIT = 20
function statusLabel(s: string) {
@@ -191,23 +210,45 @@ function statusAccentClass(s: string) {
}
async function loadOrders(reset = false) {
const filter = activeFilter.value
// 如果有缓存且是重置切换tab直接用缓存数据
if (reset) {
const cached = getCachedData(filter)
if (cached) {
orders.value = [...cached.items]
hasMore.value = cached.hasMore
page.value = cached.page
return
}
}
// 初始加载或下拉刷新,需要请求接口
if (loading.value) return
if (reset) page.value = 1
loading.value = true
try {
const params: { page: number; limit: number; status?: string } = {
page: page.value,
limit: LIMIT,
}
if (activeFilter.value) params.status = activeFilter.value
if (filter) params.status = filter
const result = await adminStore.fetchAdminOrders(params)
if (reset) {
orders.value = [...result.data]
} else {
orders.value.push(...result.data)
}
hasMore.value = orders.value.length < result.total
totalCount.value = result.total
const newItems = reset ? [...result.items] : [...orders.value, ...result.items]
const newHasMore = newItems.length < result.total
// 缓存数据
setCachedData(filter, {
items: newItems,
total: result.total,
page: page.value,
hasMore: newHasMore,
})
orders.value = newItems
hasMore.value = newHasMore
} catch {
uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
@@ -216,30 +257,79 @@ async function loadOrders(reset = false) {
}
}
async function loadSummaryCounts() {
// 初始加载所有分类的数据
async function loadAllFiltersData() {
loading.value = true
try {
const [allResult, paidResult, pendingResult] = await Promise.all([
adminStore.fetchAdminOrders({ page: 1, limit: 1 }),
adminStore.fetchAdminOrders({ page: 1, limit: 1, status: OrderStatus.PAID }),
adminStore.fetchAdminOrders({ page: 1, limit: 1, status: OrderStatus.PENDING }),
// 并行请求所有分类(第一页数据)
const [allResult, paidResult, pendingResult, refundedResult] = await Promise.all([
adminStore.fetchAdminOrders({ page: 1, limit: LIMIT }),
adminStore.fetchAdminOrders({ page: 1, limit: LIMIT, status: OrderStatus.PAID }),
adminStore.fetchAdminOrders({ page: 1, limit: LIMIT, status: OrderStatus.PENDING }),
adminStore.fetchAdminOrders({ page: 1, limit: LIMIT, status: OrderStatus.REFUNDED }),
])
// 缓存全部
setCachedData('', {
items: [...allResult.items],
total: allResult.total,
page: 1,
hasMore: allResult.items.length < allResult.total,
})
totalCount.value = allResult.total
// 缓存已支付
setCachedData(OrderStatus.PAID, {
items: [...paidResult.items],
total: paidResult.total,
page: 1,
hasMore: paidResult.items.length < paidResult.total,
})
paidCount.value = paidResult.total
// 缓存待支付
setCachedData(OrderStatus.PENDING, {
items: [...pendingResult.items],
total: pendingResult.total,
page: 1,
hasMore: pendingResult.items.length < pendingResult.total,
})
pendingCount.value = pendingResult.total
// 缓存已退款
setCachedData(OrderStatus.REFUNDED, {
items: [...refundedResult.items],
total: refundedResult.total,
page: 1,
hasMore: refundedResult.items.length < refundedResult.total,
})
// 设置当前 tab 的数据
orders.value = [...allResult.items]
hasMore.value = allResult.items.length < allResult.total
} catch {
// non-critical, ignore
uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
loading.value = false
refreshing.value = false
}
}
function selectFilter(value: string) {
activeFilter.value = value
totalCount.value = null
loadOrders(true)
// 切换 tab 直接从缓存读取
const cached = getCachedData(value)
if (cached) {
orders.value = [...cached.items]
hasMore.value = cached.hasMore
page.value = cached.page
}
}
async function onRefresh() {
refreshing.value = true
await Promise.all([loadOrders(true), loadSummaryCounts()])
// 下拉刷新重新请求所有分类的数据
await loadAllFiltersData()
}
function loadMore() {
@@ -249,8 +339,7 @@ function loadMore() {
}
onMounted(() => {
loadOrders(true)
loadSummaryCounts()
loadAllFiltersData()
})
</script>
@@ -266,13 +355,18 @@ onMounted(() => {
/* ── Stats bar ──────────────────────────────── */
.stats-bar {
position: fixed;
top: calc(var(--status-bar) + 44px);
left: 0;
right: 0;
display: flex;
align-items: center;
height: 96rpx;
background: #FFFFFF;
padding: 28rpx 0;
margin: 0;
padding: 0;
border-bottom: 1rpx solid rgba(180, 160, 130, 0.2);
box-shadow: 0 2rpx 12rpx rgba(180, 160, 130, 0.08);
z-index: 100;
}
.stat-item {
@@ -309,9 +403,13 @@ onMounted(() => {
/* ── Filter pills ───────────────────────────── */
.filter-wrap {
position: fixed;
top: calc(var(--status-bar) + 92px);
left: 0;
right: 0;
background: #FAF8F5;
border-bottom: 1rpx solid rgba(180, 160, 130, 0.15);
flex-shrink: 0;
z-index: 99;
}
.filter-scroll { overflow: hidden; }
@@ -364,7 +462,11 @@ onMounted(() => {
/* ── List ───────────────────────────────────── */
.list-scroll {
flex: 1;
position: fixed;
top: calc(var(--status-bar) + 144px);
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
}

View File

@@ -0,0 +1,81 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="专业评估" show-back />
<view class="card" v-for="field in fields" :key="field.key">
<text class="name">{{ field.label }} {{ form.observations[field.key] }}/5</text>
<slider :min="1" :max="5" :value="form.observations[field.key]" @change="onObserve(field.key, $event)" />
</view>
<view class="card">
<text class="name">主观紧张 0-10</text>
<slider :min="0" :max="10" :value="form.subjectiveTension || 0" @change="onTension" />
</view>
<view class="card">
<textarea v-model="form.coachSummary" placeholder="教练观察" class="area" />
<textarea v-model="form.trainingFocus" placeholder="训练重点" class="area" />
<textarea v-model="form.phaseGoal" placeholder="第一阶段目标" class="area" />
</view>
<view class="cta" @tap="save">保存评估报告</view>
</view>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from './stores/admin'
import { getErrorMessage } from '../../utils/auth'
import { ProfessionalAssessmentKind } from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const admin = useAdminStore()
const userId = ref('')
const form = reactive({
kind: ProfessionalAssessmentKind.INITIAL,
recordedAt: new Date().toISOString().slice(0, 10),
observations: { headPosition: 3, shoulderPosition: 3, thoracicExtension: 3, shoulderFlexion: 3, breathing: 3, pelvis: 3, coreControl: 3, hipMobility: 3, singleLeg: 3 },
subjectiveTension: 5,
coachSummary: '',
trainingFocus: '',
phaseGoal: '',
})
const fields = [
{ key: 'headPosition', label: '头部位置' },
{ key: 'shoulderPosition', label: '肩部位置' },
{ key: 'thoracicExtension', label: '胸椎活动' },
{ key: 'shoulderFlexion', label: '肩屈活动' },
{ key: 'breathing', label: '呼吸模式' },
{ key: 'pelvis', label: '骨盆位置' },
{ key: 'coreControl', label: '核心控制' },
{ key: 'hipMobility', label: '髋部活动' },
{ key: 'singleLeg', label: '单腿稳定' },
] as const
onLoad((query) => { userId.value = String(query?.userId || '') })
function onObserve(key: keyof typeof form.observations, event: { detail: { value: number } }) {
form.observations[key] = Number(event.detail.value)
}
function onTension(event: { detail: { value: number } }) {
form.subjectiveTension = Number(event.detail.value)
}
async function save() {
try {
await admin.createProfessionalAssessment(userId.value, form)
uni.showToast({ title: '已保存', icon: 'success' })
setTimeout(() => uni.navigateBack(), 400)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '保存失败'), icon: 'none' })
}
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 32rpx 80rpx; }
.card { background: #fff; border-radius: 20rpx; padding: 24rpx; margin-top: 16rpx; }
.name { display: block; font-size: 26rpx; color: #4a4035; margin-bottom: 8rpx; }
.area { width: 100%; min-height: 120rpx; font-size: 26rpx; margin-top: 12rpx; }
.cta { margin-top: 32rpx; height: 88rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; }
</style>

View File

@@ -0,0 +1,67 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="线索详情" show-back />
<view v-if="lead" class="card">
<text class="name">{{ lead.nickname }} · {{ lead.phone || '未留手机' }}</text>
<text class="detail">来源 {{ lead.source || 'organic' }} · {{ lead.campaignId || '无活动' }}</text>
<text class="detail">画像 {{ lead.report?.headline || '尚未生成' }}</text>
</view>
<view v-if="lead?.report" class="card">
<text class="name">五维关注度</text>
<text class="detail">肩颈 {{ lead.report.scores.cervicalShoulder }} · 脊柱 {{ lead.report.scores.spinalMobility }} · 核心 {{ lead.report.scores.coreControl }} · 髋骨盆 {{ lead.report.scores.hipPelvis }} · 下肢 {{ lead.report.scores.lowerLimb }}</text>
</view>
<view v-if="lead?.safetyFlagged" class="card"><text class="name">安全分流</text><text class="detail">不要强推体验课先确认运动条件</text></view>
<view class="card">
<text class="name">首次评估建议</text>
<text v-for="hint in lead?.firstAssessmentHints || []" :key="hint" class="detail"> {{ hint }}</text>
</view>
<view class="card">
<text class="name">跟进文案</text>
<text class="draft">{{ lead?.followUpDraft }}</text>
<view class="cta" @tap="copy">复制 微信发送</view>
</view>
<view class="cta ghost" @tap="goAssess">记录线下评估</view>
<view class="cta ghost" @tap="goPlan">生成 12 周计划</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from './stores/admin'
import type { GrowthLeadDetail } from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const admin = useAdminStore()
const lead = ref<GrowthLeadDetail | null>(null)
const leadId = ref('')
onLoad(async (query) => {
leadId.value = String(query?.id || '')
lead.value = await admin.fetchGrowthLead(leadId.value)
})
function copy() {
if (!lead.value) return
uni.setClipboardData({ data: lead.value.followUpDraft })
}
function goAssess() {
if (!lead.value) return
uni.navigateTo({ url: `/pages/admin/portrait-assessment?userId=${lead.value.userId}` })
}
function goPlan() {
if (!lead.value) return
uni.navigateTo({ url: `/pages/admin/portrait-plan?userId=${lead.value.userId}` })
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 32rpx 80rpx; }
.card { background: #fff; border-radius: 20rpx; padding: 28rpx; margin-top: 16rpx; }
.name { display: block; font-size: 30rpx; color: #4a4035; }
.detail, .draft { display: block; margin-top: 10rpx; color: #7a6a5a; font-size: 24rpx; line-height: 1.7; }
.cta { margin-top: 20rpx; height: 84rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; }
.ghost { background: #efe8e1; color: #5d5148; }
</style>

View File

@@ -0,0 +1,41 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="身体画像线索" show-back />
<view v-for="item in items" :key="item.id" class="card" @tap="open(item.id)">
<text class="name">{{ item.nickname }} · {{ stageLabel(item.stage) }}</text>
<text class="detail">{{ item.phone || '未留手机号' }} · {{ item.source || 'organic' }}</text>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from './stores/admin'
import { GROWTH_LEAD_STAGE_LABELS, type GrowthLeadStage, type GrowthLeadSummary } from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const admin = useAdminStore()
const items = ref<GrowthLeadSummary[]>([])
onShow(async () => {
const result = await admin.fetchGrowthLeads()
items.value = [...result.items]
})
function stageLabel(stage: GrowthLeadStage) {
return GROWTH_LEAD_STAGE_LABELS[stage] || stage
}
function open(id: string) {
uni.navigateTo({ url: `/pages/admin/portrait-lead-detail?id=${id}` })
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 32rpx 40rpx; }
.card { background: #fff; border-radius: 20rpx; padding: 28rpx; margin-top: 16rpx; }
.name { display: block; font-size: 30rpx; color: #4a4035; }
.detail { display: block; margin-top: 8rpx; color: #7a6a5a; font-size: 24rpx; }
</style>

View File

@@ -0,0 +1,46 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="12 周改善计划" show-back />
<text class="lead">生成后学员可在小程序看到三阶段计划而不是 12 节课</text>
<view class="cta" @tap="create">生成计划</view>
<view v-if="plan" class="card">
<text class="name">{{ plan.title }}</text>
<text v-for="phase in plan.phases" :key="phase.id" class="detail">{{ phase.name }} · {{ phase.lessonStart }}-{{ phase.lessonEnd }} </text>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from './stores/admin'
import { getErrorMessage } from '../../utils/auth'
import type { TrainingPlanRecord } from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const admin = useAdminStore()
const userId = ref('')
const plan = ref<TrainingPlanRecord | null>(null)
onLoad((query) => { userId.value = String(query?.userId || '') })
async function create() {
try {
plan.value = await admin.createTrainingPlan(userId.value, { title: '你的 12 周身体改善计划', weeks: 12 })
uni.showToast({ title: '已生成', icon: 'success' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '生成失败'), icon: 'none' })
}
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 32rpx 60rpx; }
.lead { display: block; padding: 24rpx 8rpx; color: #7a6a5a; font-size: 26rpx; line-height: 1.6; }
.cta { height: 88rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; }
.card { margin-top: 24rpx; background: #fff; border-radius: 20rpx; padding: 28rpx; }
.name { display: block; font-size: 30rpx; color: #4a4035; }
.detail { display: block; margin-top: 10rpx; color: #7a6a5a; font-size: 24rpx; }
</style>

View File

@@ -0,0 +1,55 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="今日经营助手" show-back />
<view class="hero">
<text class="title">今天有 {{ dashboard.tasks.length }} 件值得关注的事</text>
</view>
<view v-for="task in dashboard.tasks" :key="task.leadId + task.kind" class="card" @tap="handleTask(task)">
<text class="name">{{ task.title }}</text>
<text class="detail">{{ task.detail }}</text>
</view>
<view class="card">
<text class="name">渠道转化</text>
<text v-for="row in dashboard.funnel" :key="row.source" class="detail">
{{ row.source }} · 测评 {{ row.completed }} · 预约 {{ row.booked }} · 到店 {{ row.attended }} · 成交 {{ row.purchased }}
</text>
</view>
<view class="link" @tap="navigate('/pages/admin/portrait-leads')">全部线索 </view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from './stores/admin'
import type { GrowthTodayDashboard, GrowthTodayTask } from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const admin = useAdminStore()
const dashboard = ref<GrowthTodayDashboard>({ tasks: [], funnel: [] })
onShow(async () => {
dashboard.value = await admin.fetchGrowthToday()
})
function handleTask(task: GrowthTodayTask) {
if (task.kind === 'reassessment_due') {
uni.navigateTo({ url: `/pages/admin/portrait-assessment?userId=${task.userId}` })
} else if (task.leadId && task.leadId.length >= 20) {
uni.navigateTo({ url: `/pages/admin/portrait-lead-detail?id=${task.leadId}` })
}
}
function navigate(path: string) { uni.navigateTo({ url: path }) }
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 32rpx 60rpx; }
.hero { padding: 24rpx 8rpx; }
.title { font-size: 36rpx; color: #4a4035; }
.card { background: #fff; border-radius: 20rpx; padding: 28rpx; margin-bottom: 16rpx; }
.name { display: block; font-size: 30rpx; color: #4a4035; }
.detail { display: block; margin-top: 10rpx; color: #7a6a5a; font-size: 24rpx; line-height: 1.6; }
.link { padding: 24rpx 8rpx; color: #6b8276; }
</style>

View File

@@ -0,0 +1,53 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight + 'px' }">
<CustomNavBar :title="userId ? '学员评价历史' : '课后评价'" show-back />
<view class="content">
<text class="kicker">LISTEN & GROW</text><text class="title">听见每一次练习</text><text class="intro">真实的感受是下一次更好教学的起点</text>
<view v-if="error" class="state">{{ error }}<button @tap="reload">重新加载</button></view>
<template v-else>
<template v-if="!userId && trend.length">
<picker mode="date" fields="month" :value="month" :end="today" @change="changeMonth($event.detail.value)"><view class="month-picker">{{ month }} 教学反馈 <text>切换月份 </text></view></picker>
<view class="summary"><view><text class="number">{{ current?.average ?? '—' }}</text><text>星级均分 / 5</text><text class="muted">{{ current?.count || 0 }} 份评价</text></view><view><text class="number">{{ current?.nps ?? '—' }}</text><text>净推荐值 NPS</text><text class="muted">{{ current?.npsCount || 0 }} 份推荐评分</text></view></view>
<view class="panel"><text class="section-title">近六个月 · 星级均分</text><view class="chart"><view v-for="item in trend" :key="item.month" class="column"><text>{{ item.average ?? '—' }}</text><view class="track"><view class="bar" :style="{ height: ((item.average || 0) / 5 * 100) + '%' }" /></view><text class="muted">{{ item.month.slice(5) }} </text></view></view></view>
<view class="panel"><text class="section-title">推荐意愿趋势</text><view v-for="item in trend" :key="item.month" class="trend-row"><text>{{ item.month }}</text><text>{{ item.nps === null ? '暂无样本' : 'NPS ' + item.nps }}</text><text class="muted">{{ item.npsCount }} 人</text></view><text class="footnote">推荐意愿 910 分为推荐者06 分为贬损者NPS = 推荐者占比 贬损者占比仅统计填写推荐分的评价星级不参与 NPS</text></view>
</template>
<view class="list-heading"><text>评价原声</text><text class="muted">{{ total }} · 按提交时间</text></view>
<view v-if="!rows.length && !loading" class="state">还没有评价<text class="intro">学员完成课程后可在预约详情留下反馈</text></view>
<view v-for="row in rows" :key="row.id" class="panel">
<view class="list-heading"><button class="member" @tap="openMember(row.booking.userId)">{{ row.booking.user.nickname || '学员' }} </button><text class="stars">{{ '★'.repeat(row.rating) }}{{ '☆'.repeat(5 - row.rating) }}</text></view>
<text class="lesson">{{ formatChinaDate(row.booking.timeSlot.date) }} · {{ row.booking.timeSlot.startTime }}{{ row.booking.timeSlot.endTime }}</text>
<view class="tags"><text v-for="tag in row.tags" :key="tag">{{ tag }}</text></view><text class="comment">{{ row.comment || '这位学员留下了星级评分' }}</text>
<view class="list-heading"><text class="muted">{{ formatChinaDate(row.createdAt) }} 提交</text><text v-if="row.recommendation !== null" class="muted">推荐意愿 {{ row.recommendation }} / 10</text></view>
</view>
<view v-if="loading" class="state">正在读取反馈…</view><button v-else-if="rows.length < total" class="more" @tap="loadMore">加载更多</button>
</template>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import type { ReviewEntry, ReviewSummary } from '@mp-pilates/shared'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { formatChinaDate } from '../../utils/format'
import { useAdminStore } from './stores/admin'
const store = useAdminStore(), navBarHeight = getSystemLayout().navBarHeight
const today = new Date(Date.now() + 8 * 3600000).toISOString().slice(0, 10), month = ref(today.slice(0, 7)), userId = ref('')
const rows = ref<ReviewEntry[]>([]), trend = ref<ReviewSummary[]>([]), total = ref(0), page = ref(0), loading = ref(false), error = ref('')
const current = computed(() => trend.value[trend.value.length - 1])
let sequence = 0
async function reload() {
const seq = ++sequence; loading.value = true; error.value = ''
try { const [list, summary] = await Promise.all([store.fetchReviews(userId.value, 1), userId.value ? Promise.resolve([]) : store.fetchReviewTrend(month.value)]); if (seq !== sequence) return; rows.value = list.data; total.value = list.total; page.value = 1; trend.value = summary }
catch (e) { if (seq === sequence) error.value = e instanceof Error ? e.message : '加载失败' } finally { if (seq === sequence) loading.value = false }
}
async function loadMore() { if (loading.value) return; loading.value = true; const seq = sequence; try { const list = await store.fetchReviews(userId.value, page.value + 1); if (seq !== sequence) return; rows.value = [...rows.value, ...list.data]; total.value = list.total; page.value++ } catch { uni.showToast({ title: '加载失败,请重试', icon: 'none' }) } finally { if (seq === sequence) loading.value = false } }
function changeMonth(value: string) { month.value = value.slice(0, 7); void reload() }
function openMember(id: string) { uni.navigateTo({ url: `/pages/admin/member-detail?userId=${id}` }) }
onLoad(query => { userId.value = String(query?.userId || '') })
onShow(() => { void reload() })
</script>
<style lang="scss" scoped>
.page{min-height:100vh;box-sizing:border-box;background:#fbf9f6;color:#514943;}.content{padding:36rpx 32rpx 80rpx;}.kicker{display:block;font-size:21rpx;letter-spacing:4rpx;color:#8b806e;}.title{display:block;font-family:'Songti SC','STSong',serif;font-size:44rpx;margin:22rpx 0 14rpx;}.intro{display:block;font-size:25rpx;color:#8b8174;line-height:1.8;margin-bottom:30rpx;}.month-picker{display:flex;justify-content:space-between;align-items:center;min-height:88rpx;font-size:28rpx;}.month-picker text{font-size:23rpx;color:#728065;}.summary{display:flex;padding:34rpx 0;background:#e9eee3;border:1rpx solid #dce3d3;border-radius:24rpx;margin:12rpx 0 24rpx;}.summary>view{flex:1;text-align:center;border-right:1rpx solid #d2dac9;}.summary>view:last-child{border:0;}.summary text{display:block;font-size:24rpx;line-height:1.8;}.summary .number{font-size:64rpx;font-family:'Baskerville',serif;color:#576b50;line-height:1.2;margin-bottom:10rpx;}.summary .muted,.muted{font-size:22rpx;color:#8b8276;line-height:1.7;}.panel{border:1rpx solid #e6dfd4;border-radius:24rpx;background:#fffdf9;padding:28rpx;margin-bottom:22rpx;}.section-title{font-size:28rpx;}.chart{display:flex;gap:12rpx;margin-top:25rpx;}.column{flex:1;text-align:center;font-size:23rpx;color:#62715c;}.track{height:140rpx;display:flex;align-items:flex-end;justify-content:center;margin:14rpx 0;}.bar{width:34rpx;background:#97aa89;border-radius:6rpx 6rpx 0 0;}.trend-row{display:flex;justify-content:space-between;gap:16rpx;padding:20rpx 0;border-bottom:1rpx solid #eee8df;font-size:24rpx;}.footnote{display:block;font-size:22rpx;line-height:1.8;color:#938575;margin-top:22rpx;}.list-heading{display:flex;align-items:center;justify-content:space-between;gap:16rpx;min-height:50rpx;font-size:29rpx;}.content>.list-heading{margin:34rpx 0 20rpx;}.member{margin:0;padding:0;background:transparent;color:#5f6856;font-size:28rpx;line-height:64rpx;max-width:60%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.member::after,.more::after{border:0;}.stars{font-size:29rpx;color:#ab8951;}.lesson{display:block;font-size:23rpx;color:#928575;margin:10rpx 0 22rpx;}.tags{display:flex;flex-wrap:wrap;gap:12rpx;}.tags text{padding:7rpx 16rpx;font-size:22rpx;border-radius:10rpx;background:#eff1e8;color:#748064;}.comment{display:block;white-space:pre-wrap;overflow-wrap:anywhere;font-size:28rpx;line-height:1.9;margin:22rpx 0;}.state{padding:50rpx 15rpx;text-align:center;font-size:26rpx;color:#8b806f;line-height:1.8;}.more{font-size:26rpx;background:#ebece2;color:#69745b;border-radius:20rpx;line-height:88rpx;}
</style>

View File

@@ -15,7 +15,7 @@
<view v-else-if="editableSlots.length === 0" class="empty-state">
<text class="empty-icon">📭</text>
<text class="empty-text">当日暂无排课</text>
<text class="empty-sub">无模板匹配请手动添加时段或先配置排课模板</text>
<text class="empty-sub">当日暂无默认时段请点击下方按钮手动添加</text>
</view>
<!-- Slot list -->
@@ -40,9 +40,10 @@
<view class="slot-body">
<view class="time-section">
<picker
mode="time"
:value="slot.startTime"
@change="(e: any) => updateSlotTime(slot, 'startTime', e.detail.value)"
mode="multiSelector"
:range="timePickerRange"
:value="timeToPickerIndex(slot.startTime)"
@change="(e: any) => updateSlotTime(slot, 'startTime', pickerIndexToTime(e.detail.value))"
>
<view class="time-display">
<text class="time-text">{{ slot.startTime }}</text>
@@ -50,9 +51,10 @@
</picker>
<text class="time-separator"></text>
<picker
mode="time"
:value="slot.endTime"
@change="(e: any) => updateSlotTime(slot, 'endTime', e.detail.value)"
mode="multiSelector"
:range="timePickerRange"
:value="timeToPickerIndex(slot.endTime)"
@change="(e: any) => updateSlotTime(slot, 'endTime', pickerIndexToTime(e.detail.value))"
>
<view class="time-display">
<text class="time-text">{{ slot.endTime }}</text>
@@ -112,8 +114,9 @@
<view class="modal-field">
<text class="modal-label">开始时间</text>
<picker
mode="time"
:value="addForm.startTime"
mode="multiSelector"
:range="timePickerRange"
:value="timeToPickerIndex(addForm.startTime)"
@change="onAddStartTimeChange"
>
<view class="picker-display">
@@ -157,11 +160,20 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { ScheduleSlotPreview } from '@mp-pilates/shared'
import { TimeSlotStatus } from '@mp-pilates/shared'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import { useAdminStore } from './stores/admin'
import { formatDate } from '../../utils/format'
import DateSelector from '../../components/DateSelector.vue'
import {
SCHEDULE_TIME_PICKER_RANGE,
timeToPickerIndex,
pickerIndexToTime,
addOneHourCapped,
} from './utils/schedule-time'
const timePickerRange = SCHEDULE_TIME_PICKER_RANGE
interface EditableSlot {
readonly key: string
@@ -170,6 +182,7 @@ interface EditableSlot {
endTime: string
capacity: number
bookedCount: number
status: TimeSlotStatus
isPublished: boolean
isNew: boolean
isRemoved: boolean
@@ -186,8 +199,8 @@ const showAddModal = ref(false)
const editableSlots = ref<EditableSlot[]>([])
const addForm = ref({
startTime: '09:00',
endTime: '10:00',
startTime: '09:30',
endTime: '10:30',
capacityStr: '1',
})
@@ -211,6 +224,7 @@ function mapPreviewToEditable(previews: readonly ScheduleSlotPreview[]): Editabl
endTime: p.endTime,
capacity: p.capacity,
bookedCount: p.bookedCount,
status: (p.status ?? TimeSlotStatus.OPEN) as TimeSlotStatus,
isPublished: p.isPublished,
isNew: false,
isRemoved: false,
@@ -270,23 +284,14 @@ function removeSlot(slot: EditableSlot) {
// ── Add slot ──────────────────────────────────────────────
/** 将 "HH:mm" 加一小时,最大 23:59 */
function addOneHour(time: string): string {
const [h, m] = time.split(':').map(Number)
const newH = Math.min(h + 1, 23)
// 如果原本就是 23:xx结束时间设为 23:59
if (h >= 23) return '23:59'
return String(newH).padStart(2, '0') + ':' + String(m).padStart(2, '0')
}
function onAddStartTimeChange(e: any) {
const start = e.detail.value as string
const start = pickerIndexToTime(e.detail.value as number[])
addForm.value.startTime = start
addForm.value.endTime = addOneHour(start)
addForm.value.endTime = addOneHourCapped(start)
}
function openAddModal() {
addForm.value = { startTime: '09:00', endTime: '10:00', capacityStr: '1' }
addForm.value = { startTime: '09:30', endTime: '10:30', capacityStr: '1' }
showAddModal.value = true
}
@@ -305,6 +310,10 @@ function submitAdd() {
uni.showToast({ title: '请选择时间', icon: 'none' })
return
}
if (addForm.value.startTime >= addForm.value.endTime) {
uni.showToast({ title: '结束时间须晚于开始时间', icon: 'none' })
return
}
if (isNaN(capacity) || capacity < 1) {
uni.showToast({ title: '请填写有效容量', icon: 'none' })
return
@@ -317,6 +326,7 @@ function submitAdd() {
endTime: addForm.value.endTime,
capacity,
bookedCount: 0,
status: TimeSlotStatus.OPEN,
isPublished: false,
isNew: true,
isRemoved: false,
@@ -390,21 +400,24 @@ async function doPublish(slots: readonly EditableSlot[]) {
// ── Style helpers ─────────────────────────────────────────
function slotCardClass(slot: EditableSlot): string {
if (slot.status === TimeSlotStatus.CLOSED) return 'slot-card--closed'
if (slot.isNew) return 'slot-card--new'
if (slot.isPublished) return 'slot-card--published'
return 'slot-card--template'
}
function slotBadgeClass(slot: EditableSlot): string {
if (slot.status === TimeSlotStatus.CLOSED) return 'badge--closed'
if (slot.isNew) return 'badge--new'
if (slot.isPublished) return 'badge--published'
return 'badge--template'
}
function slotBadgeText(slot: EditableSlot): string {
if (slot.status === TimeSlotStatus.CLOSED) return '已关闭'
if (slot.isNew) return '新增'
if (slot.isPublished) return '已发布'
return '来自模板'
return '默认时段'
}
// ── Lifecycle ─────────────────────────────────────────────
@@ -489,6 +502,12 @@ onMounted(() => {
border-color: #3498db;
background: rgba(52, 152, 219, 0.04);
}
&--closed {
opacity: 0.55;
background: #fafafa;
border-color: #e5e5e5;
}
}
/* ── Slot header ─────────────────────────── */
@@ -510,6 +529,8 @@ onMounted(() => {
.badge--template .slot-badge-text { font-size: 22rpx; color: #b8860b; font-weight: 600; }
.badge--new { background: rgba(52, 152, 219, 0.1); }
.badge--new .slot-badge-text { font-size: 22rpx; color: #3498db; font-weight: 600; }
.badge--closed { background: rgba(0, 0, 0, 0.06); }
.badge--closed .slot-badge-text { font-size: 22rpx; color: #888; font-weight: 600; }
.booked-info { }
.booked-text { font-size: 22rpx; color: #e67e22; }

View File

@@ -28,7 +28,12 @@
</view>
<view class="form-row">
<text class="form-label">开始时间</text>
<picker mode="time" :value="addForm.startTime" @change="(e: any) => addForm.startTime = e.detail.value">
<picker
mode="multiSelector"
:range="timePickerRange"
:value="timeToPickerIndex(addForm.startTime)"
@change="(e: any) => addForm.startTime = pickerIndexToTime(e.detail.value)"
>
<view class="picker-display">
<text class="picker-text">{{ addForm.startTime || '请选择' }}</text>
<text class="picker-arrow"></text>
@@ -37,7 +42,12 @@
</view>
<view class="form-row">
<text class="form-label">结束时间</text>
<picker mode="time" :value="addForm.endTime" @change="(e: any) => addForm.endTime = e.detail.value">
<picker
mode="multiSelector"
:range="timePickerRange"
:value="timeToPickerIndex(addForm.endTime)"
@change="(e: any) => addForm.endTime = pickerIndexToTime(e.detail.value)"
>
<view class="picker-display">
<text class="picker-text">{{ addForm.endTime || '请选择' }}</text>
<text class="picker-arrow"></text>
@@ -128,7 +138,7 @@
</picker>
</view>
</view>
<text class="gen-hint">根据排课模板自动生成所选日期范围内的时段</text>
<text class="gen-hint">按默认时间表8:00-9:00之后从 9:30 起每小时一节至 21:30自动生成所选日期范围内的时段</text>
<view class="action-wrap">
<view class="action-btn" :class="{ 'action-btn--loading': submitting }" @tap="submitGenerate">
<text class="action-btn-text">{{ submitting ? '生成中...' : '批量生成' }}</text>
@@ -142,9 +152,16 @@
import { ref, onMounted } from 'vue'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import { useAdminStore } from './stores/admin'
import { formatDate } from '../../utils/format'
import type { TimeSlot } from '@mp-pilates/shared'
import {
SCHEDULE_TIME_PICKER_RANGE,
timeToPickerIndex,
pickerIndexToTime,
} from './utils/schedule-time'
const timePickerRange = SCHEDULE_TIME_PICKER_RANGE
const adminStore = useAdminStore()
@@ -157,8 +174,8 @@ const slotsLoading = ref(false)
// ── Add slot form ────────────────────────────────────────────────
const addForm = ref({
date: formatDate(new Date()),
startTime: '09:00',
endTime: '10:00',
startTime: '09:30',
endTime: '10:30',
capacityStr: '10',
})
@@ -168,6 +185,10 @@ async function submitAddSlot() {
uni.showToast({ title: '请填写完整信息', icon: 'none' })
return
}
if (addForm.value.startTime >= addForm.value.endTime) {
uni.showToast({ title: '结束时间须晚于开始时间', icon: 'none' })
return
}
const capacity = parseInt(addForm.value.capacityStr, 10)
submitting.value = true
try {

View File

@@ -0,0 +1,346 @@
import type { ReviewEntry, ReviewSummary } from '@mp-pilates/shared'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { get, post, put, del } from '../../../utils/request'
import type {
TeachingAnalytics,
CardType,
CreateCardTypeDto,
UpdateCardTypeDto,
StudioConfig,
UpdateStudioConfigDto,
OrderWithDetails,
TimeSlot,
CreateManualSlotDto,
PaginatedData,
ScheduleSlotPreview,
PublishDaySlotsDto,
CreateStudioUploadCredentialDto,
StudioUploadCredential,
AdminMemberSummary,
AdminMemberDetail,
LessonSupplementRecord,
CreateLessonSupplementDto,
UpdateAdminMemberProfileDto,
AdminArrangeBookingDto,
MembershipWithCardType,
BookingWithDetails,
GrowthTodayDashboard,
GrowthLeadSummary,
GrowthLeadDetail,
ProfessionalAssessmentSessionRecord,
CreateProfessionalAssessmentDto,
TrainingPlanRecord,
CreateTrainingPlanDto,
} from '@mp-pilates/shared'
interface LegacyPaginatedData<T> {
readonly data: readonly T[]
readonly total: number
readonly page: number
readonly limit: number
}
function normalizePaginatedData<T>(
result: PaginatedData<T> | LegacyPaginatedData<T>,
): PaginatedData<T> {
if ('items' in result) {
return {
items: [...result.items],
total: result.total,
page: result.page,
limit: result.limit,
}
}
return {
items: [...result.data],
total: result.total,
page: result.page,
limit: result.limit,
}
}
export type MemberSummary = AdminMemberSummary
export interface UserMembership {
userId: string
membership: {
id: string
cardTypeId: string
remainingTimes: number | null
startDate: string
expireDate: string
status: string
cardType: {
id: string
name: string
type: string
totalTimes: number | null
durationDays: number
}
} | null
}
export const useAdminStore = defineStore('admin', () => {
async function fetchReviews(userId = '', page = 1) { return get<{ data: ReviewEntry[]; total: number }>('/admin/reviews', { ...(userId ? { userId } : {}), page }) }
async function fetchReviewTrend(month: string) { return get<ReviewSummary[]>('/admin/reviews/trend', { month }) }
// ── Card types ───────────────────────────────────────────────────
const cardTypes = ref<CardType[]>([])
async function fetchCardTypes(): Promise<CardType[]> {
const data = await get<CardType[]>('/admin/card-types')
cardTypes.value = [...data].sort((a, b) => a.sortOrder - b.sortOrder)
return cardTypes.value
}
async function createCardType(dto: CreateCardTypeDto): Promise<CardType> {
const data = await post<CardType>('/admin/card-types', dto as unknown as Record<string, unknown>)
await fetchCardTypes()
return data
}
async function updateCardType(id: string, dto: UpdateCardTypeDto): Promise<CardType> {
const data = await put<CardType>(`/admin/card-types/${id}`, dto as unknown as Record<string, unknown>)
await fetchCardTypes()
return data
}
async function deleteCardType(id: string): Promise<{ deleted: boolean; deactivated: boolean }> {
const result = await del<{ deleted: boolean; deactivated: boolean }>(`/admin/card-types/${id}`)
await fetchCardTypes()
return result
}
// ── Studio config ────────────────────────────────────────────────
const studioConfig = ref<StudioConfig | null>(null)
async function fetchStudioConfig(): Promise<StudioConfig> {
const data = await get<StudioConfig>('/studio/info')
studioConfig.value = data
return data
}
async function saveStudioConfig(dto: UpdateStudioConfigDto): Promise<StudioConfig> {
const data = await put<StudioConfig>('/admin/studio/info', dto as unknown as Record<string, unknown>)
studioConfig.value = data
return data
}
async function createStudioUploadCredential(
dto: CreateStudioUploadCredentialDto,
): Promise<StudioUploadCredential> {
return post<StudioUploadCredential>(
'/admin/studio/upload-credentials',
dto as unknown as Record<string, unknown>,
)
}
// ── Orders ───────────────────────────────────────────────────────
async function fetchAdminOrders(params: {
page?: number
limit?: number
status?: string
}): Promise<PaginatedData<OrderWithDetails>> {
const result = await get<PaginatedData<OrderWithDetails> | LegacyPaginatedData<OrderWithDetails>>(
'/admin/orders',
params,
)
return normalizePaginatedData(result)
}
// ── Bookings ─────────────────────────────────────────────────────
async function fetchAdminBookings(params?: {
page?: number
limit?: number
userId?: string
}): Promise<PaginatedData<any>> {
return get<PaginatedData<any>>('/admin/bookings', params)
}
// ── Members ──────────────────────────────────────────────────────
async function fetchMembers(params?: {
page?: number
limit?: number
search?: string
cardType?: string
}): Promise<PaginatedData<MemberSummary>> {
const cleanParams: Record<string, unknown> = {}
if (params?.page != null) cleanParams.page = params.page
if (params?.limit != null) cleanParams.limit = params.limit
if (params?.search) cleanParams.search = params.search
if (params?.cardType) cleanParams.cardType = params.cardType
return get<PaginatedData<MemberSummary>>('/admin/members', cleanParams)
}
async function getUserMembership(userId: string): Promise<UserMembership> {
return get<UserMembership>(`/admin/members/${userId}/membership`)
}
async function fetchLessonSupplements(userId: string): Promise<LessonSupplementRecord[]> {
return get<LessonSupplementRecord[]>(`/admin/members/${userId}/lesson-supplements`)
}
async function createLessonSupplement(userId: string, dto: CreateLessonSupplementDto): Promise<LessonSupplementRecord> {
return post<LessonSupplementRecord>(`/admin/members/${userId}/lesson-supplements`, { ...dto })
}
async function revokeLessonSupplement(userId: string, id: string): Promise<void> {
await post(`/admin/members/${userId}/lesson-supplements/${id}/revoke`)
}
async function fetchMemberDetail(userId: string): Promise<AdminMemberDetail> {
return get<AdminMemberDetail>(`/admin/members/${userId}`)
}
async function updateMemberProfile(
userId: string,
dto: UpdateAdminMemberProfileDto,
): Promise<AdminMemberDetail> {
return put<AdminMemberDetail>(`/admin/members/${userId}`, dto as unknown as Record<string, unknown>)
}
async function arrangeMemberBooking(dto: AdminArrangeBookingDto): Promise<BookingWithDetails> {
return post<BookingWithDetails>('/admin/bookings', dto as unknown as Record<string, unknown>)
}
async function updateUserMembership(
userId: string,
dto: {
membershipId?: string
cardTypeId: string
remainingTimes?: number | null
startDate: string
expireDate: string
},
): Promise<MembershipWithCardType> {
return put<MembershipWithCardType>(`/admin/members/${userId}/membership`, dto)
}
async function deleteUserMembership(userId: string, membershipId: string): Promise<void> {
return del<void>(
`/admin/members/${userId}/membership?membershipId=${encodeURIComponent(membershipId)}`,
)
}
// ── Time slots ───────────────────────────────────────────────────
async function fetchSlotsByDate(date: string): Promise<TimeSlot[]> {
return get<TimeSlot[]>('/admin/time-slots', { date })
}
async function createManualSlot(dto: CreateManualSlotDto): Promise<TimeSlot> {
return post<TimeSlot>('/admin/time-slot/manual', dto as unknown as Record<string, unknown>)
}
async function closeSlot(id: string): Promise<TimeSlot> {
return put<TimeSlot>(`/admin/time-slot/${id}/close`, {})
}
async function generateSlots(startDate: string, endDate: string): Promise<{ count: number }> {
return post<{ count: number }>('/admin/generate-slots', { startDate, endDate })
}
// ── Schedule management ─────────────────────────────────────────
const schedulePreview = ref<ScheduleSlotPreview[]>([])
const scheduleLoading = ref(false)
async function fetchSchedulePreview(date: string): Promise<ScheduleSlotPreview[]> {
scheduleLoading.value = true
try {
const data = await previewScheduleByDate(date)
schedulePreview.value = data
return data
} finally {
scheduleLoading.value = false
}
}
async function previewScheduleByDate(date: string): Promise<ScheduleSlotPreview[]> {
return get<ScheduleSlotPreview[]>('/admin/schedule/preview', { date })
}
async function publishDaySlots(dto: PublishDaySlotsDto): Promise<void> {
await post('/admin/schedule/publish', dto as unknown as Record<string, unknown>)
await fetchSchedulePreview(dto.date)
}
// ── Teaching analytics ─────────────────────────────────────────
async function fetchTeachingAnalytics(month: string): Promise<TeachingAnalytics> {
return get<TeachingAnalytics>('/admin/teaching-analytics', { month })
}
async function fetchGrowthToday() {
return get<GrowthTodayDashboard>('/admin/growth/today')
}
async function fetchGrowthLeads(params: { page?: number; search?: string; stage?: string } = {}) {
return get<PaginatedData<GrowthLeadSummary>>('/admin/growth/leads', params)
}
async function fetchGrowthLead(id: string) {
return get<GrowthLeadDetail>(`/admin/growth/leads/${id}`)
}
async function createProfessionalAssessment(userId: string, dto: CreateProfessionalAssessmentDto) {
return post<ProfessionalAssessmentSessionRecord>(
`/admin/members/${userId}/professional-assessments`,
dto as unknown as Record<string, unknown>,
)
}
async function createTrainingPlan(userId: string, dto: CreateTrainingPlanDto) {
return post<TrainingPlanRecord>(
`/admin/members/${userId}/training-plans`,
dto as unknown as Record<string, unknown>,
)
}
return {
fetchReviews, fetchReviewTrend,
fetchTeachingAnalytics,
// State
cardTypes,
studioConfig,
schedulePreview,
scheduleLoading,
// Card types
fetchCardTypes,
createCardType,
updateCardType,
deleteCardType,
// Studio
fetchStudioConfig,
saveStudioConfig,
createStudioUploadCredential,
// Orders
fetchAdminOrders,
// Bookings
fetchAdminBookings,
// Members
fetchMembers,
fetchMemberDetail,
fetchLessonSupplements,
createLessonSupplement,
revokeLessonSupplement,
updateMemberProfile,
arrangeMemberBooking,
getUserMembership,
updateUserMembership,
deleteUserMembership,
// Time slots
fetchSlotsByDate,
createManualSlot,
closeSlot,
generateSlots,
// Schedule
fetchSchedulePreview,
previewScheduleByDate,
publishDaySlots,
fetchGrowthToday,
fetchGrowthLeads,
fetchGrowthLead,
createProfessionalAssessment,
createTrainingPlan,
}
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,67 @@
import {
DEFAULT_SCHEDULE_START_TIME,
DEFAULT_SCHEDULE_END_TIME,
SCHEDULE_MINUTE_STEP,
} from '@mp-pilates/shared'
function buildHourOptions(): string[] {
const startHour = parseInt(DEFAULT_SCHEDULE_START_TIME.slice(0, 2), 10)
const endHour = parseInt(DEFAULT_SCHEDULE_END_TIME.slice(0, 2), 10)
const list: string[] = []
for (let h = startHour; h <= endHour; h++) {
list.push(String(h).padStart(2, '0'))
}
return list
}
function buildMinuteOptions(): string[] {
const list: string[] = []
for (let m = 0; m < 60; m += SCHEDULE_MINUTE_STEP) {
list.push(String(m).padStart(2, '0'))
}
return list
}
export const SCHEDULE_HOUR_OPTIONS = buildHourOptions()
export const SCHEDULE_MINUTE_OPTIONS = buildMinuteOptions()
export const SCHEDULE_TIME_PICKER_RANGE = [SCHEDULE_HOUR_OPTIONS, SCHEDULE_MINUTE_OPTIONS]
export function timeToMinutes(time: string): number {
const [h, m] = time.split(':').map(Number)
return h * 60 + (m || 0)
}
export function minutesToTime(total: number): string {
const h = Math.floor(total / 60)
const m = total % 60
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`
}
export function timeToPickerIndex(time: string): number[] {
let total = timeToMinutes(time || DEFAULT_SCHEDULE_START_TIME)
const minTotal = timeToMinutes(DEFAULT_SCHEDULE_START_TIME)
const maxTotal = timeToMinutes(DEFAULT_SCHEDULE_END_TIME)
total = Math.max(minTotal, Math.min(maxTotal, total))
total = Math.round(total / SCHEDULE_MINUTE_STEP) * SCHEDULE_MINUTE_STEP
total = Math.max(minTotal, Math.min(maxTotal, total))
const hour = String(Math.floor(total / 60)).padStart(2, '0')
const minute = String(total % 60).padStart(2, '0')
return [
Math.max(0, SCHEDULE_HOUR_OPTIONS.indexOf(hour)),
Math.max(0, SCHEDULE_MINUTE_OPTIONS.indexOf(minute)),
]
}
export function pickerIndexToTime(value: number[]): string {
const hour = SCHEDULE_HOUR_OPTIONS[value[0]] ?? SCHEDULE_HOUR_OPTIONS[0]
const minute = SCHEDULE_MINUTE_OPTIONS[value[1]] ?? SCHEDULE_MINUTE_OPTIONS[0]
return `${hour}:${minute}`
}
/** 将 "HH:mm" 加一小时,不超过当日最晚结束时间 21:30 */
export function addOneHourCapped(time: string): string {
const next = timeToMinutes(time) + 60
const cap = timeToMinutes(DEFAULT_SCHEDULE_END_TIME)
return minutesToTime(Math.min(next, cap))
}

View File

@@ -0,0 +1,72 @@
import type {
CreateStudioUploadCredentialDto,
StudioAssetType,
StudioUploadCredential,
} from '@mp-pilates/shared'
import type { useAdminStore } from '../stores/admin'
type AdminStore = ReturnType<typeof useAdminStore>
function inferContentType(fileName: string): string | undefined {
const extension = fileName.split('.').pop()?.toLowerCase()
if (extension === 'jpg' || extension === 'jpeg') {
return 'image/jpeg'
}
if (extension === 'png') {
return 'image/png'
}
if (extension === 'webp') {
return 'image/webp'
}
if (extension === 'heic') {
return 'image/heic'
}
if (extension === 'heif') {
return 'image/heif'
}
return undefined
}
function uploadToCos(filePath: string, credential: StudioUploadCredential): Promise<void> {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: credential.uploadUrl,
filePath,
name: 'file',
formData: credential.formData as unknown as Record<string, string>,
success: (result) => {
if (result.statusCode >= 200 && result.statusCode < 300) {
resolve()
return
}
const body = typeof result.data === 'string' ? result.data : JSON.stringify(result.data)
const code = body.match(/<Code>([^<]+)<\/Code>/)?.[1]
const message = body.match(/<Message>([^<]+)<\/Message>/)?.[1]
const detail = code || message ? `${code ?? 'COS'}: ${message ?? body}` : body
reject(new Error(`COS 上传失败 (${result.statusCode}) ${detail}`))
},
fail: (error) => {
reject(new Error(error.errMsg || 'COS 上传失败'))
},
})
})
}
export async function uploadStudioAsset(params: {
adminStore: AdminStore
filePath: string
fileName: string
assetType: StudioAssetType
}): Promise<string> {
const payload: CreateStudioUploadCredentialDto = {
fileName: params.fileName,
contentType: inferContentType(params.fileName),
assetType: params.assetType,
}
const credential = await params.adminStore.createStudioUploadCredential(payload)
await uploadToCos(params.filePath, credential)
return credential.fileUrl
}

View File

@@ -1,528 +0,0 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="排课模板" show-back />
<!-- Toolbar -->
<view class="toolbar">
<text class="toolbar-hint"> {{ templates.length }} 条模板</text>
<view class="add-btn" @tap="openAdd">
<text class="add-btn-text"> 新增时段</text>
</view>
</view>
<!-- Loading skeleton -->
<view v-if="loading" class="skeleton-list">
<view v-for="i in 5" :key="i" class="skeleton-item" />
</view>
<!-- Empty -->
<view v-else-if="!templates.length" class="empty-state">
<text class="empty-icon">📅</text>
<text class="empty-text">暂无模板点击右上角新增</text>
</view>
<!-- Template list grouped by weekday -->
<view v-else>
<view v-for="(group, day) in grouped" :key="day" class="day-group">
<view class="day-header">
<text class="day-label">{{ WEEKDAY_LABELS[Number(day)] }}</text>
<text class="day-count">{{ group.length }} 个时段</text>
</view>
<view
v-for="tpl in group"
:key="tpl.id ?? tpl._key"
class="tpl-row"
:class="{ 'tpl-row--inactive': !tpl.isActive }"
>
<view class="tpl-time">
<text class="tpl-time-text">{{ tpl.startTime }} {{ tpl.endTime }}</text>
<text class="tpl-capacity">{{ tpl.capacity }} </text>
</view>
<view class="tpl-actions">
<view
class="tpl-toggle"
:class="tpl.isActive ? 'toggle--on' : 'toggle--off'"
@tap="toggleTemplate(tpl)"
>
<text class="tpl-toggle-text">{{ tpl.isActive ? '启用' : '停用' }}</text>
</view>
<view class="tpl-edit" @tap="openEdit(tpl)">
<text class="tpl-edit-text">编辑</text>
</view>
<view class="tpl-delete" @tap="deleteTemplate(tpl)">
<text class="tpl-delete-text">删除</text>
</view>
</view>
</view>
</view>
</view>
<!-- Save bar -->
<view v-if="isDirty" class="save-bar">
<view class="save-btn" :class="{ 'save-btn--loading': saving }" @tap="handleSave">
<text class="save-btn-text">{{ saving ? '保存中...' : '保存全部更改' }}</text>
</view>
</view>
<!-- Add / Edit modal -->
<view v-if="showModal" class="modal-mask" @tap.self="closeModal">
<view class="modal">
<text class="modal-title">{{ editTarget ? '编辑时段' : '新增时段' }}</text>
<view class="modal-field">
<text class="modal-label">星期</text>
<picker
mode="selector"
:range="dayOptions"
range-key="label"
:value="form.dayIdx"
@change="(e: any) => form.dayIdx = Number(e.detail.value)"
>
<view class="picker-display">
<text class="picker-text">{{ dayOptions[form.dayIdx].label }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view class="modal-field">
<text class="modal-label">开始时间</text>
<picker
mode="time"
:value="form.startTime"
@change="(e: any) => form.startTime = e.detail.value"
>
<view class="picker-display">
<text class="picker-text">{{ form.startTime || '请选择' }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view class="modal-field">
<text class="modal-label">结束时间</text>
<picker
mode="time"
:value="form.endTime"
@change="(e: any) => form.endTime = e.detail.value"
>
<view class="picker-display">
<text class="picker-text">{{ form.endTime || '请选择' }}</text>
<text class="picker-arrow"></text>
</view>
</picker>
</view>
<view class="modal-field modal-field--last">
<text class="modal-label">容量</text>
<input
class="modal-input"
type="number"
v-model="form.capacityStr"
placeholder="如10"
placeholder-style="color:#bbb"
/>
</view>
<view class="modal-actions">
<view class="modal-cancel" @tap="closeModal">
<text class="modal-cancel-text">取消</text>
</view>
<view class="modal-confirm" @tap="submitForm">
<text class="modal-confirm-text">确认</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import { WEEKDAY_LABELS } from '@mp-pilates/shared'
import type { WeekTemplate } from '@mp-pilates/shared'
type LocalTemplate = Partial<WeekTemplate> & {
_key?: string
dayOfWeek: number
startTime: string
endTime: string
capacity: number
isActive: boolean
}
const adminStore = useAdminStore()
const navBarHeight = ref('64px')
const loading = ref(false)
const saving = ref(false)
const isDirty = ref(false)
const showModal = ref(false)
const editTarget = ref<LocalTemplate | null>(null)
const templates = ref<LocalTemplate[]>([])
const dayOptions = [1, 2, 3, 4, 5, 6, 7].map((d) => ({ label: WEEKDAY_LABELS[d], value: d }))
const form = ref({
dayIdx: 0,
startTime: '08:00',
endTime: '09:00',
capacityStr: '1',
})
const grouped = computed(() => {
const map: Record<number, LocalTemplate[]> = {}
for (const tpl of templates.value) {
if (!map[tpl.dayOfWeek]) map[tpl.dayOfWeek] = []
map[tpl.dayOfWeek].push(tpl)
}
// Sort by day
return Object.fromEntries(
Object.entries(map).sort(([a], [b]) => Number(a) - Number(b)),
)
})
/** 生成默认模板周一到周日8:00-22:00 每小时一个时段 */
function generateDefaultTemplates(): LocalTemplate[] {
const defaults: LocalTemplate[] = []
for (let day = 1; day <= 7; day++) {
for (let hour = 8; hour < 22; hour++) {
const start = String(hour).padStart(2, '0') + ':00'
const end = String(hour + 1).padStart(2, '0') + ':00'
defaults.push({
_key: `default-${day}-${start}`,
dayOfWeek: day,
startTime: start,
endTime: end,
capacity: 1,
isActive: true,
})
}
}
return defaults
}
async function fetchTemplates() {
loading.value = true
try {
const data = await adminStore.fetchWeekTemplates()
if (data.length === 0) {
// No templates yet — pre-fill with defaults
templates.value = generateDefaultTemplates()
isDirty.value = true
} else {
templates.value = data
isDirty.value = false
}
} catch {
uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
loading.value = false
}
}
function openAdd() {
editTarget.value = null
form.value = { dayIdx: 0, startTime: '08:00', endTime: '09:00', capacityStr: '1' }
showModal.value = true
}
function openEdit(tpl: LocalTemplate) {
editTarget.value = tpl
const dayIdx = dayOptions.findIndex((d) => d.value === tpl.dayOfWeek)
form.value = {
dayIdx: dayIdx >= 0 ? dayIdx : 0,
startTime: tpl.startTime,
endTime: tpl.endTime,
capacityStr: String(tpl.capacity),
}
showModal.value = true
}
function closeModal() {
showModal.value = false
editTarget.value = null
}
function submitForm() {
const capacity = parseInt(form.value.capacityStr, 10)
if (!form.value.startTime || !form.value.endTime) {
uni.showToast({ title: '请填写时间', icon: 'none' })
return
}
if (isNaN(capacity) || capacity < 1) {
uni.showToast({ title: '请填写有效容量', icon: 'none' })
return
}
const day = dayOptions[form.value.dayIdx].value
if (editTarget.value) {
const tpl = editTarget.value
tpl.dayOfWeek = day
tpl.startTime = form.value.startTime
tpl.endTime = form.value.endTime
tpl.capacity = capacity
} else {
templates.value.push({
_key: String(Date.now()),
dayOfWeek: day,
startTime: form.value.startTime,
endTime: form.value.endTime,
capacity,
isActive: true,
})
}
isDirty.value = true
closeModal()
}
function toggleTemplate(tpl: LocalTemplate) {
tpl.isActive = !tpl.isActive
isDirty.value = true
}
function deleteTemplate(tpl: LocalTemplate) {
uni.showModal({
title: '确认删除',
content: '删除该时段模板?',
success: (res) => {
if (res.confirm) {
const idx = templates.value.indexOf(tpl)
if (idx >= 0) templates.value.splice(idx, 1)
isDirty.value = true
}
},
})
}
async function handleSave() {
if (saving.value) return
saving.value = true
try {
const payload = templates.value.map((t) => ({
id: t.id,
dayOfWeek: t.dayOfWeek,
startTime: t.startTime,
endTime: t.endTime,
capacity: t.capacity,
isActive: t.isActive,
}))
await adminStore.saveWeekTemplates(payload as any)
isDirty.value = false
uni.showToast({ title: '保存成功', icon: 'success' })
await fetchTemplates()
} catch (e: any) {
uni.showToast({ title: e?.message ?? '保存失败', icon: 'none' })
} finally {
saving.value = false
}
}
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
fetchTemplates()
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background: #f5f3f0;
padding-bottom: 120rpx;
}
/* ── Toolbar ─────────────────────────────── */
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24rpx 24rpx 16rpx;
}
.toolbar-hint { font-size: 24rpx; color: #999; }
.add-btn {
background: #1a1a2e;
border-radius: 32rpx;
padding: 12rpx 28rpx;
}
.add-btn-text { font-size: 26rpx; font-weight: 600; color: $primary-dark; }
/* ── Skeleton ────────────────────────────── */
.skeleton-list { padding: 0 24rpx; }
.skeleton-item {
height: 80rpx;
border-radius: 12rpx;
margin-bottom: 16rpx;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
}
/* ── Empty ───────────────────────────────── */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 100rpx 0;
gap: 20rpx;
}
.empty-icon { font-size: 80rpx; }
.empty-text { font-size: 28rpx; color: #bbb; }
/* ── Day group ───────────────────────────── */
.day-group { margin: 0 24rpx 24rpx; }
.day-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16rpx 8rpx;
}
.day-label { font-size: 28rpx; font-weight: 700; color: #1a1a2e; }
.day-count { font-size: 22rpx; color: #999; }
/* ── Template row ────────────────────────── */
.tpl-row {
background: #ffffff;
border-radius: 12rpx;
padding: 20rpx 24rpx;
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
&--inactive { opacity: 0.5; }
}
.tpl-time { display: flex; flex-direction: column; gap: 6rpx; }
.tpl-time-text { font-size: 28rpx; font-weight: 600; color: #1a1a2e; }
.tpl-capacity { font-size: 22rpx; color: #888; }
.tpl-actions { display: flex; gap: 12rpx; }
.tpl-toggle,
.tpl-edit,
.tpl-delete {
border-radius: 20rpx;
padding: 8rpx 20rpx;
}
.toggle--on { background: rgba(39,174,96,0.12); }
.toggle--on .tpl-toggle-text { font-size: 24rpx; color: #27ae60; }
.toggle--off { background: rgba(230,126,34,0.12); }
.toggle--off .tpl-toggle-text { font-size: 24rpx; color: #e67e22; }
.tpl-edit { background: rgba(26,26,46,0.08); }
.tpl-edit-text { font-size: 24rpx; color: #1a1a2e; }
.tpl-delete { background: rgba(192,57,43,0.08); }
.tpl-delete-text { font-size: 24rpx; color: #c0392b; }
/* ── Save bar ────────────────────────────── */
.save-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 20rpx 24rpx 48rpx;
background: #ffffff;
box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.08);
}
.save-btn {
width: 100%;
height: 96rpx;
border-radius: 48rpx;
background: linear-gradient(90deg, #1a1a2e, #2d2d5e);
display: flex;
align-items: center;
justify-content: center;
&--loading { opacity: 0.6; }
}
.save-btn-text { font-size: 30rpx; font-weight: 700; color: $primary-dark; }
/* ── Modal ───────────────────────────────── */
.modal-mask {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
display: flex;
align-items: flex-end;
z-index: 100;
}
.modal {
width: 100%;
background: #ffffff;
border-radius: 24rpx 24rpx 0 0;
padding: 40rpx 32rpx 60rpx;
}
.modal-title {
font-size: 32rpx;
font-weight: 700;
color: #1a1a2e;
display: block;
margin-bottom: 24rpx;
}
.modal-field {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24rpx 0;
border-bottom: 1rpx solid #f5f5f5;
&--last { border-bottom: none; }
}
.modal-label { font-size: 26rpx; color: #555; width: 140rpx; flex-shrink: 0; }
.modal-input { flex: 1; text-align: right; font-size: 26rpx; color: #222; }
.picker-display { display: flex; align-items: center; gap: 8rpx; }
.picker-text { font-size: 26rpx; color: #222; }
.picker-arrow { font-size: 26rpx; color: #bbb; }
.modal-actions {
display: flex;
gap: 16rpx;
margin-top: 32rpx;
}
.modal-cancel {
flex: 1;
height: 88rpx;
background: #f0f0f0;
border-radius: 44rpx;
display: flex;
align-items: center;
justify-content: center;
}
.modal-cancel-text { font-size: 28rpx; color: #555; }
.modal-confirm {
flex: 2;
height: 88rpx;
background: linear-gradient(90deg, #1a1a2e, #2d2d5e);
border-radius: 44rpx;
display: flex;
align-items: center;
justify-content: center;
}
.modal-confirm-text { font-size: 28rpx; font-weight: 700; color: $primary-dark; }
</style>

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
<template>
<view class="booking-page">
<view class="booking-page" :style="{ height: pageHeight }">
<!-- Status bar spacing -->
<view class="status-bar" :style="{ height: statusBarHeight }" />
@@ -10,15 +10,20 @@
<!-- Date & period filters -->
<view class="filter-header">
<DateSelector v-model="selectedDate" @select="onDateSelect" />
<TimePeriodFilter v-model="selectedPeriod" @change="onPeriodChange" />
<view class="calendar-heading">
<text class="calendar-month">{{ selectedMonthLabel }}</text>
<text class="calendar-hint">选择上课日期</text>
</view>
<DateSelector v-model="selectedDate" variant="soft" @select="onDateSelect" />
<TimePeriodFilter v-model="selectedPeriod" variant="soft" @change="onPeriodChange" />
</view>
<!-- Slot list -->
<scroll-view
class="slot-scroll"
scroll-y
:style="{ height: scrollHeight }"
:scroll-into-view="targetSlotId"
scroll-with-animation
refresher-enabled
:refresher-triggered="refreshing"
@refresherrefresh="onRefresh"
@@ -37,10 +42,7 @@
<!-- Empty state -->
<view v-else-if="filteredSlots.length === 0" class="empty-wrap">
<view class="empty-icon-circle">
<text class="empty-icon-text">📅</text>
</view>
<text class="empty-text">当日暂无可约时段</text>
<text class="empty-text">这个时段还没有课程</text>
<text class="empty-sub">请选择其他日期或时段查看</text>
</view>
@@ -48,19 +50,23 @@
<view v-else class="slot-list">
<!-- Date summary -->
<view class="date-summary">
<text class="date-summary-text">
{{ filteredSlots.length }} 可选时段
</text>
<text class="date-summary-title">{{ selectedDayLabel }}</text>
<text class="date-summary-text">{{ filteredSlots.length }} 个时段</text>
</view>
<SlotCard
<view
v-for="item in filteredSlots"
:id="`slot-${item.id}`"
:key="item.id"
>
<SlotCard
:time-slot="item"
@book="onBookTap"
@cancel="onCancelTap"
@card-tap="onSlotCardTap"
/>
</view>
</view>
<!-- Bottom padding spacer -->
<view class="scroll-bottom-spacer" />
@@ -68,7 +74,8 @@
<!-- Confirm popup -->
<BookingConfirmPopup
:visible="showConfirmPopup"
v-if="showConfirmPopup"
:visible="true"
:time-slot="pendingSlot"
:memberships="userStore.activeMemberships as MembershipWithCardType[]"
@confirm="onConfirmBooking"
@@ -78,18 +85,20 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { ref, computed, onMounted, nextTick, getCurrentInstance } from 'vue'
import { onResize, onShareAppMessage, onShareTimeline, onShow } from '@dcloudio/uni-app'
import type { TimeSlotWithBookingStatus, MembershipWithCardType } from '@mp-pilates/shared'
import { TIME_PERIODS } from '@mp-pilates/shared'
import { BookingStatus, TIME_PERIODS } from '@mp-pilates/shared'
import { useBookingStore } from '../../stores/booking'
import { useUserStore } from '../../stores/user'
import { formatDate } from '../../utils/format'
import { getErrorMessage } from '../../utils/auth'
import { formatDate, isSlotPast } from '../../utils/format'
import { getSystemLayout } from '../../utils/system'
import DateSelector from '../../components/DateSelector.vue'
import TimePeriodFilter from '../../components/TimePeriodFilter.vue'
import SlotCard from '../../components/SlotCard.vue'
import BookingConfirmPopup from '../../components/BookingConfirmPopup.vue'
import { requestBookingCancelSubscriptionMessage } from '../../utils/wechat-subscription'
type PeriodKey = keyof typeof TIME_PERIODS | null
@@ -103,6 +112,10 @@ const selectedPeriod = ref<PeriodKey>(null)
const showConfirmPopup = ref(false)
const pendingSlot = ref<TimeSlotWithBookingStatus | null>(null)
const refreshing = ref(false)
const targetSlotId = ref('')
// 仅在「每次启动首次进入预约 TAB」时自动定位到当前时段及以后
// 切换日期/时段或下拉刷新后不再重置位置,避免打断用户的浏览位置。
const hasAutoScrolled = ref(false)
// ─── 微信分享 ───────────────────────────────────────────────
onShareAppMessage(() => {
@@ -122,33 +135,31 @@ onShareTimeline(() => {
// ─── Layout ───────────────────────────────────────────────
const statusBarHeight = ref('20px')
const scrollHeight = ref('500px')
// Heights of static elements above scroll-view (in rpx, converted to px)
const PAGE_HEADER_RPX = 88 // title bar height
const FILTER_HEADER_RPX = 240 // DateSelector + TimePeriodFilter
const TABBAR_RPX = 100
const pageHeight = ref('100vh')
function updateLayout() {
const { statusBarHeight: statusBarPx, windowWidth } = getSystemLayout()
const ratio = windowWidth / 750
statusBarHeight.value = `${statusBarPx}px`
const headerPx = Math.round(PAGE_HEADER_RPX * ratio)
const filterPx = Math.round(FILTER_HEADER_RPX * ratio)
const tabbarPx = Math.round(TABBAR_RPX * ratio)
// scroll-view fills remaining space: window - statusBar - pageHeader - filters - tabbar
const { windowHeight } = uni.getWindowInfo()
const remaining = windowHeight - statusBarPx - headerPx - filterPx - tabbarPx
scrollHeight.value = `${remaining}px`
statusBarHeight.value = `${getSystemLayout().statusBarHeight}px`
// The mini-program window already excludes its native tab bar. Flex layout
// gives the remaining height to the list as the filters change size.
pageHeight.value = `${uni.getWindowInfo().windowHeight}px`
}
updateLayout()
onResize(updateLayout)
const selectedMonthLabel = computed(() => {
const [year, month] = selectedDate.value.split('-')
return `${year}${Number(month)}`
})
const selectedDayLabel = computed(() => {
const [, month, day] = selectedDate.value.split('-')
return `${Number(month)}${Number(day)} 日的课程`
})
// ─── Filtered slots ───────────────────────────────────────
const filteredSlots = computed<TimeSlotWithBookingStatus[]>(() => {
const slots = bookingStore.slots as TimeSlotWithBookingStatus[]
if (!selectedPeriod.value) return [...slots]
if (!selectedPeriod.value) return slots
const period = TIME_PERIODS[selectedPeriod.value]
return slots.filter((slot) => {
@@ -168,6 +179,94 @@ async function onRefresh() {
refreshing.value = false
}
const instance = getCurrentInstance()
let isAutoScrolling = false
/**
* 轮询等待目标节点在视图层完成挂载与排版
*/
function waitForElement(selector: string, maxRetries = 10, interval = 50): Promise<boolean> {
return new Promise((resolve) => {
let retries = 0
function check() {
const query = instance?.proxy
? uni.createSelectorQuery().in(instance.proxy)
: uni.createSelectorQuery()
const q = query
.select(selector)
.boundingClientRect((data) => {
const node = Array.isArray(data) ? data[0] : data
if (node && node.top !== undefined) {
resolve(true)
} else if (retries < maxRetries) {
retries++
setTimeout(check, interval)
} else {
resolve(false)
}
})
// 触发查询
q['exec']()
}
check()
})
}
// 首次进入时滚动到当天第一个未开始的课程("本时段及以后"
async function scrollToUpcoming() {
if (hasAutoScrolled.value || isAutoScrolling) return
if (bookingStore.loadingSlots) return
const slots = filteredSlots.value
if (slots.length === 0) {
// 列表还没加载出来(加载中或当天无课),不要把「仅一次」用掉。
return
}
const upcomingIndex = slots.findIndex((slot) => !isSlotPast(slot.date, slot.startTime))
if (upcomingIndex === -1) {
// 当天所有课程均已结束,标记已滚动过,留在当前位置
hasAutoScrolled.value = true
return
}
if (upcomingIndex === 0) {
// 本时段及以后的第一个课程正好是列表第 1 项,页面已经在顶部,无需额外滚动
hasAutoScrolled.value = true
return
}
isAutoScrolling = true
const dateWhenStarted = selectedDate.value
const upcoming = slots[upcomingIndex]
const targetId = `slot-${upcoming.id}`
try {
// 等待 Vue 虚拟 DOM 提交并分发 setData
await nextTick()
// 确保原生视图层已完成该节点的挂载与布局排版
const isReady = await waitForElement(`#${targetId}`, 10, 50)
if (!isReady || selectedDate.value !== dateWhenStarted) {
// 节点尚未在视图层就绪(例如 Tab 处于后台未完成渲染)或用户已切换日期,不锁定 hasAutoScrolled留待 onShow 或后续就绪时执行
return
}
if (targetSlotId.value === targetId) {
targetSlotId.value = ''
await new Promise((resolve) => setTimeout(resolve, 50))
if (selectedDate.value !== dateWhenStarted) return
}
targetSlotId.value = targetId
hasAutoScrolled.value = true
} finally {
isAutoScrolling = false
}
}
// ─── Event handlers ───────────────────────────────────────
function onDateSelect(date: string) {
selectedDate.value = date
@@ -175,11 +274,36 @@ function onDateSelect(date: string) {
}
function onPeriodChange(_period: PeriodKey) {
// Filtering is done client-side via computed property
// No-op: filtering is done client-side via computed property
void _period
}
// ─── Card tap → navigate to detail ───────────────────────
function onSlotCardTap(slot: TimeSlotWithBookingStatus) {
if (slot.isBookedByMe && slot.myBookingId) {
// Already booked → show booking detail
uni.navigateTo({ url: `/pages/booking/detail?id=${slot.myBookingId}` })
} else {
// Not booked → show slot preview with booking action
uni.navigateTo({ url: `/pages/booking/detail?slotId=${slot.id}&date=${slot.date}` })
}
}
// ─── Book flow ────────────────────────────────────────────
async function onBookTap(slot: TimeSlotWithBookingStatus) {
if (slot.isBookedByMe) {
if (slot.myBookingId) {
uni.navigateTo({ url: `/pages/booking/detail?id=${slot.myBookingId}` })
return
}
const title = slot.myBookingStatus === BookingStatus.PENDING_CONFIRMATION
? '该时段已预约,等待老师确认'
: '该时段已预约'
uni.showToast({ title, icon: 'none' })
return
}
// 1. Ensure logged in
if (!userStore.loggedIn) {
uni.showModal({
@@ -189,12 +313,12 @@ async function onBookTap(slot: TimeSlotWithBookingStatus) {
success: async (res) => {
if (res.confirm) {
try {
await userStore.login()
await userStore.fetchMemberships()
// Retry booking flow after login
const { isNewUser } = await userStore.loginWithSetup()
if (!isNewUser) {
onBookTap(slot)
} catch {
uni.showToast({ title: '登录失败', icon: 'none' })
}
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '登录失败'), icon: 'none' })
}
}
},
@@ -211,7 +335,9 @@ async function onBookTap(slot: TimeSlotWithBookingStatus) {
cancelText: '取消',
success: (res) => {
if (res.confirm) {
uni.navigateTo({ url: '/pages/store/index' })
// Switch to home tab and auto-scroll to card shop
uni.$emit('scrollToCardShop')
uni.switchTab({ url: '/pages/home/index' })
}
},
})
@@ -243,6 +369,12 @@ async function onConfirmBooking(payload: { timeSlotId: string; membershipId: str
async function onCancelTap(slot: TimeSlotWithBookingStatus) {
if (!slot.myBookingId) return
try {
await requestBookingCancelSubscriptionMessage()
} catch (err: unknown) {
console.warn('[subscribe] cancel pre-subscribe failed', err)
}
uni.showModal({
title: '取消预约',
content: '确定要取消这个预约吗?',
@@ -269,182 +401,52 @@ async function onCancelTap(slot: TimeSlotWithBookingStatus) {
// ─── Lifecycle ────────────────────────────────────────────
onMounted(async () => {
const tasks: Promise<unknown>[] = [loadSlots(selectedDate.value)]
// Load memberships if logged in but not yet fetched
if (userStore.loggedIn && userStore.activeMemberships.length === 0) {
await userStore.fetchMemberships()
tasks.push(userStore.fetchMemberships())
}
await Promise.all(tasks)
// 首次进入:自动定位到当天本时段及以后的第一个课程
await scrollToUpcoming()
})
onShow(async () => {
// 如果首次进入时页面在后台预加载完成,或从其他 Tab 切入时定位未生效,在页面可见时触发定位
if (!hasAutoScrolled.value && filteredSlots.value.length > 0 && !bookingStore.loadingSlots) {
await scrollToUpcoming()
}
// Load today's slots
await loadSlots(selectedDate.value)
})
</script>
<style lang="scss" scoped>
.booking-page {
height: 100vh;
background: $primary-bg;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* ── Status bar ───────────────────────────────────── */
.status-bar {
flex-shrink: 0;
background: #fff;
}
/* ── Page header ──────────────────────────────────── */
.page-header {
flex-shrink: 0;
height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
}
.page-title {
font-size: 34rpx;
font-weight: 600;
color: #1a1a2e;
}
/* ── Filter header ────────────────────────────────── */
.filter-header {
flex-shrink: 0;
background: #fff;
box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
}
/* ── Scroll container ──────────────────────────────── */
.slot-scroll {
flex: 1;
width: 100%;
box-sizing: border-box;
}
/* ── Slot list ─────────────────────────────────────── */
.slot-list {
display: flex;
flex-direction: column;
gap: 20rpx;
padding: 24rpx 24rpx 0;
}
/* ── Date summary ──────────────────────────────────── */
.date-summary {
padding: 0 8rpx 4rpx;
}
.date-summary-text {
font-size: 24rpx;
color: #999;
font-weight: 400;
}
/* ── Loading skeleton ──────────────────────────────── */
.loading-wrap {
display: flex;
flex-direction: column;
gap: 20rpx;
padding: 28rpx 24rpx;
}
.skeleton-card {
height: 140rpx;
border-radius: 24rpx;
background: #fff;
display: flex;
flex-direction: row;
align-items: center;
padding: 32rpx 28rpx 32rpx 36rpx;
gap: 24rpx;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
}
.skeleton-time {
width: 80rpx;
height: 72rpx;
border-radius: 12rpx;
background: linear-gradient(90deg, $primary-border 25%, $primary-light 50%, $primary-border 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
flex-shrink: 0;
}
.skeleton-body {
flex: 1;
display: flex;
flex-direction: column;
gap: 12rpx;
}
.skeleton-title {
width: 60%;
height: 28rpx;
border-radius: 8rpx;
background: linear-gradient(90deg, $primary-border 25%, $primary-light 50%, $primary-border 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
}
.skeleton-sub {
width: 40%;
height: 20rpx;
border-radius: 6rpx;
background: linear-gradient(90deg, $primary-border 25%, $primary-light 50%, $primary-border 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
}
.skeleton-btn {
width: 140rpx;
height: 72rpx;
border-radius: 36rpx;
background: linear-gradient(90deg, $primary-border 25%, $primary-light 50%, $primary-border 75%);
background-size: 400% 100%;
animation: shimmer 1.4s infinite;
flex-shrink: 0;
}
/* ── Empty state ───────────────────────────────────── */
.empty-wrap {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 140rpx 40rpx;
gap: 16rpx;
}
.empty-icon-circle {
width: 140rpx;
height: 140rpx;
border-radius: 50%;
background: $primary-border;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 16rpx;
}
.empty-icon-text {
font-size: 56rpx;
}
.empty-text {
font-size: 30rpx;
color: #666;
font-weight: 600;
}
.empty-sub {
font-size: 26rpx;
color: #bbb;
}
/* ── Bottom spacer ─────────────────────────────────── */
.scroll-bottom-spacer {
height: 48rpx;
.booking-page { height: 100vh; background: #fbf9f6; display: flex; flex-direction: column; overflow: hidden; }
.status-bar { flex-shrink: 0; }
.page-header { flex-shrink: 0; height: 88rpx; display: flex; align-items: center; justify-content: center; }
.page-title { font-size: 34rpx; font-weight: 500; color: #514943; }
.filter-header { flex-shrink: 0; border-bottom: 1rpx solid #eee8e3; }
.calendar-heading { display: flex; align-items: baseline; justify-content: space-between; padding: 24rpx 32rpx 16rpx; gap: 16rpx; }
.calendar-month { font-size: 28rpx; font-weight: 500; color: #514943; }
.calendar-hint { font-size: 22rpx; color: #8b817b; }
.slot-scroll { flex: 1; height: 0; min-height: 0; width: 100%; box-sizing: border-box; }
.slot-list { display: flex; flex-direction: column; padding-top: 28rpx; }
.date-summary { display: flex; justify-content: space-between; align-items: baseline; gap: 16rpx; padding: 0 32rpx 20rpx; }
.date-summary-title { font-size: 25rpx; color: #6f655e; }
.date-summary-text { font-size: 22rpx; color: #8b817b; }
.loading-wrap { display: flex; flex-direction: column; gap: 20rpx; padding: 28rpx 32rpx; }
.skeleton-card { height: 200rpx; box-sizing: border-box; border-radius: 28rpx; background: #fff; display: flex; align-items: center; padding: 28rpx; gap: 20rpx; }
.skeleton-time, .skeleton-title, .skeleton-sub, .skeleton-btn {
border-radius: 10rpx;
background: linear-gradient(90deg, #f0eae5 25%, #faf7f3 50%, #f0eae5 75%);
background-size: 400% 100%; animation: shimmer 1.4s infinite;
}
.skeleton-time { width: 90rpx; height: 70rpx; flex-shrink: 0; }
.skeleton-body { flex: 1; display: flex; flex-direction: column; gap: 12rpx; }
.skeleton-title { width: 80%; height: 28rpx; }
.skeleton-sub { width: 60%; height: 20rpx; }
.skeleton-btn { width: 110rpx; height: 60rpx; border-radius: 999rpx; flex-shrink: 0; }
.empty-wrap { margin: 32rpx; padding: 64rpx 28rpx; border-radius: 28rpx; background: #f3efea; display: flex; flex-direction: column; align-items: center; gap: 14rpx; }
.empty-text { font-size: 28rpx; color: #6f655e; font-weight: 400; }
.empty-sub { font-size: 23rpx; color: #8b817b; text-align: center; line-height: 1.6; }
.scroll-bottom-spacer { height: 28rpx; }
</style>

File diff suppressed because it is too large Load Diff

View File

@@ -1,58 +1,43 @@
<template>
<view class="home-page" :style="pageStyle">
<!-- Custom nav bar -->
<CustomNavBar title="场馆首页" />
<!-- Pull-to-refresh wrapper -->
<scroll-view
class="page-scroll"
scroll-y
:refresher-enabled="true"
:refresher-triggered="refreshing"
@refresherrefresh="handleRefresh"
@refresherrestore="refreshing = false"
>
<!-- Brand Banner (hero with bg image + centered logo) -->
<view class="home-page" :style="{ height: pageHeight }">
<view class="banner-fixed">
<BrandBanner :studio-info="studioStore.studioInfo" />
<!-- Studio Info (photo strip + address/phone) -->
<StudioInfo :studio-info="studioStore.studioInfo" />
<!-- Divider -->
<view class="section-divider" />
<!-- Quick Entry (login / trial / book / renew) -->
</view>
<scroll-view class="page-scroll" scroll-y :scroll-into-view="scrollTarget"
scroll-with-animation refresher-enabled :refresher-triggered="refreshing"
@refresherrefresh="handleRefresh" @refresherrestore="refreshing = false">
<view class="banner-spacer" />
<view class="floating-card">
<view class="card-handle"><view class="card-handle-bar" /></view>
<QuickEntry @scroll-to-card-shop="scrollToCardShop" />
<!-- Upcoming Bookings -->
<UpcomingBooking />
<!-- Card Shop (vertical list) -->
<ReviewSummaryCard />
<StudioInfo :studio-info="studioStore.studioInfo" />
<view :id="cardShopAnchorId">
<CardShop ref="cardShopRef" />
</view>
<!-- Bottom padding for tab bar -->
<AboutSection />
<view class="bottom-padding" />
</view>
</scroll-view>
</view>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { ref, nextTick, onUnmounted } from 'vue'
import { onShow, onResize, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import BrandBanner from '../../components/BrandBanner.vue'
import ReviewSummaryCard from '../../components/ReviewSummaryCard.vue'
import StudioInfo from '../../components/StudioInfo.vue'
import QuickEntry from '../../components/QuickEntry.vue'
import UpcomingBooking from '../../components/UpcomingBooking.vue'
import CardShop from '../../components/CardShop.vue'
import AboutSection from '../../components/AboutSection.vue'
import { useUserStore } from '../../stores/user'
import { useStudioStore } from '../../stores/studio'
import { useBookingStore } from '../../stores/booking'
import { getSystemLayout } from '../../utils/system'
const userStore = useUserStore()
const studioStore = useStudioStore()
@@ -75,28 +60,33 @@ onShareTimeline(() => {
})
// ─── Layout ───────────────────────────────────────────────
const navBarHeight = ref('64px')
function updateLayout() {
const { statusBarHeight: statusBarPx, windowWidth, navBarHeight: navBarPx } = getSystemLayout()
const ratio = windowWidth / 750
const navTitlePx = 88 * ratio
navBarHeight.value = `${navBarPx}px`
}
updateLayout()
const pageStyle = computed(() => ({
'--nav-bar-height': navBarHeight.value,
}))
const refreshing = ref(false)
const cardShopRef = ref<InstanceType<typeof CardShop> | null>(null)
const cardShopAnchorId = 'card-shop-anchor'
const scrollTarget = ref('')
const pageHeight = ref(`${uni.getWindowInfo().windowHeight}px`)
onResize(() => { pageHeight.value = `${uni.getWindowInfo().windowHeight}px` })
const pendingScrollToCardShop = ref(false)
// Listen for cross-page scroll request (e.g. from booking page "去购买")
uni.$on('scrollToCardShop', () => {
pendingScrollToCardShop.value = true
})
onUnmounted(() => {
uni.$off('scrollToCardShop')
})
// Refresh all data on every show
onShow(async () => {
await refreshData()
// If another page requested scroll to card shop, execute after data is ready
if (pendingScrollToCardShop.value) {
pendingScrollToCardShop.value = false
await nextTick()
scrollToCardShop()
}
})
async function refreshData() {
@@ -104,6 +94,7 @@ async function refreshData() {
if (userStore.loggedIn) {
tasks.push(
userStore.fetchProfile(),
userStore.fetchMemberships(),
bookingStore.fetchUpcomingBookings(),
)
@@ -112,7 +103,9 @@ async function refreshData() {
await Promise.allSettled(tasks)
// Also refresh card shop
cardShopRef.value?.fetchCardTypes()
await Promise.allSettled([
cardShopRef.value?.fetchCardTypes(),
])
}
async function handleRefresh() {
@@ -124,31 +117,30 @@ async function handleRefresh() {
}
}
function scrollToCardShop() {
uni.pageScrollTo({
selector: `#${cardShopAnchorId}`,
duration: 300,
})
async function scrollToCardShop() {
scrollTarget.value = ''
await nextTick()
scrollTarget.value = cardShopAnchorId
}
</script>
<style lang="scss" scoped>
.home-page {
.home-page { position: relative; height: 100vh; background: #fbf9f6; }
.banner-fixed { position: fixed; top: 0; left: 0; width: 100%; z-index: 0; }
.page-scroll { position: relative; z-index: 1; height: 100%; }
.banner-spacer { height: 420rpx; }
.floating-card {
position: relative;
min-height: 100vh;
background: #FAF8F5;
padding-top: var(--nav-bar-height);
}
.page-scroll {
height: calc(100vh - var(--nav-bar-height));
}
.section-divider {
height: 16rpx;
background: #FAF8F5;
}
.bottom-padding {
height: 120rpx;
padding-top: 12rpx;
border-radius: 32rpx 32rpx 0 0;
border-top: 1rpx solid rgba(255, 255, 255, 0.7);
background: linear-gradient(180deg, rgba(251, 249, 246, 0.86), #fbf9f6 260rpx);
-webkit-backdrop-filter: blur(16px);
backdrop-filter: blur(16px);
box-shadow: 0 -4rpx 20rpx rgba(66, 54, 45, 0.06);
}
.card-handle { display: flex; justify-content: center; padding: 16rpx 0 8rpx; }
.card-handle-bar { width: 64rpx; height: 8rpx; border-radius: 4rpx; background: rgba(112, 94, 79, 0.18); }
.bottom-padding { height: 48rpx; }
</style>

View File

@@ -0,0 +1,45 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="日常建议" show-back />
<SafetyNotice v-if="report?.safety.flagged" :message="report.safety.message || ''" />
<view v-else-if="report?.advice">
<text class="title">给你的三个日常建议</text>
<view v-for="item in report.advice.items" :key="item.title" class="card">
<text class="name">{{ item.title }}</text>
<text class="body">{{ item.detail }}</text>
<text class="stop">如出现{{ item.stopIf }}</text>
</view>
</view>
<text class="disclaimer">这些建议用于日常活动参考不能替代现场评估</text>
<view class="cta" @tap="next">了解线上画像的局限</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { onShow } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import SafetyNotice from '../../components/SafetyNotice.vue'
import { getSystemLayout } from '../../utils/system'
import { useBodyPortraitStore } from '../../stores/body-portrait'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const portrait = useBodyPortraitStore()
const { report } = storeToRefs(portrait)
onShow(() => { portrait.track('advice_viewed') })
function next() {
uni.navigateTo({ url: '/pages/portrait/trial' })
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 40rpx 120rpx; }
.title { display: block; font-size: 40rpx; color: #4a4035; margin: 12rpx 0 24rpx; }
.card { background: #fff; border-radius: 24rpx; padding: 28rpx; margin-bottom: 20rpx; }
.name { display: block; font-size: 30rpx; color: #4a4035; }
.body, .stop, .disclaimer { display: block; margin-top: 12rpx; color: #7a6a5a; font-size: 26rpx; line-height: 1.7; }
.cta { margin-top: 32rpx; height: 92rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; }
</style>

View File

@@ -0,0 +1,156 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="身体状态评估" show-back />
<PortraitProgress :step="step + 1" :total="steps.length" />
<text class="q">{{ current.title }}</text>
<text class="d">{{ current.hint }}</text>
<BodySilhouette v-if="current.body" :selected="bodyValue" @change="onBody" />
<view v-else class="options">
<view
v-for="option in current.options"
:key="option.value"
class="opt"
:class="{ on: isOn(option.value) }"
@tap="pick(option.value)"
>
{{ option.label }}
</view>
</view>
<text class="disclaimer">非医疗诊断仅用于运动训练参考</text>
<view class="nav">
<view v-if="step > 0" class="ghost" @tap="step -= 1">上一步</view>
<view class="next" @tap="next">{{ step === steps.length - 1 ? '生成画像' : '继续' }}</view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import BodySilhouette from '../../components/BodySilhouette.vue'
import PortraitProgress from '../../components/PortraitProgress.vue'
import { getSystemLayout } from '../../utils/system'
import { getErrorMessage } from '../../utils/auth'
import { useBodyPortraitStore } from '../../stores/body-portrait'
import {
AFTER_SITTING_LABELS,
AfterSitting,
BodyRegion,
EXERCISE_FREQ_LABELS,
ExerciseFreq,
PORTRAIT_GOAL_LABELS,
PortraitGoal,
SAFETY_FLAG_LABELS,
SafetyFlag,
SITTING_HOURS_LABELS,
SittingHours,
STANDING_NOTICE_LABELS,
StandingNotice,
WORK_POSTURE_LABELS,
WorkPosture,
} from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const portrait = useBodyPortraitStore()
const step = ref(0)
const steps = [
{ key: 'concerns', title: '最近身体哪里最困扰你?', hint: '可以多选,我们会据此调整后面的问题。', body: true },
{ key: 'goal', title: '如果训练有效果,你最希望看到什么变化?', hint: '后面的报告会用你自己的目标来写。', options: enumOptions(PORTRAIT_GOAL_LABELS) },
{ key: 'sittingHours', title: '每天坐多久?', hint: '这能帮助理解当前身体状态是怎么形成的。', options: enumOptions(SITTING_HOURS_LABELS) },
{ key: 'exerciseFreq', title: '平时运动频率?', hint: '没有对错,如实选择即可。', options: enumOptions(EXERCISE_FREQ_LABELS) },
{ key: 'workPosture', title: '工作时最常见状态?', hint: '选最常出现的一种。', options: enumOptions(WORK_POSTURE_LABELS) },
{ key: 'endOfDayFatigue', title: '一天结束后,身体哪里最累?', hint: '可以和困扰区域不同。', body: true },
{ key: 'afterSitting', title: '长时间坐着后,你会出现?', hint: '可多选。', options: enumOptions(AFTER_SITTING_LABELS), multi: true },
{ key: 'standingNotice', title: '自然站立时,你有没有注意过?', hint: '用日常语言描述,不需要专业判断。', options: enumOptions(STANDING_NOTICE_LABELS), multi: true },
{ key: 'safety', title: '最近是否存在以下情况?', hint: '这一题不计入关注度,只用于安全分流。', options: enumOptions(SAFETY_FLAG_LABELS), multi: true },
]
const current = computed(() => steps[step.value])
const bodyValue = computed(() => (current.value.key === 'concerns' ? portrait.answers.concerns : portrait.answers.endOfDayFatigue) as string[])
function enumOptions(labels: Record<string, string>) {
return Object.entries(labels).map(([value, label]) => ({ value, label }))
}
function isOn(value: string) {
const answers = portrait.answers as unknown as Record<string, unknown>
const currentValue = answers[current.value.key]
return Array.isArray(currentValue) ? currentValue.includes(value) : currentValue === value
}
async function persist(patch: Record<string, unknown>) {
await portrait.saveAnswers(patch as never)
}
async function onBody(value: BodyRegion[]) {
await persist({ [current.value.key]: value })
}
async function pick(value: string) {
if (current.value.multi) {
const answers = portrait.answers as unknown as Record<string, unknown>
const list = [...((answers[current.value.key] as string[]) || [])]
const exclusiveNone = current.value.key === 'safety' || current.value.key === 'afterSitting' || current.value.key === 'standingNotice'
if (value === 'none' || value === 'unnoticed') {
await persist({ [current.value.key]: [value] })
return
}
const next = list.includes(value) ? list.filter((item) => item !== value) : [...list.filter((item) => item !== 'none' && item !== 'unnoticed'), value]
if (exclusiveNone && !next.length) return
await persist({ [current.value.key]: next })
return
}
await persist({ [current.value.key]: value })
}
async function next() {
try {
if (step.value < steps.length - 1) {
step.value += 1
return
}
uni.showLoading({ title: '生成画像...' })
await portrait.complete()
uni.hideLoading()
uni.redirectTo({ url: '/pages/portrait/report' })
} catch (err) {
uni.hideLoading()
uni.showToast({ title: getErrorMessage(err, '请先完成必答题'), icon: 'none' })
}
}
onLoad(async () => {
try {
await portrait.ensureSession()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '测评暂时无法开始'), icon: 'none' })
}
})
void AfterSitting
void ExerciseFreq
void PortraitGoal
void SafetyFlag
void SittingHours
void StandingNotice
void WorkPosture
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 40rpx 160rpx; }
.q { display: block; font-size: 40rpx; line-height: 1.4; color: #4a4035; }
.d { display: block; margin: 16rpx 0 28rpx; color: #8a7b6e; font-size: 26rpx; line-height: 1.6; }
.options { display: flex; flex-direction: column; gap: 16rpx; }
.opt { padding: 28rpx; border-radius: 20rpx; background: #fff; color: #5d5148; font-size: 28rpx; }
.opt.on { background: #6b8276; color: #fff; }
.disclaimer { display: block; margin-top: 36rpx; color: #a09080; font-size: 22rpx; }
.nav { position: fixed; left: 0; right: 0; bottom: 0; padding: 24rpx 40rpx 48rpx; display: flex; gap: 16rpx; background: #fbf9f6; }
.ghost, .next { flex: 1; height: 88rpx; border-radius: 999rpx; display: flex; align-items: center; justify-content: center; }
.ghost { background: #efe8e1; color: #6b5c50; }
.next { background: #6b8276; color: #fff; }
</style>

View File

@@ -0,0 +1,50 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="身体状态评估" :show-back="false" />
<view class="hero">
<text class="kicker">3 分钟身体状态评估</text>
<text class="title">最近身体哪里最让你困扰</text>
<text class="lead">用一份对话式问卷生成你的身体画像不是医疗诊断只用于运动训练参考</text>
<text v-if="stats?.completedCount" class="count">已有 {{ stats.completedCount }} 人完成评估</text>
<view class="cta" @tap="start">开始测试</view>
</view>
<view class="trust">
<text>STOTT 认证教练</text>
<text>一对一专业评估</text>
<text>非医疗诊断仅用于运动训练参考</text>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useBodyPortraitStore } from '../../stores/body-portrait'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const portrait = useBodyPortraitStore()
const { stats } = storeToRefs(portrait)
onLoad((query) => {
portrait.captureAttribution((query || {}) as Record<string, string>)
portrait.fetchStats().catch(() => {})
})
function start() {
uni.navigateTo({ url: '/pages/portrait/assessment' })
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 40rpx 80rpx; }
.hero { padding-top: 48rpx; }
.kicker { display: block; color: #8a7b6e; font-size: 22rpx; letter-spacing: 3rpx; }
.title { display: block; margin-top: 20rpx; font-size: 48rpx; line-height: 1.35; color: #4a4035; }
.lead { display: block; margin-top: 20rpx; font-size: 28rpx; line-height: 1.7; color: #7a6a5a; }
.count { display: block; margin-top: 24rpx; color: #6b8276; font-size: 24rpx; }
.cta { margin-top: 48rpx; height: 96rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 30rpx; }
.trust { margin-top: 56rpx; padding: 28rpx; border-radius: 24rpx; background: #fff; display: flex; flex-direction: column; gap: 12rpx; color: #7a6a5a; font-size: 24rpx; }
</style>

View File

@@ -0,0 +1,70 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="改善计划" show-back />
<view v-if="plan" class="card">
<text class="title">{{ plan.title }}</text>
<view v-for="phase in plan.phases" :key="phase.id" class="phase">
<text class="name">{{ phase.name }}</text>
<text class="meta"> {{ phase.lessonStart }}{{ phase.lessonEnd }} · {{ phase.focus.join(' / ') }}</text>
<text class="body">{{ phase.summary }}</text>
</view>
</view>
<view v-if="todos.length" class="card">
<text class="name">阶段复测</text>
<text v-for="todo in todos" :key="todo.id" class="body"> {{ todo.lessonCheckpoint }} {{ todo.completedAt ? '已完成' : '待安排' }}</text>
</view>
<view v-if="share" class="card">
<text class="title">{{ share.title }}</text>
<text class="body">{{ share.caption }}</text>
<text v-for="row in share.rows" :key="row.label" class="meta">{{ row.label }} {{ row.first === row.latest ? row.first : `${row.first} ${row.latest}` }}</text>
</view>
<view v-if="plan" class="cta" @tap="makeShare">生成我的成长卡片</view>
<view v-else class="body">完成到店评估后教练会为你生成 12 周改善计划</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { onShow, onShareAppMessage } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { get, post } from '../../utils/request'
import { getErrorMessage } from '../../utils/auth'
import type { GrowthShareCardRecord, ReassessmentTodoRecord, TrainingPlanRecord } from '@mp-pilates/shared'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const plan = ref<TrainingPlanRecord | null>(null)
const todos = ref<ReassessmentTodoRecord[]>([])
const share = ref<GrowthShareCardRecord | null>(null)
onShow(async () => {
try {
const plans = await get<TrainingPlanRecord[]>('/body-portrait/plans')
plan.value = plans[0] || null
todos.value = await get<ReassessmentTodoRecord[]>('/body-portrait/todos')
} catch {}
})
async function makeShare() {
try {
share.value = await post<GrowthShareCardRecord>('/body-portrait/share-cards', { includePhotos: false })
uni.showToast({ title: '已生成,可分享给朋友', icon: 'none' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '暂时无法生成'), icon: 'none' })
}
}
onShareAppMessage(() => ({
title: share.value?.title || '我的普拉提变化',
path: share.value ? `/pages/portrait/index?source=member_share&shareCode=${share.value.shareCode}` : '/pages/portrait/index?source=member_share',
}))
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 40rpx 80rpx; }
.card { background: #fff; border-radius: 24rpx; padding: 28rpx; margin-bottom: 20rpx; }
.title { display: block; font-size: 36rpx; color: #4a4035; }
.name { display: block; margin-top: 16rpx; font-size: 30rpx; color: #4a4035; }
.meta, .body { display: block; margin-top: 10rpx; color: #7a6a5a; font-size: 26rpx; line-height: 1.6; }
.cta { height: 92rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; }
</style>

View File

@@ -0,0 +1,75 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="你的身体画像" show-back />
<view v-if="teaser" class="card">
<text class="kicker">你的身体画像</text>
<text class="title">{{ teaser.headline }}</text>
<text class="summary">{{ claimed && report ? report.summary : '登录后查看完整个性化报告。问卷画像只能反映生活习惯和主观感受。' }}</text>
<text class="match">问卷依据{{ teaser.matchQuality === 'full' ? '充分' : '一般' }}这表示回答是否足够形成解释不是诊断准确率</text>
</view>
<SafetyNotice v-if="report?.safety.flagged" :message="report.safety.message || ''" />
<PortraitRadar v-if="claimed && report" :scores="report.scores" />
<view v-if="claimed && report" class="block">
<view v-for="(item, index) in report.evidence" :key="item.title" class="evidence">
<text class="etitle">{{ index + 1 }} {{ item.title }}</text>
<text class="eans">根据你的答案{{ item.answers.join('、') }}</text>
<text class="ebody">{{ item.explanation }}</text>
</view>
</view>
<view v-if="claimed && report" class="block">
<text class="etitle">这些问题是有关联的</text>
<text v-for="stepItem in report.chain.steps" :key="stepItem" class="chain">{{ stepItem }}</text>
<text class="ebody">{{ report.chain.takeaway }}</text>
</view>
<text class="disclaimer">非医疗诊断仅用于运动训练参考</text>
<view class="cta" @tap="continueFlow">{{ claimed ? '查看建议' : '登录查看完整报告' }}</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { onShow } from '@dcloudio/uni-app'
import CustomNavBar from '../../components/CustomNavBar.vue'
import PortraitRadar from '../../components/PortraitRadar.vue'
import SafetyNotice from '../../components/SafetyNotice.vue'
import { getSystemLayout } from '../../utils/system'
import { getErrorMessage } from '../../utils/auth'
import { useBodyPortraitStore } from '../../stores/body-portrait'
import { useUserStore } from '../../stores/user'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const portrait = useBodyPortraitStore()
const userStore = useUserStore()
const { teaser, report, claimed } = storeToRefs(portrait)
onShow(async () => {
if (!teaser.value && !portrait.session) {
await portrait.loadMine().catch(() => {})
}
if (teaser.value) await portrait.track('report_viewed')
})
async function continueFlow() {
try {
if (!claimed.value) {
if (!userStore.loggedIn) await userStore.login()
await portrait.claim()
}
uni.navigateTo({ url: '/pages/portrait/advice' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '请先登录后查看完整报告'), icon: 'none' })
}
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 40rpx 120rpx; }
.card, .block, .evidence { background: #fff; border-radius: 24rpx; padding: 32rpx; margin-bottom: 24rpx; }
.kicker { color: #8a7b6e; font-size: 22rpx; }
.title { display: block; margin-top: 12rpx; font-size: 40rpx; color: #4a4035; line-height: 1.4; }
.summary, .match, .ebody, .eans, .chain { display: block; margin-top: 16rpx; color: #7a6a5a; font-size: 26rpx; line-height: 1.7; }
.etitle { display: block; font-size: 30rpx; color: #4a4035; }
.disclaimer { display: block; color: #a09080; font-size: 22rpx; margin: 12rpx 0 24rpx; }
.cta { height: 92rpx; border-radius: 999rpx; background: #6b8276; color: #fff; display: flex; align-items: center; justify-content: center; }
</style>

View File

@@ -0,0 +1,68 @@
<template>
<view class="page" :style="{ paddingTop: navBarHeight }">
<CustomNavBar title="到店评估" show-back />
<text class="title">线上画像只能看到一部分</text>
<text class="lead">问卷能够帮助我们了解你的生活习惯和主观感受但身体真正如何运动需要通过现场观察进一步判断</text>
<view class="card">
<text class="name">到店专业评估会进一步看</text>
<text class="row">静态体态脊柱骨盆</text>
<text class="row">呼吸活动度稳定性与基础动作</text>
<text class="row">明确个人训练重点</text>
</view>
<view v-if="report?.safety.flagged" class="card">
<text class="name">当前不适合直接预约体验训练</text>
<text class="lead">建议先确认运动条件你也可以联系工作室我们会帮你判断下一步</text>
</view>
<button v-else-if="!userStore.user?.phone" class="cta" open-type="getPhoneNumber" @getphonenumber="book">预约身体评估体验</button>
<view v-else class="cta" @tap="goTrial">预约身体评估体验</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { getErrorMessage, wxBindPhone } from '../../utils/auth'
import { useBodyPortraitStore } from '../../stores/body-portrait'
import { useUserStore } from '../../stores/user'
const navBarHeight = ref(`${getSystemLayout().navBarHeight}px`)
const portrait = useBodyPortraitStore()
const userStore = useUserStore()
const { report } = storeToRefs(portrait)
async function goTrial() {
try {
if (!userStore.loggedIn) await userStore.login()
await portrait.track('trial_clicked')
uni.navigateTo({ url: '/pages/card/detail?trial=1&fromPortrait=1' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '请先登录'), icon: 'none' })
}
}
async function book(e: { detail: { encryptedData: string; iv: string; errMsg: string } }) {
try {
if (!userStore.loggedIn) await userStore.login()
if (e.detail.errMsg !== 'getPhoneNumber:ok') {
uni.showToast({ title: '预约体验需要授权手机号', icon: 'none' })
return
}
await wxBindPhone(e as Parameters<typeof wxBindPhone>[0])
await userStore.fetchProfile()
await goTrial()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '请先授权手机号'), icon: 'none' })
}
}
</script>
<style lang="scss" scoped>
.page { min-height: 100vh; background: #fbf9f6; padding: 0 40rpx 80rpx; }
.title { display: block; font-size: 40rpx; color: #4a4035; margin-top: 12rpx; }
.lead, .row { display: block; margin-top: 16rpx; color: #7a6a5a; font-size: 26rpx; line-height: 1.7; }
.card { margin-top: 28rpx; background: #fff; border-radius: 24rpx; padding: 28rpx; }
.name { display: block; font-size: 30rpx; color: #4a4035; }
.cta { margin-top: 48rpx; height: 92rpx; border-radius: 999rpx; background: #6b8276; color: #fff; font-size: 30rpx; display: flex; align-items: center; justify-content: center; }
</style>

File diff suppressed because it is too large Load Diff

View File

@@ -1,57 +1,67 @@
<template>
<view class="profile-page">
<!-- Custom nav bar (transparent, blends with UserCard gradient) -->
<CustomNavBar title="我的" transparent />
<view class="profile-page" :style="{ paddingTop: navBarHeight + 'px' }">
<view class="profile-page__nav" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="profile-page__nav-title">我的</view>
</view>
<!-- User card -->
<UserCard
:logged-in="loggedIn"
:has-profile="hasProfile"
:user="user"
:stats="stats"
:memberships="memberships"
:loading="loginLoading"
:nav-bar-height="navBarHeight"
@login="handleLogin"
/>
<UserCard :logged-in="loggedIn" :has-profile="hasProfile" :user="user" :memberships="memberships" :now="membershipNow"
:memberships-loading="membershipsLoading" :memberships-loaded="membershipsLoaded" :memberships-error="membershipsError"
:loading="loginLoading" @login="handleLogin" @edit="goToInfo" @refresh-memberships="userStore.fetchMemberships()" />
<InviteCard />
<!-- Menu section: always visible -->
<ProfileMenu
:is-admin="isAdmin"
:require-auth="loggedIn"
@clear-cache="handleClearCache"
@about="handleAbout"
@require-login="handleLogin"
/>
@open-notifications="showNotificationsModal = true"
>
<PracticeActivityCard v-if="loggedIn" :key="userStore.token" :refresh-key="activityRefreshKey" />
</ProfileMenu>
<!-- Logout button: only when logged in -->
<view v-if="loggedIn" class="profile-page__logout-wrap">
<button class="profile-page__logout-btn" @tap="handleLogout">退出登录</button>
</view>
<!-- Notification Settings Modal -->
<SubscriptionSettingsModal v-model:visible="showNotificationsModal" />
</view>
</template>
<script setup lang="ts">
import InviteCard from '../../components/InviteCard.vue'
import { useInviteStore } from '../../stores/invite'
import { ref, onMounted } from 'vue'
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../stores/user'
import { getSystemLayout } from '../../utils/system'
import { getErrorMessage } from '../../utils/auth'
import PracticeActivityCard from '../../components/PracticeActivityCard.vue'
import UserCard from '../../components/UserCard.vue'
import ProfileMenu from '../../components/ProfileMenu.vue'
import CustomNavBar from '../../components/CustomNavBar.vue'
import SubscriptionSettingsModal from '../../components/SubscriptionSettingsModal.vue'
const invite = useInviteStore()
const userStore = useUserStore()
const { loggedIn, hasProfile, user, stats, memberships, isAdmin } = storeToRefs(userStore)
const { loggedIn, hasProfile, user, memberships, membershipsLoading, membershipsLoaded, membershipsError, isAdmin } = storeToRefs(userStore)
const showNotificationsModal = ref(false)
const activityRefreshKey = ref(0)
const membershipNow = ref(Date.now())
const loginLoading = ref(false)
const navBarHeight = ref(64)
const navBarHeight = ref(getSystemLayout().navBarHeight)
const statusBarHeight = getSystemLayout().statusBarHeight
// ─── 微信分享 ───────────────────────────────────────────────
onShareAppMessage(() => {
return {
title: '我的普拉提会所,记录每一次进步',
path: '/pages/profile/index',
title: invite.code ? '送你 95 折购卡礼,一起练普拉提' : '一起练普拉提',
path: invite.code ? `/pages/card/detail?showAll=1&inviteCode=${invite.code}` : '/pages/home/index',
imageUrl: '',
}
})
@@ -68,10 +78,13 @@ onMounted(() => {
})
onShow(async () => {
membershipNow.value = Date.now()
activityRefreshKey.value += 1
if (loggedIn.value) {
await Promise.all([
invite.refresh().catch(() => {}),
invite.refreshActivity().catch(() => {}),
userStore.fetchProfile(),
userStore.fetchStats(),
userStore.fetchMemberships(),
])
}
@@ -81,25 +94,27 @@ async function handleLogin() {
if (loginLoading.value) return
loginLoading.value = true
try {
await userStore.login()
await Promise.all([
userStore.fetchProfile(),
userStore.fetchStats(),
userStore.fetchMemberships(),
])
} catch {
uni.showToast({ title: '登录失败,请重试', icon: 'none' })
const { isNewUser } = await userStore.loginWithSetup()
if (!isNewUser) {
await invite.refreshActivity().catch(() => {})
}
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '登录失败,请重试'), icon: 'none' })
} finally {
loginLoading.value = false
}
}
function goToInfo() {
uni.navigateTo({ url: '/pages/profile/info' })
}
function handleLogout() {
uni.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
confirmText: '退出',
confirmColor: '#ff4d4f',
confirmColor: '#9c7a6e',
success(res) {
if (res.confirm) {
userStore.logout()
@@ -121,39 +136,14 @@ function handleClearCache() {
})
}
function handleAbout() {
uni.showModal({
title: '关于我们',
content: 'Focus Core 普拉提工作室\n版本 1.0.0\n\n专注核心遇见更好的自己',
showCancel: false,
})
}
</script>
<style lang="scss" scoped>
.profile-page {
min-height: 100vh;
background: $bg-page;
&__logout-wrap {
margin: $spacing-xl $spacing-lg $spacing-xl;
}
&__logout-btn {
width: 100%;
height: 88rpx;
line-height: 88rpx;
background: $bg-card;
color: $error-color;
font-size: 30rpx;
font-weight: 500;
border: none;
border-radius: $radius-lg;
text-align: center;
&::after {
border: none;
}
}
min-height: 100vh; box-sizing: border-box; background: #fbf9f6; padding-bottom: 36rpx;
&__nav { position: fixed; top: 0; left: 0; right: 0; z-index: 101; background: #fbf9f6; }
&__nav-title { height: 88rpx; display: flex; align-items: center; justify-content: center; font-size: 34rpx; font-weight: 500; color: #514943; }
&__logout-wrap { margin: 28rpx 32rpx 0; }
&__logout-btn { width: 100%; height: 80rpx; line-height: 80rpx; padding: 0; margin: 0; border: none; border-radius: 24rpx; background: #f2ede7; color: #91766a; font-size: 25rpx; font-weight: 400; &::after { border: none; } }
}
</style>

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