Author SHA1 Message Date
xiaowang 4d2918f8a8 修复:恢复后端Nacos环境变量引导
Salon SIT 自动发布 / deploy (push) Successful in 3m8s
发布 Nacos 配置 / publish (push) Successful in 41s
2026-10-12 09:49:18 +08:00
xiaowang faa9cadc62 文档:设计后端Nacos启动引导修复 2026-10-12 09:49:18 +08:00
xiaowang fc148afc69 Merge pull request 'Dev合并到Sit' (#54) from dev into sit
发布 Nacos 配置 / publish (push) Failing after 33s
Salon SIT 自动发布 / deploy (push) Failing after 5m4s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/54
2026-10-12 09:16:31 +08:00
xiaowang 6f62137bf8 配置修改添加微信小程序AppSecret
发布 Nacos 配置 / publish (push) Successful in 42s
2026-10-10 14:11:26 +08:00
xiaowang fff1a0a97f 配置:统一后端参数由Nacos明文管理 2026-10-10 11:52:49 +08:00
xiaowang 9e3b37a36c 文档:制定后端Nacos明文配置实施计划 2026-10-10 11:43:09 +08:00
xiaowang 043dfff1b1 文档:设计后端配置统一由Nacos明文管理 2026-10-10 11:41:29 +08:00
xiaowang 4bb8665aab 功能:改造Salon小程序OpenID快捷登录 2026-10-10 11:02:45 +08:00
xiaowang dd3bcd40bc 文档:补充JayuCloud命名统一设计 2026-10-09 17:26:26 +08:00
xiaowang bda3933959 Merge pull request 'Dev' (#53) from dev into sit
发布 Nacos 配置 / publish (push) Failing after 30s
Salon SIT 自动发布 / deploy (push) Successful in 2m57s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/53
2026-09-16 16:55:18 +08:00
xiaowang 1587d1dd8f 同步sit分支解决PR合并冲突
发布 Nacos 配置 / publish (push) Successful in 24s
2026-09-16 16:19:09 +08:00
xiaowang cfe5cfeaf7 Merge remote-tracking branch 'origin/sit' into HEAD
发布 Nacos 配置 / publish (push) Successful in 27s
2026-09-16 16:15:12 +08:00
xiaowang fab7d7789d 精简快捷登录文案
发布 Nacos 配置 / publish (push) Successful in 26s
2026-09-16 12:27:28 +08:00
xiaowang be3d0cccec 简化Salon登录页面布局 2026-09-16 12:22:02 +08:00
xiaowang 5288dbf9b0 调整验证码有效期提示和重发状态 2026-09-16 10:47:01 +08:00
xiaowang e8e8e5a404 完善手机号校验和验证码发送限制 2026-09-16 09:22:30 +08:00
xiaowang 0c827782ff 修复Salon短信模板编码 2026-09-15 23:42:20 +08:00
xiaowang 52dcd143ff 修复SIT短信服务地址
发布 Nacos 配置 / publish (push) Failing after 30s
Salon SIT 自动发布 / deploy (push) Failing after 2m47s
2026-09-15 20:55:12 +08:00
xiaowang 7b68ef32e1 修复SIT短信服务地址 2026-09-15 20:47:33 +08:00
xiaowang 672cd936fe 修复SIT注册审核接口路由 2026-09-14 22:09:00 +08:00
xiaowang 8906eb39db 修复SIT发布跳过测试构建 2026-09-14 16:35:44 +08:00
xiaowang d2d17cef93 更新SIT重建服务器地址 2026-09-14 10:14:26 +08:00
xiaowang 381dad1fed 修复后台登录后跳转404 2026-09-11 16:11:24 +08:00
xiaowang 2ebaaeec77 修正微信注册绑定凭证时效 2026-09-11 15:35:41 +08:00
xiaowang e9a2e74b91 修正已验证手机号登录校验 2026-09-11 15:31:33 +08:00
xiaowang 8c5170cb7e 优化小程序手机号与微信授权登录 2026-09-11 15:27:20 +08:00
xiaowang 966a911014 Merge pull request '实现手机号登录自动进入注册审核流程' (#52) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 26s
Salon SIT 自动发布 / deploy (push) Successful in 3m9s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/52
2026-09-10 13:49:57 +08:00
xiaowang 8d84cb25d4 实现手机号登录自动进入注册审核流程
发布 Nacos 配置 / publish (push) Successful in 27s
Salon 生产发布准备 / prepare (pull_request) Has been skipped
2026-09-08 22:12:29 +08:00
xiaowang c0979f447c Merge pull request 'Dev' (#50) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 25s
Salon SIT 自动发布 / deploy (push) Successful in 3m38s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/50
2026-09-08 21:28:26 +08:00
xiaowang c849f44787 修复注册审核Mapper扫描配置
发布 Nacos 配置 / publish (push) Successful in 26s
2026-09-07 20:48:18 +08:00
xiaowang 8cb5cae808 修复Nacos工作流外部Action下载超时 2026-09-07 20:36:53 +08:00
xiaowang 003dedf5d0 Merge pull request 'Dev' (#49) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 34s
Salon SIT 自动发布 / deploy (push) Failing after 5m3s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/49
2026-09-07 20:29:16 +08:00
xiaowang f02601c25c 修复店务注册接口网关鉴权白名单
发布 Nacos 配置 / publish (push) Failing after 11s
2026-09-07 20:12:36 +08:00
xiaowang 63b226fe61 关联微信新账号与注册申请
发布 Nacos 配置 / publish (push) Successful in 34s
2026-09-07 12:14:02 +08:00
xiaowang a26252c020 补充微信登录和注册申请重提 2026-09-07 12:11:20 +08:00
xiaowang b4af2d6ab1 实现Salon工作台注册审核闭环 2026-09-07 12:09:42 +08:00
xiaowang 28c2c2603e 修复登录验证码表单对齐
发布 Nacos 配置 / publish (push) Successful in 50s
2026-09-07 11:47:44 +08:00
xiaowang 4f4d985673 修复注册页样式解析异常 2026-09-07 11:42:21 +08:00
xiaowang 6c8b3f8447 修正注册表单标题和控件对齐 2026-09-07 11:27:36 +08:00
xiaowang ddf7e4823b 调整登录方式标签顺序 2026-09-07 11:18:39 +08:00
xiaowang 29ad14b24a 修正登录页默认验证码模式 2026-09-07 11:15:51 +08:00
xiaowang edc14b3d41 重设计Salon登录注册工作台流程 2026-09-07 11:09:34 +08:00
xiaowang f3e480de33 Merge pull request '修正Spug短信名称参数' (#48) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 32s
Salon SIT 自动发布 / deploy (push) Successful in 2m55s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/48
2026-09-06 22:00:31 +08:00
xiaowang 211cdc9838 修正Spug短信名称参数
发布 Nacos 配置 / publish (push) Successful in 31s
2026-09-06 21:57:45 +08:00
xiaowang e3bb72b3f1 Merge pull request 'Dev' (#47) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 33s
Salon SIT 自动发布 / deploy (push) Successful in 3m30s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/47
2026-09-06 21:52:19 +08:00
xiaowang 3401c2f5e5 增加Salon短信供应商全局切换
发布 Nacos 配置 / publish (push) Successful in 32s
2026-09-06 21:41:09 +08:00
xiaowang dc46ff359b 切换Salon短信模板为Spug 2026-09-06 20:50:19 +08:00
xiaowang 7c43ab636a 修正Salon短信阿里云通道配置 2026-09-06 18:18:45 +08:00
xiaowang 4260da2942 Merge pull request '修正MessageHub短信通道字段' (#46) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 30s
Salon SIT 自动发布 / deploy (push) Successful in 3m1s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/46
2026-09-06 18:02:08 +08:00
xiaowang 1aee997e48 修正MessageHub短信通道字段
发布 Nacos 配置 / publish (push) Successful in 30s
2026-09-06 17:57:42 +08:00
xiaowang db3defffdf Merge pull request 'Dev' (#45) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 29s
Salon SIT 自动发布 / deploy (push) Successful in 3m23s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/45
2026-09-06 17:42:24 +08:00
xiaowang 1dd4b1c2cb 修正阿里云短信通道编码
发布 Nacos 配置 / publish (push) Successful in 34s
2026-09-06 17:40:06 +08:00
xiaowang 54414f56cd 优化小程序验证码倒计时样式 2026-09-06 17:36:53 +08:00
xiaowang a65063e419 记录小程序验证码倒计时设计 2026-09-06 17:34:49 +08:00
xiaowang ed4cc4e83d 调整Salon短信模板映射 2026-09-06 17:21:25 +08:00
xiaowang 285fed64fa 修复SIT短信模板编码 2026-09-06 17:06:51 +08:00
xiaowang c3a6287547 Merge pull request '修复短信消息缺少消息编号' (#44) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 33s
Salon SIT 自动发布 / deploy (push) Successful in 3m11s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/44
2026-09-06 16:10:04 +08:00
xiaowang 2942f29438 修复短信消息缺少消息编号
发布 Nacos 配置 / publish (push) Successful in 32s
2026-09-06 16:09:19 +08:00
xiaowang fd76865a0a Merge pull request '接入MessageHub标准MQ验证码投递' (#43) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 35s
Salon SIT 自动发布 / deploy (push) Successful in 2m58s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/43
2026-09-06 15:48:08 +08:00
xiaowang 048c19e5fe 接入MessageHub标准MQ验证码投递
发布 Nacos 配置 / publish (push) Successful in 34s
2026-09-06 15:42:56 +08:00
xiaowang a50b7b6c66 增加后台默认密码管理入口 2026-09-05 23:46:35 +08:00
xiaowang 852a715722 修复网页端未知路径跳转逻辑 2026-09-05 23:37:13 +08:00
xiaowang 9ac56115d0 完善小程序排班与预约快捷操作 2026-09-04 16:13:58 +08:00
xiaowang 4209ee732c 在小程序我的页面增加店铺今日概览 2026-09-04 15:50:55 +08:00
xiaowang 89c9deeeb2 收敛Salon网页后台管理范围 2026-09-04 15:17:08 +08:00
xiaowang c0a51a278e 补充用户重置密码提示 2026-09-04 14:10:28 +08:00
xiaowang d5535fbfa2 统一各环境网关JWT发行者配置
发布 Nacos 配置 / publish (push) Successful in 33s
2026-09-04 14:01:15 +08:00
xiaowang c3511d2f47 修复小程序登录店铺选择流程 2026-09-04 13:57:17 +08:00
xiaowang 6dd2233c16 统一小程序多环境请求地址 2026-09-04 13:37:42 +08:00
xiaowang aee4c0ff3d 确认SIT部署前置配置并修正MinIO地址 2026-09-04 09:14:37 +08:00
xiaowang b2fe9dc53a Merge pull request '修复复用发布包时清单目录缺失' (#42) from dev into sit
发布 Nacos 配置 / publish (push) Failing after 1m34s
Salon SIT 自动发布 / deploy (push) Failing after 4m56s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/42
2026-09-04 00:25:28 +08:00
xiaowang 47611d5c7a 修复复用发布包时清单目录缺失
发布 Nacos 配置 / publish (push) Failing after 1s
2026-09-03 23:45:38 +08:00
xiaowang c0fc27a175 Merge pull request '修复Salon部署服务器匹配规则' (#41) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 33s
Salon SIT 自动发布 / deploy (push) Failing after 3m0s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/41
2026-09-03 13:40:41 +08:00
xiaowang 2bf5e9d45b 修复Salon部署服务器匹配规则
发布 Nacos 配置 / publish (push) Successful in 32s
2026-09-03 10:49:10 +08:00
xiaowang b1e8b5a723 Merge pull request '修复发布临时目录缺失' (#40) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 31s
Salon SIT 自动发布 / deploy (push) Failing after 3m49s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/40
2026-09-03 10:43:59 +08:00
xiaowang 006306171b 修复发布临时目录缺失
发布 Nacos 配置 / publish (push) Successful in 35s
2026-09-03 10:30:01 +08:00
xiaowang dddb55f462 改用账号密码执行Salon发布
发布 Nacos 配置 / publish (push) Successful in 34s
Salon SIT 自动发布 / deploy (push) Failing after 2m24s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/39
2026-09-03 10:09:31 +08:00
xiaowang fd35a330e0 改用账号密码执行Salon发布
发布 Nacos 配置 / publish (push) Successful in 37s
2026-09-03 09:46:54 +08:00
xiaowang 5235c77e4a Merge pull request '修复SIT工具链检查管道错误' (#38) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 38s
Salon SIT 自动发布 / deploy (push) Failing after 2m49s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/38
2026-09-02 21:27:21 +08:00
xiaowang 6110227ad6 修复SIT工具链检查管道错误
发布 Nacos 配置 / publish (push) Successful in 32s
2026-09-02 21:25:33 +08:00
xiaowang 63cdf3ef2d Merge pull request '修复SIT前端接口地址配置' (#37) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 30s
Salon SIT 自动发布 / deploy (push) Failing after 26s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/37
2026-09-02 20:46:37 +08:00
xiaowang 629375cd2e 修复SIT前端接口地址配置
发布 Nacos 配置 / publish (push) Successful in 32s
2026-09-02 20:45:35 +08:00
xiaowang 8c7c919ddd 解决dev合并sit的发布流程冲突
发布 Nacos 配置 / publish (push) Successful in 31s
Salon SIT 自动发布 / deploy (push) Failing after 2m49s
2026-09-02 11:50:19 +08:00
xiaowang cad7afb12e 新增Salon SIT单机自动发布流程
发布 Nacos 配置 / publish (push) Successful in 32s
2026-09-01 16:34:02 +08:00
xiaowang f62fb02ef0 改用共享目录传递Salon生产发布包 2026-09-01 16:08:10 +08:00
xiaowang 82f660ff6d Merge pull request '文档提交' (#34) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 36s
Salon 生产发布准备 / prepare (pull_request) Successful in 3m4s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/34
2026-09-01 14:19:13 +08:00
xiaowang 317e482534 文档提交
发布 Nacos 配置 / publish (push) Successful in 57s
2026-09-01 14:13:57 +08:00
GiteaConflictResolver 5aef5bbe79 解决Salon生产发布工作流合并冲突
Salon 生产发布准备 / prepare (pull_request) Successful in 3m35s
2026-08-30 15:03:47 +08:00
xiaowang d5815bcaf4 Merge pull request '修复Salon发布包下载兼容性' (#31) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 34s
Salon 生产发布准备 / prepare (pull_request) Has been skipped
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/31
2026-08-30 14:39:06 +08:00
xiaowang 29291b7b35 修复Salon发布包下载兼容性
发布 Nacos 配置 / publish (push) Successful in 33s
2026-08-30 01:40:52 +08:00
xiaowang a2b3cab0e3 Merge pull request 'Sit' (#30) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/30
2026-08-30 01:28:45 +08:00
xiaowang a8a2d94626 Merge pull request '增加Salon准备部署参数输出' (#29) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 35s
Salon 生产发布准备 / prepare (pull_request) Successful in 3m36s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/29
2026-08-30 01:27:42 +08:00
xiaowang 0fab855185 增加Salon准备部署参数输出
发布 Nacos 配置 / publish (push) Successful in 35s
2026-08-30 01:24:21 +08:00
Gitea运维 ad599674e1 修复Salon流水线Artifact上传兼容性 2026-08-28 16:45:29 +08:00
xiaowang 63c991b1d5 Merge pull request 'Sit' (#28) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/28
2026-08-28 16:05:57 +08:00
xiaowang 347414470e Merge pull request '修复Salon生产包Maven构建阻塞' (#27) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 36s
Salon 生产发布准备 / prepare (pull_request) Successful in 3m7s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/27
2026-08-28 16:05:23 +08:00
xiaowang 184ec8444d 修复Salon生产包Maven构建阻塞
发布 Nacos 配置 / publish (push) Successful in 34s
2026-08-28 15:41:25 +08:00
xiaowang 3e53561caf Merge pull request 'Sit' (#26) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/26
2026-08-28 15:19:44 +08:00
xiaowang 1c3b61bc33 Merge pull request '修复生产构建根目录解析' (#25) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 35s
Salon 生产发布准备 / prepare (pull_request) Failing after 5m10s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/25
2026-08-28 15:19:29 +08:00
xiaowang 10be2b2e9d 修复生产构建根目录解析
发布 Nacos 配置 / publish (push) Successful in 33s
2026-08-28 15:16:28 +08:00
xiaowang e1f7e04d05 Merge pull request 'Sit修复Gitea内网检出超时' (#24) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/24
2026-08-28 15:12:20 +08:00
xiaowang f4a4191a4c Merge pull request '修复Gitea内网检出超时' (#23) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 35s
Salon 生产发布准备 / prepare (pull_request) Failing after 32s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/23
2026-08-28 15:10:35 +08:00
xiaowang c50695d249 修复Gitea内网检出超时
发布 Nacos 配置 / publish (push) Successful in 35s
2026-08-28 15:08:01 +08:00
xiaowang 0bc40b5823 Merge pull request 'Sit' (#22) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/22
2026-08-28 15:05:01 +08:00
xiaowang 0a355a7e68 Merge pull request '修复Gitea合并提交构建失败' (#21) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 38s
Salon 生产发布准备 / prepare (pull_request) Failing after 12s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/21
2026-08-28 15:04:49 +08:00
xiaowang b0181edbd3 修复Gitea合并提交构建失败
发布 Nacos 配置 / publish (push) Successful in 37s
2026-08-28 13:07:49 +08:00
xiaowang cbd00d0597 Merge pull request 'Sit' (#20) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/20
2026-08-28 12:44:33 +08:00
xiaowang d38fd639bc Merge pull request 'Dev' (#19) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 33s
Salon 生产发布准备 / prepare (pull_request) Failing after 1m0s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/19
2026-08-28 12:44:09 +08:00
xiaowang 1bec2e5bcd 修复Gitea Runner构建工具链
发布 Nacos 配置 / publish (push) Successful in 1m59s
2026-08-27 15:43:18 +08:00
xiaowang 2054b32267 补充Salon后端服务端口环境变量 2026-08-27 14:59:01 +08:00
xiaowang 31112b1b1c 补充生产Salon后端环境变量准备说明 2026-08-27 14:48:09 +08:00
xiaowang d63f2011ec 2026-08-27-sit合并到prod,第一次上线部署后端
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/18
2026-08-27 14:27:09 +08:00
xiaowang a2c8f0baea Merge pull request 'Dev合并到sit' (#17) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 30s
Salon 生产发布准备 / prepare (pull_request) Failing after 13m59s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/17
2026-08-27 14:26:23 +08:00
xiaowang ccadd8dc62 整理开发分支当前代码与项目规则
发布 Nacos 配置 / publish (push) Successful in 34s
2026-08-27 13:28:24 +08:00
xiaowang 57dfe82a5d 补充Salon业务服务器清单 2026-08-27 13:24:43 +08:00
xiaowang 5211c2d6cd 实现Salon生产流水线自动准备 2026-08-27 12:39:20 +08:00
xiaowang 0df0a86d9a 新增Salon生产发布流水线设计 2026-08-27 12:24:22 +08:00
xiaowang e9748119ef 记录Salon生产基础环境准备 2026-08-27 12:13:21 +08:00
xiaowang 216efa6b3c 修正Salon初始化SQL误删业务表 2026-08-27 11:31:27 +08:00
xiaowang c08a65e14f 修复SalonAdmin标识与登录令牌校验 2026-08-27 11:19:43 +08:00
xiaowang a0f659c5c4 修正Salon管理后台品牌环境配置 2026-08-26 23:18:16 +08:00
xiaowang 025af6ba9b 统一Salon管理后台品牌配置 2026-08-26 22:26:06 +08:00
xiaowang fe4baad70c 收敛Salon后台首页管理入口 2026-08-26 22:04:41 +08:00
xiaowang a10769de45 重构Salon管理员后台入口 2026-08-26 21:57:15 +08:00
xiaowang bfe4d4c344 redis密码更改
发布 Nacos 配置 / publish (push) Successful in 29s
2026-08-26 20:50:07 +08:00
xiaowang 8270784e39 修复Dev Salon Redis无用户名认证配置
发布 Nacos 配置 / publish (push) Successful in 33s
2026-08-26 20:30:23 +08:00
xiaowang 346dde8197 配置修改
发布 Nacos 配置 / publish (push) Successful in 35s
2026-08-26 20:21:49 +08:00
xiaowang 581136cb24 配置修改以及bug修复
发布 Nacos 配置 / publish (push) Successful in 33s
2026-08-26 20:18:47 +08:00
xiaowang 2ad41221ff 整理双端初始化SQL脚本 2026-08-26 19:09:56 +08:00
xiaowang 449d57916d 实现Dev和SIT配置推送自动发布
发布 Nacos 配置 / publish (push) Successful in 31s
2026-08-26 18:28:32 +08:00
xiaowang abf34267a1 配置Dev店务Core和Gateway端口 2026-08-26 18:20:38 +08:00
xiaowang 4e9b8c8ede 修正店务Core的MyBatis扫描包名 2026-08-26 18:06:49 +08:00
xiaowang 47a49cd6b3 Merge pull request 'Sit' (#16) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/16
2026-08-26 16:55:05 +08:00
xiaowang df1ec06d39 Merge pull request 'Dev' (#15) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/15
2026-08-26 16:54:54 +08:00
xiaowang 4703f1e9ed 补全Dev店务数据库默认参数 2026-08-26 16:54:05 +08:00
xiaowang 911e759827 补全Dev店务启动默认参数 2026-08-26 16:52:00 +08:00
xiaowang 2ca3cc3652 补全Dev店务中间件默认配置 2026-08-26 16:45:56 +08:00
xiaowang 3ac1f5a7c8 补充Dev店务Nacos默认凭据 2026-08-26 16:43:55 +08:00
xiaowang 857a07fd7b 补充项目环境变量运维说明 2026-08-26 16:28:35 +08:00
xiaowang 42919aad21 Merge pull request 'Sit' (#14) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/14
2026-08-26 16:17:51 +08:00
xiaowang a6ecf47020 Merge pull request 'Dev' (#13) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/13
2026-08-26 16:15:55 +08:00
xiaowang 63d133d7c9 增加Dev环境Nacos配置发布流程 2026-08-26 15:35:52 +08:00
xiaowang 24018c42f2 修改包名 2026-08-26 14:02:28 +08:00
xiaowang 90f00feefd Merge pull request 'sit' (#11) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/11
2026-08-26 12:59:41 +08:00
xiaowang 56eb63ca0c Merge pull request '增加Nacos配置回读重试' (#10) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/10
2026-08-26 12:59:24 +08:00
xiaowang 2a5d18e339 增加Nacos配置回读重试 2026-08-26 12:58:34 +08:00
xiaowang 074cbd0c8c Merge pull request 'sit' (#9) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/9
2026-08-26 12:46:52 +08:00
xiaowang e59bb424f0 Merge pull request '修正Nacos地址路径兼容' (#8) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/8
2026-08-26 12:46:28 +08:00
xiaowang 4223f42e43 修正Nacos地址路径兼容 2026-08-26 12:44:23 +08:00
xiaowang ee12fee6b6 Merge pull request 'sit' (#7) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/7
2026-08-26 12:21:45 +08:00
xiaowang 8f1b85ec7f Merge pull request '修正流水线仓库访问地址' (#6) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/6
2026-08-26 12:21:30 +08:00
xiaowang 55b8b8e73c 修正流水线仓库访问地址 2026-08-26 12:11:42 +08:00
xiaowang 4ae6cffdf1 Merge pull request '工作流runner标签调整sit合并到prod' (#4) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/4
2026-08-26 10:43:28 +08:00
xiaowang 8af439f1d2 Merge pull request '调整Nacos流水线Runner标签' (#3) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/3
2026-08-26 10:42:59 +08:00
xiaowang 8e303f5d9d 调整Nacos流水线Runner标签 2026-08-26 10:40:21 +08:00
xiaowang da6d1b7f5b Merge pull request 'sit合并到prod' (#2) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/2
2026-08-26 10:13:47 +08:00
xiaowang 2d9cf472a8 Merge pull request 'dev合并到sit-20260826' (#1) from dev into sit
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/1
2026-08-26 10:12:13 +08:00
xiaowang 65193c6b6c 实现双中心Nacos顺序发布流水线 2026-08-26 09:55:28 +08:00
xiaowang 0d30999768 澄清Nacos流水线配置仓库归属 2026-08-26 09:43:42 +08:00
xiaowang 542403cf0e 补充生产Gitea发布Nacos准备说明 2026-08-26 09:40:55 +08:00
xiaowang bf29f27629 完善生产与测试环境Nacos配置 2026-08-26 09:33:10 +08:00
xiaowang 501054ce12 新增生产与测试Nacos配置分离设计 2026-08-26 09:26:44 +08:00
xiaowang 75e6d37603 整理项目文档与脚本目录 2026-08-26 00:18:17 +08:00
xiaowang 2831543bac 补齐生产对象存储与中间件配置 2026-08-25 23:36:46 +08:00
xiaowang 4e14468bc1 整理当前项目完整状态 2026-08-25 16:49:57 +08:00
xiaowang 0c83acc7c2 清理设计师端管理免鉴权配置 2026-08-25 16:30:39 +08:00
xiaowang a2491b72b9 移除设计师端后台网关路由 2026-08-25 16:28:40 +08:00
xiaowang abce4a2787 完成JC-ArtList与JC-Salon端侧清理和统一命名 2026-08-25 16:21:05 +08:00
xiaowang aa93695704 补充双端隔离运维文档 2026-08-25 10:59:23 +08:00
xiaowang c7b2daba71 完成设计师端与店务端生产隔离改造 2026-08-25 10:56:55 +08:00
1894 changed files with 102756 additions and 28674 deletions
BIN
View File
Binary file not shown.
+133
View File
@@ -0,0 +1,133 @@
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { join, relative, sep } from 'node:path';
const repositoryRoot = process.cwd();
const target = requiredNacosTarget('NACOS_ENVIRONMENT');
const group = 'DEFAULT_GROUP';
const configRoot = join(repositoryRoot, 'nacos', 'namespaces', target.environment);
const configFiles = await collectYamlFiles(configRoot);
if (configFiles.length === 0) {
throw new Error(`nacos/namespaces/${target.environment} 下没有可发布的 YAML 配置`);
}
for (const destination of target.destinations) {
await publishDestination(destination, configFiles);
}
async function publishDestination(destination, files) {
const nacosUrls = requiredEnvironment(`${destination.prefix}_URLS`).split(',').map((value) => normalizeNacosBaseUrl(value.trim())).filter(Boolean);
if (nacosUrls.length < destination.verificationNodeCount) {
throw new Error(`${destination.name} 至少需要 ${destination.verificationNodeCount} 个 Nacos 地址用于发布校验`);
}
const username = requiredEnvironment(`${destination.prefix}_USERNAME`);
const password = requiredEnvironment(`${destination.prefix}_PASSWORD`);
const token = await login(nacosUrls[0], username, password);
for (const filePath of files) {
const root = join(repositoryRoot, 'nacos', 'namespaces', destination.environment);
const relativePath = relative(root, filePath).split(sep);
if (relativePath.length !== 3 || relativePath[1] !== group) {
throw new Error(`配置路径必须是 <namespace>/${group}/<dataId>.yaml:${relativePath.join('/')}`);
}
const [namespace, , dataId] = relativePath;
const content = await readFile(filePath, 'utf8');
await publish(nacosUrls[0], token, namespace, group, dataId, content);
await verify(nacosUrls.slice(0, destination.verificationNodeCount), token, namespace, group, dataId, content);
console.log(`已发布并校验 ${destination.name}/${namespace}/${group}/${dataId}`);
}
}
function requiredEnvironment(name) {
const value = process.env[name];
if (!value) {
throw new Error(`缺少环境变量 ${name}`);
}
return value;
}
function normalizeNacosBaseUrl(value) {
return value.replace(/\/+$/, '').replace(/\/nacos$/, '');
}
function requiredNacosTarget(name) {
const value = requiredEnvironment(name);
const destinations = {
dev: [{ name: 'dev', environment: 'dev', prefix: 'NACOS_DEV', verificationNodeCount: 1 }],
sit: [{ name: 'sit', environment: 'sit', prefix: 'NACOS_SIT', verificationNodeCount: 1 }],
'prod-center1': [{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 }],
'prod-center2': [{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 }],
'prod-both': [
{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 },
{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 },
],
}[value];
if (!destinations) {
throw new Error(`不支持的 Nacos 发布目标:${value}`);
}
return { environment: destinations[0].environment, destinations };
}
async function collectYamlFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const entryPath = join(directory, entry.name);
if (entry.isDirectory()) {
files.push(...await collectYamlFiles(entryPath));
} else if (entry.isFile() && entry.name.endsWith('.yaml')) {
files.push(entryPath);
}
}
return files.sort();
}
async function login(baseUrl, user, secret) {
const body = new URLSearchParams({ username: user, password: secret });
const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body });
if (!response.ok) {
throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`);
}
const payload = await response.json();
if (!payload.accessToken) {
throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`);
}
return payload.accessToken;
}
async function publish(baseUrl, token, namespace, configGroup, dataId, content) {
const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content });
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body });
const result = await response.text();
if (!response.ok || result.trim() !== 'true') {
throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`);
}
}
async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) {
const expectedHash = sha256(expectedContent);
for (const baseUrl of baseUrls) {
const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace });
let lastStatus = 0;
let lastContent = '';
for (let attempt = 1; attempt <= 3; attempt += 1) {
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`);
const content = await response.text();
lastStatus = response.status;
lastContent = content;
if (response.ok && sha256(content) === expectedHash) {
break;
}
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
if (lastStatus !== 200 || sha256(lastContent) !== expectedHash) {
throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${lastStatus} ${lastContent.slice(0, 200)}`);
}
}
}
function sha256(value) {
return createHash('sha256').update(value, 'utf8').digest('hex');
}
+59
View File
@@ -0,0 +1,59 @@
name: 发布 Nacos 配置
on:
push:
branches:
- dev
- sit
workflow_dispatch:
inputs:
environment:
description: 发布目标
required: true
type: choice
options:
- dev
- sit
- prod-center1
- prod-center2
- prod-both
jobs:
publish:
runs-on: jayucloud
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
steps:
- name: 从内网 Gitea 检出配置源
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 检查 Node.js 运行时
shell: bash
run: |
set -euo pipefail
node_version="$(node --version)"
[[ "$node_version" == v20.* ]]
- name: 发布并校验配置
env:
NACOS_ENVIRONMENT: ${{ inputs.environment || github.ref_name }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }}
NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }}
NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }}
run: node .gitea/scripts/publish-nacos.mjs
+123
View File
@@ -0,0 +1,123 @@
name: Salon 生产发布
on:
workflow_dispatch:
inputs:
prepare_run_id:
description: 自动准备工作流的运行 ID
required: true
type: string
release_sha:
description: prod 合并提交 SHA
required: true
type: string
jobs:
deploy:
runs-on: jayucloud
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
steps:
- name: 从内网 Gitea 检出发布脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHECKOUT_SHA: ${{ inputs.release_sha }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
test -n "$CHECKOUT_SHA"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$CHECKOUT_SHA"
git checkout --detach "$CHECKOUT_SHA"
- name: 检查发布工具链
shell: bash
run: |
set -euo pipefail
java_version="$(java -version 2>&1)"
[[ "$java_version" == *'17.'* ]]
node_version="$(node --version)"
[[ "$node_version" == v20.* ]]
pwsh --version
- name: 准备 SSH 密码登录工具
shell: bash
run: |
set -euo pipefail
if ! command -v sshpass >/dev/null 2>&1; then
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
fi
sshpass -V >/dev/null 2>&1
- name: 读取已审核发布包
shell: bash
env:
RELEASE_SHA: ${{ inputs.release_sha }}
run: |
set -euo pipefail
test -n "$RELEASE_SHA"
shared_dir="/salon-release/$RELEASE_SHA"
test -d "$shared_dir"
test -f "$shared_dir/.manifest.sha256"
(cd "$shared_dir" && sha256sum -c .manifest.sha256)
mkdir -p artifacts/release
cp -a "$shared_dir/." artifacts/release/
test -f artifacts/release/manifest.json
test -f artifacts/release/backend/JC-Salon-Core.jar
test -f artifacts/release/backend/JC-Salon-Gateway.jar
- name: 发布并校验 Salon 生产 Nacos
shell: bash
env:
NACOS_ENVIRONMENT: prod-both
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
run: node .gitea/scripts/publish-nacos.mjs
- name: 写入临时 SSH 配置和目标清单
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$WEB_TARGET_HOST"
test -n "$WEB_TARGET_PORT"
test -n "$WEB_TARGET_USER"
test -n "$WEB_REMOTE_DIR"
mkdir -p "$RUNNER_TEMP/salon-prod"
cat > "$RUNNER_TEMP/salon-prod/servers.json" <<JSON
[
{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Purpose":"Salon Core","Environment":"prod"},
{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Purpose":"Salon Core","Environment":"prod"},
{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Purpose":"Salon Core","Environment":"prod"},
{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Purpose":"Salon Gateway","Environment":"prod"},
{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Purpose":"Salon Gateway","Environment":"prod"},
{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Purpose":"Salon Gateway","Environment":"prod"},
{"Name":"salon-web","Host":"${WEB_TARGET_HOST}","Port":${WEB_TARGET_PORT},"User":"${WEB_TARGET_USER}","Purpose":"Salon NGINX","Environment":"prod"}
]
JSON
- name: 人工确认后执行生产发布
shell: pwsh
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
SERVER_INFO_JSON: ${{ runner.temp }}/salon-prod/servers.json
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-Deploy
-SkipDatabaseInit
-RequireSystemd
-PackageDirectory "artifacts/release"
-ServerInfoJsonPath "$env:SERVER_INFO_JSON"
-SshPassword "$env:SALON_PROD_SSH_PASSWORD"
-CorePattern "^core01-"
-GatewayPattern "^gateway01-"
-WebTargetName salon-web
-WebRemoteDir "$env:WEB_REMOTE_DIR"
+80
View File
@@ -0,0 +1,80 @@
name: Salon 生产发布准备
on:
pull_request:
types:
- closed
branches:
- prod
jobs:
prepare:
if: >-
github.event.pull_request.merged == true &&
github.event.pull_request.base.ref == 'prod' &&
github.event.pull_request.head.ref == 'sit'
runs-on: jayucloud
env:
GITHUB_REF_NAME: prod
GITHUB_SERVER_URL: http://192.168.5.15:3000
steps:
- name: 从内网 Gitea 检出合并提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHECKOUT_SHA: ${{ github.event.pull_request.merge_commit_sha }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
test -n "$CHECKOUT_SHA"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$CHECKOUT_SHA"
git checkout --detach "$CHECKOUT_SHA"
- name: 检查构建工具链
shell: bash
run: |
set -euo pipefail
java -version 2>&1 | grep -q '17\.'
node --version | grep -q '^v20\.'
mvn --version > "$RUNNER_TEMP/maven-version.txt"
grep -q 'Java version: 17\.' "$RUNNER_TEMP/maven-version.txt"
pwsh --version
- name: 构建 Salon 发布包
shell: pwsh
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-PackageOnly
-SkipTests
-SkipDatabaseInit
- name: 保存发布包到共享目录
shell: bash
env:
RELEASE_SHA: ${{ github.event.pull_request.merge_commit_sha }}
run: |
set -euo pipefail
test -n "$RELEASE_SHA"
shared_dir="/salon-release/$RELEASE_SHA"
rm -rf "$shared_dir"
mkdir -p "$shared_dir"
cp -a artifacts/release/. "$shared_dir/"
test -f "$shared_dir/manifest.json"
(cd "$shared_dir" && sha256sum manifest.json > .manifest.sha256)
- name: 输出部署参数
shell: bash
env:
RELEASE_SHA: ${{ github.event.pull_request.merge_commit_sha }}
run: |
{
echo "## Salon 生产部署参数"
echo ""
echo "**prepare_run_id**: \`${{ github.run_id }}\`"
echo ""
echo "**release_sha**: \`$RELEASE_SHA\`"
echo ""
echo "**共享目录**: \`/salon-release/$RELEASE_SHA\`"
} >> "$GITHUB_STEP_SUMMARY"
echo "prepare_run_id=${{ github.run_id }}"
echo "release_sha=$RELEASE_SHA"
echo "artifact_name=salon-prod-$RELEASE_SHA"
+115
View File
@@ -0,0 +1,115 @@
name: Salon SIT 自动发布
on:
push:
branches:
- sit
workflow_dispatch:
jobs:
deploy:
runs-on: jayucloud
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }}
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
steps:
- name: 从内网 Gitea 检出代码
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 检查发布工具链
shell: bash
run: |
set -euo pipefail
java_version="$(java -version 2>&1)"
[[ "$java_version" == *'17.'* ]]
node_version="$(node --version)"
[[ "$node_version" == v20.* ]]
mvn_version="$(mvn --version 2>&1)"
[[ "$mvn_version" == *'Java version: 17.'* ]]
pwsh --version
- name: 构建 Salon SIT 发布包
shell: pwsh
env:
VITE_API_BASE_URL: https://sit.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-PackageOnly
-SkipTests
-SkipDatabaseInit
- name: 准备 SSH 密码登录工具
shell: bash
run: |
set -euo pipefail
if ! command -v sshpass >/dev/null 2>&1; then
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
fi
sshpass -V >/dev/null 2>&1
- name: 写入 SIT SSH 配置和目标清单
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$WEB_TARGET_HOST"
test -n "$WEB_TARGET_PORT"
test -n "$WEB_TARGET_USER"
mkdir -p "$RUNNER_TEMP/salon-sit"
cat > "$RUNNER_TEMP/salon-sit/servers.json" <<JSON
[
{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},
{"Name":"salon-web-sit","Host":"${WEB_TARGET_HOST}","Port":${WEB_TARGET_PORT},"User":"${WEB_TARGET_USER}","Purpose":"Salon SIT NGINX","Environment":"sit"}
]
JSON
- name: 写入 MessageHub 运行时 Token
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$MESSAGEHUB_ACCESS_TOKEN"
printf 'MESSAGEHUB_ACCESS_TOKEN=%s\n' "$MESSAGEHUB_ACCESS_TOKEN" |
SSHPASS="$SALON_PROD_SSH_PASSWORD" sshpass -e ssh -o StrictHostKeyChecking=no -p 22 root@192.168.10.15 \
'install -d -m 700 /etc/sysconfig /etc/systemd/system/jc-salon-core-sit.service.d; install -m 600 /dev/stdin /etc/sysconfig/jc-salon-messagehub; printf "[Service]\\nEnvironmentFile=/etc/sysconfig/jc-salon-messagehub\\n" | install -m 644 /dev/stdin /etc/systemd/system/jc-salon-core-sit.service.d/messagehub.conf; systemctl daemon-reload'
- name: 自动发布 Salon SIT
shell: pwsh
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
SERVER_INFO_JSON: ${{ runner.temp }}/salon-sit/servers.json
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-Deploy
-SkipDatabaseInit
-AllowSitTarget
-RequireSystemd
-PackageDirectory "artifacts/release"
-ServerInfoJsonPath "$env:SERVER_INFO_JSON"
-SshPassword "$env:SALON_PROD_SSH_PASSWORD"
-CoreRemoteAppDir "/opt/jc-salon-core-sit"
-GatewayRemoteAppDir "/opt/jc-salon-gateway-sit"
-CorePattern "^sit-app01$"
-GatewayPattern "^sit-app01$"
-CoreServiceName "jc-salon-core-sit"
-GatewayServiceName "jc-salon-gateway-sit"
-CoreHealthPort 181
-GatewayHealthPort 180
-WebTargetName "salon-web-sit"
-WebRemoteDir "$env:WEB_REMOTE_DIR"
-PublicBaseUrl "https://sit.yunail.art"
+5 -5
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **FingertipDesigner** (15270 symbols, 32958 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -24,10 +24,10 @@ This project is indexed by GitNexus as **FingertipDesigner** (15270 symbols, 329
| Resource | Use for |
|----------|---------|
| `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness |
| `gitnexus://repo/FingertipDesigner/clusters` | All functional areas |
| `gitnexus://repo/FingertipDesigner/processes` | All execution flows |
| `gitnexus://repo/FingertipDesigner/process/{name}` | Step-by-step execution trace |
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
| `gitnexus://repo/JayuCloud/process/{name}` | Step-by-step execution trace |
## CLI
+5 -5
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **FingertipDesigner** (15270 symbols, 32958 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -24,10 +24,10 @@ This project is indexed by GitNexus as **FingertipDesigner** (15270 symbols, 329
| Resource | Use for |
|----------|---------|
| `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness |
| `gitnexus://repo/FingertipDesigner/clusters` | All functional areas |
| `gitnexus://repo/FingertipDesigner/processes` | All execution flows |
| `gitnexus://repo/FingertipDesigner/process/{name}` | Step-by-step execution trace |
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
| `gitnexus://repo/JayuCloud/process/{name}` | Step-by-step execution trace |
## CLI
@@ -1,7 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.analytics.service;
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO;
public interface OperationsAnalyticsService {
OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId);
}
@@ -1,7 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.analytics.service;
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.StoreWorkbenchVO;
public interface WorkbenchService {
StoreWorkbenchVO getWorkbench(Long shopId, Long artistId);
}
@@ -1,24 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.service;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
import java.time.LocalDate;
import java.util.List;
public interface ArtistScheduleService {
ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto);
List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate);
ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId);
ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto);
ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto);
}
@@ -1,7 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO;
public interface ObjectStorageReplicaMapper extends BaseMapper<ObjectStorageReplicaDO> {
}
@@ -1,14 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.inventory.service;
import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryAdjustDTO;
import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryItemDTO;
import com.xiaowang.fingertipdesigner.core.modules.inventory.vo.InventoryItemVO;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
public interface InventoryService {
InventoryItemVO saveItem(InventoryItemDTO dto);
InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto);
PageResultVO<InventoryItemVO> listItems(Long shopId, Integer page, Integer size);
}
@@ -1,11 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.marketing.service;
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CampaignDTO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CampaignVO;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
public interface CampaignService {
CampaignVO saveCampaign(CampaignDTO dto);
PageResultVO<CampaignVO> listCampaigns(Long shopId, Integer status, Integer page, Integer size);
}
@@ -1,7 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.marketing.service;
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.GrowthSummaryVO;
public interface GrowthService {
GrowthSummaryVO getSummary(Long userId);
}
@@ -1,22 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.planning.service;
import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO;
import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentMoveDTO;
import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentStatusDTO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningCalendarVO;
import java.time.LocalDate;
public interface PlanningService {
PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId);
PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto);
PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId);
PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto);
Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto);
}
-51
View File
@@ -1,51 +0,0 @@
spring:
application:
name: fingertip-designer-core
cloud:
nacos:
discovery:
# Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# Nacos 命名空间,默认指向开发环境。
namespace: FingertipDesigner-Dev
# 服务注册分组。
group: DEFAULT_GROUP
# 注册到 Nacos 的服务名。
service: ${spring.application.name}
# 是否启用服务发现。
enabled: true
# 是否将当前服务注册到 Nacos。
register-enabled: true
# Nacos 认证用户名。
username: xiaowang
# Nacos 认证密码。
password: 122503wcy....
config:
# Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# Nacos 配置中心命名空间,默认指向开发环境。
namespace: FingertipDesigner-Dev
# 配置分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# Core 服务独有配置文件。
name: core
# 所有 Nacos 配置均使用 YAML。
file-extension: yaml
# 是否启用配置中心。
enabled: true
# Nacos 认证用户名。
username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
# Core 与 Gateway 共享的公共配置文件。
shared-configs:
- data-id: infra.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: secret.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: logging.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
@@ -1,213 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ArtistScheduleServiceImplTest {
@Mock
private ArtistScheduleMapper scheduleMapper;
@Mock
private ArtistScheduleRuleMapper ruleMapper;
@Mock
private ArtistScheduleExceptionMapper exceptionMapper;
@Mock
private AppointmentReservationMapper reservationMapper;
private ArtistScheduleServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new ArtistScheduleServiceImpl(scheduleMapper, ruleMapper, exceptionMapper, reservationMapper);
when(ruleMapper.selectOne(any())).thenReturn(null);
when(exceptionMapper.selectList(any())).thenReturn(List.of());
when(scheduleMapper.selectDayScheduleForUpdate(eq(8L), eq(30L), any(LocalDate.class))).thenAnswer(invocation -> existingSchedule(invocation.getArgument(2)));
when(reservationMapper.countActiveByArtistAndDateForUpdate(eq(8L), eq(30L), any(LocalDate.class))).thenReturn(0);
when(reservationMapper.countActiveOutsideScheduleForUpdate(eq(8L), eq(30L), any(LocalDate.class), any(LocalTime.class), any(LocalTime.class))).thenReturn(0);
}
@Test
void saveDoubleRestRuleGeneratesWeekdaySchedulesAndWeekendRestRows() {
service.saveRule(rule("DOUBLE_REST", List.of(1, 2, 3, 4, 5), LocalTime.of(9, 0), LocalTime.of(17, 0)));
ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class);
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), any(), any(), statusCaptor.capture(), any());
assertThat(statusCaptor.getAllValues()).contains(1, 0);
}
@Test
void saveCustomRuleUsesSelectedWeekdaysOnly() {
service.saveRule(rule("CUSTOM", List.of(2, 4), LocalTime.of(10, 0), LocalTime.of(20, 0)));
ArgumentCaptor<LocalDate> dateCaptor = ArgumentCaptor.forClass(LocalDate.class);
ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class);
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).selectDayScheduleForUpdate(eq(8L), eq(30L), dateCaptor.capture());
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), any(), any(), statusCaptor.capture(), any());
List<LocalDate> dates = dateCaptor.getAllValues();
List<Integer> statuses = statusCaptor.getAllValues();
for (int index = 0; index < statuses.size(); index++) {
DayOfWeek dayOfWeek = dates.get(index).getDayOfWeek();
if (List.of(DayOfWeek.TUESDAY, DayOfWeek.THURSDAY).contains(dayOfWeek)) {
assertThat(statuses.get(index)).isEqualTo(1);
} else {
assertThat(statuses.get(index)).isEqualTo(0);
}
}
}
@Test
void saveRestExceptionRejectsDateWithActiveReservation() {
LocalDate date = LocalDate.now().plusDays(1L);
when(ruleMapper.selectOne(any())).thenReturn(existingRule());
when(exceptionMapper.selectOne(any())).thenReturn(null);
when(reservationMapper.countActiveByArtistAndDateForUpdate(8L, 30L, date)).thenReturn(2);
assertThatThrownBy(() -> service.saveException(restException(date)))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining(date.toString())
.hasMessageContaining("2");
verify(exceptionMapper).insert(any(ArtistScheduleExceptionDO.class));
verify(scheduleMapper, never()).updateGeneratedSchedule(any(), any(), any(), any(), any(), any(), any());
}
@Test
void saveExtraWorkExceptionGeneratesWorkingScheduleOnRestDay() {
LocalDate sunday = next(DayOfWeek.SUNDAY);
when(ruleMapper.selectOne(any())).thenReturn(existingRule());
when(exceptionMapper.selectOne(any())).thenReturn(null);
service.saveException(extraWorkException(sunday));
verify(scheduleMapper).updateGeneratedSchedule(any(), eq(LocalTime.of(10, 0)), eq(LocalTime.of(18, 0)), eq(60), eq(1), eq(1), any());
}
@Test
void saveRuleUsesInternalCapacityAndSlotDefaults() {
service.saveRule(rule("DOUBLE_REST", List.of(1, 2, 3, 4, 5), LocalTime.of(9, 0), LocalTime.of(17, 0)));
ArgumentCaptor<Integer> slotCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> capacityCaptor = ArgumentCaptor.forClass(Integer.class);
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), slotCaptor.capture(), capacityCaptor.capture(), any(), any());
assertThat(slotCaptor.getAllValues()).allMatch(value -> value == 60);
assertThat(capacityCaptor.getAllValues()).allMatch(value -> value == 1);
}
@Test
void saveScheduleUpdatesExistingSlotInsteadOfDuplicatingGeneratedRow() {
LocalDate date = LocalDate.now().plusDays(1L);
ArtistScheduleDTO dto = new ArtistScheduleDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setWorkDate(date);
dto.setStartTime(LocalTime.of(9, 0));
dto.setEndTime(LocalTime.of(19, 0));
dto.setSlotMinutes(30);
dto.setCapacity(3);
dto.setStatus(1);
when(scheduleMapper.selectSlotScheduleForUpdate(8L, 30L, date, LocalTime.of(9, 0))).thenReturn(existingSchedule(date));
service.saveSchedule(dto);
verify(scheduleMapper, never()).insert(any(ArtistScheduleDO.class));
verify(scheduleMapper).updateGeneratedSchedule(any(), eq(LocalTime.of(9, 0)), eq(LocalTime.of(19, 0)), eq(30), eq(3), eq(1), any());
}
private ArtistScheduleRuleDTO rule(String presetType, List<Integer> workDays, LocalTime startTime, LocalTime endTime) {
ArtistScheduleRuleDTO dto = new ArtistScheduleRuleDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setPresetType(presetType);
dto.setWorkDays(workDays);
dto.setStartTime(startTime);
dto.setEndTime(endTime);
return dto;
}
private ArtistScheduleExceptionDTO restException(LocalDate date) {
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setWorkDate(date);
dto.setExceptionType("REST");
return dto;
}
private ArtistScheduleExceptionDTO extraWorkException(LocalDate date) {
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setWorkDate(date);
dto.setExceptionType("EXTRA_WORK");
dto.setStartTime(LocalTime.of(10, 0));
dto.setEndTime(LocalTime.of(18, 0));
return dto;
}
private ArtistScheduleRuleDO existingRule() {
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setId(1L);
rule.setShopId(8L);
rule.setArtistId(30L);
rule.setPresetType("DOUBLE_REST");
rule.setWorkDays("1,2,3,4,5");
rule.setStartTime(LocalTime.of(9, 0));
rule.setEndTime(LocalTime.of(17, 0));
rule.setSlotMinutes(60);
rule.setCapacity(1);
rule.setStatus(1);
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleDO existingSchedule(LocalDate date) {
ArtistScheduleDO schedule = new ArtistScheduleDO();
schedule.setId(1000L + date.getDayOfYear());
schedule.setShopId(8L);
schedule.setArtistId(30L);
schedule.setWorkDate(date);
schedule.setStartTime(LocalTime.of(9, 0));
schedule.setEndTime(LocalTime.of(17, 0));
schedule.setSlotMinutes(60);
schedule.setCapacity(1);
schedule.setStatus(1);
schedule.setIsDelete(0);
return schedule;
}
private LocalDate next(DayOfWeek dayOfWeek) {
LocalDate cursor = LocalDate.now();
while (cursor.getDayOfWeek() != dayOfWeek) {
cursor = cursor.plusDays(1L);
}
return cursor;
}
}
@@ -1,292 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO;
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.util.ReflectionTestUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.when;
class NailArtistInfoServiceImplTest {
@Mock
private NailArtistInfoMapper nailArtistInfoMapper;
@Mock
private UserMapper userMapper;
@Mock
private ShopMapper shopMapper;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private ProductMapper productMapper;
@Mock
private OrderMapper orderMapper;
@Mock
private OrderItemMapper orderItemMapper;
@Mock
private OrderArtistReviewMapper orderArtistReviewMapper;
@Mock
private ObjectStorageFileService objectStorageFileService;
@Mock
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Mock
private ArtistScheduleMapper artistScheduleMapper;
@Mock
private AppointmentReservationMapper appointmentReservationMapper;
private NailArtistInfoServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new NailArtistInfoServiceImpl();
ReflectionTestUtils.setField(service, "baseMapper", nailArtistInfoMapper);
ReflectionTestUtils.setField(service, "userMapper", userMapper);
ReflectionTestUtils.setField(service, "shopMapper", shopMapper);
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
ReflectionTestUtils.setField(service, "productMapper", productMapper);
ReflectionTestUtils.setField(service, "orderMapper", orderMapper);
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper);
ReflectionTestUtils.setField(service, "objectStorageFileService", objectStorageFileService);
ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport);
ReflectionTestUtils.setField(service, "artistScheduleMapper", artistScheduleMapper);
ReflectionTestUtils.setField(service, "appointmentReservationMapper", appointmentReservationMapper);
when(userShopBindingSupport.listShopOptionsByUserId(any(), anyBoolean(), anyBoolean())).thenReturn(List.of());
when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class)))
.thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl());
}
@Test
void getPublicProfileAggregatesArtistBasicsWorksReviewsAndAvailability() {
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
artistInfo.setId(11L);
artistInfo.setUserId(7L);
artistInfo.setIdentity("Yumi senior artist");
artistInfo.setExperience(5);
artistInfo.setSkills("法式,猫眼");
artistInfo.setRating(new BigDecimal("4.7"));
artistInfo.setStatus(1);
artistInfo.setPortfolio("31");
artistInfo.setWorkStartTime(LocalTime.of(10, 0));
artistInfo.setWorkEndTime(LocalTime.of(12, 0));
artistInfo.setIsDelete(0);
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
UserDO artist = new UserDO();
artist.setId(7L);
artist.setNickname("Mina");
artist.setAvatar("https://img.test/mina.jpg");
artist.setSignature("Clean lines and soft colors");
artist.setType(3);
artist.setShopId(9L);
artist.setIsDelete(0);
when(userMapper.selectById(7L)).thenReturn(artist);
ShopDO shop = new ShopDO();
shop.setId(9L);
shop.setShopName("Yumi Test Shop");
when(shopMapper.selectById(9L)).thenReturn(shop);
when(userShopBindingSupport.listShopOptionsByUserId(7L, true, true)).thenReturn(List.of());
ProductDO product = new ProductDO();
product.setId(31L);
product.setShopId(9L);
product.setTitle("Soft French");
product.setPrice(new BigDecimal("168.00"));
product.setImageFileIds("201");
product.setTags("通勤;显白");
product.setIsDelete(0);
when(productMapper.selectBatchIds(any())).thenReturn(List.of(product));
ObjectStorageFileVO productImage = new ObjectStorageFileVO();
productImage.setId(201L);
productImage.setFileUrl("https://img.test/product.jpg");
when(objectStorageFileService.getObjectStorageFileMapByIds(any())).thenReturn(Map.of(201L, productImage));
OrderDO completedOrder = new OrderDO();
completedOrder.setId(41L);
completedOrder.setStatus(2);
completedOrder.setIsDelete(0);
when(orderMapper.selectByArtistId(7L)).thenReturn(List.of(completedOrder));
OrderItemDO servedItem = new OrderItemDO();
servedItem.setId(51L);
servedItem.setOrderId(41L);
servedItem.setArtistId(7L);
servedItem.setProductId(31L);
servedItem.setQuantity(2);
servedItem.setIsDelete(0);
when(orderItemMapper.selectByOrderId(41L)).thenReturn(List.of(servedItem));
when(orderItemMapper.selectArtistCalendarItems(any(), any(), any())).thenReturn(List.of());
OrderArtistReviewDO submitted = new OrderArtistReviewDO();
submitted.setId(61L);
submitted.setArtistId(7L);
submitted.setCustomerId(71L);
submitted.setProductId(31L);
submitted.setRatingScore(new BigDecimal("5.0"));
submitted.setContent("Lines are precise");
submitted.setStatus(1);
submitted.setSubmittedAt(LocalDateTime.now().minusDays(1));
submitted.setIsDelete(0);
when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted));
when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(7L)).thenReturn(new BigDecimal("5.0"));
UserDO customer = new UserDO();
customer.setId(71L);
customer.setNickname("Ava");
when(userMapper.selectBatchIds(List.of(71L))).thenReturn(List.of(customer));
NailArtistProfileVO profile = service.getPublicProfile(7L);
assertThat(profile.getArtistId()).isEqualTo(7L);
assertThat(profile.getArtistName()).isEqualTo("Mina");
assertThat(profile.getShopName()).isEqualTo("Yumi Test Shop");
assertThat(profile.getStyleTags()).containsExactly("法式", "猫眼");
assertThat(profile.getRating()).isEqualByComparingTo("5.0");
assertThat(profile.getServiceCount()).isEqualTo(2L);
assertThat(profile.getWorks()).hasSize(1);
assertThat(profile.getWorks().get(0).getCoverImageUrl()).isEqualTo("https://img.test/product.jpg");
assertThat(profile.getReviews()).hasSize(1);
assertThat(profile.getReviews().get(0).getCustomerName()).isEqualTo("Ava");
assertThat(profile.getAvailability()).isNotEmpty();
}
@Test
void listPublicReviewsReturnsSubmittedReviewsOnly() {
OrderArtistReviewDO submitted = new OrderArtistReviewDO();
submitted.setId(61L);
submitted.setArtistId(7L);
submitted.setCustomerId(71L);
submitted.setRatingScore(new BigDecimal("4.5"));
submitted.setContent("Gentle and detailed");
submitted.setStatus(1);
submitted.setSubmittedAt(LocalDateTime.now().minusHours(2));
submitted.setIsDelete(0);
when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted));
UserDO customer = new UserDO();
customer.setId(71L);
customer.setNickname("Ava");
when(userMapper.selectBatchIds(List.of(71L))).thenReturn(List.of(customer));
List<NailArtistReviewVO> reviews = service.listPublicReviews(7L);
assertThat(reviews).hasSize(1);
assertThat(reviews.get(0).getRating()).isEqualByComparingTo("4.5");
assertThat(reviews.get(0).getContent()).isEqualTo("Gentle and detailed");
}
@Test
void getAvailabilitySkipsBookedSlots() {
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
artistInfo.setUserId(7L);
artistInfo.setStatus(1);
artistInfo.setWorkStartTime(LocalTime.of(10, 0));
artistInfo.setWorkEndTime(LocalTime.of(12, 0));
artistInfo.setIsDelete(0);
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
UserDO artist = new UserDO();
artist.setId(7L);
artist.setType(3);
artist.setIsDelete(0);
when(userMapper.selectById(7L)).thenReturn(artist);
OrderItemDO booked = new OrderItemDO();
booked.setArtistId(7L);
booked.setAppointmentTime(LocalDateTime.now().plusDays(1).withHour(10).withMinute(0).withSecond(0).withNano(0));
when(orderItemMapper.selectArtistCalendarItems(any(), any(), any())).thenReturn(List.of(booked));
List<NailArtistAvailabilityVO> slots = service.getAvailability(7L);
assertThat(slots).isNotEmpty();
assertThat(slots)
.noneMatch(slot -> slot.getStartTime().toLocalDate().equals(booked.getAppointmentTime().toLocalDate())
&& slot.getStartTime().toLocalTime().equals(LocalTime.of(10, 0)));
}
@Test
void getAvailabilityUsesScheduleCapacityWhenConfigured() {
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
artistInfo.setUserId(7L);
artistInfo.setStatus(1);
artistInfo.setWorkStartTime(LocalTime.of(10, 0));
artistInfo.setWorkEndTime(LocalTime.of(12, 0));
artistInfo.setIsDelete(0);
when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo);
UserDO artist = new UserDO();
artist.setId(7L);
artist.setType(3);
artist.setShopId(9L);
artist.setIsDelete(0);
when(userMapper.selectById(7L)).thenReturn(artist);
ShopDO shop = new ShopDO();
shop.setId(9L);
shop.setShopName("Yumi Test Shop");
ShopSimpleVO shopOption = new ShopSimpleVO();
shopOption.setId(9L);
shopOption.setShopName("Yumi Test Shop");
when(shopMapper.selectById(9L)).thenReturn(shop);
when(userShopBindingSupport.listShopOptionsByUserId(7L, true, true)).thenReturn(List.of(shopOption));
LocalDate workDate = LocalDate.now().plusDays(1);
ArtistScheduleDO schedule = new ArtistScheduleDO();
schedule.setShopId(9L);
schedule.setArtistId(7L);
schedule.setWorkDate(workDate);
schedule.setStartTime(LocalTime.of(10, 0));
schedule.setEndTime(LocalTime.of(12, 0));
schedule.setSlotMinutes(60);
schedule.setCapacity(1);
schedule.setStatus(1);
schedule.setIsDelete(0);
when(artistScheduleMapper.selectList(any())).thenReturn(List.of(schedule));
when(appointmentReservationMapper.countOverlappingActive(any(), any(), any()))
.thenReturn(1)
.thenReturn(0);
List<NailArtistAvailabilityVO> slots = service.getAvailability(7L);
assertThat(slots).hasSize(1);
assertThat(slots.get(0).getStartTime().toLocalDate()).isEqualTo(workDate);
assertThat(slots.get(0).getStartTime().toLocalTime()).isEqualTo(LocalTime.of(11, 0));
}
}
@@ -1,17 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file;
import com.xiaowang.fingertipdesigner.core.modules.file.config.AliyunOssConfig;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class FileObjectStorageConfigurationTest {
@Test
void aliyunOssConfigDoesNotHardCodeEnvironmentValues() {
AliyunOssConfig config = new AliyunOssConfig();
assertThat(config.getBucketName()).isNull();
assertThat(config.getSignedUrlExpireMinutes()).isNull();
}
}
@@ -1,96 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file.controller.front;
import com.xiaowang.fingertipdesigner.core.common.Result;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.EffectDiagramMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class FrontendFileControllerTest {
private ObjectStorageFileService objectStorageFileService;
private ObjectStorageUrlSupport objectStorageUrlSupport;
private ProductMapper productMapper;
private ShopMapper shopMapper;
private EffectDiagramMapper effectDiagramMapper;
private FrontendFileController controller;
@BeforeEach
void setUp() {
objectStorageFileService = mock(ObjectStorageFileService.class);
objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class);
productMapper = mock(ProductMapper.class);
shopMapper = mock(ShopMapper.class);
effectDiagramMapper = mock(EffectDiagramMapper.class);
controller = new FrontendFileController(
objectStorageFileService,
objectStorageUrlSupport,
productMapper,
shopMapper,
effectDiagramMapper
);
}
@Test
void getSignedUrlRejectsAvailableFileWhenItIsNotPubliclyReferenced() throws Exception {
ObjectStorageFileVO file = file();
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
when(productMapper.countPublicImageReference(12L)).thenReturn(0L);
when(shopMapper.countPublicImageReference(12L)).thenReturn(0L);
when(effectDiagramMapper.countPublicImageReference(12L)).thenReturn(0L);
Result<String> result = controller.getSignedUrl(12L, 60);
assertThat(result.getCode()).isNotEqualTo(200);
verify(objectStorageUrlSupport, never()).toAccessibleUrl(any(ObjectStorageFileVO.class), anyInt());
verify(objectStorageUrlSupport, never()).getSignedUrlOrThrow(any(ObjectStorageFileVO.class), anyInt());
}
@Test
void getSignedUrlAllowsPublicProductImageReference() throws Exception {
ObjectStorageFileVO file = file();
file.setObjectName("public/a.png");
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
when(productMapper.countPublicImageReference(12L)).thenReturn(1L);
when(objectStorageUrlSupport.getSignedUrlOrThrow(file, 30)).thenReturn("https://signed.test/public/a.png");
Result<String> result = controller.getSignedUrl(12L, 30);
assertThat(result.getCode()).isEqualTo(200);
assertThat(result.getData()).isEqualTo("https://signed.test/public/a.png");
}
@Test
void getSignedUrlFallsBackToOriginalPublicExternalUrlWhenObjectNameCannotBeExtracted() throws Exception {
ObjectStorageFileVO file = file();
file.setFileUrl("https://acceptance.local/images/public-a.png");
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
when(productMapper.countPublicImageReference(12L)).thenReturn(1L);
Result<String> result = controller.getSignedUrl(12L, 30);
assertThat(result.getCode()).isEqualTo(200);
assertThat(result.getData()).isEqualTo("https://acceptance.local/images/public-a.png");
verify(objectStorageUrlSupport, never()).getSignedUrlOrThrow(any(ObjectStorageFileVO.class), anyInt());
}
private ObjectStorageFileVO file() {
ObjectStorageFileVO file = new ObjectStorageFileVO();
file.setId(12L);
file.setStatus(1);
file.setFileUrl("https://cdn.test/public/a.png");
return file;
}
}
@@ -1,67 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file.scheduler;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties;
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO;
import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageReplicaMapper;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageBackupService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ObjectStorageBackupRetrySchedulerTest {
private ObjectStorageReplicaMapper objectStorageReplicaMapper;
private ObjectStorageBackupService objectStorageBackupService;
private ObjectStorageBackupRetryScheduler scheduler;
@BeforeEach
void setUp() {
objectStorageReplicaMapper = mock(ObjectStorageReplicaMapper.class);
objectStorageBackupService = mock(ObjectStorageBackupService.class);
scheduler = new ObjectStorageBackupRetryScheduler(
objectStorageReplicaMapper,
objectStorageBackupService,
objectStorageProperties()
);
}
@Test
void retryPendingOrFailedBackupsScansRetryableFilesAndDispatchesBackup() {
ObjectStorageReplicaDO pending = new ObjectStorageReplicaDO();
pending.setFileId(1L);
ObjectStorageReplicaDO failed = new ObjectStorageReplicaDO();
failed.setFileId(2L);
when(objectStorageReplicaMapper.selectList(any())).thenReturn(List.of(pending, failed));
scheduler.retryPendingOrFailedBackups();
@SuppressWarnings("unchecked")
ArgumentCaptor<Wrapper<ObjectStorageReplicaDO>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(objectStorageReplicaMapper).selectList(captor.capture());
assertThat(captor.getValue()).isNotNull();
verify(objectStorageBackupService).backupFile(1L);
verify(objectStorageBackupService).backupFile(2L);
}
private ObjectStorageProperties objectStorageProperties() {
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setPrimaryProvider("QINIU_KODO");
properties.setBackupProvider("ALIYUN_OSS");
properties.setSignedUrlExpireMinutes(60);
properties.setBackupQueueName("test.queue");
properties.setBackupExchangeName("test.exchange");
properties.setBackupRoutingKey("test.routing");
properties.setBackupRetryBatchLimit(500);
properties.setBackupRetryCron("0 0 2 * * ?");
return properties;
}
}
@@ -1,88 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageFileMapper;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ObjectStorageBackupServiceImplTest {
private ObjectStorageFileMapper objectStorageFileMapper;
private ObjectStorageOrchestrationService objectStorageOrchestrationService;
private ObjectStorageFileService objectStorageFileService;
private ObjectStorageBackupServiceImpl service;
@BeforeEach
void setUp() {
objectStorageFileMapper = mock(ObjectStorageFileMapper.class);
objectStorageOrchestrationService = mock(ObjectStorageOrchestrationService.class);
objectStorageFileService = mock(ObjectStorageFileService.class);
service = new ObjectStorageBackupServiceImpl(
objectStorageFileMapper,
objectStorageOrchestrationService,
objectStorageFileService
);
}
@Test
void backupFileMarksFileSucceededAfterCompletingReplicas() {
ObjectStorageFileDO file = activePrimaryFile();
when(objectStorageFileMapper.selectById(88L)).thenReturn(file);
service.backupFile(88L);
verify(objectStorageOrchestrationService).completeReplicas(file);
ArgumentCaptor<ObjectStorageFileDO> captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
verify(objectStorageFileMapper).updateById(captor.capture());
ObjectStorageFileDO updated = captor.getValue();
assertThat(updated.getId()).isEqualTo(88L);
assertThat(updated.getBackupUploadStatus()).isEqualTo(1);
assertThat(updated.getBackupUploadedAt()).isNotNull();
assertThat(updated.getBackupLastError()).isNull();
verify(objectStorageFileService).evictObjectStorageFileCache(88L);
}
@Test
void backupFileMarksFileFailedAndTruncatesErrorWhenReplicaCompletionFails() {
ObjectStorageFileDO file = activePrimaryFile();
file.setBackupRetryCount(2);
when(objectStorageFileMapper.selectById(88L)).thenReturn(file);
doThrow(new IllegalStateException("x".repeat(700)))
.when(objectStorageOrchestrationService)
.completeReplicas(file);
service.backupFile(88L);
ArgumentCaptor<ObjectStorageFileDO> captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
verify(objectStorageFileMapper).updateById(captor.capture());
ObjectStorageFileDO updated = captor.getValue();
assertThat(updated.getBackupUploadStatus()).isEqualTo(2);
assertThat(updated.getBackupRetryCount()).isEqualTo(3);
assertThat(updated.getBackupLastRetryTime()).isNotNull();
assertThat(updated.getBackupLastError()).hasSizeLessThanOrEqualTo(500);
verify(objectStorageFileService).evictObjectStorageFileCache(88L);
}
private ObjectStorageFileDO activePrimaryFile() {
ObjectStorageFileDO file = new ObjectStorageFileDO();
file.setId(88L);
file.setStatus(1);
file.setObjectName("product/a.png");
file.setPrimaryProvider("QINIU_KODO");
file.setBackupProvider("ALIYUN_OSS");
file.setPrimaryUploadStatus(1);
file.setBackupUploadStatus(0);
file.setContentType("image/png");
file.setFileSize(3L);
return file;
}
}
@@ -1,91 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file.service.impl;
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties;
import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageFileMapper;
import com.xiaowang.fingertipdesigner.core.modules.file.mq.ObjectStorageBackupMessagePublisher;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ObjectStorageFileServiceImplTest {
private ObjectStorageFileMapper objectStorageFileMapper;
private ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher;
private ObjectStorageReplicaService objectStorageReplicaService;
private ObjectStorageFileServiceImpl service;
@BeforeEach
void setUp() {
objectStorageFileMapper = mock(ObjectStorageFileMapper.class);
MultiLevelCacheService multiLevelCacheService = mock(MultiLevelCacheService.class);
AppCacheProperties appCacheProperties = new AppCacheProperties();
objectStorageBackupMessagePublisher = mock(ObjectStorageBackupMessagePublisher.class);
objectStorageReplicaService = mock(ObjectStorageReplicaService.class);
service = new ObjectStorageFileServiceImpl(
objectStorageFileMapper,
multiLevelCacheService,
appCacheProperties,
objectStorageBackupMessagePublisher,
objectStorageProperties(),
objectStorageReplicaService
);
}
@Test
void createObjectStorageFilePublishesBackupMessageAfterPrimaryUploadSucceeded() {
when(objectStorageFileMapper.insert(any(ObjectStorageFileDO.class))).thenAnswer(invocation -> {
ObjectStorageFileDO file = invocation.getArgument(0);
file.setId(66L);
return 1;
});
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName("a.png");
dto.setFileUrl("https://cdn.test/product/a.png");
dto.setObjectName("product/a.png");
dto.setPrimaryProvider("QINIU_KODO");
dto.setPrimaryUrl(dto.getFileUrl());
dto.setBackupProvider("ALIYUN_OSS");
dto.setContentType("image/png");
dto.setFileSize(3L);
dto.setStatus(1);
dto.setPrimaryUploadStatus(1);
dto.setBackupUploadStatus(0);
dto.setBackupRetryCount(0);
Long fileId = service.createObjectStorageFile(dto);
assertThat(fileId).isEqualTo(66L);
ArgumentCaptor<ObjectStorageFileDO> captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
verify(objectStorageFileMapper).insert(captor.capture());
assertThat(captor.getValue().getObjectName()).isEqualTo("product/a.png");
assertThat(captor.getValue().getPrimaryUploadStatus()).isEqualTo(1);
assertThat(captor.getValue().getBackupUploadStatus()).isEqualTo(0);
verify(objectStorageReplicaService).saveInitialReplicas(66L, dto.getUploadAttempts());
verify(objectStorageBackupMessagePublisher).publish(66L);
}
private ObjectStorageProperties objectStorageProperties() {
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setPrimaryProvider("QINIU_KODO");
properties.setBackupProvider("ALIYUN_OSS");
properties.setSignedUrlExpireMinutes(60);
properties.setBackupQueueName("test.queue");
properties.setBackupExchangeName("test.exchange");
properties.setBackupRoutingKey("test.routing");
properties.setBackupRetryBatchLimit(500);
properties.setBackupRetryCron("0 0 2 * * ?");
return properties;
}
}
@@ -1,153 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.file.support;
import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties;
import com.xiaowang.fingertipdesigner.core.modules.file.config.QiniuKodoConfig;
import com.xiaowang.fingertipdesigner.core.modules.file.service.AliyunOssService;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.fingertipdesigner.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class ObjectStorageUrlSupportTest {
private PrimaryObjectStorageService primaryObjectStorageService;
private AliyunOssService aliyunOssService;
private ObjectStorageOrchestrationService objectStorageOrchestrationService;
private ObjectStorageUrlSupport support;
@BeforeEach
void setUp() {
primaryObjectStorageService = mock(PrimaryObjectStorageService.class);
aliyunOssService = mock(AliyunOssService.class);
objectStorageOrchestrationService = mock(ObjectStorageOrchestrationService.class);
QiniuKodoConfig qiniuKodoConfig = new QiniuKodoConfig();
qiniuKodoConfig.setDomain("https://cdn.test");
support = new ObjectStorageUrlSupport(
primaryObjectStorageService,
qiniuKodoConfig,
aliyunOssService,
objectStorageProperties(),
objectStorageOrchestrationService
);
}
@Test
void toAccessibleUrlFallsBackToOriginalExternalUrlWhenObjectNameCannotBeExtracted() {
String externalUrl = "https://acceptance.local/assets/product-a.jpg";
String result = support.toAccessibleUrl(externalUrl);
assertThat(result).isEqualTo(externalUrl);
verifyNoInteractions(primaryObjectStorageService, aliyunOssService, objectStorageOrchestrationService);
}
@Test
void extractObjectNameStillAcceptsRawObjectName() {
assertThat(support.extractObjectName("product/a.jpg?x=1")).isEqualTo("product/a.jpg");
}
@Test
void toAccessibleUrlMatchesHttpFileUrlWhenQiniuDomainMissesScheme() throws Exception {
QiniuKodoConfig qiniuKodoConfig = new QiniuKodoConfig();
qiniuKodoConfig.setDomain("img.example.com");
ObjectStorageUrlSupport urlSupport = new ObjectStorageUrlSupport(
primaryObjectStorageService,
qiniuKodoConfig,
aliyunOssService,
objectStorageProperties(),
objectStorageOrchestrationService
);
when(objectStorageOrchestrationService.getPresignedUrl("product/a.jpg", 60))
.thenReturn("http://img.example.com/product/a.jpg?e=1&token=test");
assertThat(urlSupport.toAccessibleUrl("http://img.example.com/product/a.jpg"))
.isEqualTo("http://img.example.com/product/a.jpg?e=1&token=test");
}
@Test
void toAccessibleUrlReturnsNullInsteadOfRawUrlWhenStringObjectSigningFails() throws Exception {
when(objectStorageOrchestrationService.getPresignedUrl("product/a.jpg", 60))
.thenThrow(new IllegalStateException("primary down"));
String result = support.toAccessibleUrl("https://cdn.test/product/a.jpg");
assertThat(result).isNull();
}
@Test
void toAccessibleUrlFallsBackToBackupSignedUrlWhenPrimarySigningFailsAndBackupSucceeded() throws Exception {
ObjectStorageFileVO file = new ObjectStorageFileVO();
file.setId(12L);
file.setFileUrl("https://cdn.test/product/a.png");
file.setPrimaryUrl("https://cdn.test/product/a.png");
file.setObjectName("product/a.png");
file.setBackupUploadStatus(1);
when(objectStorageOrchestrationService.getPresignedUrl(12L, "product/a.png", 60))
.thenThrow(new IllegalStateException("primary down"));
when(aliyunOssService.getPresignedUrl("product/a.png")).thenReturn("https://oss-signed.test/product/a.png");
String result = support.toAccessibleUrl(file);
assertThat(result).isEqualTo("https://oss-signed.test/product/a.png");
}
@Test
void toAccessibleUrlReturnsNullInsteadOfRawObjectStorageUrlWhenBothBackendsAreUnavailable() throws Exception {
ObjectStorageFileVO file = new ObjectStorageFileVO();
file.setId(12L);
file.setFileUrl("https://cdn.test/product/a.png");
file.setPrimaryUrl("https://cdn.test/product/a.png");
file.setObjectName("product/a.png");
file.setBackupUploadStatus(1);
when(objectStorageOrchestrationService.getPresignedUrl(12L, "product/a.png", 60))
.thenThrow(new IllegalStateException("primary down"));
when(aliyunOssService.getPresignedUrl("product/a.png")).thenThrow(new IllegalStateException("backup down"));
String result = support.toAccessibleUrl(file);
assertThat(result).isNull();
}
@Test
void getSignedUrlOrThrowReportsClearFailureWhenBothBackendsAreUnavailable() throws Exception {
ObjectStorageFileVO file = new ObjectStorageFileVO();
file.setId(12L);
file.setFileUrl("https://cdn.test/product/a.png");
file.setObjectName("product/a.png");
file.setBackupUploadStatus(1);
when(objectStorageOrchestrationService.getPresignedUrl(12L, "product/a.png", 20))
.thenThrow(new IllegalStateException("primary down"));
when(aliyunOssService.getPresignedUrl("product/a.png")).thenThrow(new IllegalStateException("backup down"));
assertThatThrownBy(() -> support.getSignedUrlOrThrow(file, 20))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No available object storage signed URL");
}
private ObjectStorageProperties objectStorageProperties() {
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setPrimaryProvider("QINIU_KODO");
properties.setBackupProvider("ALIYUN_OSS");
properties.setSignedUrlExpireMinutes(60);
properties.setBackupQueueName("test.queue");
properties.setBackupExchangeName("test.exchange");
properties.setBackupRoutingKey("test.routing");
properties.setBackupRetryBatchLimit(500);
properties.setBackupRetryCron("0 0 2 * * ?");
return properties;
}
}
@@ -1,63 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.integration.entity.BusinessEventOutboxDO;
import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.BusinessEventOutboxMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Scheduled;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class BusinessEventOutboxServiceTest {
@Mock
private BusinessEventOutboxMapper outboxMapper;
private BusinessEventOutboxServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new BusinessEventOutboxServiceImpl(outboxMapper);
}
@Test
void enqueueOrderCompletedCreatesIdempotentEvent() {
service.enqueueOrderCompleted(1L);
ArgumentCaptor<BusinessEventOutboxDO> captor = ArgumentCaptor.forClass(BusinessEventOutboxDO.class);
verify(outboxMapper).insert(captor.capture());
BusinessEventOutboxDO event = captor.getValue();
assertThat(event.getEventType()).isEqualTo("ORDER_COMPLETED");
assertThat(event.getBusinessType()).isEqualTo("ORDER");
assertThat(event.getBusinessId()).isEqualTo(1L);
assertThat(event.getEventKey()).isEqualTo("ORDER:1:COMPLETED");
assertThat(event.getStatus()).isEqualTo("PENDING");
assertThat(event.getPayloadJson()).contains("\"orderId\":1");
}
@Test
void duplicateOrderCompletedEventIsIgnored() {
when(outboxMapper.insert(any(BusinessEventOutboxDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
service.enqueueOrderCompleted(1L);
verify(outboxMapper).insert(any(BusinessEventOutboxDO.class));
}
@Test
void processorPollsFrequentlyEnoughForOrderReviewPromptAcceptanceWindow() throws NoSuchMethodException {
Scheduled scheduled = BusinessEventOutboxProcessor.class.getMethod("processDueEvents")
.getAnnotation(Scheduled.class);
assertThat(scheduled).isNotNull();
assertThat(scheduled.fixedDelay()).isLessThanOrEqualTo(3000L);
}
}
@@ -1,127 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.fingertipdesigner.core.config.BrandProperties;
import com.xiaowang.fingertipdesigner.core.modules.integration.entity.MessageHubPushConfigDO;
import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubPushConfigService;
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class MessageHubClientServiceImplTest {
private static final long ALIYUN_CHANNEL_ID = 314055468907909120L;
@Mock
private RabbitTemplate rabbitTemplate;
@Mock
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
@Mock
private MessageHubPushConfigService messageHubPushConfigService;
@Mock
private BrandProperties brandProperties;
private final ObjectMapper objectMapper = new ObjectMapper();
private MessageHubClientServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new MessageHubClientServiceImpl(
rabbitTemplate,
objectMapper,
snowflakeIdGenerator,
messageHubPushConfigService,
brandProperties
);
when(snowflakeIdGenerator.nextIdString()).thenReturn("sms-message-1");
}
@Test
void registerVerificationMessageIncludesAliyunTemplateParameters() throws Exception {
String sceneCode = "USER_REGISTER_SMS_CODE";
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
.thenReturn(aliyunConfig(sceneCode, "100001"));
service.sendSmsVerificationCode(sceneCode, "13800138000", "123456");
Map<String, Object> messageBody = capturedMessageBody();
assertThat(messageBody)
.containsEntry("templateCode", "100001")
.containsEntry("sourceSystem", "fingertipdesigner")
.containsEntry("sendMethod", "OTHER");
assertThat(((Number) messageBody.get("channelId")).longValue()).isEqualTo(ALIYUN_CHANNEL_ID);
Map<String, Object> templateParams = templateParams(messageBody);
assertThat(templateParams)
.containsEntry("code", "123456")
.containsEntry("min", "5")
.containsEntry("minutes", "5")
.containsEntry("number", "5");
}
@Test
void resetPasswordVerificationMessageUsesResetTemplateWithAliyunParameters() throws Exception {
String sceneCode = "USER_RESET_PASSWORD_SMS_CODE";
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
.thenReturn(aliyunConfig(sceneCode, "100003"));
service.sendSmsVerificationCode(sceneCode, "13800138000", "654321");
Map<String, Object> messageBody = capturedMessageBody();
assertThat(messageBody).containsEntry("templateCode", "100003");
assertThat(((Number) messageBody.get("channelId")).longValue()).isEqualTo(ALIYUN_CHANNEL_ID);
Map<String, Object> templateParams = templateParams(messageBody);
assertThat(templateParams)
.containsEntry("code", "654321")
.containsEntry("min", "5")
.containsEntry("minutes", "5")
.containsEntry("number", "5");
}
private MessageHubPushConfigDO aliyunConfig(String sceneCode, String templateCode) {
MessageHubPushConfigDO config = new MessageHubPushConfigDO();
config.setSceneCode(sceneCode);
config.setPlatform("SMS");
config.setMsgType("VERIFICATION");
config.setQueueName("smsQueue");
config.setSourceSystem("fingertipdesigner");
config.setTemplateCode(templateCode);
config.setChannelId(ALIYUN_CHANNEL_ID);
config.setSendMethod("OTHER");
config.setEnabled(1);
config.setIsDelete(0);
return config;
}
private Map<String, Object> capturedMessageBody() throws Exception {
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(rabbitTemplate).convertAndSend(eq("smsQueue"), messageCaptor.capture());
String jsonBody = new String(messageCaptor.getValue().getBody(), StandardCharsets.UTF_8);
return objectMapper.readValue(jsonBody, new TypeReference<Map<String, Object>>() {});
}
@SuppressWarnings("unchecked")
private Map<String, Object> templateParams(Map<String, Object> messageBody) {
return (Map<String, Object>) messageBody.get("templateParams");
}
}
@@ -1,184 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.fingertipdesigner.core.common.BusinessException;
import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO;
import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.integration.entity.WechatMiniBindingDO;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.WechatMiniBindingMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService;
import com.xiaowang.fingertipdesigner.core.modules.integration.service.WechatMiniClientService;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO;
import com.xiaowang.fingertipdesigner.core.modules.integration.vo.WechatMiniLoginResultVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.xiaowang.fingertipdesigner.core.common.Result;
class WechatMiniAuthServiceImplTest {
@Mock
private WechatMiniClientService wechatMiniClientService;
@Mock
private WechatMiniBindingMapper wechatMiniBindingMapper;
@Mock
private UserMapper userMapper;
@Mock
private UserService userService;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private StringRedisTemplate redisTemplate;
@Mock
private ValueOperations<String, String> valueOperations;
private WechatMiniAuthServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
initTableInfo(WechatMiniBindingDO.class);
initTableInfo(UserDO.class);
service = new WechatMiniAuthServiceImpl(
wechatMiniClientService,
wechatMiniBindingMapper,
userMapper,
userService,
userShopBindingSupport,
redisTemplate,
new ObjectMapper(),
new TimeOrderedSnowflakeIdGenerator(1704067200000L, 1L, 1L, "test-app")
);
}
private void initTableInfo(Class<?> entityClass) {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
assistant.setCurrentNamespace(entityClass.getName());
TableInfoHelper.initTableInfo(assistant, entityClass);
}
@Test
void autoLoginShouldDeactivateInvalidBindingAndFallbackToManualLogin() {
WechatMiniAutoLoginRequestDTO requestDTO = new WechatMiniAutoLoginRequestDTO();
requestDTO.setWxCode("wx-code");
when(wechatMiniClientService.code2Session("wx-code"))
.thenReturn(new WechatMiniClientService.SessionInfo("openid-1", "union-1", "session-1"));
WechatMiniBindingDO bindingDO = new WechatMiniBindingDO();
bindingDO.setId(100L);
bindingDO.setUserId(200L);
bindingDO.setStatus(1);
when(wechatMiniBindingMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(bindingDO);
UserDO deletedUser = new UserDO();
deletedUser.setId(200L);
deletedUser.setIsDelete(1);
when(userMapper.selectById(200L)).thenReturn(deletedUser);
WechatMiniLoginResultVO result = service.autoLogin(requestDTO);
assertEquals(WechatMiniLoginResultVO.STATUS_NEED_MANUAL_LOGIN, result.getStatus());
assertFalse(Boolean.TRUE.equals(result.getNewUser()));
verify(wechatMiniBindingMapper).update(eq(null), any(LambdaUpdateWrapper.class));
}
@Test
void phoneLoginShouldReturnSelectShopWhenNewWechatPhoneNeedsShopSelection() {
WechatMiniPhoneLoginRequestDTO requestDTO = new WechatMiniPhoneLoginRequestDTO();
requestDTO.setWxCode("wx-code");
requestDTO.setPhoneCode("phone-code");
when(wechatMiniClientService.code2Session("wx-code"))
.thenReturn(new WechatMiniClientService.SessionInfo("openid-2", "union-2", "session-2"));
when(wechatMiniClientService.getPhoneNumber("phone-code")).thenReturn("13800138000");
when(wechatMiniBindingMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
when(userMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
when(userShopBindingSupport.listAllActiveShopOptions()).thenReturn(List.of(
new ShopSimpleVO(1L, "A 店"),
new ShopSimpleVO(2L, "B 店")
));
WechatMiniLoginResultVO result = service.phoneLogin(requestDTO);
assertEquals(WechatMiniLoginResultVO.STATUS_SELECT_SHOP, result.getStatus());
assertTrue(Boolean.TRUE.equals(result.getNewUser()));
assertEquals(2, result.getShops().size());
}
@Test
void ensureBindingShouldDeactivateHistoricalDuplicatesAndKeepSingleActiveRecord() {
when(wechatMiniClientService.getConfiguredAppId()).thenReturn("mini-app");
WechatMiniBindingDO currentBinding = new WechatMiniBindingDO();
currentBinding.setId(1L);
currentBinding.setUserId(8L);
currentBinding.setOpenId("openid-3");
currentBinding.setAppId("mini-app");
currentBinding.setStatus(1);
WechatMiniBindingDO duplicateBinding = new WechatMiniBindingDO();
duplicateBinding.setId(2L);
duplicateBinding.setUserId(8L);
duplicateBinding.setOpenId("openid-legacy");
duplicateBinding.setAppId("mini-app");
duplicateBinding.setStatus(0);
when(wechatMiniBindingMapper.selectList(any(LambdaQueryWrapper.class)))
.thenReturn(List.of(currentBinding), List.of(currentBinding, duplicateBinding));
service.ensureBinding(8L, "openid-3", "union-3");
verify(wechatMiniBindingMapper).updateById(currentBinding);
verify(wechatMiniBindingMapper).update(eq(null), any(LambdaUpdateWrapper.class));
verify(wechatMiniBindingMapper, never()).insert(any(WechatMiniBindingDO.class));
}
@Test
void ensureBindingShouldRejectOtherUsersActiveBinding() {
when(wechatMiniClientService.getConfiguredAppId()).thenReturn("mini-app");
WechatMiniBindingDO activeBinding = new WechatMiniBindingDO();
activeBinding.setId(11L);
activeBinding.setUserId(9L);
activeBinding.setOpenId("openid-4");
activeBinding.setAppId("mini-app");
activeBinding.setStatus(1);
when(wechatMiniBindingMapper.selectList(any(LambdaQueryWrapper.class)))
.thenReturn(List.of(activeBinding), List.of());
BusinessException exception = assertThrows(BusinessException.class, () -> service.ensureBinding(8L, "openid-4", "union-4"));
assertEquals("当前微信已绑定其他账号,无法完成登录", exception.getMessage());
}
}
@@ -1,61 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.fingertipdesigner.core.common.BusinessException;
import com.xiaowang.fingertipdesigner.core.config.WechatMiniProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
class WechatMiniClientServiceImplTest {
@Mock
private RestTemplate restTemplate;
@Mock
private StringRedisTemplate redisTemplate;
@Mock
private ValueOperations<String, String> valueOperations;
private WechatMiniClientServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
WechatMiniProperties properties = new WechatMiniProperties();
properties.setAppId("app-id");
properties.setAppSecret("app-secret");
service = new WechatMiniClientServiceImpl(restTemplate, redisTemplate, new ObjectMapper(), properties);
}
@Test
void getPhoneNumberShouldFailWhenWechatResponseMissesPhoneInfo() {
when(valueOperations.get(anyString())).thenReturn(null);
when(restTemplate.getForObject(anyString(), any())).thenReturn("{\"access_token\":\"access-token\",\"expires_in\":7200}");
when(restTemplate.postForObject(anyString(), any(HttpEntity.class), any())).thenReturn("{\"errcode\":0}");
BusinessException exception = assertThrows(BusinessException.class, () -> service.getPhoneNumber("phone-code"));
assertEquals("获取微信手机号失败:未返回手机号信息", exception.getMessage());
}
@Test
void code2SessionShouldFailWhenWechatResponseMissesOpenId() {
when(restTemplate.getForObject(anyString(), any())).thenReturn("{\"errcode\":0,\"session_key\":\"abc\"}");
BusinessException exception = assertThrows(BusinessException.class, () -> service.code2Session("wx-code"));
assertEquals("获取微信登录身份失败:缺少 openid", exception.getMessage());
}
}
@@ -1,280 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.manager.controller.admin;
import com.xiaowang.fingertipdesigner.core.common.Result;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.fingertipdesigner.core.modules.manager.dto.ManagerCustomerCreateDTO;
import com.xiaowang.fingertipdesigner.core.modules.planning.service.PlanningService;
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO;
import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService;
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO;
import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService;
import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AdminManagerControllerTest {
@Mock
private PlanningService planningService;
@Mock
private UserService userService;
@Mock
private NailArtistInfoService nailArtistInfoService;
@Mock
private ArtistScheduleService artistScheduleService;
@Mock
private ProductService productService;
@Mock
private ShopService shopService;
@Mock
private AdminScopeHelper adminScopeHelper;
private AdminManagerController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
controller = new AdminManagerController(planningService, userService, nailArtistInfoService, artistScheduleService, productService, shopService, adminScopeHelper);
}
@Test
void controllerShouldExposeManagerBoundary() {
RequestMapping mapping = AdminManagerController.class.getAnnotation(RequestMapping.class);
assertThat(mapping.value()).containsExactly("/admin/manager");
}
@Test
void customersShouldResolveShopScopeAndForceCustomerType() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setType(2);
manager.setShopId(8L);
PageResultVO<UserVO> pageResult = new PageResultVO<>();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(userService.pageUsers(1, 10, "ann", 8L, 0, null, null, null, null, null, null, null, null, true)).thenReturn(pageResult);
Result<PageResultVO<UserVO>> result = controller.customers(request, 1, 10, "ann", 99L, true);
assertThat(result.getData()).isSameAs(pageResult);
verify(adminScopeHelper).resolveShopScope(manager, 99L);
verify(userService).pageUsers(1, 10, "ann", 8L, 0, null, null, null, null, null, null, null, null, true);
}
@Test
void createEmployeeUserShouldBindNonPlatformUserToManagedShop() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setType(2);
manager.setShopId(8L);
UserDTO dto = new UserDTO();
dto.setType(3);
dto.setShopId(99L);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
when(adminScopeHelper.getManagedShopId(manager)).thenReturn(8L);
when(userService.createUser(dto)).thenReturn(101L);
Result<Long> result = controller.createEmployeeUser(request, dto);
assertThat(result.getData()).isEqualTo(101L);
assertThat(dto.getShopId()).isEqualTo(8L);
assertThat(dto.getShopIds()).containsExactly(8L);
verify(adminScopeHelper).ensureAssignableUserType(manager, 3);
}
@Test
void createEmployeeUserShouldForceNailArtistType() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setType(2);
UserDTO dto = new UserDTO();
dto.setType(0);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(true);
when(userService.createUser(dto)).thenReturn(102L);
Result<Long> result = controller.createEmployeeUser(request, dto);
assertThat(result.getData()).isEqualTo(102L);
assertThat(dto.getType()).isEqualTo(3);
verify(adminScopeHelper).ensureAssignableUserType(manager, 3);
}
@Test
void createCustomerShouldForceNormalUserInCurrentShop() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setType(2);
ManagerCustomerCreateDTO dto = new ManagerCustomerCreateDTO();
dto.setNickname(" 小王客户 ");
dto.setPhone(" 13800138000 ");
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(userService.createUser(any(UserDTO.class))).thenReturn(103L);
Result<Long> result = controller.createCustomer(request, dto);
assertThat(result.getData()).isEqualTo(103L);
verify(adminScopeHelper).requireShopContext(manager, "请先选择店铺后再新增客户");
verify(userService).createUser(org.mockito.ArgumentMatchers.argThat(userDTO ->
"小王客户".equals(userDTO.getNickname())
&& "13800138000".equals(userDTO.getPhone())
&& "13800138000".equals(userDTO.getContactPhone())
&& "13800138000".equals(userDTO.getAccount())
&& Integer.valueOf(0).equals(userDTO.getType())
&& Long.valueOf(8L).equals(userDTO.getShopId())
&& userDTO.getShopIds().equals(List.of(8L))
&& "普通".equals(userDTO.getLevel())
&& Long.valueOf(0L).equals(userDTO.getVipId())
));
}
@Test
void saveScheduleShouldResolveShopScopeBeforeSaving() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleDTO dto = new ArtistScheduleDTO();
dto.setShopId(99L);
ArtistScheduleVO vo = new ArtistScheduleVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(artistScheduleService.saveSchedule(dto)).thenReturn(vo);
Result<ArtistScheduleVO> result = controller.saveSchedule(request, dto);
assertThat(result.getData()).isSameAs(vo);
assertThat(dto.getShopId()).isEqualTo(8L);
}
@Test
void scheduleRuleShouldResolveShopScopeBeforeReading() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleRuleSettingVO vo = new ArtistScheduleRuleSettingVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(artistScheduleService.getRuleSetting(8L, 30L)).thenReturn(vo);
Result<ArtistScheduleRuleSettingVO> result = controller.scheduleRule(request, 30L);
assertThat(result.getData()).isSameAs(vo);
verify(artistScheduleService).getRuleSetting(8L, 30L);
}
@Test
void saveScheduleRuleShouldResolveShopScopeBeforeSaving() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleRuleDTO dto = new ArtistScheduleRuleDTO();
dto.setShopId(99L);
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(artistScheduleService.saveRule(dto)).thenReturn(vo);
Result<ArtistScheduleRuleVO> result = controller.saveScheduleRule(request, dto);
assertThat(result.getData()).isSameAs(vo);
assertThat(dto.getShopId()).isEqualTo(8L);
}
@Test
void saveScheduleExceptionShouldResolveShopScopeBeforeSaving() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
dto.setShopId(99L);
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(artistScheduleService.saveException(dto)).thenReturn(vo);
Result<ArtistScheduleExceptionVO> result = controller.saveScheduleException(request, dto);
assertThat(result.getData()).isSameAs(vo);
assertThat(dto.getShopId()).isEqualTo(8L);
}
@Test
void updateShopShouldPreserveAuthorizationExpireTimeForNonPlatformUser() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ShopDTO dto = new ShopDTO();
ShopVO shop = new ShopVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(shopService.getShopById(8L)).thenReturn(shop);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
when(shopService.updateShop(8L, dto)).thenReturn(true);
Result<Boolean> result = controller.updateShop(request, dto);
assertThat(result.getData()).isTrue();
verify(adminScopeHelper).requireShopContext(manager);
verify(shopService).updateShop(8L, dto);
}
@Test
void employeesShouldReturnScopedArtistsForNonPlatformUser() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
List<NailArtistInfoDTO> artists = List.of(new NailArtistInfoDTO());
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.isPlatformAdmin(manager)).thenReturn(false);
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(nailArtistInfoService.getByShopId(8L)).thenReturn(artists);
Result<List<NailArtistInfoDTO>> result = controller.employees(request);
assertThat(result.getData()).isSameAs(artists);
}
@Test
void productsShouldResolveShopScope() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
PageResultVO<ProductVO> pageResult = new PageResultVO<>();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(productService.pageProducts(1, 10, "gel", 8L, null, null, null, null, null)).thenReturn(pageResult);
Result<PageResultVO<ProductVO>> result = controller.products(request, 1, 10, "gel", 99L, null, null, null, null, null);
assertThat(result.getData()).isSameAs(pageResult);
verify(productService).pageProducts(1, 10, "gel", 8L, null, null, null, null, null);
}
}
@@ -1,208 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistAddWithGroupDTO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistMoveDTO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistGroupDTO;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistDO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistGroupDO;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.WishlistGroupMapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.WishlistMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistGroupVO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistInspirationVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.math.BigDecimal;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class WishlistServiceImplTest {
private static final String RECENT_GROUP = "\u6700\u8fd1\u60f3\u505a";
private static final String WEDDING_GROUP = "\u5a5a\u793c\u6b3e";
private static final String SUMMER_GROUP = "\u590f\u5929\u6b3e";
private WishlistMapper wishlistMapper;
private WishlistGroupMapper wishlistGroupMapper;
private ProductMapper productMapper;
private ProductService productService;
private WishlistServiceImpl service;
@BeforeEach
void setUp() {
wishlistMapper = mock(WishlistMapper.class);
wishlistGroupMapper = mock(WishlistGroupMapper.class);
productMapper = mock(ProductMapper.class);
productService = mock(ProductService.class);
service = new WishlistServiceImpl(wishlistMapper, wishlistGroupMapper, productService, productMapper);
}
@Test
void listGroupsCreatesPresetGroupsForNewUser() {
when(wishlistGroupMapper.selectList(any(Wrapper.class))).thenReturn(List.of());
List<WishlistGroupVO> groups = service.listGroups(88L);
ArgumentCaptor<WishlistGroupDO> captor = ArgumentCaptor.forClass(WishlistGroupDO.class);
verify(wishlistGroupMapper, org.mockito.Mockito.times(3)).insert(captor.capture());
assertThat(captor.getAllValues())
.extracting(WishlistGroupDO::getName)
.containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP);
assertThat(groups).extracting(WishlistGroupVO::getName)
.containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP);
}
@Test
void addWithGroupCreatesWishlistEntryWithGroupMetadata() {
ProductDO product = new ProductDO();
product.setId(9L);
product.setIsDelete(0);
when(productMapper.selectById(9L)).thenReturn(product);
when(wishlistGroupMapper.selectById(3L)).thenReturn(group(3L, 88L, WEDDING_GROUP, 20));
when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(null);
WishlistAddWithGroupDTO request = new WishlistAddWithGroupDTO();
request.setProductId(9L);
request.setGroupId(3L);
request.setNote("Ask for pearl accent");
request.setSortOrder(7);
service.addToWishlist(88L, request);
ArgumentCaptor<WishlistDO> captor = ArgumentCaptor.forClass(WishlistDO.class);
verify(wishlistMapper).insert(captor.capture());
assertThat(captor.getValue().getUserId()).isEqualTo(88L);
assertThat(captor.getValue().getProductId()).isEqualTo(9L);
assertThat(captor.getValue().getGroupId()).isEqualTo(3L);
assertThat(captor.getValue().getNote()).isEqualTo("Ask for pearl accent");
assertThat(captor.getValue().getSortOrder()).isEqualTo(7);
verify(productMapper).incrementCollectCount(9L);
}
@Test
void addWithGroupUpdatesExistingWishlistWithoutIncrementingCollectCount() {
ProductDO product = new ProductDO();
product.setId(9L);
product.setIsDelete(0);
WishlistDO existing = new WishlistDO();
existing.setId(11L);
existing.setUserId(88L);
existing.setProductId(9L);
when(productMapper.selectById(9L)).thenReturn(product);
when(wishlistGroupMapper.selectById(3L)).thenReturn(group(3L, 88L, WEDDING_GROUP, 20));
when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(existing);
WishlistAddWithGroupDTO request = new WishlistAddWithGroupDTO();
request.setProductId(9L);
request.setGroupId(3L);
request.setNote("Move to wedding board");
service.addToWishlist(88L, request);
assertThat(existing.getGroupId()).isEqualTo(3L);
assertThat(existing.getNote()).isEqualTo("Move to wedding board");
verify(wishlistMapper).updateById(existing);
verify(productMapper, never()).incrementCollectCount(9L);
}
@Test
void moveWishlistChangesGroupNoteAndOrder() {
WishlistDO existing = new WishlistDO();
existing.setId(11L);
existing.setUserId(88L);
existing.setProductId(9L);
when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(existing);
when(wishlistGroupMapper.selectById(2L)).thenReturn(group(2L, 88L, SUMMER_GROUP, 30));
WishlistMoveDTO request = new WishlistMoveDTO();
request.setProductId(9L);
request.setGroupId(2L);
request.setNote("Try blue");
request.setSortOrder(4);
service.moveWishlist(88L, request);
assertThat(existing.getGroupId()).isEqualTo(2L);
assertThat(existing.getNote()).isEqualTo("Try blue");
assertThat(existing.getSortOrder()).isEqualTo(4);
verify(wishlistMapper).updateById(existing);
}
@Test
void inspirationGroupsWishlistItemsByGroupAndKeepsUngroupedInDefaultGroup() {
WishlistGroupDO recent = group(1L, 88L, RECENT_GROUP, 10);
WishlistGroupDO summer = group(2L, 88L, SUMMER_GROUP, 30);
WishlistDO grouped = wishlist(101L, 88L, 9L, 2L, "Try blue", 4);
WishlistDO legacy = wishlist(102L, 88L, 10L, null, null, 0);
when(wishlistGroupMapper.selectList(any(Wrapper.class))).thenReturn(List.of(recent, summer));
when(wishlistMapper.selectList(any(Wrapper.class))).thenReturn(List.of(grouped, legacy));
when(productService.getProductById(9L)).thenReturn(product(9L, "Ocean glass"));
when(productService.getProductById(10L)).thenReturn(product(10L, "Plain nude"));
WishlistInspirationVO inspiration = service.getInspiration(88L);
assertThat(inspiration.getTotal()).isEqualTo(2);
assertThat(inspiration.getGroups()).extracting(WishlistGroupVO::getName)
.containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP);
assertThat(inspiration.getGroups().get(0).getItems())
.extracting(item -> item.getProduct().getTitle())
.containsExactly("Plain nude");
assertThat(inspiration.getGroups().get(1).getItems()).isEmpty();
assertThat(inspiration.getGroups().get(2).getItems())
.extracting(item -> item.getProduct().getTitle())
.containsExactly("Ocean glass");
}
@Test
void createGroupNormalizesNameAndSortOrder() {
WishlistGroupDTO request = new WishlistGroupDTO();
request.setName(" Bride ideas ");
service.createGroup(88L, request);
ArgumentCaptor<WishlistGroupDO> captor = ArgumentCaptor.forClass(WishlistGroupDO.class);
verify(wishlistGroupMapper).insert(captor.capture());
assertThat(captor.getValue().getName()).isEqualTo("Bride ideas");
assertThat(captor.getValue().getSortOrder()).isEqualTo(100);
assertThat(captor.getValue().getIsDelete()).isZero();
}
private WishlistGroupDO group(Long id, Long userId, String name, Integer sortOrder) {
WishlistGroupDO group = new WishlistGroupDO();
group.setId(id);
group.setUserId(userId);
group.setName(name);
group.setSortOrder(sortOrder);
group.setIsDelete(0);
return group;
}
private WishlistDO wishlist(Long id, Long userId, Long productId, Long groupId, String note, Integer sortOrder) {
WishlistDO wishlist = new WishlistDO();
wishlist.setId(id);
wishlist.setUserId(userId);
wishlist.setProductId(productId);
wishlist.setGroupId(groupId);
wishlist.setNote(note);
wishlist.setSortOrder(sortOrder);
wishlist.setIsDelete(0);
return wishlist;
}
private ProductVO product(Long id, String title) {
ProductVO product = new ProductVO();
product.setId(id);
product.setTitle(title);
product.setPrice(new BigDecimal("168.00"));
return product;
}
}
@@ -1,113 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.order.controller.admin;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.common.Result;
import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService;
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderVO;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.annotation.RequestParam;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doThrow;
class AdminOrderControllerTest {
@Mock
private OrderService orderService;
@Mock
private AdminScopeHelper adminScopeHelper;
private AdminOrderController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
controller = new AdminOrderController(orderService, adminScopeHelper);
}
@Test
void listOrdersShouldAcceptShopFilterAndResolveScopeOnServer() throws Exception {
Method method = Arrays.stream(AdminOrderController.class.getDeclaredMethods())
.filter(candidate -> "listOrders".equals(candidate.getName()))
.filter(candidate -> Arrays.stream(candidate.getParameters()).anyMatch(this::isShopIdRequestParam))
.findFirst()
.orElseThrow(() -> new AssertionError("listOrders must expose optional shopId request parameter"));
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO platformAdmin = new UserDO();
platformAdmin.setType(4);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(platformAdmin);
when(adminScopeHelper.resolveShopScope(platformAdmin, 8L)).thenReturn(8L);
OrderVO visibleOrder = order(8L);
OrderVO hiddenOrder = order(9L);
when(orderService.getAllOrders()).thenReturn(List.of(visibleOrder, hiddenOrder));
@SuppressWarnings("unchecked")
Result<PageResultVO<OrderVO>> result = (Result<PageResultVO<OrderVO>>) method.invoke(controller, request, 1, 10, null, 8L, null);
verify(adminScopeHelper).resolveShopScope(platformAdmin, 8L);
assertThat(result.getData().getList()).containsExactly(visibleOrder);
}
@Test
void getOrderDetailShouldReturnVisibleOrderForAdmin() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO platformAdmin = new UserDO();
platformAdmin.setType(4);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(platformAdmin);
OrderVO visibleOrder = order(8L);
when(orderService.getAllOrders()).thenReturn(List.of(visibleOrder));
Result<OrderVO> result = controller.getOrderDetail(request, visibleOrder.getId());
assertThat(result.getData()).isSameAs(visibleOrder);
}
@Test
void getOrderDetailShouldRejectOtherShopForManager() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
manager.setType(2);
manager.setShopId(8L);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
OrderVO otherShopOrder = order(9L);
when(orderService.getAllOrders()).thenReturn(List.of(otherShopOrder));
doThrow(new RuntimeException("无权查看其他店铺订单"))
.when(adminScopeHelper)
.ensureShopAccessible(manager, otherShopOrder.getShopId(), "无权查看其他店铺订单");
assertThatThrownBy(() -> controller.getOrderDetail(request, otherShopOrder.getId()))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("无权查看其他店铺订单");
}
private boolean isShopIdRequestParam(Parameter parameter) {
RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
return requestParam != null && Long.class.equals(parameter.getType());
}
private OrderVO order(Long shopId) {
OrderVO order = new OrderVO();
order.setId(shopId);
order.setShopId(shopId);
return order;
}
}
@@ -1,101 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.order.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleApplyDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleAuditDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleLogDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleLogMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.vo.AfterSaleVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.math.BigDecimal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.xiaowang.fingertipdesigner.core.common.Result;
class AfterSaleServiceImplTest {
@Mock
private AfterSaleMapper afterSaleMapper;
@Mock
private AfterSaleLogMapper afterSaleLogMapper;
@Mock
private OrderMapper orderMapper;
@Mock
private SystemMessageMapper systemMessageMapper;
private AfterSaleServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new AfterSaleServiceImpl(afterSaleMapper, afterSaleLogMapper, orderMapper, systemMessageMapper);
}
@Test
void applyCreatesPendingAfterSaleForOwnedOrder() {
OrderDO order = order();
when(orderMapper.selectById(1L)).thenReturn(order);
when(afterSaleMapper.insert(any(AfterSaleDO.class))).thenAnswer(invocation -> {
AfterSaleDO afterSale = invocation.getArgument(0);
afterSale.setId(100L);
return 1;
});
AfterSaleApplyDTO dto = new AfterSaleApplyDTO();
dto.setOrderId(1L);
dto.setType("REFUND_CONSULT");
dto.setReason("Need help");
dto.setRefundAmount(new BigDecimal("20.00"));
AfterSaleVO result = service.apply(2L, dto);
assertThat(result.getStatus()).isEqualTo("PENDING");
ArgumentCaptor<AfterSaleLogDO> logCaptor = ArgumentCaptor.forClass(AfterSaleLogDO.class);
verify(afterSaleLogMapper).insert(logCaptor.capture());
assertThat(logCaptor.getValue().getAction()).isEqualTo("CREATE");
}
@Test
void approveChangesStatusAndNotifiesCustomer() {
AfterSaleDO afterSale = new AfterSaleDO();
afterSale.setId(100L);
afterSale.setOrderId(1L);
afterSale.setUserId(2L);
afterSale.setShopId(9L);
afterSale.setStatus("PENDING");
when(afterSaleMapper.selectById(100L)).thenReturn(afterSale);
AfterSaleAuditDTO dto = new AfterSaleAuditDTO();
dto.setAuditReason("OK");
AfterSaleVO result = service.approve(900L, 100L, dto);
assertThat(result.getStatus()).isEqualTo("APPROVED");
verify(afterSaleMapper).updateById(afterSale);
verify(systemMessageMapper).insert(any(SystemMessageDO.class));
}
private OrderDO order() {
OrderDO order = new OrderDO();
order.setId(1L);
order.setOrderNo("ORD1");
order.setUserId(2L);
order.setShopId(9L);
order.setActualAmount(new BigDecimal("88.00"));
order.setStatus(1);
order.setIsDelete(0);
return order;
}
}
@@ -1,296 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.order.service.impl;
import com.xiaowang.fingertipdesigner.core.common.BusinessException;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.CheckoutPreviewDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderItemDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.CartDO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO;
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.CartMapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService;
import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService;
import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutPreviewVO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.UserCouponVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.util.ReflectionTestUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class OrderServiceImplCheckoutPreviewTest {
@Mock
private ProductMapper productMapper;
@Mock
private CartMapper cartMapper;
@Mock
private CouponMapper couponMapper;
@Mock
private OrderItemMapper orderItemMapper;
@Mock
private UserMapper userMapper;
@Mock
private ShopMapper shopMapper;
@Mock
private CouponService couponService;
@Mock
private BookableArtistSupport bookableArtistSupport;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private AppointmentCapacityService appointmentCapacityService;
@Mock
private AppointmentReservationMapper appointmentReservationMapper;
private OrderServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new OrderServiceImpl();
ReflectionTestUtils.setField(service, "productMapper", productMapper);
ReflectionTestUtils.setField(service, "cartMapper", cartMapper);
ReflectionTestUtils.setField(service, "couponMapper", couponMapper);
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
ReflectionTestUtils.setField(service, "userMapper", userMapper);
ReflectionTestUtils.setField(service, "shopMapper", shopMapper);
ReflectionTestUtils.setField(service, "couponService", couponService);
ReflectionTestUtils.setField(service, "bookableArtistSupport", bookableArtistSupport);
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
ReflectionTestUtils.setField(service, "appointmentCapacityService", appointmentCapacityService);
ReflectionTestUtils.setField(service, "appointmentReservationMapper", appointmentReservationMapper);
}
@Test
void checkoutPreviewExplainsBestAvailableCouponAndUnavailableReasons() {
ProductDO product = product(100L, "温柔法式", "法式,通勤", new BigDecimal("100.00"));
CartDO cartItem = cartItem(100L, 2);
UserCouponVO vipCoupon = couponOption(300L, 300L, "SYSTEM_VIP", "黄金VIP自动90折券", 1, "9.0", null, null);
UserCouponVO userCoupon = couponOption(400L, 500L, "USER_COUPON", "满150减30", 2, null, "150.00", "30.00");
when(productMapper.selectById(100L)).thenReturn(product);
when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem);
when(userMapper.selectById(20L)).thenReturn(user("黄金"));
when(userMapper.selectById(30L)).thenReturn(artist(30L));
when(bookableArtistSupport.isBookableServiceUser(any(UserDO.class))).thenReturn(true);
when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true);
when(userShopBindingSupport.isUserAccessibleInShop(30L, 9L)).thenReturn(true);
when(couponService.getAvailableCoupons(20L, "法式,通勤", 200.0, 9L)).thenReturn(List.of(userCoupon, vipCoupon));
when(couponMapper.selectById(300L)).thenReturn(coupon(300L, "黄金VIP自动90折券", 1, new BigDecimal("9.0"), null, null, 9L));
when(couponMapper.selectById(400L)).thenReturn(coupon(400L, "满150减30", 2, null, new BigDecimal("150.00"), new BigDecimal("30.00"), 9L));
when(couponMapper.selectList(any())).thenReturn(List.of(
coupon(600L, "满300减80", 2, null, new BigDecimal("300.00"), new BigDecimal("80.00"), 9L),
coupon(700L, "其他门店券", 2, null, new BigDecimal("50.00"), new BigDecimal("5.00"), 10L)
));
CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 2));
assertThat(preview.getSubtotalAmount()).isEqualByComparingTo("200.00");
assertThat(preview.getSavedAmount()).isEqualByComparingTo("30.00");
assertThat(preview.getPayableAmount()).isEqualByComparingTo("170.00");
assertThat(preview.getBestCoupon().getCouponName()).isEqualTo("满150减30");
assertThat(preview.getAvailableCoupons()).extracting("couponName")
.containsExactly("满150减30", "黄金VIP自动90折券");
assertThat(preview.getUnavailableCoupons()).extracting("couponName")
.containsExactly("满300减80", "其他门店券");
assertThat(preview.getUnavailableCoupons()).extracting("unavailableReason")
.containsExactly("还差 ¥100.00 可用", "仅限其他门店使用");
assertThat(preview.getVipTip()).isEqualTo("黄金VIP本单可省 ¥20.00,已为你计算。");
assertThat(preview.getSummaryText()).isEqualTo("参考价小计 ¥200.00,预估优惠 ¥30.00,预估应付 ¥170.00。");
assertThat(ReflectionTestUtils.getField(preview, "bookingAvailable")).isEqualTo(true);
assertThat((List<?>) ReflectionTestUtils.getField(preview, "bookingIssues")).isEmpty();
}
@Test
void checkoutPreviewReportsBookingIssuesWithoutReservingCapacity() {
ProductDO product = product(100L, "夜间款", "通勤", new BigDecimal("80.00"));
product.setApproximateDuration("60分钟");
product.setBookableArtists("77");
CartDO cartItem = cartItem(100L, 1);
LocalDateTime appointmentTime = LocalDateTime.now().plusDays(1)
.withHour(17)
.withMinute(30)
.withSecond(0)
.withNano(0);
when(productMapper.selectById(100L)).thenReturn(product);
when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem);
when(userMapper.selectById(77L)).thenReturn(artist(77L));
when(bookableArtistSupport.isBookableServiceUser(any(UserDO.class))).thenReturn(true);
when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true);
when(userShopBindingSupport.isUserAccessibleInShop(77L, 9L)).thenReturn(true);
when(shopMapper.selectById(9L)).thenReturn(shop("09:00-18:00"));
when(couponService.getAvailableCoupons(20L, "通勤", 80.0, 9L)).thenReturn(List.of());
when(couponMapper.selectList(any())).thenReturn(List.of());
CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 1, 77L, appointmentTime));
assertThat(preview.getSubtotalAmount()).isEqualByComparingTo("80.00");
assertThat(ReflectionTestUtils.getField(preview, "bookingAvailable")).isEqualTo(false);
List<?> bookingIssues = (List<?>) ReflectionTestUtils.getField(preview, "bookingIssues");
assertThat(bookingIssues).hasSize(1);
Object issue = bookingIssues.get(0);
assertThat(ReflectionTestUtils.getField(issue, "code")).isEqualTo("BUSINESS_HOURS");
assertThat(ReflectionTestUtils.getField(issue, "message").toString()).contains("营业时间");
assertThat(ReflectionTestUtils.getField(issue, "productId")).isEqualTo(100L);
assertThat(ReflectionTestUtils.getField(issue, "productTitle")).isEqualTo("夜间款");
verifyNoInteractions(appointmentCapacityService);
}
@Test
void checkoutPreviewReportsReservationOccupancyConflict() {
ProductDO product = product(100L, "Classic", "regular", new BigDecimal("80.00"));
product.setApproximateDuration("60");
product.setBookableArtists("77");
CartDO cartItem = cartItem(100L, 1);
LocalDateTime appointmentTime = LocalDateTime.now().plusDays(1)
.withHour(10)
.withMinute(0)
.withSecond(0)
.withNano(0);
LocalDateTime appointmentEndTime = appointmentTime.plusHours(1);
when(productMapper.selectById(100L)).thenReturn(product);
when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem);
when(userMapper.selectById(77L)).thenReturn(artist(77L));
when(bookableArtistSupport.isBookableServiceUser(any(UserDO.class))).thenReturn(true);
when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true);
when(userShopBindingSupport.isUserAccessibleInShop(77L, 9L)).thenReturn(true);
when(shopMapper.selectById(9L)).thenReturn(shop("09:00-18:00"));
when(appointmentReservationMapper.countOverlappingActive(77L, appointmentTime, appointmentEndTime)).thenReturn(1);
when(couponService.getAvailableCoupons(20L, "regular", 80.0, 9L)).thenReturn(List.of());
when(couponMapper.selectList(any())).thenReturn(List.of());
CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 1, 77L, appointmentTime));
assertThat(ReflectionTestUtils.getField(preview, "bookingAvailable")).isEqualTo(false);
List<?> bookingIssues = (List<?>) ReflectionTestUtils.getField(preview, "bookingIssues");
assertThat(bookingIssues).hasSize(1);
Object issue = bookingIssues.get(0);
assertThat(ReflectionTestUtils.getField(issue, "code")).isEqualTo("EXISTING_CONFLICT");
assertThat(ReflectionTestUtils.getField(issue, "productId")).isEqualTo(100L);
verifyNoInteractions(appointmentCapacityService);
}
@Test
void createOrderReturnsBusinessCodeForBookingValidationBeforeLocking() {
assertThatThrownBy(() -> service.createOrder(20L, null))
.isInstanceOfSatisfying(BusinessException.class, exception -> {
assertThat(exception.getCode()).isEqualTo(409);
assertThat(exception.getMessage()).isEqualTo("订单项不能为空");
});
}
private CheckoutPreviewDTO order(Long productId, Integer quantity) {
return order(productId, quantity, 30L, LocalDateTime.now().plusDays(1)
.withHour(10)
.withMinute(0)
.withSecond(0)
.withNano(0));
}
private CheckoutPreviewDTO order(Long productId, Integer quantity, Long artistId, LocalDateTime appointmentTime) {
OrderItemDTO item = new OrderItemDTO();
item.setProductId(productId);
item.setQuantity(quantity);
item.setArtistId(artistId);
item.setAppointmentTime(appointmentTime.toString());
CheckoutPreviewDTO dto = new CheckoutPreviewDTO();
dto.setItems(List.of(item));
return dto;
}
private ProductDO product(Long id, String title, String tags, BigDecimal price) {
ProductDO product = new ProductDO();
product.setId(id);
product.setTitle(title);
product.setTags(tags);
product.setPrice(price);
product.setShopId(9L);
product.setIsDelete(0);
return product;
}
private ShopDO shop(String businessHours) {
ShopDO shop = new ShopDO();
shop.setId(9L);
shop.setBusinessHours(businessHours);
shop.setIsDelete(0);
return shop;
}
private CartDO cartItem(Long productId, Integer quantity) {
CartDO item = new CartDO();
item.setUserId(20L);
item.setProductId(productId);
item.setQuantity(quantity);
item.setIsDelete(0);
return item;
}
private UserDO user(String level) {
UserDO user = new UserDO();
user.setId(20L);
user.setLevel(level);
user.setIsDelete(0);
return user;
}
private UserDO artist(Long id) {
UserDO artist = new UserDO();
artist.setId(id);
artist.setStatus(1);
artist.setIsDelete(0);
return artist;
}
private CouponDO coupon(Long id, String name, Integer type, BigDecimal discountValue, BigDecimal minAmount, BigDecimal reduceAmount, Long shopId) {
CouponDO coupon = new CouponDO();
coupon.setId(id);
coupon.setCouponName(name);
coupon.setCouponType(type);
coupon.setDiscountValue(discountValue);
coupon.setMinAmount(minAmount);
coupon.setReduceAmount(reduceAmount);
coupon.setShopId(shopId);
coupon.setStatus(1);
coupon.setStartTime(LocalDateTime.now().minusDays(1));
coupon.setEndTime(LocalDateTime.now().plusDays(1));
coupon.setIsDelete(0);
return coupon;
}
private UserCouponVO couponOption(Long id, Long couponId, String sourceType, String name, Integer type, String discountValue, String minAmount, String reduceAmount) {
UserCouponVO coupon = new UserCouponVO();
coupon.setId(id);
coupon.setCouponId(couponId);
coupon.setSourceType(sourceType);
coupon.setCouponName(name);
coupon.setCouponType(type);
coupon.setDiscountValue(discountValue);
coupon.setMinAmount(minAmount);
coupon.setReduceAmount(reduceAmount);
return coupon;
}
}
@@ -1,557 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRejectDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRequestDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistReviewSubmitDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistChangeRequestDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistChangeRequestMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService;
import com.xiaowang.fingertipdesigner.core.modules.integration.service.BusinessEventOutboxService;
import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport;
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.test.util.ReflectionTestUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class OrderServiceImplReviewChangeTest {
@Mock
private OrderMapper orderMapper;
@Mock
private OrderItemMapper orderItemMapper;
@Mock
private OrderArtistReviewMapper orderArtistReviewMapper;
@Mock
private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
@Mock
private ProductMapper productMapper;
@Mock
private UserMapper userMapper;
@Mock
private SystemMessageMapper systemMessageMapper;
@Mock
private NailArtistInfoMapper nailArtistInfoMapper;
@Mock
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private BookableArtistSupport bookableArtistSupport;
@Mock
private BusinessEventOutboxService businessEventOutboxService;
@Mock
private AppointmentCapacityService appointmentCapacityService;
private OrderServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new OrderServiceImpl();
ReflectionTestUtils.setField(service, "orderMapper", orderMapper);
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper);
ReflectionTestUtils.setField(service, "orderArtistChangeRequestMapper", orderArtistChangeRequestMapper);
ReflectionTestUtils.setField(service, "productMapper", productMapper);
ReflectionTestUtils.setField(service, "userMapper", userMapper);
ReflectionTestUtils.setField(service, "systemMessageMapper", systemMessageMapper);
ReflectionTestUtils.setField(service, "nailArtistInfoMapper", nailArtistInfoMapper);
ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport);
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
ReflectionTestUtils.setField(service, "bookableArtistSupport", bookableArtistSupport);
ReflectionTestUtils.setField(service, "businessEventOutboxService", businessEventOutboxService);
ReflectionTestUtils.setField(service, "appointmentCapacityService", appointmentCapacityService);
}
@Test
void processOrderCompletionUpdatesStatusAndEnqueuesOutboxEvent() {
OrderDO order = pendingOrder();
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(1);
service.processOrder(1L, 2);
verify(orderMapper).updateStatusIfCurrent(1L, 1, 2);
verify(businessEventOutboxService).enqueueOrderCompleted(1L);
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
}
@Test
void processOrderCompletionRejectsConcurrentStatusChangeBeforeSideEffects() {
OrderDO order = pendingOrder();
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(0);
assertThatThrownBy(() -> service.processOrder(1L, 2))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("状态已变化");
verify(businessEventOutboxService, never()).enqueueOrderCompleted(any());
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
}
@Test
void outboxOrderCompletedCreatesPendingReviewTaskAndPopupMessageOnce() {
OrderDO order = completedOrder();
OrderItemDO item = orderItem();
ProductDO product = product();
UserDO artist = artist(30L);
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
when(productMapper.selectById(20L)).thenReturn(product);
when(userMapper.selectById(30L)).thenReturn(artist);
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
OrderArtistReviewDO review = invocation.getArgument(0);
review.setId(1000L);
return 1;
});
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
OrderArtistReviewDO review = reviewCaptor.getValue();
assertThat(review.getOrderItemId()).isEqualTo(10L);
assertThat(review.getCustomerId()).isEqualTo(2L);
assertThat(review.getArtistId()).isEqualTo(30L);
assertThat(review.getStatus()).isZero();
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
verify(systemMessageMapper).insert(messageCaptor.capture());
assertThat(messageCaptor.getValue().getBusinessType()).isEqualTo("ORDER_ARTIST_REVIEW");
assertThat(messageCaptor.getValue().getTargetIds()).isEqualTo("2");
}
@Test
void outboxOrderCompletedDoesNotCreateDuplicateReviewTask() {
OrderDO order = completedOrder();
OrderItemDO item = orderItem();
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
existingReview.setId(99L);
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(existingReview);
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
}
@Test
void outboxOrderCompletedRecoversWhenConcurrentReviewTaskInsertWins() {
OrderDO order = completedOrder();
OrderItemDO item = orderItem();
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
existingReview.setId(99L);
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null, existingReview);
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
verify(orderArtistReviewMapper).insert(any(OrderArtistReviewDO.class));
verify(orderArtistReviewMapper, never()).updateById(existingReview);
}
@Test
void outboxOrderCompletedReusesExistingReviewReminderMessage() {
OrderDO order = completedOrder();
OrderItemDO item = orderItem();
ProductDO product = product();
SystemMessageDO existingMessage = new SystemMessageDO();
existingMessage.setId(300L);
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
when(productMapper.selectById(20L)).thenReturn(product);
when(userMapper.selectById(30L)).thenReturn(artist(30L));
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
OrderArtistReviewDO review = invocation.getArgument(0);
review.setId(1000L);
return 1;
});
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(existingMessage);
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
verify(orderArtistReviewMapper).updateById(reviewCaptor.getValue());
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(300L);
}
@Test
void outboxOrderCompletedRecoversReviewReminderWhenConcurrentInsertWins() {
OrderDO order = completedOrder();
OrderItemDO item = orderItem();
ProductDO product = product();
SystemMessageDO existingMessage = new SystemMessageDO();
existingMessage.setId(301L);
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
when(productMapper.selectById(20L)).thenReturn(product);
when(userMapper.selectById(30L)).thenReturn(artist(30L));
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
OrderArtistReviewDO review = invocation.getArgument(0);
review.setId(1001L);
return 1;
});
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null, existingMessage);
when(systemMessageMapper.insert(any(SystemMessageDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
verify(systemMessageMapper).insert(messageCaptor.capture());
assertThat(messageCaptor.getValue().getIdempotencyKey()).isEqualTo("ORDER_ARTIST_REVIEW:1001:2");
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
verify(orderArtistReviewMapper).updateById(reviewCaptor.capture());
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(301L);
}
@Test
void requestArtistChangeLocksOrderItemBeforeCheckingPendingRequest() {
OrderDO order = pendingOrder();
OrderItemDO item = orderItem();
ProductDO product = product();
UserDO requester = artist(30L);
UserDO requestedArtist = artist(31L);
product.setBookableArtists("30,31");
OrderArtistChangeRequestDTO dto = new OrderArtistChangeRequestDTO();
dto.setOrderId(1L);
dto.setOrderItemId(10L);
dto.setRequestedArtistId(31L);
dto.setReason("临时调整");
when(userMapper.selectById(30L)).thenReturn(requester);
when(userMapper.selectById(31L)).thenReturn(requestedArtist);
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
when(productMapper.selectById(20L)).thenReturn(product);
when(userShopBindingSupport.isUserAccessibleInShop(30L, 3L)).thenReturn(true);
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
when(bookableArtistSupport.isBookableServiceUser(requestedArtist)).thenReturn(true);
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
service.requestArtistChange(30L, dto);
ArgumentCaptor<OrderArtistChangeRequestDO> requestCaptor = ArgumentCaptor.forClass(OrderArtistChangeRequestDO.class);
verify(orderArtistChangeRequestMapper).insert(requestCaptor.capture());
assertThat(requestCaptor.getValue().getPendingKey()).isEqualTo("ORDER_ITEM:10");
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderItemMapper).selectByIdForUpdate(10L);
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderArtistChangeRequestMapper).selectPendingByOrderItemId(10L);
verify(orderItemMapper, never()).selectById(10L);
}
@Test
void approveArtistChangeRejectsAlreadyProcessedRequest() {
OrderArtistChangeRequestDO request = pendingChangeRequest();
request.setStatus("APPROVED");
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
.isInstanceOf(RuntimeException.class)
.hasMessage("改派申请已处理");
verify(orderItemMapper, never()).selectByIdForUpdate(any());
}
@Test
void approveArtistChangeUsesPendingConditionalUpdateBeforeAssigningArtist() {
OrderArtistChangeRequestDO request = pendingChangeRequest();
OrderDO order = pendingOrder();
OrderItemDO item = orderItem();
ProductDO product = product();
UserDO newArtist = artist(31L);
product.setBookableArtists("30,31");
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
when(productMapper.selectById(20L)).thenReturn(product);
when(userMapper.selectById(31L)).thenReturn(newArtist);
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(1);
service.approveArtistChange(500L, 2L, 0);
inOrder(orderArtistChangeRequestMapper, orderItemMapper)
.verify(orderArtistChangeRequestMapper).approvePending(eq(500L), any(LocalDateTime.class));
inOrder(orderArtistChangeRequestMapper, orderItemMapper).verify(orderItemMapper).updateById(item);
assertThat(item.getArtistId()).isEqualTo(31L);
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
}
@Test
void approveArtistChangeRejectsConcurrentProcessedRequestBeforeAssigningArtist() {
OrderArtistChangeRequestDO request = pendingChangeRequest();
OrderDO order = pendingOrder();
OrderItemDO item = orderItem();
ProductDO product = product();
UserDO newArtist = artist(31L);
product.setBookableArtists("30,31");
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
when(productMapper.selectById(20L)).thenReturn(product);
when(userMapper.selectById(31L)).thenReturn(newArtist);
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(0);
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
.isInstanceOf(RuntimeException.class)
.hasMessage("改派申请已处理");
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
}
@Test
void approveArtistChangeExpiresPendingRequestBeforeProcessing() {
OrderArtistChangeRequestDO request = pendingChangeRequest();
request.setExpireTime(LocalDateTime.now().minusMinutes(1));
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("过期");
verify(orderArtistChangeRequestMapper).expirePendingById(eq(500L), any(LocalDateTime.class));
verify(orderItemMapper, never()).selectByIdForUpdate(any());
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
}
@Test
void rejectArtistChangeUsesPendingConditionalUpdate() {
OrderArtistChangeRequestDO request = pendingChangeRequest();
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(1);
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
dto.setRejectReason("客户不方便");
service.rejectArtistChange(500L, 2L, 0, dto);
verify(orderArtistChangeRequestMapper).rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class));
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
}
@Test
void rejectArtistChangeRejectsConcurrentProcessedRequest() {
OrderArtistChangeRequestDO request = pendingChangeRequest();
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(0);
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
dto.setRejectReason("客户不方便");
assertThatThrownBy(() -> service.rejectArtistChange(500L, 2L, 0, dto))
.isInstanceOf(RuntimeException.class)
.hasMessage("改派申请已处理");
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
}
@Test
void listMyPendingArtistChangeRequestsExpiresDueRequestsFirst() {
when(orderArtistChangeRequestMapper.selectPendingByUserId(2L)).thenReturn(List.of());
assertThat(service.listMyPendingArtistChangeRequests(2L, 0)).isEmpty();
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
verify(orderArtistChangeRequestMapper).selectPendingByUserId(2L);
}
@Test
void listOrderArtistChangeRequestsExpiresDueRequestsAndReturnsHistoryForAccessibleOrder() {
OrderDO order = pendingOrder();
OrderArtistChangeRequestDO approved = pendingChangeRequest();
approved.setStatus("APPROVED");
approved.setApprovedTime(LocalDateTime.now().minusHours(2));
OrderArtistChangeRequestDO rejected = pendingChangeRequest();
rejected.setId(501L);
rejected.setStatus("REJECTED");
rejected.setRejectedTime(LocalDateTime.now().minusHours(1));
rejected.setRejectReason("时间不合适");
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderArtistChangeRequestMapper.selectByOrderId(1L)).thenReturn(List.of(approved, rejected));
when(productMapper.selectById(20L)).thenReturn(product());
when(userMapper.selectById(30L)).thenReturn(artist(30L));
when(userMapper.selectById(31L)).thenReturn(artist(31L));
assertThat(service.listOrderArtistChangeRequests(1L, 2L, 0))
.extracting("id")
.containsExactly(500L, 501L);
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
verify(orderArtistChangeRequestMapper).selectByOrderId(1L);
}
@Test
void listOrderArtistChangeRequestsRejectsInaccessibleOrder() {
OrderDO order = pendingOrder();
when(orderMapper.selectById(1L)).thenReturn(order);
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(orderItem()));
assertThatThrownBy(() -> service.listOrderArtistChangeRequests(1L, 99L, 0))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("ORDER_ARTIST_CHANGE_FORBIDDEN");
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
verify(orderArtistChangeRequestMapper, never()).selectByOrderId(any());
}
@Test
void submitArtistReviewRequiresHalfPointRating() {
OrderArtistReviewDO review = pendingReview();
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
dto.setRating(new BigDecimal("4.25"));
assertThatThrownBy(() -> service.submitArtistReview(100L, 2L, dto))
.isInstanceOf(RuntimeException.class)
.hasMessage("评分必须按0.5分递增");
verify(orderArtistReviewMapper, never()).updateById(any(OrderArtistReviewDO.class));
}
@Test
void submitArtistReviewAcceptsValidRatingAndRefreshesArtistRating() {
OrderArtistReviewDO review = pendingReview();
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
artistInfo.setId(200L);
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(30L)).thenReturn(new BigDecimal("4.75"));
when(nailArtistInfoMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(artistInfo);
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
dto.setRating(new BigDecimal("4.5"));
dto.setContent("服务很细致");
assertThat(service.submitArtistReview(100L, 2L, dto).getRatingScore()).isEqualByComparingTo("4.5");
verify(orderArtistReviewMapper).updateById(review);
verify(nailArtistInfoMapper).updateById(artistInfo);
assertThat(artistInfo.getRating()).isEqualByComparingTo("4.8");
}
private OrderDO pendingOrder() {
OrderDO order = new OrderDO();
order.setId(1L);
order.setUserId(2L);
order.setShopId(3L);
order.setStatus(1);
order.setIsDelete(0);
return order;
}
private OrderDO completedOrder() {
OrderDO order = pendingOrder();
order.setStatus(2);
return order;
}
private OrderItemDO orderItem() {
OrderItemDO item = new OrderItemDO();
item.setId(10L);
item.setOrderId(1L);
item.setProductId(20L);
item.setArtistId(30L);
item.setQuantity(1);
item.setIsDelete(0);
return item;
}
private ProductDO product() {
ProductDO product = new ProductDO();
product.setId(20L);
product.setTitle("凝胶美甲");
product.setIsDelete(0);
return product;
}
private UserDO artist(Long id) {
UserDO artist = new UserDO();
artist.setId(id);
artist.setType(3);
artist.setStatus(1);
artist.setIsDelete(0);
artist.setNickname("美甲师" + id);
return artist;
}
private OrderArtistReviewDO pendingReview() {
OrderArtistReviewDO review = new OrderArtistReviewDO();
review.setId(100L);
review.setOrderId(1L);
review.setOrderItemId(10L);
review.setProductId(20L);
review.setCustomerId(2L);
review.setArtistId(30L);
review.setStatus(0);
review.setIsDelete(0);
return review;
}
private OrderArtistChangeRequestDO pendingChangeRequest() {
OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO();
request.setId(500L);
request.setOrderId(1L);
request.setOrderItemId(10L);
request.setProductId(20L);
request.setShopId(3L);
request.setCustomerId(2L);
request.setFromArtistId(30L);
request.setToArtistId(31L);
request.setRequesterId(30L);
request.setStatus("PENDING");
request.setExpireTime(LocalDateTime.now().plusDays(1));
request.setIsDelete(0);
return request;
}
}
@@ -1,37 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.order.support;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class OrderStateMachineTest {
@Test
void allowsPriceConfirmingOrderToBecomePendingServiceOrCancelled() {
assertThat(OrderStateMachine.isAllowedTransition(0, 1)).isTrue();
assertThat(OrderStateMachine.isAllowedTransition(0, 3)).isTrue();
assertThat(OrderStateMachine.isAllowedTransition(0, 2)).isFalse();
}
@Test
void allowsPendingOrderToCompleteOrCancel() {
assertThat(OrderStateMachine.isAllowedTransition(1, 2)).isTrue();
assertThat(OrderStateMachine.isAllowedTransition(1, 3)).isTrue();
}
@Test
void rejectsInvalidOrderTransition() {
assertThat(OrderStateMachine.isAllowedTransition(2, 3)).isFalse();
assertThatThrownBy(() -> OrderStateMachine.requireAllowedTransition(2, 3))
.isInstanceOf(RuntimeException.class)
.hasMessage("订单状态不允许处理");
}
@Test
void rejectsUnknownTargetStatus() {
assertThatThrownBy(() -> OrderStatus.requireKnown(9))
.isInstanceOf(RuntimeException.class)
.hasMessage("无效的订单状态");
}
}
@@ -1,124 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.payment.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
import com.xiaowang.fingertipdesigner.core.modules.payment.entity.PaymentOrderDO;
import com.xiaowang.fingertipdesigner.core.modules.payment.entity.RefundOrderDO;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.PaymentOrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.RefundOrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.payment.vo.PaymentOrderVO;
import com.xiaowang.fingertipdesigner.core.modules.payment.vo.RefundOrderVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.math.BigDecimal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.xiaowang.fingertipdesigner.core.common.Result;
class PaymentServiceImplTest {
@Mock
private OrderMapper orderMapper;
@Mock
private PaymentOrderMapper paymentOrderMapper;
@Mock
private RefundOrderMapper refundOrderMapper;
private PaymentServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new PaymentServiceImpl(orderMapper, paymentOrderMapper, refundOrderMapper);
}
@Test
void prepareOrderPaymentCreatesManualPaymentOrderForUnpaidOrder() {
OrderDO order = order();
when(orderMapper.selectById(1L)).thenReturn(order);
when(paymentOrderMapper.selectLatestByOrderId(1L)).thenReturn(null);
when(paymentOrderMapper.insert(any(PaymentOrderDO.class))).thenAnswer(invocation -> {
PaymentOrderDO payment = invocation.getArgument(0);
payment.setId(100L);
return 1;
});
PaymentOrderVO result = service.prepareOrderPayment(2L, 1L);
assertThat(result.getOrderId()).isEqualTo(1L);
assertThat(result.getStatus()).isEqualTo("PAYING");
assertThat(result.getPayAmount()).isEqualByComparingTo("88.00");
ArgumentCaptor<PaymentOrderDO> captor = ArgumentCaptor.forClass(PaymentOrderDO.class);
verify(paymentOrderMapper).insert(captor.capture());
assertThat(captor.getValue().getChannel()).isEqualTo("MANUAL");
}
@Test
void manualConfirmOrderPaidUpdatesPaymentAndOrderSnapshot() {
OrderDO order = order();
PaymentOrderDO payment = new PaymentOrderDO();
payment.setId(100L);
payment.setOrderId(1L);
payment.setStatus("PAYING");
payment.setPayAmount(new BigDecimal("88.00"));
when(orderMapper.selectById(1L)).thenReturn(order);
when(paymentOrderMapper.selectLatestByOrderId(1L)).thenReturn(payment);
PaymentOrderVO result = service.manualConfirmOrderPaid(900L, 1L, "cash");
assertThat(result.getStatus()).isEqualTo("PAID");
verify(paymentOrderMapper).updateById(payment);
verify(orderMapper).updateById(order);
assertThat(order.getPaymentStatus()).isEqualTo("PAID");
assertThat(order.getPaidAmount()).isEqualByComparingTo("88.00");
}
@Test
void manualRefundOrderCreatesRefundAndUpdatesOrderSnapshot() {
OrderDO order = order();
order.setPaymentStatus("PAID");
PaymentOrderDO payment = new PaymentOrderDO();
payment.setId(100L);
payment.setOrderId(1L);
payment.setStatus("PAID");
payment.setPayAmount(new BigDecimal("88.00"));
payment.setPaidAmount(new BigDecimal("88.00"));
payment.setChannel("MANUAL");
when(orderMapper.selectById(1L)).thenReturn(order);
when(paymentOrderMapper.selectLatestByOrderId(1L)).thenReturn(payment);
when(refundOrderMapper.insert(any(RefundOrderDO.class))).thenAnswer(invocation -> {
RefundOrderDO refund = invocation.getArgument(0);
refund.setId(200L);
return 1;
});
RefundOrderVO result = service.manualRefundOrder(900L, 1L, 300L, "manual");
assertThat(result.getStatus()).isEqualTo("REFUNDED");
assertThat(result.getRefundAmount()).isEqualByComparingTo("88.00");
verify(refundOrderMapper).insert(any(RefundOrderDO.class));
verify(orderMapper).updateById(order);
assertThat(order.getPaymentStatus()).isEqualTo("REFUNDED");
assertThat(order.getRefundStatus()).isEqualTo("REFUNDED");
}
private OrderDO order() {
OrderDO order = new OrderDO();
order.setId(1L);
order.setOrderNo("ORD1");
order.setUserId(2L);
order.setShopId(9L);
order.setActualAmount(new BigDecimal("88.00"));
order.setStatus(1);
order.setIsDelete(0);
order.setPaymentStatus("UNPAID");
return order;
}
}
@@ -1,175 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.planning.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.when;
class AppointmentCapacityServiceImplTest {
@Mock
private AppointmentReservationMapper reservationMapper;
@Mock
private ArtistScheduleMapper scheduleMapper;
private AppointmentCapacityServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new AppointmentCapacityServiceImpl(reservationMapper, scheduleMapper);
}
@Test
void reserveRejectsWhenConfiguredCapacityIsFull() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(2));
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(2);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class);
}
@Test
void reserveCreatesConfirmedReservationWhenCapacityRemains() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(2));
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(1);
service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end);
ArgumentCaptor<AppointmentReservationDO> captor = ArgumentCaptor.forClass(AppointmentReservationDO.class);
verify(reservationMapper).insert(captor.capture());
AppointmentReservationDO reservation = captor.getValue();
assertThat(reservation.getOrderId()).isEqualTo(1L);
assertThat(reservation.getOrderItemId()).isEqualTo(10L);
assertThat(reservation.getArtistId()).isEqualTo(30L);
assertThat(reservation.getStatus()).isEqualTo("CONFIRMED");
}
@Test
void reservePendingQuoteCreatesPendingReservationWithClientRequestId() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(2));
when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(0);
service.reservePendingQuoteOrThrow(1L, 10L, 9L, 30L, "French", start, end, "req-1");
ArgumentCaptor<AppointmentReservationDO> captor = ArgumentCaptor.forClass(AppointmentReservationDO.class);
verify(reservationMapper).insert(captor.capture());
AppointmentReservationDO reservation = captor.getValue();
assertThat(reservation.getStatus()).isEqualTo("PENDING_QUOTE");
assertThat(reservation.getClientRequestId()).isEqualTo("req-1");
}
@Test
void confirmReservationUpgradesExistingPendingReservationWithoutSelfConflict() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(2));
when(reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(30L, 10L, start, end)).thenReturn(0);
when(reservationMapper.updateActiveReservationForOrderItemWithClientRequest(10L, 1L, 9L, 30L, "French", start, end, "CONFIRMED", null))
.thenReturn(1);
service.confirmReservationOrThrow(1L, 10L, 9L, 30L, "French", start, end);
verify(reservationMapper).updateActiveReservationForOrderItemWithClientRequest(10L, 1L, 9L, 30L, "French", start, end, "CONFIRMED", null);
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@Test
void reserveRejectsWhenNoCoveringScheduleExists() {
LocalDateTime start = LocalDateTime.of(2026, 6, 2, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(null);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@Test
void reserveRejectsWhenCoveringScheduleIsDisabled() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
ArtistScheduleDO disabled = schedule(1);
disabled.setStatus(0);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(disabled);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@Test
void reserveRejectsWhenCoveringScheduleHasZeroCapacity() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(0));
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
@Test
void moveReservationRechecksNewArtistCapacityBeforeUpdatingArtist() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1);
when(scheduleMapper.selectCoveringSchedule(9L, 31L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()))
.thenReturn(schedule(1));
when(reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(31L, 10L, start, end)).thenReturn(0);
when(reservationMapper.updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED"))
.thenReturn(1);
service.moveReservationForArtistChange(1L, 10L, 9L, 30L, 31L, "French", start, end);
verify(reservationMapper).updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED");
verify(reservationMapper, never()).releaseByOrderItem(10L, "RELEASED");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
}
private ArtistScheduleDO schedule(int capacity) {
ArtistScheduleDO schedule = new ArtistScheduleDO();
schedule.setShopId(9L);
schedule.setArtistId(30L);
schedule.setWorkDate(LocalDate.of(2026, 6, 1));
schedule.setStartTime(LocalTime.of(10, 0));
schedule.setEndTime(LocalTime.of(20, 0));
schedule.setCapacity(capacity);
schedule.setStatus(1);
schedule.setIsDelete(0);
return schedule;
}
}
@@ -1,305 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.planning.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService;
import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO;
import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class PlanningServiceImplTest {
@Mock
private AdminScopeHelper adminScopeHelper;
@Mock
private UserMapper userMapper;
@Mock
private NailArtistInfoMapper nailArtistInfoMapper;
@Mock
private ArtistScheduleMapper artistScheduleMapper;
@Mock
private AppointmentReservationMapper appointmentReservationMapper;
@Mock
private OrderMapper orderMapper;
@Mock
private OrderItemMapper orderItemMapper;
@Mock
private ProductMapper productMapper;
@Mock
private ShopMapper shopMapper;
@Mock
private AppointmentCapacityService appointmentCapacityService;
@Mock
private OrderService orderService;
@Mock
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private PlanningServiceImpl planningService;
@BeforeEach
void setUp() {
planningService = new PlanningServiceImpl(
adminScopeHelper,
userMapper,
nailArtistInfoMapper,
artistScheduleMapper,
appointmentReservationMapper,
orderMapper,
orderItemMapper,
productMapper,
shopMapper,
appointmentCapacityService,
orderService,
snowflakeIdGenerator
);
}
@Test
void createAppointmentShouldHideManualProductFromFront() {
UserDO manager = user(2, 8L);
UserDO artist = user(3, 8L);
artist.setId(20L);
UserDO customer = user(0, 8L);
customer.setId(30L);
ShopDO shop = new ShopDO();
shop.setBusinessHours("10:00-22:00");
PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO();
dto.setCustomerUserId(30L);
dto.setArtistId(20L);
dto.setAppointmentDate("2026-06-26");
dto.setAppointmentTime("13:00");
dto.setDurationMinutes(90);
dto.setManualProductTitle(" 日落贝壳 ");
dto.setManualProductPrice(new BigDecimal("168.00"));
dto.setClientRequestId("manual-product-test");
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(productMapper.insert(any(ProductDO.class))).thenAnswer(invocation -> {
ProductDO product = invocation.getArgument(0);
product.setId(100L);
return 1;
});
when(userMapper.selectById(20L)).thenReturn(artist);
when(userMapper.selectById(30L)).thenReturn(customer);
when(shopMapper.selectById(8L)).thenReturn(shop);
when(snowflakeIdGenerator.nextIdString()).thenReturn("202606260001");
when(orderMapper.insert(any(OrderDO.class))).thenAnswer(invocation -> {
OrderDO order = invocation.getArgument(0);
order.setId(200L);
return 1;
});
when(orderItemMapper.insert(any(OrderItemDO.class))).thenAnswer(invocation -> {
OrderItemDO item = invocation.getArgument(0);
item.setId(300L);
return 1;
});
when(orderItemMapper.selectById(300L)).thenAnswer(invocation -> {
OrderItemDO item = new OrderItemDO();
item.setId(300L);
item.setOrderId(200L);
item.setProductId(100L);
item.setArtistId(20L);
item.setQuantity(1);
item.setAppointmentTime(LocalDateTime.of(2026, 6, 26, 13, 0));
item.setIsDelete(0);
return item;
});
when(orderMapper.selectById(200L)).thenAnswer(invocation -> {
OrderDO order = new OrderDO();
order.setId(200L);
order.setUserId(30L);
order.setShopId(8L);
order.setStatus(1);
order.setIsDelete(0);
return order;
});
when(productMapper.selectById(100L)).thenAnswer(invocation -> {
ProductDO product = new ProductDO();
product.setId(100L);
product.setShopId(8L);
product.setTitle("日落贝壳");
product.setPrice(new BigDecimal("168.00"));
product.setApproximateDuration("90分钟");
product.setFrontVisible(0);
product.setSourceType("MANAGER_APPOINTMENT");
product.setIsDelete(0);
return product;
});
AppointmentReservationDO reservation = new AppointmentReservationDO();
reservation.setOrderItemId(300L);
reservation.setArtistId(20L);
reservation.setProductTitle("日落贝壳");
reservation.setAppointmentStartTime(LocalDateTime.of(2026, 6, 26, 13, 0));
reservation.setAppointmentEndTime(LocalDateTime.of(2026, 6, 26, 14, 30));
when(appointmentReservationMapper.selectOne(any())).thenReturn(reservation);
when(userMapper.selectBatchIds(any())).thenReturn(List.of(customer));
planningService.createAppointment(manager, dto);
ArgumentCaptor<ProductDO> captor = ArgumentCaptor.forClass(ProductDO.class);
org.mockito.Mockito.verify(productMapper).insert(captor.capture());
ProductDO product = captor.getValue();
assertThat(product.getTitle()).isEqualTo("日落贝壳");
assertThat(product.getFrontVisible()).isZero();
assertThat(product.getSourceType()).isEqualTo("MANAGER_APPOINTMENT");
assertThat(product.getImageFileIds()).isNull();
}
@Test
void calendarMarksMonthAvailabilityByContinuousNinetyMinuteWindow() {
UserDO manager = user(2, 8L);
UserDO freeArtist = user(3, 8L);
freeArtist.setId(20L);
freeArtist.setNickname("小王");
UserDO shortShiftArtist = user(3, 8L);
shortShiftArtist.setId(21L);
shortShiftArtist.setNickname("小李");
LocalDate date = LocalDate.of(2026, 6, 26);
ShopDO shop = new ShopDO();
shop.setBusinessHours("09:00-18:00");
ArtistScheduleDO freeSchedule = schedule(20L, date, LocalTime.of(9, 0), LocalTime.of(12, 0));
ArtistScheduleDO shortSchedule = schedule(21L, date, LocalTime.of(9, 0), LocalTime.of(10, 0));
AppointmentReservationDO reservation = reservation(20L, 200L, 300L, date.atTime(10, 30), date.atTime(12, 0));
OrderDO order = order(200L, 8L, 30L);
OrderItemDO item = orderItem(300L, 200L, 100L, 20L, date.atTime(10, 30));
ProductDO product = product(100L, 8L, "90分钟");
UserDO customer = user(0, 8L);
customer.setId(30L);
customer.setNickname("测试客户");
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(shopMapper.selectById(8L)).thenReturn(shop);
when(userMapper.selectList(any())).thenReturn(List.of(freeArtist, shortShiftArtist));
when(nailArtistInfoMapper.selectList(any())).thenReturn(List.of());
when(artistScheduleMapper.selectList(any())).thenReturn(List.of(freeSchedule, shortSchedule));
when(appointmentReservationMapper.selectList(any())).thenReturn(List.of(reservation));
when(orderItemMapper.selectList(any())).thenReturn(List.of());
when(orderItemMapper.selectBatchIds(any())).thenReturn(List.of(item));
when(orderMapper.selectBatchIds(any())).thenReturn(List.of(order));
when(productMapper.selectBatchIds(any())).thenReturn(List.of(product));
when(userMapper.selectBatchIds(any())).thenReturn(List.of(customer));
var calendar = planningService.getCalendar(manager, date, date, null);
var summary = calendar.getDaySummaries().get(0);
assertThat(summary.getDayStatus()).isEqualTo("working");
assertThat(summary.getArtistCounts())
.extracting(count -> count.getArtistId() + ":" + count.getStatus())
.contains("20:working", "21:full");
}
private UserDO user(Integer type, Long shopId) {
UserDO user = new UserDO();
user.setId(10L + type);
user.setType(type);
user.setShopId(shopId);
user.setIsDelete(0);
user.setNickname("测试用户");
user.setPhone("13800138000");
return user;
}
private ArtistScheduleDO schedule(Long artistId, LocalDate date, LocalTime startTime, LocalTime endTime) {
ArtistScheduleDO schedule = new ArtistScheduleDO();
schedule.setId(1000L + artistId);
schedule.setShopId(8L);
schedule.setArtistId(artistId);
schedule.setWorkDate(date);
schedule.setStartTime(startTime);
schedule.setEndTime(endTime);
schedule.setCapacity(1);
schedule.setSlotMinutes(90);
schedule.setStatus(1);
schedule.setIsDelete(0);
return schedule;
}
private AppointmentReservationDO reservation(Long artistId, Long orderId, Long orderItemId,
LocalDateTime startTime, LocalDateTime endTime) {
AppointmentReservationDO reservation = new AppointmentReservationDO();
reservation.setOrderId(orderId);
reservation.setOrderItemId(orderItemId);
reservation.setShopId(8L);
reservation.setArtistId(artistId);
reservation.setProductTitle("测试预约");
reservation.setAppointmentStartTime(startTime);
reservation.setAppointmentEndTime(endTime);
reservation.setStatus("CONFIRMED");
reservation.setIsDelete(0);
return reservation;
}
private OrderDO order(Long orderId, Long shopId, Long customerId) {
OrderDO order = new OrderDO();
order.setId(orderId);
order.setShopId(shopId);
order.setUserId(customerId);
order.setStatus(1);
order.setIsDelete(0);
return order;
}
private OrderItemDO orderItem(Long orderItemId, Long orderId, Long productId, Long artistId, LocalDateTime appointmentTime) {
OrderItemDO item = new OrderItemDO();
item.setId(orderItemId);
item.setOrderId(orderId);
item.setProductId(productId);
item.setArtistId(artistId);
item.setQuantity(1);
item.setAppointmentTime(appointmentTime);
item.setIsDelete(0);
return item;
}
private ProductDO product(Long productId, Long shopId, String durationText) {
ProductDO product = new ProductDO();
product.setId(productId);
product.setShopId(shopId);
product.setTitle("测试作品");
product.setApproximateDuration(durationText);
product.setIsDelete(0);
return product;
}
}
@@ -1,43 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.planning.support;
import org.junit.jupiter.api.Test;
import java.time.LocalTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PlanningCalendarSupportTest {
@Test
void shortNameUsesReadableSingleCharacterForDenseMonthCells() {
assertEquals("王", PlanningCalendarSupport.shortName("小王"));
assertEquals("李", PlanningCalendarSupport.shortName("李老师"));
assertEquals("A", PlanningCalendarSupport.shortName("Alice"));
}
@Test
void businessHoursFallbackToShopManagerPlanningDefaults() {
PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours("10:00-22:00");
assertEquals(LocalTime.of(10, 0), hours.start());
assertEquals(LocalTime.of(22, 0), hours.end());
PlanningCalendarSupport.BusinessHours fallback = PlanningCalendarSupport.parseBusinessHours(null);
assertEquals(LocalTime.of(10, 0), fallback.start());
assertEquals(LocalTime.of(22, 0), fallback.end());
}
@Test
void durationParserSupportsChineseHourAndMinuteText() {
assertEquals(90, PlanningCalendarSupport.parseDurationMinutes("1.5小时", 60));
assertEquals(120, PlanningCalendarSupport.parseDurationMinutes("约120分钟", 60));
assertEquals(60, PlanningCalendarSupport.parseDurationMinutes("", 60));
}
@Test
void dayStatusKeepsMonthViewOperationalAtAGlance() {
assertEquals("rest", PlanningCalendarSupport.resolveDayStatus(0, false, false));
assertEquals("free", PlanningCalendarSupport.resolveDayStatus(0, true, false));
assertEquals("working", PlanningCalendarSupport.resolveDayStatus(2, true, false));
assertEquals("full", PlanningCalendarSupport.resolveDayStatus(6, true, true));
}
}
@@ -1,102 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.product.controller.front;
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService;
import com.xiaowang.fingertipdesigner.core.utils.JwtUtil;
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.List;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ProductControllerTest {
@Mock
private ProductService productService;
@Mock
private AdminScopeHelper adminScopeHelper;
@Mock
private JwtUtil jwtUtil;
@Mock
private UserSessionService userSessionService;
@Mock
private UserShopBindingSupport userShopBindingSupport;
private ProductController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
controller = new ProductController(productService, adminScopeHelper, jwtUtil, userSessionService, userShopBindingSupport);
}
@Test
void listAllProductsShouldUseCurrentShopFromValidToken() {
MockHttpServletRequest request = authenticatedShopRequest(7L, 3L);
when(productService.listPublicProductsByShopId(3L)).thenReturn(List.of(new ProductVO()));
controller.listAllProducts(request);
verify(productService).listPublicProductsByShopId(3L);
verify(productService, never()).listPublicProducts();
}
@Test
void searchProductsShouldUseCurrentShopFromValidToken() {
MockHttpServletRequest request = authenticatedShopRequest(7L, 3L);
when(productService.searchProducts("猫眼", 3L)).thenReturn(List.of(new ProductVO()));
controller.searchProducts(request, "猫眼");
verify(productService).searchProducts("猫眼", 3L);
verify(productService, never()).searchProducts("猫眼");
}
@Test
void listAllProductsShouldRemainPublicWithoutToken() {
MockHttpServletRequest request = new MockHttpServletRequest();
when(productService.listPublicProducts()).thenReturn(List.of(new ProductVO()));
controller.listAllProducts(request);
verify(productService).listPublicProducts();
verify(productService, never()).listPublicProductsByShopId(3L);
}
@Test
void pagePublicProductsShouldPassGroupedTagIdsToService() {
MockHttpServletRequest request = new MockHttpServletRequest();
controller.pagePublicProducts(request, 1, 10, "", "", "11,22");
verify(productService).pagePublicProducts(1, 10, "", "", "11,22", null);
}
private MockHttpServletRequest authenticatedShopRequest(Long userId, Long shopId) {
String token = "access-token";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + token);
when(jwtUtil.validateToken(token)).thenReturn(true);
when(jwtUtil.isAccessToken(token)).thenReturn(true);
when(jwtUtil.getShopIdFromToken(token)).thenReturn(shopId);
when(jwtUtil.getUserIdFromToken(token)).thenReturn(userId);
when(jwtUtil.getSessionIdFromToken(token)).thenReturn("session-id");
when(jwtUtil.getJtiFromToken(token)).thenReturn("jti");
when(userSessionService.isAccessSessionActive(userId, "session-id", "jti")).thenReturn(true);
when(userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)).thenReturn(true);
return request;
}
}
@@ -1,153 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.product.service.impl;
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
import com.xiaowang.fingertipdesigner.core.modules.product.dto.ProductDTO;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport;
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService;
@ExtendWith(MockitoExtension.class)
class ProductServiceImplTest {
@Mock
private ProductMapper productMapper;
@Mock
private ObjectStorageFileService objectStorageFileService;
@Mock
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Mock
private CouponMapper couponMapper;
@Mock
private ShopMapper shopMapper;
@Mock
private TagMapper tagMapper;
@Mock
private BookableArtistSupport bookableArtistSupport;
@Mock
private MultiLevelCacheService multiLevelCacheService;
private ProductServiceImpl productService;
@BeforeEach
void setUp() {
AppCacheProperties cacheProperties = new AppCacheProperties();
productService = new ProductServiceImpl(
productMapper,
objectStorageFileService,
objectStorageUrlSupport,
couponMapper,
shopMapper,
tagMapper,
bookableArtistSupport,
multiLevelCacheService,
cacheProperties
);
}
@Test
void createProductShouldPersistTargetAudienceAndPrecautions() {
ProductDTO dto = new ProductDTO();
dto.setShopId(3L);
dto.setTitle("French cat eye");
dto.setDescription("soft shimmer");
dto.setPrice(new BigDecimal("168.00"));
dto.setTargetAudience("Short nails, daily office style");
dto.setPrecautions("Avoid long hot baths within 24 hours");
when(bookableArtistSupport.filterValidBookableArtists(3L, null)).thenReturn("");
when(productMapper.insert(any(ProductDO.class))).thenAnswer(invocation -> {
ProductDO product = invocation.getArgument(0);
product.setId(99L);
return 1;
});
productService.createProduct(dto);
ArgumentCaptor<ProductDO> captor = ArgumentCaptor.forClass(ProductDO.class);
org.mockito.Mockito.verify(productMapper).insert(captor.capture());
assertEquals("Short nails, daily office style", captor.getValue().getTargetAudience());
assertEquals("Avoid long hot baths within 24 hours", captor.getValue().getPrecautions());
assertEquals(1, captor.getValue().getFrontVisible());
assertEquals("BACKEND", captor.getValue().getSourceType());
}
@Test
void getProductByIdShouldExposeTargetAudienceAndPrecautions() {
ProductDO product = new ProductDO();
product.setId(99L);
product.setShopId(3L);
product.setTitle("French cat eye");
product.setDescription("soft shimmer");
product.setPrice(new BigDecimal("168.00"));
product.setTargetAudience("Short nails, daily office style");
product.setPrecautions("Avoid long hot baths within 24 hours");
product.setIsDelete(0);
when(productMapper.selectById(99L)).thenReturn(product);
when(bookableArtistSupport.filterValidBookableArtists(3L, null)).thenReturn("");
when(multiLevelCacheService.getOrLoad(
anyString(),
any(Duration.class),
any(Duration.class),
any(),
any()
)).thenAnswer(invocation -> ((java.util.function.Supplier<?>) invocation.getArgument(4)).get());
ProductVO productVO = productService.getProductById(99L);
assertEquals("Short nails, daily office style", productVO.getTargetAudience());
assertEquals("Avoid long hot baths within 24 hours", productVO.getPrecautions());
}
@Test
void getPublicProductByIdShouldHideInvisibleProduct() {
ProductDO product = new ProductDO();
product.setId(99L);
product.setShopId(3L);
product.setTitle("Manual appointment item");
product.setDescription("hidden");
product.setPrice(new BigDecimal("88.00"));
product.setFrontVisible(0);
product.setIsDelete(0);
when(productMapper.selectById(99L)).thenReturn(product);
when(multiLevelCacheService.getOrLoad(
anyString(),
any(Duration.class),
any(Duration.class),
any(),
any()
)).thenAnswer(invocation -> ((java.util.function.Supplier<?>) invocation.getArgument(4)).get());
ProductVO productVO = productService.getPublicProductById(99L);
assertNull(productVO);
}
}
@@ -1,73 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.product.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper;
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagFilterGroupVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TagServiceImplTest {
private TagMapper tagMapper;
private TagServiceImpl service;
@BeforeEach
void setUp() {
tagMapper = mock(TagMapper.class);
ShopMapper shopMapper = mock(ShopMapper.class);
MultiLevelCacheService cacheService = mock(MultiLevelCacheService.class);
AppCacheProperties cacheProperties = new AppCacheProperties();
when(cacheService.getOrLoad(
anyString(),
any(Duration.class),
any(Duration.class),
any(TypeReference.class),
any(Supplier.class)
)).thenAnswer(invocation -> ((Supplier<?>) invocation.getArgument(4)).get());
service = new TagServiceImpl(tagMapper, shopMapper, cacheService, cacheProperties);
}
@Test
void listFilterOptionsGroupsOnlyFrontVisibleTagsAndKeepsLegacyDefaults() {
TagDO style = tag(1L, "日常", "风格", "通勤", 20, 1);
TagDO legacy = tag(2L, "显白", null, null, null, null);
TagDO hidden = tag(3L, "隐藏", "风格", "隐藏", 1, 0);
when(tagMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(hidden, legacy, style));
List<TagFilterGroupVO> groups = service.listFilterOptions(null);
assertThat(groups).hasSize(2);
assertThat(groups.get(0).getGroupName()).isEqualTo("风格");
assertThat(groups.get(0).getTags()).extracting("displayName").containsExactly("通勤");
assertThat(groups.get(1).getGroupName()).isEqualTo("其他");
assertThat(groups.get(1).getTags()).extracting("displayName").containsExactly("显白");
}
private TagDO tag(Long id, String tagName, String sceneGroup, String displayName, Integer sortOrder, Integer frontVisible) {
TagDO tag = new TagDO();
tag.setId(id);
tag.setShopId(8L);
tag.setTagName(tagName);
tag.setSceneGroup(sceneGroup);
tag.setDisplayName(displayName);
tag.setSortOrder(sortOrder);
tag.setFrontVisible(frontVisible);
tag.setIsDelete(0);
return tag;
}
}
@@ -1,46 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.security.controller.admin;
import com.xiaowang.fingertipdesigner.core.common.Result;
import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AdminSecurityAuditControllerTest {
@Mock
private SecurityAuditLogService securityAuditLogService;
private AdminSecurityAuditController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
controller = new AdminSecurityAuditController(securityAuditLogService);
}
@Test
void listLogsDelegatesToServiceWithFilters() {
PageResultVO<SecurityAuditLogVO> page = new PageResultVO<>();
page.setTotal(0L);
when(securityAuditLogService.pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
any(), any(), eq(1), eq(20))).thenReturn(page);
Result<PageResultVO<SecurityAuditLogVO>> result = controller.listLogs(
"admin", "ORDER_PROCESS", "SUCCESS",
"2026-05-01 00:00:00", "2026-05-23 23:59:59", 1, 20);
assertThat(result.getData()).isSameAs(page);
verify(securityAuditLogService).pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
any(), any(), eq(1), eq(20));
}
}
@@ -1,258 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.security.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO;
import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRolePermissionDO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserPermissionDO;
import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserShopRoleDO;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.ShopRolePermissionMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserPermissionMapper;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper;
import com.xiaowang.fingertipdesigner.core.support.RequestShopContext;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class PermissionServiceImplTest {
@Mock
private PermissionMapper permissionMapper;
@Mock
private UserPermissionMapper userPermissionMapper;
@Mock
private ShopRolePermissionMapper shopRolePermissionMapper;
@Mock
private UserShopRoleMapper userShopRoleMapper;
@Mock
private UserMapper userMapper;
@Mock
private UserShopBindingSupport userShopBindingSupport;
private PermissionServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new PermissionServiceImpl(
permissionMapper,
userPermissionMapper,
shopRolePermissionMapper,
userShopRoleMapper,
userMapper,
userShopBindingSupport
);
}
@AfterEach
void tearDown() {
RequestContextHolder.resetRequestAttributes();
}
@Test
void activeShopRoleRestrictsWritePermissionFromDefaultUserPermissions() {
long userId = 10L;
long productCreateId = 101L;
long productViewId = 102L;
long roleId = 201L;
UserDO user = new UserDO();
user.setId(userId);
user.setType(2);
user.setIsDelete(0);
when(userMapper.selectById(userId)).thenReturn(user);
UserPermissionDO defaultProductCreate = new UserPermissionDO();
defaultProductCreate.setUserId(userId);
defaultProductCreate.setPermissionId(productCreateId);
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
PermissionDO productCreate = permission(productCreateId, "product:create");
PermissionDO productView = permission(productViewId, "product:view");
when(permissionMapper.selectOne(any()))
.thenReturn(productCreate)
.thenReturn(productView);
UserShopRoleDO roleBinding = new UserShopRoleDO();
roleBinding.setUserId(userId);
roleBinding.setRoleId(roleId);
roleBinding.setStatus(1);
roleBinding.setIsDelete(0);
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
rolePermission.setRoleId(roleId);
rolePermission.setPermissionId(productViewId);
rolePermission.setIsDelete(0);
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
assertThat(service.hasPermission(userId, "product:create")).isFalse();
assertThat(service.hasPermission(userId, "product:view")).isTrue();
}
@Test
void listUserPermissionsUsesActiveShopRoleAsVisiblePermissions() {
long userId = 10L;
long productCreateId = 101L;
long productViewId = 102L;
long roleId = 201L;
UserDO user = new UserDO();
user.setId(userId);
user.setType(2);
user.setIsDelete(0);
when(userMapper.selectById(userId)).thenReturn(user);
UserPermissionDO defaultProductCreate = new UserPermissionDO();
defaultProductCreate.setUserId(userId);
defaultProductCreate.setPermissionId(productCreateId);
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
UserShopRoleDO roleBinding = new UserShopRoleDO();
roleBinding.setUserId(userId);
roleBinding.setRoleId(roleId);
roleBinding.setStatus(1);
roleBinding.setIsDelete(0);
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
rolePermission.setRoleId(roleId);
rolePermission.setPermissionId(productViewId);
rolePermission.setIsDelete(0);
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
when(permissionMapper.selectList(any())).thenReturn(List.of(permission(productViewId, "product:view")));
List<PermissionVO> permissions = service.listUserPermissions(userId);
assertThat(permissions)
.extracting(PermissionVO::getPermissionCode)
.containsExactly("product:view");
verify(shopRolePermissionMapper).selectList(any());
}
@Test
void staleDirectPermissionsCannotExceedUserTypeDefaultPermissions() {
long userId = 30L;
UserDO user = new UserDO();
user.setId(userId);
user.setType(3);
user.setIsDelete(0);
when(userMapper.selectById(userId)).thenReturn(user);
assertThat(service.hasPermission(userId, "product:create")).isFalse();
verifyNoInteractions(userPermissionMapper);
verifyNoInteractions(userShopRoleMapper);
verifyNoInteractions(shopRolePermissionMapper);
}
@Test
void activeShopRolesAreScopedToCurrentShop() {
long userId = 10L;
long currentShopId = 301L;
long otherShopId = 302L;
long currentShopRoleId = 401L;
long otherShopRoleId = 402L;
long productCreateId = 101L;
long productViewId = 102L;
MockHttpServletRequest request = new MockHttpServletRequest();
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
UserDO user = new UserDO();
user.setId(userId);
user.setType(2);
user.setIsDelete(0);
when(userMapper.selectById(userId)).thenReturn(user);
UserShopRoleDO currentShopRole = roleBinding(userId, currentShopId, currentShopRoleId);
UserShopRoleDO otherShopRole = roleBinding(userId, otherShopId, otherShopRoleId);
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(currentShopRole, otherShopRole));
ShopRolePermissionDO currentShopPermission = rolePermission(currentShopRoleId, productViewId);
ShopRolePermissionDO otherShopPermission = rolePermission(otherShopRoleId, productCreateId);
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(currentShopPermission, otherShopPermission));
when(permissionMapper.selectOne(any()))
.thenReturn(permission(productCreateId, "product:create"))
.thenReturn(permission(productViewId, "product:view"));
assertThat(service.hasPermission(userId, "product:create")).isFalse();
assertThat(service.hasPermission(userId, "product:view")).isTrue();
}
@Test
void shoplessPlatformAdminCurrentPermissionsIncludeSecurityAuditView() {
long userId = 1L;
UserDO user = new UserDO();
user.setId(userId);
user.setType(4);
user.setIsDelete(0);
when(userMapper.selectById(userId)).thenReturn(user);
when(permissionMapper.selectList(any())).thenReturn(List.of(
permission(101L, "shop:view"),
permission(102L, "security:audit:view")
));
List<PermissionVO> permissions = service.listUserPermissions(userId);
assertThat(permissions)
.extracting(PermissionVO::getPermissionCode)
.contains("security:audit:view");
verifyNoInteractions(userPermissionMapper);
verifyNoInteractions(userShopRoleMapper);
verifyNoInteractions(shopRolePermissionMapper);
}
private UserShopRoleDO roleBinding(long userId, long shopId, long roleId) {
UserShopRoleDO roleBinding = new UserShopRoleDO();
roleBinding.setUserId(userId);
roleBinding.setShopId(shopId);
roleBinding.setRoleId(roleId);
roleBinding.setStatus(1);
roleBinding.setIsDelete(0);
return roleBinding;
}
private ShopRolePermissionDO rolePermission(long roleId, long permissionId) {
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
rolePermission.setRoleId(roleId);
rolePermission.setPermissionId(permissionId);
rolePermission.setIsDelete(0);
return rolePermission;
}
private PermissionDO permission(long id, String code) {
PermissionDO permission = new PermissionDO();
permission.setId(id);
permission.setPermissionCode(code);
permission.setPermissionName(code);
permission.setPermissionGroup("test");
permission.setIsDelete(0);
return permission;
}
}
@@ -1,81 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.security.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaowang.fingertipdesigner.core.modules.security.entity.SecurityAuditLogDO;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.SecurityAuditLogMapper;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.xiaowang.fingertipdesigner.core.common.Result;
class SecurityAuditLogServiceImplTest {
@Mock
private SecurityAuditLogMapper auditLogMapper;
private SecurityAuditLogServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new SecurityAuditLogServiceImpl(auditLogMapper);
}
@Test
void recordTruncatesOversizedFieldsAndCapturesForwardedIp() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Forwarded-For", "10.0.0.1, 10.0.0.2");
service.record(1L, "a".repeat(100), "b".repeat(100), "SUCCESS", "c".repeat(600), request);
ArgumentCaptor<SecurityAuditLogDO> captor = ArgumentCaptor.forClass(SecurityAuditLogDO.class);
verify(auditLogMapper).insert(captor.capture());
SecurityAuditLogDO log = captor.getValue();
assertThat(log.getAccount()).hasSize(80);
assertThat(log.getAction()).hasSize(80);
assertThat(log.getReason()).hasSize(500);
assertThat(log.getIpAddress()).isEqualTo("10.0.0.1");
}
@Test
@SuppressWarnings("unchecked")
void pageLogsFiltersAndMapsPagedResult() {
SecurityAuditLogDO log = new SecurityAuditLogDO();
log.setId(100L);
log.setUserId(1L);
log.setAccount("admin");
log.setAction("ORDER_PROCESS");
log.setResult("SUCCESS");
log.setReason("orderId=1");
log.setIpAddress("127.0.0.1");
log.setDeviceId("device-1");
log.setOperateTime(LocalDateTime.now());
Page<SecurityAuditLogDO> page = new Page<>(2, 5);
page.setRecords(List.of(log));
page.setTotal(11);
when(auditLogMapper.selectPage(any(Page.class), any(LambdaQueryWrapper.class))).thenReturn(page);
PageResultVO<SecurityAuditLogVO> result = service.pageLogs("admin", "ORDER_PROCESS", "SUCCESS",
LocalDateTime.now().minusDays(1), LocalDateTime.now(), 2, 5);
assertThat(result.getTotal()).isEqualTo(11);
assertThat(result.getPage()).isEqualTo(2);
assertThat(result.getSize()).isEqualTo(5);
assertThat(result.getList()).hasSize(1);
assertThat(result.getList().get(0).getAction()).isEqualTo("ORDER_PROCESS");
}
}
@@ -1,97 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.security.support;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
class PermissionCatalogTest {
@Test
void announcementPermissionsUseChineseDisplayText() {
assertChinesePermission("announcement:view", "查看公告", "公告管理", "查看公告列表与详情");
assertChinesePermission("announcement:create", "发布公告", "公告管理", "发布公告");
assertChinesePermission("announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
}
@Test
void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() {
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
.contains("messagehub:config:manage", "security:audit:view", "legal_agreement:manage");
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:create")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:balance:manage")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("permission:assign")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("messagehub:config:manage")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("security:audit:view")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("legal_agreement:manage")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:view")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:create")).isFalse();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:process")).isFalse();
}
@Test
void everyManagedDefaultPermissionHasDefinition() {
Set<String> definedCodes = PermissionCatalog.getManagedPermissionCodes();
assertThat(definedCodes)
.containsAll(PermissionCatalog.getDefaultPermissionCodes(4))
.containsAll(PermissionCatalog.getDefaultPermissionCodes(2))
.containsAll(PermissionCatalog.getDefaultPermissionCodes(3));
}
@Test
void nailArtistDefaultPermissionsAreWorkbenchOnly() {
assertThat(PermissionCatalog.getDefaultPermissionCodes(3))
.contains("product:view", "tag:view", "coupon:view", "order:view", "order:process", "order:artist-change")
.doesNotContain("product:create", "product:edit", "product:delete",
"tag:create", "tag:edit", "tag:delete",
"user:create", "user:edit", "coupon:create", "coupon:assign");
}
@Test
void artistChangePermissionIsGrantedToProductionRoles() {
assertChinesePermission("order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请");
assertThat(PermissionCatalog.getDefaultPermissionCodes(2)).contains("order:artist-change");
assertThat(PermissionCatalog.getDefaultPermissionCodes(3)).contains("order:artist-change");
}
@Test
void vNextOperationsPermissionsAreGrantedByRole() {
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
.contains("schedule:view", "schedule:edit", "payment:manage", "refund:manage",
"after_sale:view", "after_sale:audit", "inventory:view", "inventory:manage",
"campaign:view", "campaign:manage", "growth:view", "analytics:view", "performance:view");
assertThat(PermissionCatalog.getDefaultPermissionCodes(2))
.contains("schedule:view", "schedule:edit", "payment:view", "refund:view",
"after_sale:view", "after_sale:audit", "inventory:view", "inventory:manage",
"campaign:view", "campaign:manage", "analytics:view", "performance:view");
assertThat(PermissionCatalog.getDefaultPermissionCodes(3))
.contains("schedule:view", "after_sale:view", "performance:view")
.doesNotContain("payment:manage", "refund:manage", "inventory:manage", "campaign:manage");
}
@Test
void everyManagedDefaultPermissionUsesChineseDisplayText() {
PermissionCatalog.getManagedDefinitions().forEach(definition -> {
assertThat(definition.permissionName()).matches(PermissionCatalogTest::containsChinese);
assertThat(definition.permissionGroup()).matches(PermissionCatalogTest::containsChinese);
assertThat(definition.description()).matches(PermissionCatalogTest::containsChinese);
});
}
private void assertChinesePermission(String code, String name, String group, String description) {
PermissionCatalog.PermissionDefinition definition = PermissionCatalog.getRequiredDefinition(code);
assertThat(definition.permissionName()).isEqualTo(name);
assertThat(definition.permissionGroup()).isEqualTo(group);
assertThat(definition.description()).isEqualTo(description);
}
private static boolean containsChinese(String value) {
return value != null && value.chars().anyMatch(codePoint -> codePoint >= 0x4E00 && codePoint <= 0x9FFF);
}
}
@@ -1,209 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.shop.service.impl;
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO;
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
import com.xiaowang.fingertipdesigner.core.modules.content.mapper.CommentMapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper;
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.UserCouponMapper;
import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService;
import com.xiaowang.fingertipdesigner.core.modules.integration.service.MapService;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopTrustProfileVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class ShopServiceImplTest {
@Mock
private ShopMapper shopMapper;
@Mock
private CouponService couponService;
@Mock
private CouponMapper couponMapper;
@Mock
private ProductMapper productMapper;
@Mock
private TagMapper tagMapper;
@Mock
private CommentMapper commentMapper;
@Mock
private UserCouponMapper userCouponMapper;
@Mock
private OrderArtistReviewMapper orderArtistReviewMapper;
@Mock
private ObjectStorageFileService objectStorageFileService;
@Mock
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private NailArtistInfoService nailArtistInfoService;
@Mock
private MultiLevelCacheService multiLevelCacheService;
@Mock
private AppCacheProperties appCacheProperties;
@Mock
private MapService mapService;
private ShopServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new ShopServiceImpl(
shopMapper,
couponService,
couponMapper,
productMapper,
tagMapper,
commentMapper,
userCouponMapper,
orderArtistReviewMapper,
objectStorageFileService,
objectStorageUrlSupport,
userShopBindingSupport,
nailArtistInfoService,
multiLevelCacheService,
appCacheProperties,
mapService
);
when(objectStorageUrlSupport.toAccessibleUrl(anyString()))
.thenAnswer(invocation -> invocation.getArgument(0, String.class));
when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class)))
.thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl());
}
@Test
void deleteShopRejectsBusinessDeleteWithoutCascadeSoftDelete() {
assertThatThrownBy(() -> service.deleteShop(1L))
.isInstanceOf(RuntimeException.class)
.hasMessage("店铺删除已停用,请使用停用封存");
verifyNoInteractions(
shopMapper,
couponMapper,
productMapper,
tagMapper,
commentMapper,
userCouponMapper,
userShopBindingSupport
);
}
@Test
void updateShopRejectsDisabledArchivedShop() {
ShopDO disabledShop = new ShopDO();
disabledShop.setId(1L);
disabledShop.setStatus(0);
disabledShop.setIsDelete(0);
when(shopMapper.selectById(1L)).thenReturn(disabledShop);
assertThatThrownBy(() -> service.updateShop(1L, new ShopDTO()))
.isInstanceOf(RuntimeException.class)
.hasMessage("停用店铺已封存,仅允许重新启用");
verify(shopMapper, never()).updateById(disabledShop);
}
@Test
void getShopTrustProfileAggregatesPublicTrustDataWithoutContactPhone() {
ShopDO shop = new ShopDO();
shop.setId(9L);
shop.setShopName("Yumi Test Shop");
shop.setStatus(1);
shop.setIsDelete(0);
shop.setBusinessHours("10:00-20:00");
shop.setImageFileIds("101,102");
shop.setCoverImageFileId("100");
shop.setCreateTime(LocalDateTime.now().minusDays(10));
when(shopMapper.selectById(9L)).thenReturn(shop);
ProductDO featured = new ProductDO();
featured.setId(31L);
featured.setShopId(9L);
featured.setTitle("琉璃猫眼");
featured.setDescription("透亮显白");
featured.setPrice(new BigDecimal("168.00"));
featured.setImageFileIds("201");
featured.setLikeCount(5);
featured.setCollectCount(12);
featured.setBookableArtists("7,8");
featured.setIsDelete(0);
featured.setCreateTime(LocalDateTime.now().minusDays(1));
when(productMapper.selectCount(any())).thenReturn(1L);
when(productMapper.selectList(any())).thenReturn(List.of(featured));
OrderArtistReviewDO submitted = new OrderArtistReviewDO();
submitted.setId(51L);
submitted.setShopId(9L);
submitted.setProductId(31L);
submitted.setRatingScore(new BigDecimal("4.5"));
submitted.setContent("环境干净,做得很细");
submitted.setStatus(1);
submitted.setIsDelete(0);
submitted.setSubmittedAt(LocalDateTime.now().minusHours(3));
OrderArtistReviewDO pending = new OrderArtistReviewDO();
pending.setId(52L);
pending.setShopId(9L);
pending.setRatingScore(new BigDecimal("1.0"));
pending.setContent("待评价不应展示");
pending.setStatus(0);
pending.setIsDelete(0);
when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted));
when(orderArtistReviewMapper.selectCount(any())).thenReturn(1L);
ObjectStorageFileVO cover = new ObjectStorageFileVO();
cover.setId(100L);
cover.setFileUrl("https://img.test/cover.jpg");
ObjectStorageFileVO env = new ObjectStorageFileVO();
env.setId(101L);
env.setFileUrl("https://img.test/env.jpg");
ObjectStorageFileVO productImage = new ObjectStorageFileVO();
productImage.setId(201L);
productImage.setFileUrl("https://img.test/product.jpg");
when(objectStorageFileService.getObjectStorageFileMapByIds(any()))
.thenReturn(Map.of(100L, cover, 101L, env, 201L, productImage));
ShopTrustProfileVO profile = service.getShopTrustProfile(9L);
assertThat(profile).isNotNull();
assertThat(profile.getShopId()).isEqualTo(9L);
assertThat(profile.getStats().getProductCount()).isEqualTo(1L);
assertThat(profile.getStats().getReviewCount()).isEqualTo(1L);
assertThat(profile.getStats().getAverageRating()).isEqualByComparingTo("4.5");
assertThat(profile.getEnvironmentImages()).contains("https://img.test/cover.jpg", "https://img.test/env.jpg");
assertThat(profile.getFeaturedProducts()).hasSize(1);
assertThat(profile.getFeaturedProducts().get(0).getImageUrl()).isEqualTo("https://img.test/product.jpg");
assertThat(profile.getRecentReviews()).hasSize(1);
assertThat(profile.getRecentReviews().get(0).getContent()).isEqualTo("环境干净,做得很细");
assertThat(profile.getContactSummary().getPhoneExposed()).isFalse();
assertThat(profile.getContactSummary().getPhone()).isNull();
}
}
@@ -1,30 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.shop.support;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class ShopThemeSupportTest {
@Test
void normalizeColorAcceptsOnlySixDigitHexAndUppercasesIt() {
assertThat(ShopThemeSupport.normalizeColor("#c6597d", "themePrimaryColor")).isEqualTo("#C6597D");
assertThat(ShopThemeSupport.normalizeColor(" #ffffff ", "themeCardBgColor")).isEqualTo("#FFFFFF");
}
@Test
void normalizeColorTreatsBlankAsUnset() {
assertThat(ShopThemeSupport.normalizeColor(null, "themePrimaryColor")).isNull();
assertThat(ShopThemeSupport.normalizeColor(" ", "themePrimaryColor")).isNull();
}
@Test
void normalizeColorRejectsUnsafeValues() {
assertThatThrownBy(() -> ShopThemeSupport.normalizeColor("#fff", "themePrimaryColor"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("themePrimaryColor");
assertThatThrownBy(() -> ShopThemeSupport.normalizeColor("url(javascript:alert(1))", "themePrimaryColor"))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -1,44 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.system.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.system.dto.SystemParameterConfigDTO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.system.mapper.SystemParameterConfigMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verifyNoInteractions;
class SystemParameterConfigServiceImplTest {
@Mock
private SystemParameterConfigMapper configMapper;
private SystemParameterConfigServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new SystemParameterConfigServiceImpl(configMapper);
}
@Test
void saveConfigRejectsWeakAdminDefaultPassword() {
UserDO admin = new UserDO();
admin.setType(4);
SystemParameterConfigDTO dto = new SystemParameterConfigDTO();
dto.setConfigGroup("USER");
dto.setConfigKey("DEFAULT_PASSWORD");
dto.setConfigName("后台新增用户默认密码");
dto.setConfigValue("12345678");
dto.setEnabled(1);
assertThatThrownBy(() -> service.saveConfig(admin, dto))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("默认密码");
verifyNoInteractions(configMapper);
}
}
@@ -1,37 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.system.support;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class AdminDefaultPasswordSupportTest {
@Test
void resolveCreatePasswordUsesConfiguredDefaultWhenPasswordBlank() {
String password = AdminDefaultPasswordSupport.resolveCreatePassword(" ", " Config@123 ");
assertThat(password).isEqualTo("Config@123");
}
@Test
void resolveCreatePasswordKeepsExplicitPassword() {
String password = AdminDefaultPasswordSupport.resolveCreatePassword(" User@1234 ", "Config@123");
assertThat(password).isEqualTo("User@1234");
}
@Test
void resolveDefaultPasswordFallsBackToStrongBuiltInDefault() {
String password = AdminDefaultPasswordSupport.resolveDefaultPassword("");
assertThat(password).isEqualTo(AdminDefaultPasswordSupport.FALLBACK_DEFAULT_PASSWORD);
}
@Test
void validateDefaultPasswordRejectsWeakConfig() {
assertThatThrownBy(() -> AdminDefaultPasswordSupport.validateDefaultPassword("12345678"))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("默认密码");
}
}
@@ -1,200 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.user.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper;
import com.xiaowang.fingertipdesigner.core.config.BrandProperties;
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserInviteCodeMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserPermissionMapper;
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserRelationMapper;
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper;
import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.WechatMiniBindingMapper;
import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RegisterRequestDTO;
import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO;
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService;
import com.xiaowang.fingertipdesigner.core.modules.system.service.SystemParameterConfigService;
import com.xiaowang.fingertipdesigner.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionCatalog;
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService;
import com.xiaowang.fingertipdesigner.core.utils.JwtUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.lang.reflect.Method;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doAnswer;
import static org.assertj.core.api.Assertions.assertThat;
class UserServiceImplPermissionAssignmentTest {
@Mock
private UserMapper userMapper;
@Mock
private ShopMapper shopMapper;
@Mock
private JwtUtil jwtUtil;
@Mock
private ShopService shopService;
@Mock
private UserPermissionMapper userPermissionMapper;
@Mock
private PermissionMapper permissionMapper;
@Mock
private UserRelationMapper userRelationMapper;
@Mock
private UserInviteCodeMapper userInviteCodeMapper;
@Mock
private BrandProperties brandProperties;
@Mock
private UserShopRoleMapper userShopRoleMapper;
@Mock
private NailArtistInfoService nailArtistInfoService;
@Mock
private VerificationCodeService verificationCodeService;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Mock
private StringRedisTemplate redisTemplate;
@Mock
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
@Mock
private WechatMiniBindingMapper wechatMiniBindingMapper;
@Mock
private UserSessionService userSessionService;
@Mock
private SystemParameterConfigService systemParameterConfigService;
private AutoCloseable mocks;
private UserServiceImpl service;
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
service = new UserServiceImpl(
userMapper,
shopMapper,
jwtUtil,
shopService,
userPermissionMapper,
permissionMapper,
userRelationMapper,
userInviteCodeMapper,
brandProperties,
userShopRoleMapper,
nailArtistInfoService,
verificationCodeService,
userShopBindingSupport,
objectStorageUrlSupport,
redisTemplate,
snowflakeIdGenerator,
wechatMiniBindingMapper,
userSessionService,
systemParameterConfigService
);
}
@AfterEach
void tearDown() throws Exception {
mocks.close();
}
@Test
void assignDefaultPermissionsSkipsPermissionSyncForPlainCustomer() throws Exception {
Method method = UserServiceImpl.class.getDeclaredMethod("assignDefaultPermissions", Long.class, Integer.class);
method.setAccessible(true);
method.invoke(service, 1001L, 0);
verifyNoInteractions(permissionMapper, userPermissionMapper);
}
@Test
void ensurePermissionDefinitionsSkipsUnchangedExistingDefinitions() throws Exception {
when(permissionMapper.selectList(any())).thenReturn(existingManagedPermissionsFromCatalog());
Method method = UserServiceImpl.class.getDeclaredMethod("ensurePermissionDefinitions");
method.setAccessible(true);
method.invoke(service);
verify(permissionMapper, never()).insert(any(PermissionDO.class));
verify(permissionMapper, never()).updateById(any(PermissionDO.class));
}
@Test
void registerSkipsPermissionSyncForPlainCustomer() {
RegisterRequestDTO request = new RegisterRequestDTO();
request.setAccount("codexregister1");
request.setPassword("Abc123456");
request.setNickname("Codex");
request.setPhone("13900000001");
request.setVerificationCode("123456");
request.setShopId(1L);
when(verificationCodeService.verifyCode("13900000001", "123456")).thenReturn(true);
when(userShopBindingSupport.isShopActive(1L)).thenReturn(true);
when(userMapper.selectOne(org.mockito.ArgumentMatchers.any()))
.thenReturn(null)
.thenReturn(null)
.thenReturn(new UserDO());
doAnswer(invocation -> {
UserDO userDO = invocation.getArgument(0);
userDO.setId(42L);
return 1;
}).when(userMapper).insert(org.mockito.ArgumentMatchers.any());
assertThat(service.register(request)).isTrue();
verifyNoInteractions(permissionMapper, userPermissionMapper);
}
private static List<PermissionDO> existingManagedPermissionsFromCatalog() {
long id = 1L;
List<PermissionDO> permissions = new java.util.ArrayList<>();
for (PermissionCatalog.PermissionDefinition definition : PermissionCatalog.getManagedDefinitions()) {
PermissionDO permission = new PermissionDO();
permission.setId(id++);
permission.setPermissionCode(definition.permissionCode());
permission.setPermissionName(definition.permissionName());
permission.setPermissionGroup(definition.permissionGroup());
permission.setDescription(definition.description());
permission.setIsDelete(0);
permissions.add(permission);
}
return permissions;
}
}
@@ -1,32 +0,0 @@
package com.xiaowang.fingertipdesigner.core.modules.user.support;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class UserProfileFieldSupportTest {
@Test
void requiresWechatIdForShopManagersAndNailArtists() {
assertThatThrownBy(() -> UserProfileFieldSupport.requireWechatIdForServiceUser(2, " "))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("微信号");
assertThatThrownBy(() -> UserProfileFieldSupport.requireWechatIdForServiceUser(3, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("微信号");
}
@Test
void allowsBlankWechatIdForNormalUsersAndAdmins() {
UserProfileFieldSupport.requireWechatIdForServiceUser(0, " ");
UserProfileFieldSupport.requireWechatIdForServiceUser(4, null);
}
@Test
void normalizesOptionalProfileText() {
assertThat(UserProfileFieldSupport.normalizeOptionalText(null)).isNull();
assertThat(UserProfileFieldSupport.normalizeOptionalText(" ")).isNull();
assertThat(UserProfileFieldSupport.normalizeOptionalText(" fingertip-designer-nail ")).isEqualTo("fingertip-designer-nail");
}
}
@@ -1,127 +0,0 @@
package com.xiaowang.fingertipdesigner.core.support;
import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
class FingertipDesignerSqlSchemaTest {
private static final Path INIT_SQL_PATH = Path.of("../scripts/sql/init/FingertipDesigner.sql");
@Test
void balanceTableDefinesUpdateTimeColumnBeforeSeedMigrations() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).containsPattern("(?is)create table t_balance\\s*\\([^;]*\\bupdate_time\\s+datetime");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_balance', 'update_time'");
}
@Test
void orderArtistReviewAndChangeSchemasAreSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_review");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_change_request");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_type'");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_id'");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'action_path'");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key'");
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency'");
assertThat(sql).contains("pending_key");
assertThat(sql).contains("EXPIRED");
assertThat(sql).contains("idx_order_artist_change_expire");
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key'");
assertThat(sql).contains("'order:artist-change'");
}
@Test
void businessEventOutboxAndSecurityAuditPermissionAreSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_business_event_outbox");
assertThat(sql).contains("uk_business_event_outbox_event_key");
assertThat(sql).contains("idx_business_event_outbox_due");
assertThat(sql).contains("'security:audit:view'");
}
@Test
void tagSceneFilterColumnsAreSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("scene_group");
assertThat(sql).contains("display_name");
assertThat(sql).contains("front_visible");
assertThat(sql).contains("idx_t_tag_front_filter");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_tag', 'scene_group'");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_tag', 'front_visible'");
}
@Test
void vNextOperationsSchemasAndPermissionsAreSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_artist_schedule");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_appointment_reservation");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_payment_order");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_refund_order");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_after_sale");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_after_sale_log");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_inventory_item");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_inventory_record");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_campaign");
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_user_growth_record");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_order', 'payment_status'");
assertThat(sql).contains("'schedule:view'");
assertThat(sql).contains("'payment:manage'");
assertThat(sql).contains("'after_sale:audit'");
assertThat(sql).contains("'inventory:manage'");
assertThat(sql).contains("'campaign:manage'");
assertThat(sql).contains("'growth:view'");
assertThat(sql).contains("'analytics:view'");
assertThat(sql).contains("'performance:view'");
assertThat(sql).contains("'workbench:view'");
}
@Test
void adminDefaultPasswordConfigIsSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("'USER', 'DEFAULT_PASSWORD'");
assertThat(sql).contains("后台新增用户默认密码");
}
@Test
void userProfileContactColumnsAreSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("contact_phone varchar(50)");
assertThat(sql).contains("birthday date");
assertThat(sql).contains("wechat_id varchar(100)");
assertThat(sql).contains("wechat_qr_code varchar(512)");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_user', 'contact_phone'");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code'");
}
@Test
void objectStorageFileBackupColumnsAreSeeded() throws Exception {
String sql = Files.readString(INIT_SQL_PATH);
assertThat(sql).contains("object_name");
assertThat(sql).contains("primary_provider");
assertThat(sql).contains("primary_url");
assertThat(sql).contains("backup_provider");
assertThat(sql).contains("backup_url");
assertThat(sql).contains("content_type");
assertThat(sql).contains("file_size");
assertThat(sql).contains("primary_upload_status");
assertThat(sql).contains("backup_upload_status");
assertThat(sql).contains("backup_retry_count");
assertThat(sql).contains("backup_last_error");
assertThat(sql).contains("backup_uploaded_at");
assertThat(sql).contains("backup_last_retry_time");
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name'");
assertThat(sql).contains("CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry'");
}
}
@@ -1,33 +0,0 @@
package com.xiaowang.fingertipdesigner.core.support;
import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
class WishlistSqlSchemaTest {
@Test
void wishlistGroupsAndMetadataAreSeededInInitSql() throws Exception {
String sql = Files.readString(Path.of("../scripts/sql/init/FingertipDesigner.sql"));
assertWishlistSchema(sql);
}
private void assertWishlistSchema(String sql) {
assertThat(sql).contains("t_wishlist_group");
assertThat(sql).contains("group_id");
assertThat(sql).contains("note");
assertThat(sql).contains("sort_order");
assertThat(sql).contains("最近想做");
assertThat(sql).contains("婚礼款");
assertThat(sql).contains("夏天款");
assertThat(sql).contains("idx_t_wishlist_group_user");
assertThat(sql).contains("idx_t_wishlist_group_sort");
assertThat(sql).contains("idx_t_wishlist_group_sort");
assertThat(sql).contains("idx_t_wishlist_user_group_sort");
assertThat(sql).contains("sp_drop_auto_increment_on_id_if_exists('t_wishlist_group')");
}
}
@@ -1,20 +0,0 @@
package com.xiaowang.fingertipdesigner.core.utils;
import com.xiaowang.fingertipdesigner.core.config.JwtProperties;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class JwtUtilTest {
@Test
void resolveAccessTokenExpirationSecondsShouldUseRememberMeSeconds() {
JwtProperties properties = new JwtProperties();
properties.setAccessTokenExpirationSeconds(120L);
properties.setRememberMeAccessTokenExpirationSeconds(604800L);
JwtUtil jwtUtil = new JwtUtil(properties);
assertThat(jwtUtil.resolveAccessTokenExpirationSeconds(false)).isEqualTo(120L);
assertThat(jwtUtil.resolveAccessTokenExpirationSeconds(true)).isEqualTo(604800L);
}
}
@@ -1,56 +0,0 @@
export type AdminNavIconKey =
| 'home'
| 'dashboard'
| 'user'
| 'shop'
| 'gift'
| 'message'
| 'security'
| 'tag'
| 'shopping'
| 'calendar'
| 'tool'
| 'team'
export interface AdminNavigationItem {
path: string
iconKey: AdminNavIconKey
label: string
permissionCode: string
}
export const ADMIN_HOME_PATH = '/admin'
export const ADMIN_DASHBOARD_PATH = '/admin/dashboard'
export const adminNavigationItems: AdminNavigationItem[] = [
{ path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' },
{ path: ADMIN_DASHBOARD_PATH, iconKey: 'dashboard', label: '仪表盘', permissionCode: 'dashboard:view' },
{ path: '/admin/users', iconKey: 'user', label: '用户管理', permissionCode: 'user:view' },
{ path: '/admin/products', iconKey: 'shop', label: '作品管理', permissionCode: 'product:view' },
{ path: '/admin/coupons', iconKey: 'gift', label: '优惠券管理', permissionCode: 'coupon:view' },
{ path: '/admin/comments', iconKey: 'message', label: '评论管理', permissionCode: 'comment:view' },
{ path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' },
{ path: '/admin/permissions', iconKey: 'security', label: '权限管理', permissionCode: 'permission:view' },
{ path: '/admin/tags', iconKey: 'tag', label: '标签管理', permissionCode: 'tag:view' },
{ path: '/admin/orders', iconKey: 'shopping', label: '订单管理', permissionCode: 'order:view' },
{ path: '/admin/schedules', iconKey: 'calendar', label: '排班管理', permissionCode: 'schedule:view' },
{ path: '/admin/after-sales', iconKey: 'message', label: '售后处理', permissionCode: 'after_sale:view' },
{ path: '/admin/inventory', iconKey: 'tool', label: '库存管理', permissionCode: 'inventory:view' },
{ path: '/admin/campaigns', iconKey: 'gift', label: '活动管理', permissionCode: 'campaign:view' },
{ path: '/admin/nail-artists', iconKey: 'team', label: '美甲师管理', permissionCode: 'nail_artist:view' },
{ path: '/admin/messages', iconKey: 'message', label: '消息发布', permissionCode: 'message:view' },
{ path: '/admin/announcements', iconKey: 'message', label: '公告管理', permissionCode: 'announcement:view' },
{ path: '/admin/vip-recharge-plans', iconKey: 'gift', label: 'VIP充值配置', permissionCode: 'user:vip:manage' },
{ path: '/admin/messagehub-push-configs', iconKey: 'message', label: '参数管理', permissionCode: 'messagehub:config:manage' },
{ path: '/admin/legal-agreements', iconKey: 'security', label: '协议管理', permissionCode: 'legal_agreement:manage' }
]
export const adminPermissionRouteMap = adminNavigationItems
.filter(item => item.permissionCode)
.map(item => ({
code: item.permissionCode,
path: item.path
}))
export const findAdminNavigationItemByPath = (path: string) =>
adminNavigationItems.find(item => item.path === path)
-371
View File
@@ -1,371 +0,0 @@
import { createRouter, createWebHistory } from 'vue-router'
import {
canAccessAdminRoute,
clearAdminBootstrapSession,
ensureAdminAuthBootstrap,
getAdminBootstrapSnapshot,
resolveAdminLandingPath,
} from '@/utils/admin-auth-bootstrap'
/**
* Purpose: router supports index.ts by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'auth',
component: () => import('../views/AuthView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/home',
name: 'home',
component: () => import('../views/HomeView.vue'),
meta: { requiresAuth: false, isAdmin: false }
},
{
path: '/products',
name: 'products',
component: () => import('../views/ProductListView.vue'),
meta: { requiresAuth: false, isAdmin: false }
},
{
path: '/product/:id',
name: 'product-detail',
component: () => import('../views/ProductDetailView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/cart',
name: 'cart',
component: () => import('../views/CartView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/profile',
name: 'profile',
component: () => import('../views/ProfileView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/shop/:id',
name: 'shop-detail',
component: () => import('../views/ShopDetailView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/shop/:shopId/artists',
name: 'shop-artists',
component: () => import('../views/ArtistListView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/artist/:id',
name: 'artist-profile',
component: () => import('../views/ArtistProfileView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/wishlist',
name: 'wishlist',
component: () => import('../views/WishlistView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/orders',
name: 'orders',
component: () => import('../views/OrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/orders/:id',
name: 'order-detail',
component: () => import('../views/OrderDetailView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/after-sales',
name: 'after-sales',
component: () => import('../views/AfterSalesView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/after-sale/apply',
name: 'after-sale-apply',
component: () => import('../views/AfterSaleApplyView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/service-progress',
name: 'service-progress',
component: () => import('../views/ServiceProgressView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/help',
name: 'help',
component: () => import('../views/HelpView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/artist-orders',
name: 'artist-orders',
component: () => import('../views/ArtistOrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
},
{
path: '/artist-calendar',
name: 'artist-calendar',
component: () => import('../views/ArtistCalendarView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
},
{
path: '/settings',
name: 'settings',
component: () => import('../views/SettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/settings/account',
name: 'account-settings',
component: () => import('../views/AccountSettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/settings/password',
name: 'password-settings',
component: () => import('../views/PasswordSettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/coupons',
name: 'coupons',
component: () => import('../views/CouponView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/vip-center',
name: 'vip-center',
component: () => import('../views/VipCenterView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/notifications',
name: 'notifications',
component: () => import('../views/NotificationsView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/admin/login',
name: 'admin-login',
component: () => import('../views/admin/AdminLoginView.vue'),
meta: { requiresAuth: false, isAdmin: true, hideNav: true }
},
{
path: '/admin',
component: () => import('../views/admin/AdminLayout.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true },
children: [
{
path: '',
name: 'admin',
component: () => import('../views/admin/HomeView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
},
{
path: 'dashboard',
name: 'admin-dashboard',
component: () => import('../views/admin/DashboardView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'dashboard:view' }
},
{
path: 'users',
name: 'admin-users',
component: () => import('../views/admin/UsersView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:view' }
},
{
path: 'products',
name: 'admin-products',
component: () => import('../views/admin/ProductsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'product:view' }
},
{
path: 'coupons',
name: 'admin-coupons',
component: () => import('../views/admin/CouponsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'coupon:view' }
},
{
path: 'comments',
name: 'admin-comments',
component: () => import('../views/admin/CommentsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'comment:view' }
},
{
path: 'shops',
name: 'admin-shops',
component: () => import('../views/admin/ShopsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'shop:view' }
},
{
path: 'permissions',
name: 'admin-permissions',
component: () => import('../views/admin/PermissionsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'permission:view' }
},
{
path: 'orders',
name: 'admin-orders',
component: () => import('../views/admin/OrdersView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'order:view' }
},
{
path: 'schedules',
name: 'admin-schedules',
component: () => import('../views/admin/SchedulesView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'schedule:view' }
},
{
path: 'after-sales',
name: 'admin-after-sales',
component: () => import('../views/admin/AfterSalesView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'after_sale:view' }
},
{
path: 'inventory',
name: 'admin-inventory',
component: () => import('../views/admin/InventoryView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'inventory:view' }
},
{
path: 'campaigns',
name: 'admin-campaigns',
component: () => import('../views/admin/CampaignsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'campaign:view' }
},
{
path: 'manage',
name: 'admin-manage',
component: () => import('../views/admin/ManageView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
},
{
path: 'profile',
name: 'admin-profile',
component: () => import('../views/admin/ProfileView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
},
{
path: 'tags',
name: 'admin-tags',
component: () => import('../views/admin/TagsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'tag:view' }
},
{
path: 'nail-artists',
name: 'admin-nail-artists',
component: () => import('../views/admin/NailArtistsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'nail_artist:view' }
},
{
path: 'messages',
name: 'admin-messages',
component: () => import('../views/admin/SystemMessagesView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'message:view' }
},
{
path: 'announcements',
name: 'admin-announcements',
component: () => import('../views/admin/AnnouncementsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'announcement:view' }
},
{
path: 'vip-recharge-plans',
name: 'admin-vip-recharge-plans',
component: () => import('../views/admin/VipRechargePlansView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:vip:manage' }
},
{
path: 'messagehub-push-configs',
name: 'admin-messagehub-push-configs',
component: () => import('../views/admin/MessageHubPushConfigsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'messagehub:config:manage' }
},
{
path: 'legal-agreements',
name: 'admin-legal-agreements',
component: () => import('../views/admin/LegalAgreementsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'legal_agreement:manage' }
}
]
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFoundView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
}
]
})
router.beforeEach(async (to) => {
const isAdminRoute = Boolean(to.meta.isAdmin)
const requiresAuth = Boolean(to.meta.requiresAuth)
if (isAdminRoute) {
const snapshot = getAdminBootstrapSnapshot()
if (to.path === '/admin/login') {
if (!snapshot.token || !snapshot.userInfo) {
return true
}
const state = await ensureAdminAuthBootstrap()
return state === 'ready' ? resolveAdminLandingPath() : true
}
if (requiresAuth && (!snapshot.token || !snapshot.userInfo)) {
clearAdminBootstrapSession()
return '/admin/login'
}
const bootstrapState = await ensureAdminAuthBootstrap()
if (bootstrapState !== 'ready') {
return '/admin/login'
}
if (!canAccessAdminRoute(to.path, to.meta.permissionCode as string | undefined)) {
return resolveAdminLandingPath()
}
return true
}
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (requiresAuth && !token) {
return '/'
}
if (to.path === '/' && token) {
return '/home'
}
if (requiresAuth && token) {
const userInfo = localStorage.getItem('userInfo')
if (!userInfo) {
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
sessionStorage.removeItem('accessToken')
return '/'
}
}
return true
})
export default router
@@ -1,45 +0,0 @@
spring:
application:
name: fingertip-designer-gateway
cloud:
nacos:
discovery:
# Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# Nacos 命名空间,默认指向开发环境
namespace: FingertipDesigner-Dev
# 服务注册分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# 注册到 Nacos 的服务名。
service: ${spring.application.name}
# Nacos 认证用户名。
username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
config:
# Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# Nacos 配置中心命名空间,默认指向开发环境。
namespace: FingertipDesigner-Dev
# 配置分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# Gateway 服务独有配置文件。
name: gateway
# 所有 Nacos 配置均使用 YAML。
file-extension: yaml
# Nacos 认证用户名。
username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
# Core 与 Gateway 共享的公共配置文件。
shared-configs:
- data-id: infra.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: secret.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: logging.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
@@ -1,73 +0,0 @@
package com.xiaowang.fingertipdesigner.gateway.filter;
import com.xiaowang.fingertipdesigner.gateway.config.GatewayConfig;
import com.xiaowang.fingertipdesigner.gateway.filter.AuthGlobalFilter.AuthWhitelist;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.AntPathMatcher;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class AuthGlobalFilterWhitelistTest {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@Test
void effectiveWhitelistCoversPublicCommentListAndRejectsOrderApi() {
GatewayConfig config = new GatewayConfig();
config.setWhitelist(List.of("/api/user/login"));
List<String> patterns = AuthWhitelist.effectivePatterns(config);
assertThat(matches(patterns, "/api/comment/list/product/1")).isTrue();
assertThat(matches(patterns, "/api/order/list")).isFalse();
assertThat(matches(patterns, "/api/admin/user/list")).isFalse();
}
@Test
void defaultWhitelistIncludesOnlyExpectedPublicBusinessAreas() {
assertThat(AuthWhitelist.defaultPatterns())
.contains(
"/api/user/login",
"/api/comment/list/product/**",
"/api/admin/auth/login",
"/admin/auth/login",
"/api/nail-artist/profile/**",
"/api/nail-artist/*/availability",
"/api/nail-artist/*/reviews",
"/api/shop/list"
)
.doesNotContain("/api/order/**", "/api/shop/delete/**", "/api/permission/**");
}
@Test
void directAdminLoginCompatibilityPathIsWhitelisted() {
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/login")).isTrue();
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/login-shops/1")).isTrue();
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/refresh")).isTrue();
}
@Test
void applicationRoutesDirectAdminAuthCompatibilityPath() throws Exception {
String yaml = new String(new ClassPathResource("application.yaml").getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertThat(yaml).contains("Path=/admin/auth/**");
}
@Test
void applicationRoutesManagerApiThroughAdminRoute() throws Exception {
String yaml = new String(new ClassPathResource("application.yaml").getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertThat(yaml)
.contains("Path=/api/admin/**")
.contains("RewritePath=/api/admin/(?<remaining>.*), /admin/${remaining}");
assertThat(matches(AuthWhitelist.defaultPatterns(), "/api/admin/manager/planning/calendar")).isFalse();
}
private boolean matches(List<String> patterns, String path) {
return patterns.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
}
}
-30
View File
@@ -1,30 +0,0 @@
/**
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
* Usage: keep after-sale endpoints aligned with /admin/after-sale on the backend.
*/
const request = require('../utils/request')
module.exports = {
listAfterSales(params) {
return request({
url: '/after-sale/list',
params
})
},
approveAfterSale(id, data) {
return request({
url: `/after-sale/${id}/approve`,
method: 'PUT',
data: data || {}
})
},
rejectAfterSale(id, data) {
return request({
url: `/after-sale/${id}/reject`,
method: 'PUT',
data: data || {}
})
}
}
@@ -1,22 +0,0 @@
/**
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
* Usage: keep schedule endpoints aligned with /admin/artist-schedule on the backend.
*/
const request = require('../utils/request')
module.exports = {
listSchedules(params) {
return request({
url: '/artist-schedule/list',
params
})
},
saveSchedule(data) {
return request({
url: '/artist-schedule/save',
method: 'POST',
data
})
}
}
-68
View File
@@ -1,68 +0,0 @@
/**
* Purpose: request supports auth.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: login supports auth.js by holding or executing the login page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
login(data) {
return request({
url: '/auth/login',
method: 'POST',
data
})
},
/**
* Purpose: getLoginShops supports auth.js by holding or executing the get login shops page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getLoginShops(account) {
return request({
url: `/auth/login-shops/${encodeURIComponent(account)}`
})
},
/**
* Purpose: switchShop supports auth.js by holding or executing the switch shop page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
switchShop(shopId) {
return request({
url: '/auth/switch-shop',
method: 'POST',
data: {
shopId: shopId || undefined
}
})
},
/**
* Purpose: refreshToken supports auth.js by holding or executing the refresh token page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
refreshToken(refreshToken) {
return request({
url: '/auth/refresh',
method: 'POST',
data: {
refreshToken
}
})
},
/**
* Purpose: logout supports auth.js by holding or executing the logout page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
logout() {
return request({
url: '/auth/logout',
method: 'POST'
})
}
}
-22
View File
@@ -1,22 +0,0 @@
/**
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
* Usage: keep campaign endpoints aligned with /admin/campaign on the backend.
*/
const request = require('../utils/request')
module.exports = {
listCampaigns(params) {
return request({
url: '/campaign/list',
params
})
},
saveCampaign(data) {
return request({
url: '/campaign/save',
method: 'POST',
data
})
}
}
-29
View File
@@ -1,29 +0,0 @@
/**
* Purpose: request supports comment.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listComments supports comment.js by holding or executing the list comments page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listComments(params) {
return request({
url: '/comment/list',
params
})
},
/**
* Purpose: deleteComment supports comment.js by holding or executing the delete comment page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deleteComment(id) {
return request({
url: `/comment/delete/${id}`,
method: 'DELETE'
})
}
}
-100
View File
@@ -1,100 +0,0 @@
/**
* Purpose: request supports coupon.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listCoupons supports coupon.js by holding or executing the list coupons page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listCoupons(params) {
return request({
url: '/coupon/list',
params
})
},
/**
* Purpose: listAllCoupons supports coupon.js by holding or executing the list all coupons page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listAllCoupons(shopId) {
return request({
url: '/coupon/list/all',
params: shopId ? { shopId } : undefined
})
},
/**
* Purpose: getCouponDetail supports coupon.js by holding or executing the get coupon detail page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getCouponDetail(id) {
return request({
url: `/coupon/detail/${id}`
})
},
/**
* Purpose: createCoupon supports coupon.js by holding or executing the create coupon page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
createCoupon(data) {
return request({
url: '/coupon/create',
method: 'POST',
data
})
},
/**
* Purpose: updateCoupon supports coupon.js by holding or executing the update coupon page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateCoupon(id, data) {
return request({
url: `/coupon/update/${id}`,
method: 'PUT',
data
})
},
/**
* Purpose: deleteCoupon supports coupon.js by holding or executing the delete coupon page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deleteCoupon(id) {
return request({
url: `/coupon/delete/${id}`,
method: 'DELETE'
})
},
/**
* Purpose: assignCoupon supports coupon.js by holding or executing the assign coupon page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
assignCoupon(data) {
return request({
url: '/coupon/assign',
method: 'POST',
params: data,
data: {}
})
},
/**
* Purpose: distributeCoupon supports coupon.js by holding or executing the distribute coupon page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
distributeCoupon(data) {
return request({
url: '/coupon/distribute',
method: 'POST',
params: data,
data: {}
})
}
}
-23
View File
@@ -1,23 +0,0 @@
/**
* Purpose: request supports dashboard.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: getStats supports dashboard.js by holding or executing the get stats page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getStats() {
return request({
url: '/dashboard/stats'
})
},
getAnalytics() {
return request({
url: '/dashboard/analytics'
})
}
}
-148
View File
@@ -1,148 +0,0 @@
/**
* Purpose: request supports file.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
/**
* Purpose: actionGuard supports file.js by holding or executing the action guard page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const actionGuard = require('../utils/action-guard')
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT } = require('../utils/config')
/**
* Purpose: normalizeUploadResponse supports file.js by holding or executing the normalize upload response page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeUploadResponse(response) {
if (!response) {
throw new Error('上传失败')
}
if (response.statusCode === 401) {
throw new Error('登录已过期,请重新登录')
}
if (response.statusCode >= 400) {
throw new Error('上传失败')
}
let payload = response.data
if (typeof payload === 'string') {
try {
payload = JSON.parse(payload)
} catch (error) {}
}
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
if (payload.code === 200) {
return payload.data
}
throw new Error(payload.message || '上传失败')
}
return payload
}
module.exports = {
/**
* Purpose: initChunkUpload supports file.js by holding or executing the init chunk upload page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
initChunkUpload(data) {
return request({
url: '/object-storage-file/upload/init',
method: 'POST',
data
})
},
/**
* Purpose: uploadChunkFile supports file.js by holding or executing the upload chunk file page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
uploadChunkFile(options) {
const signedHeaders = request.buildSignatureHeaders({
url: '/object-storage-file/upload/chunk',
method: 'POST',
formData: {
uploadId: String(options.uploadId),
chunkIndex: String(options.chunkIndex),
totalChunks: String(options.totalChunks)
}
})
return actionGuard.run(
null,
`POST:/object-storage-file/upload/chunk:${String(options.uploadId)}:${String(options.chunkIndex)}`,
() => new Promise((resolve, reject) => {
const task = wx.uploadFile({
url: `${ADMIN_API_BASE_URL}/object-storage-file/upload/chunk`,
filePath: options.filePath,
name: 'chunk',
timeout: REQUEST_TIMEOUT,
formData: {
uploadId: String(options.uploadId),
chunkIndex: String(options.chunkIndex),
totalChunks: String(options.totalChunks)
},
header: signedHeaders,
success: response => {
try {
resolve(normalizeUploadResponse(response))
} catch (error) {
reject(error)
}
},
fail: error => {
reject(new Error(error.errMsg || '上传分片失败'))
}
})
if (task && typeof task.onProgressUpdate === 'function' && typeof options.onProgress === 'function') {
task.onProgressUpdate(progress => {
options.onProgress(progress)
})
}
}),
{
message: '上传处理中,请勿重复操作'
}
)
},
/**
* Purpose: completeChunkUpload supports file.js by holding or executing the complete chunk upload page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
completeChunkUpload(uploadId) {
return request({
url: '/object-storage-file/upload/complete',
method: 'POST',
data: {
uploadId
}
})
},
/**
* Purpose: cancelChunkUpload supports file.js by holding or executing the cancel chunk upload page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
cancelChunkUpload(uploadId) {
return request({
url: `/object-storage-file/upload/${uploadId}`,
method: 'DELETE'
})
},
/**
* Purpose: getSignedUrl supports file.js by holding or executing the get signed url page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getSignedUrl(fileId) {
return request({
url: `/object-storage-file/get-signed-url/${fileId}`
})
}
}
-30
View File
@@ -1,30 +0,0 @@
/**
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
* Usage: keep inventory endpoints aligned with /admin/inventory on the backend.
*/
const request = require('../utils/request')
module.exports = {
listItems(params) {
return request({
url: '/inventory/list',
params
})
},
saveItem(data) {
return request({
url: '/inventory/save',
method: 'POST',
data
})
},
adjustStock(id, data) {
return request({
url: `/inventory/${id}/adjust`,
method: 'POST',
data
})
}
}
@@ -1,39 +0,0 @@
/**
* Purpose: request supports nail-artist.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listNailArtists supports nail-artist.js by holding or executing the list nail artists page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listNailArtists() {
return request({
url: '/nail-artist/list'
})
},
/**
* Purpose: getNailArtistInfo supports nail-artist.js by holding or executing the get nail artist info page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getNailArtistInfo(userId) {
return request({
url: `/nail-artist/get/${userId}`
})
},
/**
* Purpose: saveNailArtistInfo supports nail-artist.js by holding or executing the save nail artist info page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
saveNailArtistInfo(data) {
return request({
url: '/nail-artist/save',
method: 'POST',
data
})
}
}
-88
View File
@@ -1,88 +0,0 @@
/**
* Purpose: request supports order.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listOrders supports order.js by holding or executing the list orders page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listOrders(params) {
return request({
url: '/order/list',
params
})
},
/**
* Purpose: getOrderDetail loads an authoritative admin-scoped order detail row.
* Usage: call with the order id when opening the order detail page so direct page entry works.
*/
getOrderDetail(id) {
return request({
url: `/order/detail/${id}`
})
},
/**
* Purpose: listOrderReviews supports order.js by holding or executing the list order reviews page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listOrderReviews(orderId) {
return request({
url: `/order/${orderId}/reviews`
})
},
/**
* Purpose: getArtistChangeOptions supports order.js by holding or executing the get artist change options page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getArtistChangeOptions(orderId, orderItemId) {
return request({
url: `/order/${orderId}/artist-change/options`,
params: {
orderItemId
}
})
},
/**
* Purpose: requestArtistChange supports order.js by holding or executing the request artist change page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
requestArtistChange(data) {
return request({
url: '/order/artist-change/request',
method: 'POST',
data
})
},
/**
* Purpose: listMyPendingArtistChangeRequests supports order.js by holding or executing the list my pending artist change requests page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listMyPendingArtistChangeRequests() {
return request({
url: '/order/artist-change/my-pending'
})
},
/**
* Purpose: updateOrderStatus supports order.js by holding or executing the update order status page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateOrderStatus(id, status) {
return request({
url: `/order/update-status/${id}`,
method: 'PUT',
params: {
status
},
data: {}
})
}
}
-18
View File
@@ -1,18 +0,0 @@
/**
* Purpose: request sends authenticated admin mini-program calls through the shared request wrapper.
* Usage: call manual payment operations only after UI permission checks; backend remains authoritative.
*/
const request = require('../utils/request')
module.exports = {
manualConfirmOrder(orderId, remark) {
return request({
url: `/payment/order/${orderId}/manual-confirm`,
method: 'POST',
params: {
remark
},
data: {}
})
}
}
-96
View File
@@ -1,96 +0,0 @@
/**
* Purpose: request supports permission.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: getCurrentUserPermissions supports permission.js by holding or executing the get current user permissions page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getCurrentUserPermissions() {
return request({
url: '/permission/user/current'
})
},
/**
* Purpose: getUserPermissions supports permission.js by holding or executing the get user permissions page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getUserPermissions(userId) {
return request({
url: `/permission/user/${userId}`
})
},
/**
* Purpose: getAssignablePermissionIds supports permission.js by holding or executing the get assignable permission ids page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getAssignablePermissionIds(userId) {
return request({
url: `/permission/assignable/${userId}`
})
},
/**
* Purpose: listAllPermissions supports permission.js by holding or executing the list all permissions page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listAllPermissions() {
return request({
url: '/permission/list/all'
})
},
/**
* Purpose: createPermission supports permission.js by holding or executing the create permission page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
createPermission(data) {
return request({
url: '/permission/create',
method: 'POST',
data
})
},
/**
* Purpose: updatePermission supports permission.js by holding or executing the update permission page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updatePermission(id, data) {
return request({
url: `/permission/update/${id}`,
method: 'PUT',
data
})
},
/**
* Purpose: deletePermission supports permission.js by holding or executing the delete permission page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deletePermission(id) {
return request({
url: `/permission/delete/${id}`,
method: 'DELETE'
})
},
/**
* Purpose: assignUserPermissions supports permission.js by holding or executing the assign user permissions page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
assignUserPermissions(userId, permissionIds) {
return request({
url: `/permission/assign/${userId}`,
method: 'POST',
data: {
permissionIds
}
})
}
}
-63
View File
@@ -1,63 +0,0 @@
/**
* Purpose: request supports product.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listProducts supports product.js by holding or executing the list products page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listProducts(params) {
return request({
url: '/product/list',
params
})
},
/**
* Purpose: listAllProducts supports product.js by holding or executing the list all products page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listAllProducts() {
return request({
url: '/product/list/all'
})
},
/**
* Purpose: createProduct supports product.js by holding or executing the create product page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
createProduct(data) {
return request({
url: '/product/create',
method: 'POST',
data
})
},
/**
* Purpose: updateProduct supports product.js by holding or executing the update product page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateProduct(id, data) {
return request({
url: `/product/update/${id}`,
method: 'PUT',
data
})
},
/**
* Purpose: deleteProduct supports product.js by holding or executing the delete product page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deleteProduct(id) {
return request({
url: `/product/delete/${id}`,
method: 'DELETE'
})
}
}
@@ -1,18 +0,0 @@
/**
* Purpose: request sends signed admin mini-program requests to the backend audit API.
* Usage: require this module from the audit page and call `listLogs` with filter params.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listLogs loads read-only security audit log rows for authorized administrators.
* Usage: pass account, action, result, time range, page, and size filters, then render the returned page result.
*/
listLogs(params) {
return request({
url: '/security-audit/logs',
params
})
}
}
-87
View File
@@ -1,87 +0,0 @@
/**
* Purpose: request supports shop.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listShops supports shop.js by holding or executing the list shops page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listShops(params) {
return request({
url: '/shops/list',
params
})
},
/**
* Purpose: listAllShops supports shop.js by holding or executing the list all shops page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listAllShops() {
return request({
url: '/shops/list/all'
})
},
/**
* Purpose: getShop supports shop.js by holding or executing the get shop page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getShop(id) {
return request({
url: `/shops/${id}`
})
},
/**
* Purpose: createShop supports shop.js by holding or executing the create shop page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
createShop(data) {
return request({
url: '/shops/create',
method: 'POST',
data
})
},
/**
* Purpose: updateShop supports shop.js by holding or executing the update shop page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateShop(id, data) {
return request({
url: `/shops/update/${id}`,
method: 'PUT',
data
})
},
/**
* Purpose: updateShopStatus supports shop.js by holding or executing the update shop status page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateShopStatus(id, status) {
return request({
url: `/shops/status/${id}`,
method: 'PUT',
data: {
status
}
})
},
/**
* Purpose: deleteShop supports shop.js by holding or executing the delete shop page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deleteShop(id) {
return request({
url: `/shops/delete/${id}`,
method: 'DELETE'
})
}
}
@@ -1,51 +0,0 @@
/**
* Purpose: request sends signed admin mini-program calls to the backend system-message endpoints.
* Usage: keep all system-message API wrappers in this module so pages do not build URLs by hand.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listMessages loads admin-visible system messages including popup and business navigation metadata.
* Usage: call it from the system-message management page during initial load or refresh.
*/
listMessages() {
return request({
url: '/system-message/admin/list'
})
},
/**
* Purpose: createMessage publishes a new system message to the selected target users.
* Usage: pass validated form data with targetType, popupEnabled, and optional business fields.
*/
createMessage(data) {
return request({
url: '/system-message/admin/create',
method: 'POST',
data
})
},
/**
* Purpose: revokeMessage withdraws a previously published message when the operator has delete permission.
* Usage: call it with the message id after an explicit confirmation dialog.
*/
revokeMessage(id) {
return request({
url: `/system-message/admin/${id}/revoke`,
method: 'PUT',
data: {}
})
},
/**
* Purpose: getTargetOptions loads shops and users that the current operator may target.
* Usage: call it before showing the publish form so picker data is permission-scoped.
*/
getTargetOptions() {
return request({
url: '/system-message/admin/target-options'
})
}
}
-72
View File
@@ -1,72 +0,0 @@
/**
* Purpose: request supports tag.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listAllTags supports tag.js by holding or executing the list all tags page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listAllTags() {
return request({
url: '/tag/list/all'
})
},
/**
* Purpose: listTagsByShopId supports tag.js by holding or executing the list tags by shop id page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listTagsByShopId(shopId) {
return request({
url: `/tag/list/by-shop/${shopId}`
})
},
/**
* Purpose: getTagById supports tag.js by holding or executing the get tag by id page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getTagById(id) {
return request({
url: `/tag/get/${id}`
})
},
/**
* Purpose: createTag supports tag.js by holding or executing the create tag page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
createTag(data) {
return request({
url: '/tag/create',
method: 'POST',
data
})
},
/**
* Purpose: updateTag supports tag.js by holding or executing the update tag page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateTag(id, data) {
return request({
url: `/tag/update/${id}`,
method: 'PUT',
data
})
},
/**
* Purpose: deleteTag supports tag.js by holding or executing the delete tag page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deleteTag(id) {
return request({
url: `/tag/delete/${id}`,
method: 'DELETE'
})
}
}
-176
View File
@@ -1,176 +0,0 @@
/**
* Purpose: request supports user.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const request = require('../utils/request')
module.exports = {
/**
* Purpose: listUsers supports user.js by holding or executing the list users page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listUsers(params) {
return request({
url: '/user/list',
params
})
},
/**
* Purpose: listAllUsers supports user.js by holding or executing the list all users page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listAllUsers() {
return request({
url: '/user/list/all'
})
},
/**
* Purpose: listArtists supports user.js by holding or executing the list artists page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
listArtists(shopId) {
return request({
url: '/user/list/artists',
params: shopId ? { shopId } : undefined
})
},
/**
* Purpose: createUser supports user.js by holding or executing the create user page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
createUser(data) {
return request({
url: '/user/create',
method: 'POST',
data
})
},
/**
* Purpose: updateUser supports user.js by holding or executing the update user page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateUser(id, data) {
return request({
url: `/user/update/${id}`,
method: 'PUT',
data
})
},
/**
* Purpose: updateUserStatus supports user.js by holding or executing the update user status page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
updateUserStatus(id, status) {
return request({
url: `/user/status/${id}`,
method: 'PUT',
data: {
status
}
})
},
/**
* Purpose: deleteUser supports user.js by holding or executing the delete user page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
deleteUser(id) {
return request({
url: `/user/delete/${id}`,
method: 'DELETE'
})
},
/**
* Purpose: unbindUser supports user.js by holding or executing the unbind user page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
unbindUser(id) {
return request({
url: `/user/unbind/${id}`,
method: 'PUT',
data: {}
})
},
/**
* Purpose: resetPassword supports user.js by holding or executing the reset password page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
resetPassword(id) {
return request({
url: `/user/reset-password/${id}`,
method: 'POST'
})
},
/**
* Purpose: getCurrentUserInfo supports user.js by holding or executing the get current user info page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getCurrentUserInfo() {
return request({
url: '/user/info'
})
},
/**
* Purpose: getUserAsset supports user.js by holding or executing the get user asset page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getUserAsset(id) {
return request({
url: `/user/${id}/asset`
})
},
/**
* Purpose: getUserBalanceHistory supports user.js by holding or executing the get user balance history page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
getUserBalanceHistory(id) {
return request({
url: `/user/${id}/balance/history`
})
},
/**
* Purpose: changeUserBalance supports user.js by holding or executing the change user balance page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
changeUserBalance(id, data) {
return request({
url: `/user/${id}/balance/change`,
method: 'POST',
data
})
},
/**
* Purpose: overrideUserVip supports user.js by holding or executing the override user vip page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
overrideUserVip(id, data) {
return request({
url: `/user/${id}/vip/override`,
method: 'POST',
data
})
},
/**
* Purpose: recalculateUserVip supports user.js by holding or executing the recalculate user vip page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
recalculateUserVip(id) {
return request({
url: `/user/${id}/vip/recalculate`,
method: 'POST'
})
}
}
-508
View File
@@ -1,508 +0,0 @@
page {
min-height: 100%;
background:
radial-gradient(circle at top left, rgba(240, 126, 87, 0.18), transparent 30%),
linear-gradient(180deg, #071417 0%, #0d2225 30%, #f5f0e8 30%, #f5f0e8 100%);
color: #132024;
font-size: 28rpx;
}
view,
text,
button,
input,
textarea,
scroll-view,
swiper,
swiper-item,
picker,
label,
image,
checkbox,
checkbox-group {
box-sizing: border-box;
}
image {
display: block;
}
button {
margin: 0;
padding: 0;
line-height: 1;
background: transparent;
}
button::after {
border: 0;
}
.page-shell {
min-height: 100vh;
padding-bottom: calc(env(safe-area-inset-bottom) + 36rpx);
}
.page-stack {
padding: 24rpx;
}
.hero-panel {
padding: 34rpx 30rpx;
border-radius: 36rpx;
background: linear-gradient(140deg, rgba(8, 21, 24, 0.96) 0%, rgba(20, 51, 52, 0.96) 100%);
color: #f6efe7;
box-shadow: 0 26rpx 64rpx rgba(7, 20, 23, 0.28);
}
.hero-kicker {
display: block;
font-size: 22rpx;
font-weight: 700;
letter-spacing: 3rpx;
color: #f7b296;
}
.hero-title {
display: block;
margin-top: 16rpx;
font-size: 48rpx;
line-height: 1.2;
font-weight: 800;
}
.hero-desc {
display: block;
margin-top: 16rpx;
font-size: 24rpx;
line-height: 1.8;
color: rgba(246, 239, 231, 0.78);
}
.surface-card {
margin-top: 24rpx;
padding: 28rpx;
border-radius: 30rpx;
background: rgba(255, 252, 247, 0.96);
border: 1rpx solid rgba(19, 32, 36, 0.08);
box-shadow: 0 18rpx 44rpx rgba(26, 39, 42, 0.08);
}
.section-title {
display: block;
font-size: 34rpx;
font-weight: 800;
color: #132024;
}
.section-desc {
display: block;
margin-top: 10rpx;
font-size: 24rpx;
line-height: 1.7;
color: #60706d;
}
.field-group {
margin-top: 24rpx;
}
.field-label {
display: block;
margin-bottom: 12rpx;
font-size: 24rpx;
font-weight: 700;
color: #294248;
}
.field-input,
.field-picker,
.field-textarea {
width: 100%;
min-height: 92rpx;
padding: 0 24rpx;
border-radius: 24rpx;
background: #eef1ea;
border: 1rpx solid rgba(19, 32, 36, 0.08);
color: #132024;
font-size: 28rpx;
}
.field-picker {
display: flex;
align-items: center;
}
.field-textarea {
min-height: 200rpx;
padding: 24rpx;
}
.placeholder {
color: #9eaaa5;
}
.status-text {
display: block;
margin-top: 10rpx;
font-size: 22rpx;
line-height: 1.6;
}
.status-text.success {
color: #2d8d60;
}
.status-text.error {
color: #be4f3b;
}
.status-text.warning {
color: #a66817;
}
.primary-btn,
.secondary-btn,
.danger-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 88rpx;
padding: 0 28rpx;
border-radius: 999rpx;
font-size: 28rpx;
font-weight: 700;
}
.primary-btn {
background: linear-gradient(135deg, #f8a37c 0%, #f07e57 100%);
color: #fffaf4;
}
.secondary-btn {
background: rgba(8, 21, 24, 0.04);
color: #173036;
border: 1rpx solid rgba(8, 21, 24, 0.1);
}
.danger-btn {
background: rgba(190, 79, 59, 0.12);
color: #b94432;
}
.action-row {
display: flex;
gap: 16rpx;
margin-top: 24rpx;
}
.action-row .primary-btn,
.action-row .secondary-btn,
.action-row .danger-btn {
flex: 1;
}
.badge-row {
display: flex;
flex-wrap: wrap;
gap: 12rpx;
margin-top: 18rpx;
}
.badge,
.soft-badge,
.danger-badge,
.success-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 48rpx;
padding: 0 18rpx;
border-radius: 999rpx;
font-size: 22rpx;
font-weight: 700;
}
.badge {
background: rgba(240, 126, 87, 0.14);
color: #d05f3d;
}
.soft-badge {
background: rgba(8, 21, 24, 0.06);
color: #50625f;
}
.danger-badge {
background: rgba(190, 79, 59, 0.12);
color: #b94432;
}
.success-badge {
background: rgba(45, 141, 96, 0.12);
color: #2d8d60;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16rpx;
margin-top: 22rpx;
}
.stat-card {
padding: 24rpx;
border-radius: 24rpx;
background: rgba(8, 21, 24, 0.04);
}
.stat-label {
display: block;
font-size: 22rpx;
color: #667774;
}
.stat-value {
display: block;
margin-top: 10rpx;
font-size: 34rpx;
font-weight: 800;
color: #132024;
}
.stat-note {
display: block;
margin-top: 8rpx;
font-size: 22rpx;
color: #7b8a87;
}
.list-card {
margin-top: 18rpx;
padding: 24rpx;
border-radius: 26rpx;
background: #ffffff;
border: 1rpx solid rgba(19, 32, 36, 0.08);
}
.list-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16rpx;
}
.list-title {
display: block;
font-size: 30rpx;
line-height: 1.5;
font-weight: 800;
color: #132024;
}
.list-subtitle {
display: block;
margin-top: 8rpx;
font-size: 22rpx;
color: #768582;
}
.meta-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12rpx 20rpx;
margin-top: 22rpx;
}
.meta-item {
min-width: 0;
}
.meta-label {
display: block;
font-size: 21rpx;
color: #82918e;
}
.meta-value {
display: block;
margin-top: 6rpx;
font-size: 25rpx;
color: #1b3035;
word-break: break-all;
}
.list-actions {
display: flex;
flex-wrap: wrap;
gap: 12rpx;
margin-top: 22rpx;
}
.admin-bottom-nav {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10rpx;
margin-top: 24rpx;
padding: 12rpx;
border-radius: 28rpx;
background: rgba(8, 21, 24, 0.08);
}
.admin-bottom-link {
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
min-height: 68rpx;
border-radius: 999rpx;
color: #50625f;
font-size: 24rpx;
font-weight: 700;
}
.admin-bottom-link.active {
background: rgba(240, 126, 87, 0.18);
color: #c85b39;
}
.mini-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 132rpx;
min-height: 62rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: rgba(8, 21, 24, 0.05);
color: #173036;
font-size: 24rpx;
font-weight: 700;
}
.mini-btn.primary {
background: rgba(240, 126, 87, 0.14);
color: #cf5e3c;
}
.mini-btn.danger {
background: rgba(190, 79, 59, 0.12);
color: #b94432;
}
.search-row,
.filter-row {
display: flex;
gap: 14rpx;
margin-top: 18rpx;
}
.search-input {
flex: 1;
}
.chip-row,
.checkbox-grid {
display: flex;
flex-wrap: wrap;
gap: 12rpx;
margin-top: 18rpx;
}
.chip-btn,
.checkbox-chip {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 60rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: rgba(8, 21, 24, 0.05);
color: #4d625f;
font-size: 24rpx;
font-weight: 700;
}
.chip-btn.active,
.checkbox-chip.active {
background: rgba(240, 126, 87, 0.16);
color: #c85b39;
}
.checkbox-chip.disabled {
opacity: 0.45;
}
.empty-state {
margin-top: 24rpx;
padding: 72rpx 36rpx;
border-radius: 30rpx;
background: rgba(255, 252, 247, 0.8);
text-align: center;
}
.empty-title {
display: block;
font-size: 34rpx;
font-weight: 800;
color: #132024;
}
.empty-desc {
display: block;
margin-top: 14rpx;
font-size: 24rpx;
line-height: 1.8;
color: #758582;
}
.fab {
position: fixed;
right: 28rpx;
bottom: calc(env(safe-area-inset-bottom) + 128rpx);
display: flex;
align-items: center;
justify-content: center;
width: 112rpx;
height: 112rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #f8a37c 0%, #f07e57 100%);
color: #fffaf4;
box-shadow: 0 22rpx 50rpx rgba(240, 126, 87, 0.3);
font-size: 38rpx;
font-weight: 800;
}
.hint-card {
margin-top: 18rpx;
padding: 20rpx 22rpx;
border-radius: 24rpx;
background: rgba(240, 126, 87, 0.12);
color: #8f4d33;
font-size: 24rpx;
line-height: 1.75;
}
.divider-line {
width: 100%;
height: 2rpx;
margin: 18rpx 0;
background: rgba(19, 32, 36, 0.08);
}
.image-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14rpx;
margin-top: 18rpx;
}
.image-chip {
padding: 18rpx 14rpx;
border-radius: 24rpx;
background: rgba(8, 21, 24, 0.04);
font-size: 22rpx;
color: #50625f;
line-height: 1.6;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 688 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 585 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 979 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 950 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 780 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 793 B

@@ -1,147 +0,0 @@
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
/**
* 组件的属性列表
*/
properties: {
extClass: {
type: String,
value: ''
},
title: {
type: String,
value: ''
},
background: {
type: String,
value: ''
},
color: {
type: String,
value: ''
},
back: {
type: Boolean,
value: true
},
loading: {
type: Boolean,
value: false
},
homeButton: {
type: Boolean,
value: false,
},
animated: {
// 显示隐藏的时候opacity动画效果
type: Boolean,
value: true
},
show: {
// 显示隐藏导航,隐藏的时候navigation-bar的高度占位还在
type: Boolean,
value: true,
observer: '_showChange'
},
// back为true的时候,返回的页面深度
delta: {
type: Number,
value: 1
},
},
/**
* 组件的初始数据
*/
data: {
/**
* Purpose: displayStyle supports navigation-bar.js by holding or executing the display style page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
displayStyle: ''
},
/**
* Purpose: lifetimes supports navigation-bar.js by holding or executing the lifetimes page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
lifetimes: {
attached() {
const rect = wx.getMenuButtonBoundingClientRect()
const platform = (wx.getDeviceInfo() || wx.getSystemInfoSync()).platform
const isAndroid = platform === 'android'
const isDevtools = platform === 'devtools'
const { windowWidth, safeArea: { top = 0, bottom = 0 } = {} } = wx.getWindowInfo() || wx.getSystemInfoSync()
this.setData({
/**
* Purpose: ios supports navigation-bar.js by holding or executing the ios page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
ios: !isAndroid,
/**
* Purpose: innerPaddingRight supports navigation-bar.js by holding or executing the inner padding right page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
innerPaddingRight: `padding-right: ${windowWidth - rect.left}px`,
/**
* Purpose: leftWidth supports navigation-bar.js by holding or executing the left width page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
leftWidth: `width: ${windowWidth - rect.left}px`,
/**
* Purpose: safeAreaTop supports navigation-bar.js by holding or executing the safe area top page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
safeAreaTop: isDevtools || isAndroid ? `height: calc(var(--height) + ${top}px); padding-top: ${top}px` : ``
})
},
},
/**
* 组件的方法列表
*/
methods: {
_showChange(show) {
const animated = this.data.animated
let displayStyle = ''
if (animated) {
displayStyle = `opacity: ${show ? '1' : '0'
};transition:opacity 0.5s;`
} else {
displayStyle = `display: ${show ? '' : 'none'}`
}
this.setData({
displayStyle
})
},
back() {
const data = this.data
const pages = getCurrentPages()
if (data.delta && pages.length > data.delta) {
wx.navigateBack({
/**
* Purpose: delta supports navigation-bar.js by holding or executing the delta page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
delta: data.delta
})
return
}
this.triggerEvent('back', { delta: data.delta }, {})
},
home() {
wx.redirectTo({
/**
* Purpose: url supports navigation-bar.js by holding or executing the url page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
url: '/admin/pages/workbench/index',
fail() {
wx.reLaunch({
url: '/admin/pages/workbench/index'
})
}
})
this.triggerEvent('home', {}, {})
}
},
})
@@ -1,64 +0,0 @@
<view class="weui-navigation-bar {{extClass}}">
<view class="weui-navigation-bar__inner {{ios ? 'ios' : 'android'}}" style="color: {{color}}; background: {{background}}; {{displayStyle}}; {{innerPaddingRight}}; {{safeAreaTop}};">
<!-- 左侧按钮 -->
<view class='weui-navigation-bar__left' style="{{leftWidth}};">
<block wx:if="{{back || homeButton}}">
<!-- 返回上一页 -->
<block wx:if="{{back}}">
<view class="weui-navigation-bar__buttons weui-navigation-bar__buttons_goback">
<view
bindtap="back"
class="weui-navigation-bar__btn_goback_wrapper"
hover-class="weui-active"
hover-stay-time="100"
aria-role="button"
aria-label="返回"
>
<view class="weui-navigation-bar__button weui-navigation-bar__btn_goback"></view>
</view>
</view>
</block>
<!-- 返回首页 -->
<block wx:if="{{homeButton}}">
<view class="weui-navigation-bar__buttons weui-navigation-bar__buttons_home">
<view
bindtap="home"
class="weui-navigation-bar__btn_home_wrapper"
hover-class="weui-active"
aria-role="button"
aria-label="首页"
>
<view class="weui-navigation-bar__button weui-navigation-bar__btn_home"></view>
</view>
</view>
</block>
</block>
<block wx:else>
<slot name="left"></slot>
</block>
</view>
<!-- 标题 -->
<view class='weui-navigation-bar__center'>
<view wx:if="{{loading}}" class="weui-navigation-bar__loading" aria-role="alert">
<view
class="weui-loading"
aria-role="img"
aria-label="加载中"
></view>
</view>
<block wx:if="{{title}}">
<text>{{title}}</text>
</block>
<block wx:else>
<slot name="center"></slot>
</block>
</view>
<!-- 右侧留空 -->
<view class='weui-navigation-bar__right'>
<slot name="right"></slot>
</view>
</view>
</view>
@@ -1,99 +0,0 @@
.weui-navigation-bar {
--weui-FG-0:rgba(0,0,0,.9);
--height: 44px;
--left: 16px;
}
.weui-navigation-bar .android {
--height: 48px;
}
.weui-navigation-bar {
overflow: hidden;
color: var(--weui-FG-0);
flex: none;
position: relative;
z-index: 20;
}
.weui-navigation-bar__inner {
position: relative;
top: 0;
left: 0;
z-index: 1;
height: calc(var(--height) + env(safe-area-inset-top));
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding-top: env(safe-area-inset-top);
width: 100%;
box-sizing: border-box;
}
.weui-navigation-bar__left {
position: relative;
padding-left: var(--left);
display: flex;
flex-direction: row;
align-items: flex-start;
height: 100%;
box-sizing: border-box;
}
.weui-navigation-bar__btn_goback_wrapper {
padding: 11px 18px 11px 16px;
margin: -11px -18px -11px -16px;
}
.weui-navigation-bar__btn_goback_wrapper.weui-active {
opacity: 0.5;
}
.weui-navigation-bar__btn_goback {
font-size: 12px;
width: 12px;
height: 24px;
-webkit-mask: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='24' viewBox='0 0 12 24'%3E %3Cpath fill-opacity='.9' fill-rule='evenodd' d='M10 19.438L8.955 20.5l-7.666-7.79a1.02 1.02 0 0 1 0-1.42L8.955 3.5 10 4.563 2.682 12 10 19.438z'/%3E%3C/svg%3E") no-repeat 50% 50%;
mask: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='24' viewBox='0 0 12 24'%3E %3Cpath fill-opacity='.9' fill-rule='evenodd' d='M10 19.438L8.955 20.5l-7.666-7.79a1.02 1.02 0 0 1 0-1.42L8.955 3.5 10 4.563 2.682 12 10 19.438z'/%3E%3C/svg%3E") no-repeat 50% 50%;
-webkit-mask-size: cover;
mask-size: cover;
background-color: currentColor;
}
.weui-navigation-bar__center {
font-size: 17px;
text-align: center;
position: relative;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
font-weight: bold;
flex: 1;
height: 100%;
}
.weui-navigation-bar__loading {
margin-right: 4px;
align-items: center;
}
.weui-loading {
font-size: 16px;
width: 16px;
height: 16px;
display: block;
background: transparent url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg width='80px' height='80px' viewBox='0 0 80 80' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E%3Ctitle%3Eloading%3C/title%3E%3Cdefs%3E%3ClinearGradient x1='94.0869141%25' y1='0%25' x2='94.0869141%25' y2='90.559082%25' id='linearGradient-1'%3E%3Cstop stop-color='%23606060' stop-opacity='0' offset='0%25'%3E%3C/stop%3E%3Cstop stop-color='%23606060' stop-opacity='0.3' offset='100%25'%3E%3C/stop%3E%3C/linearGradient%3E%3ClinearGradient x1='100%25' y1='8.67370605%25' x2='100%25' y2='90.6286621%25' id='linearGradient-2'%3E%3Cstop stop-color='%23606060' offset='0%25'%3E%3C/stop%3E%3Cstop stop-color='%23606060' stop-opacity='0.3' offset='100%25'%3E%3C/stop%3E%3C/linearGradient%3E%3C/defs%3E%3Cg stroke='none' stroke-width='1' fill='none' fill-rule='evenodd' opacity='0.9'%3E%3Cg%3E%3Cpath d='M40,0 C62.09139,0 80,17.90861 80,40 C80,62.09139 62.09139,80 40,80 L40,73 C58.2253967,73 73,58.2253967 73,40 C73,21.7746033 58.2253967,7 40,7 L40,0 Z' fill='url(%23linearGradient-1)'%3E%3C/path%3E%3Cpath d='M40,0 L40,7 C21.7746033,7 7,21.7746033 7,40 C7,58.2253967 21.7746033,73 40,73 L40,80 C17.90861,80 0,62.09139 0,40 C0,17.90861 17.90861,0 40,0 Z' fill='url(%23linearGradient-2)'%3E%3C/path%3E%3Ccircle id='Oval' fill='%23606060' cx='40.5' cy='3.5' r='3.5'%3E%3C/circle%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A") no-repeat;
background-size: 100%;
margin-left: 0;
animation: loading linear infinite 1s;
}
@keyframes loading {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
@@ -1,166 +0,0 @@
const afterSaleApi = require('../../api/after-sale')
const navigation = require('../../utils/navigation')
const permission = require('../../utils/permission')
const format = require('../../utils/format')
const { markDirty } = require('../../utils/page-state')
const STATUS_OPTIONS = [
{ label: '全部', value: '' },
{ label: '待处理', value: 'PENDING' },
{ label: '已同意', value: 'APPROVED' },
{ label: '已驳回', value: 'REJECTED' }
]
function safeList(response) {
if (Array.isArray(response && response.list)) {
return response.list
}
if (Array.isArray(response && response.records)) {
return response.records
}
return []
}
function statusText(status) {
if (status === 'PENDING') {
return '待处理'
}
if (status === 'APPROVED') {
return '已同意'
}
if (status === 'REJECTED') {
return '已驳回'
}
return status || '--'
}
Page({
data: {
loading: false,
list: [],
total: 0,
status: 'PENDING',
statusOptions: STATUS_OPTIONS,
canAudit: false
},
onShow() {
if (!navigation.ensureLogin('进入售后处理')) {
return
}
const permissionCodes = getApp().globalData.permissionCodes || []
this.setData({
canAudit: permission.hasPermission(permissionCodes, 'after_sale:audit')
})
this.loadAfterSales()
},
onPullDownRefresh() {
this.loadAfterSales().finally(() => {
wx.stopPullDownRefresh()
})
},
async loadAfterSales() {
this.setData({ loading: true })
try {
const response = await afterSaleApi.listAfterSales({
page: 1,
size: 20,
status: this.data.status || undefined
})
this.setData({
list: safeList(response).map(item => this.formatAfterSale(item)),
total: Number(response && response.total) || 0
})
} catch (error) {
wx.showToast({
title: error.message || '售后加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
}
},
formatAfterSale(item) {
return {
...item,
displayCreateTime: format.formatDateTime(item.createTime),
displayAuditTime: format.formatDateTime(item.auditTime),
displayRefundAmount: format.formatPrice(item.refundAmount),
statusText: statusText(item.status)
}
},
handleStatusChange(event) {
this.setData({
status: event.currentTarget.dataset.status || ''
})
this.loadAfterSales()
},
promptReason(title) {
return new Promise(resolve => {
wx.showModal({
title,
content: '可填写处理说明,留空也可以提交。',
editable: true,
placeholderText: '处理说明',
confirmText: '提交',
success: result => {
if (!result.confirm) {
resolve(null)
return
}
resolve(String(result.content || '').trim())
},
fail: () => resolve(null)
})
})
},
async handleAudit(event) {
if (!this.data.canAudit) {
wx.showToast({
title: '当前账号没有处理售后权限',
icon: 'none'
})
return
}
const id = event.currentTarget.dataset.id
const action = event.currentTarget.dataset.action
if (!id || !action) {
return
}
const reason = await this.promptReason(action === 'approve' ? '同意售后' : '驳回售后')
if (reason === null) {
return
}
try {
const data = {
auditReason: reason
}
if (action === 'approve') {
await afterSaleApi.approveAfterSale(id, data)
} else {
await afterSaleApi.rejectAfterSale(id, data)
}
markDirty('admin-workbench')
wx.showToast({
title: '售后已处理',
icon: 'none'
})
this.loadAfterSales()
} catch (error) {
wx.showToast({
title: error.message || '售后处理失败',
icon: 'none'
})
}
},
handleBack() {
navigation.goBack('/pages/manage/index')
}
})
@@ -1,6 +0,0 @@
{
"usingComponents": {
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
},
"enablePullDownRefresh": true
}
@@ -1,62 +0,0 @@
<navigation-bar title="售后处理" back="{{true}}" bindback="handleBack" color="#f6efe7" background="#081518"></navigation-bar>
<view class="page-shell">
<view class="page-stack">
<view class="hero-panel">
<text class="hero-kicker">After Sale</text>
<text class="hero-title">售后处理</text>
<text class="hero-desc">查看待处理退款/售后申请,在手机端完成同意或驳回的最小闭环。</text>
</view>
<view class="surface-card">
<text class="section-title">状态筛选</text>
<view class="chip-row">
<block wx:for="{{statusOptions}}" wx:key="value">
<view class="chip-btn {{status === item.value ? 'active' : ''}}" data-status="{{item.value}}" bindtap="handleStatusChange">{{item.label}}</view>
</block>
</view>
<text class="section-desc">共 {{total}} 条记录</text>
</view>
<block wx:for="{{list}}" wx:key="id">
<view class="list-card">
<view class="list-head">
<view>
<text class="list-title">{{item.afterSaleNo || ('售后 #' + item.id)}}</text>
<text class="list-subtitle">订单 {{item.orderId || '--'}} · {{item.displayCreateTime || '--'}}</text>
</view>
<text class="{{item.status === 'PENDING' ? 'badge' : 'soft-badge'}}">{{item.statusText}}</text>
</view>
<view class="meta-grid">
<view class="meta-item">
<text class="meta-label">类型</text>
<text class="meta-value">{{item.type || '--'}}</text>
</view>
<view class="meta-item">
<text class="meta-label">退款金额</text>
<text class="meta-value">¥{{item.displayRefundAmount}}</text>
</view>
<view class="meta-item">
<text class="meta-label">用户 ID</text>
<text class="meta-value">{{item.userId || '--'}}</text>
</view>
<view class="meta-item">
<text class="meta-label">审核时间</text>
<text class="meta-value">{{item.displayAuditTime || '--'}}</text>
</view>
</view>
<view wx:if="{{item.reason}}" class="hint-card">{{item.reason}}</view>
<view wx:if="{{item.auditReason}}" class="hint-card">处理说明:{{item.auditReason}}</view>
<view wx:if="{{item.status === 'PENDING'}}" class="list-actions">
<view class="mini-btn primary" data-id="{{item.id}}" data-action="approve" bindtap="handleAudit">同意</view>
<view class="mini-btn danger" data-id="{{item.id}}" data-action="reject" bindtap="handleAudit">驳回</view>
</view>
</view>
</block>
<view wx:if="{{!list.length && !loading}}" class="empty-state">
<text class="empty-title">暂无售后单</text>
<text class="empty-desc">当前状态下没有需要展示的售后记录。</text>
</view>
</view>
</view>
@@ -1,4 +0,0 @@
@import "../../app.wxss";
.page-shell {
background: transparent;
}
@@ -1,728 +0,0 @@
/**
* Purpose: artistApi supports index.js by holding or executing the artist api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const artistApi = require('../../api/nail-artist')
/**
* Purpose: userApi supports index.js by holding or executing the user api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const userApi = require('../../api/user')
/**
* Purpose: tagApi supports index.js by holding or executing the tag api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const tagApi = require('../../api/tag')
/**
* Purpose: productApi supports index.js by holding or executing the product api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const productApi = require('../../api/product')
/**
* Purpose: shopApi supports index.js by holding or executing the shop api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shopApi = require('../../api/shop')
/**
* Purpose: navigation supports index.js by holding or executing the navigation page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const navigation = require('../../utils/navigation')
/**
* Purpose: format supports index.js by holding or executing the format page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const format = require('../../utils/format')
const { getTempRecord, clearTempRecord } = require('../../utils/storage')
/**
* Purpose: normalizeId supports index.js by holding or executing the normalize id page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeId(value) {
return value === undefined || value === null ? '' : String(value)
}
/**
* Purpose: buildCheckableList supports index.js by holding or executing the build checkable list page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildCheckableList(list, selectedIds, labelKey) {
return (Array.isArray(list) ? list : []).map(item => ({
...item,
valueId: normalizeId(item.id),
labelText: item[labelKey],
checked: selectedIds.includes(normalizeId(item.id))
}))
}
/**
* Purpose: syncSelectedIds supports index.js by holding or executing the sync selected ids page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function syncSelectedIds(selectedIds, list) {
const availableIds = new Set((Array.isArray(list) ? list : []).map(item => normalizeId(item.id)))
return (Array.isArray(selectedIds) ? selectedIds : []).filter(id => availableIds.has(normalizeId(id)))
}
/**
* Purpose: filterProductsByShop supports index.js by holding or executing the filter products by shop page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function filterProductsByShop(products, shopId) {
const targetShopId = normalizeId(shopId)
if (!targetShopId) {
return []
}
return (Array.isArray(products) ? products : []).filter(item => normalizeId(item.shopId) === targetShopId)
}
Page({
/**
* Purpose: data supports index.js by holding or executing the data page or API role.
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
*/
data: {
/**
* Purpose: mode supports index.js by holding or executing the mode page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
mode: 'create',
/**
* Purpose: userId supports index.js by holding or executing the user id page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userId: '',
/**
* Purpose: shops supports index.js by holding or executing the shops page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shops: [],
/**
* Purpose: shopIndex supports index.js by holding or executing the shop index page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shopIndex: 0,
/**
* Purpose: shopLabel supports index.js by holding or executing the shop label page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shopLabel: '',
/**
* Purpose: statusOptions supports index.js by holding or executing the status options page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
statusOptions: ['营业中', '休息中'],
/**
* Purpose: statusIndex supports index.js by holding or executing the status index page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
statusIndex: 0,
/**
* Purpose: userForm supports index.js by holding or executing the user form page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userForm: {
/**
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
nickname: '',
/**
* Purpose: account supports index.js by holding or executing the account page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
account: '',
/**
* Purpose: phone supports index.js by holding or executing the phone page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
phone: '',
/**
* Purpose: password supports index.js by holding or executing the password page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
password: '',
/**
* Purpose: signature supports index.js by holding or executing the signature page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
signature: ''
},
/**
* Purpose: artistForm supports index.js by holding or executing the artist form page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
artistForm: {
/**
* Purpose: identity supports index.js by holding or executing the identity page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
identity: '',
/**
* Purpose: experience supports index.js by holding or executing the experience page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
experience: '',
/**
* Purpose: rating supports index.js by holding or executing the rating page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
rating: '',
/**
* Purpose: portfolioText supports index.js by holding or executing the portfolio text page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
portfolioText: ''
},
/**
* Purpose: tags supports index.js by holding or executing the tags page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
tags: [],
/**
* Purpose: products supports index.js by holding or executing the products page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
products: []
},
/**
* Purpose: onLoad supports index.js by holding or executing the on load page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
onLoad(options) {
const mode = options && options.mode ? options.mode : 'create'
const currentArtist = getTempRecord('currentArtist', null)
this.setData({
mode,
/**
* Purpose: userId supports index.js by holding or executing the user id page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userId: options && options.userId ? options.userId : ''
})
this._selectedTagIds = []
this._selectedProductIds = []
this._allProducts = []
if (mode === 'edit' && currentArtist) {
this._selectedTagIds = format.splitCsv(currentArtist.skills)
this._selectedProductIds = format.splitCsv(currentArtist.portfolio)
this._initialShopId = currentArtist.shopId
this.setData({
/**
* Purpose: artistForm supports index.js by holding or executing the artist form page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
artistForm: {
/**
* Purpose: identity supports index.js by holding or executing the identity page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
identity: currentArtist.identity || '',
/**
* Purpose: experience supports index.js by holding or executing the experience page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
experience: currentArtist.experience || '',
/**
* Purpose: rating supports index.js by holding or executing the rating page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
rating: currentArtist.rating || '',
/**
* Purpose: portfolioText supports index.js by holding or executing the portfolio text page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
portfolioText: ''
},
/**
* Purpose: userForm supports index.js by holding or executing the user form page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userForm: {
/**
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
nickname: currentArtist.nickname || '',
/**
* Purpose: account supports index.js by holding or executing the account page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
account: '',
/**
* Purpose: phone supports index.js by holding or executing the phone page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
phone: '',
/**
* Purpose: password supports index.js by holding or executing the password page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
password: '',
/**
* Purpose: signature supports index.js by holding or executing the signature page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
signature: currentArtist.signature || ''
},
/**
* Purpose: statusIndex supports index.js by holding or executing the status index page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
statusIndex: Number(currentArtist.status) === 0 ? 1 : 0
})
}
this.loadDependencies()
},
/**
* Purpose: onUnload supports index.js by holding or executing the on unload page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
onUnload() {
clearTempRecord('currentArtist')
},
async loadDependencies() {
const app = getApp()
const currentShop = app.globalData.currentShop
const operator = app.globalData.userInfo || {}
try {
const [shops, products, users] = await Promise.all([
shopApi.listAllShops(),
productApi.listAllProducts(),
userApi.listAllUsers()
])
let availableShops = Array.isArray(shops) ? shops : []
if (Number(operator.type) !== 4 && currentShop) {
availableShops = availableShops.filter(item => normalizeId(item.id) === normalizeId(currentShop.id))
}
let shopIndex = 0
if (this._initialShopId) {
const index = availableShops.findIndex(item => normalizeId(item.id) === normalizeId(this._initialShopId))
if (index >= 0) {
shopIndex = index
}
}
const selectedShop = availableShops[shopIndex]
this._allProducts = Array.isArray(products) ? products : []
if (this.data.mode === 'edit') {
const userRecord = (Array.isArray(users) ? users : []).find(item => normalizeId(item.id) === normalizeId(this.data.userId))
if (userRecord) {
this.setData({
/**
* Purpose: userForm supports index.js by holding or executing the user form page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userForm: {
/**
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
nickname: userRecord.nickname || '',
/**
* Purpose: account supports index.js by holding or executing the account page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
account: userRecord.account || '',
/**
* Purpose: phone supports index.js by holding or executing the phone page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
phone: userRecord.phone || '',
/**
* Purpose: password supports index.js by holding or executing the password page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
password: '',
/**
* Purpose: signature supports index.js by holding or executing the signature page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
signature: userRecord.signature || ''
}
})
}
}
this.setData({
/**
* Purpose: shops supports index.js by holding or executing the shops page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shops: availableShops,
shopIndex,
/**
* Purpose: shopLabel supports index.js by holding or executing the shop label page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shopLabel: selectedShop ? selectedShop.shopName : ''
})
await this.loadShopScopedOptions(selectedShop ? selectedShop.id : '')
} catch (error) {
wx.showToast({
/**
* Purpose: title supports index.js by holding or executing the title page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
title: error.message || '初始化美甲师表单失败',
/**
* Purpose: icon supports index.js by holding or executing the icon page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
icon: 'none'
})
}
},
async loadShopScopedOptions(shopId) {
if (!normalizeId(shopId)) {
this._selectedTagIds = []
this._selectedProductIds = []
this.setData({
/**
* Purpose: tags supports index.js by holding or executing the tags page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
tags: [],
/**
* Purpose: products supports index.js by holding or executing the products page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
products: []
})
return
}
try {
const tagList = await tagApi.listTagsByShopId(shopId)
const productList = filterProductsByShop(this._allProducts, shopId)
this._selectedTagIds = syncSelectedIds(this._selectedTagIds, tagList)
this._selectedProductIds = syncSelectedIds(this._selectedProductIds, productList)
this.setData({
/**
* Purpose: tags supports index.js by holding or executing the tags page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
tags: buildCheckableList(tagList, this._selectedTagIds, 'tagName'),
/**
* Purpose: products supports index.js by holding or executing the products page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
products: buildCheckableList(productList, this._selectedProductIds, 'title')
})
} catch (error) {
this.setData({
/**
* Purpose: tags supports index.js by holding or executing the tags page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
tags: [],
/**
* Purpose: products supports index.js by holding or executing the products page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
products: []
})
wx.showToast({
/**
* Purpose: title supports index.js by holding or executing the title page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
title: error.message || '店铺关联数据加载失败',
/**
* Purpose: icon supports index.js by holding or executing the icon page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
icon: 'none'
})
}
},
/**
* Purpose: handleUserInput supports index.js by holding or executing the handle user input page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleUserInput(event) {
const field = event.currentTarget.dataset.field
let value = event.detail.value
if (field === 'account') {
value = String(value || '').replace(/[^A-Za-z0-9]/g, '')
}
if (field === 'phone') {
value = String(value || '').replace(/[^\d]/g, '').slice(0, 11)
}
this.setData({
[`userForm.${field}`]: value
})
},
/**
* Purpose: handleArtistInput supports index.js by holding or executing the handle artist input page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleArtistInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`artistForm.${field}`]: event.detail.value
})
},
/**
* Purpose: handleShopChange supports index.js by holding or executing the handle shop change page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleShopChange(event) {
const shopIndex = Number(event.detail.value)
const selectedShop = this.data.shops[shopIndex]
this.setData({
shopIndex,
/**
* Purpose: shopLabel supports index.js by holding or executing the shop label page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shopLabel: selectedShop ? selectedShop.shopName : ''
})
this.loadShopScopedOptions(selectedShop ? selectedShop.id : '')
},
/**
* Purpose: handleStatusChange supports index.js by holding or executing the handle status change page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleStatusChange(event) {
this.setData({
/**
* Purpose: statusIndex supports index.js by holding or executing the status index page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
statusIndex: Number(event.detail.value)
})
},
/**
* Purpose: handleTagChange supports index.js by holding or executing the handle tag change page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleTagChange(event) {
this._selectedTagIds = event.detail.value || []
this.setData({
/**
* Purpose: tags supports index.js by holding or executing the tags page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
tags: this.data.tags.map(item => ({
...item,
/**
* Purpose: checked supports index.js by holding or executing the checked page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
checked: this._selectedTagIds.includes(item.valueId)
}))
})
},
/**
* Purpose: handleProductChange supports index.js by holding or executing the handle product change page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleProductChange(event) {
this._selectedProductIds = event.detail.value || []
this.setData({
/**
* Purpose: products supports index.js by holding or executing the products page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
products: this.data.products.map(item => ({
...item,
/**
* Purpose: checked supports index.js by holding or executing the checked page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
checked: this._selectedProductIds.includes(item.valueId)
}))
})
},
/**
* Purpose: validateForm supports index.js by holding or executing the validate form page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
validateForm() {
if (!this.data.userForm.nickname) {
return '请输入美甲师昵称'
}
if (!this.data.userForm.account) {
return '请输入账号'
}
if (!this.data.userForm.phone || this.data.userForm.phone.length !== 11) {
return '请输入 11 位手机号'
}
if (this.data.mode === 'create' && !this.data.userForm.password) {
return '新增美甲师时必须设置密码'
}
if (!this.data.shops[this.data.shopIndex]) {
return '请选择所属店铺'
}
return ''
},
async handleSubmit() {
const errorMessage = this.validateForm()
if (errorMessage) {
wx.showToast({
/**
* Purpose: title supports index.js by holding or executing the title page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
title: errorMessage,
/**
* Purpose: icon supports index.js by holding or executing the icon page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
icon: 'none'
})
return
}
const selectedShop = this.data.shops[this.data.shopIndex]
const userPayload = {
/**
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
nickname: this.data.userForm.nickname,
/**
* Purpose: account supports index.js by holding or executing the account page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
account: this.data.userForm.account,
/**
* Purpose: phone supports index.js by holding or executing the phone page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
phone: this.data.userForm.phone,
/**
* Purpose: signature supports index.js by holding or executing the signature page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
signature: this.data.userForm.signature || undefined,
/**
* Purpose: type supports index.js by holding or executing the type page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
type: 3,
/**
* Purpose: shopIds supports index.js by holding or executing the shop ids page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shopIds: selectedShop ? [Number(selectedShop.id)] : []
}
if (this.data.userForm.password) {
userPayload.password = this.data.userForm.password
}
try {
let targetUserId = this.data.userId
if (this.data.mode === 'edit') {
await userApi.updateUser(targetUserId, userPayload)
} else {
targetUserId = await userApi.createUser(userPayload)
}
await artistApi.saveNailArtistInfo({
/**
* Purpose: userId supports index.js by holding or executing the user id page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userId: Number(targetUserId),
/**
* Purpose: identity supports index.js by holding or executing the identity page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
identity: this.data.artistForm.identity || undefined,
/**
* Purpose: experience supports index.js by holding or executing the experience page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
experience: this.data.artistForm.experience ? Number(this.data.artistForm.experience) : 0,
/**
* Purpose: skills supports index.js by holding or executing the skills page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
skills: this._selectedTagIds.join(',') || undefined,
/**
* Purpose: rating supports index.js by holding or executing the rating page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
rating: this.data.artistForm.rating ? Number(this.data.artistForm.rating) : 0,
/**
* Purpose: status supports index.js by holding or executing the status page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
status: this.data.statusIndex === 1 ? 0 : 1,
/**
* Purpose: portfolio supports index.js by holding or executing the portfolio page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
portfolio: this._selectedProductIds.join(',') || undefined,
/**
* Purpose: nickname supports index.js by holding or executing the nickname page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
nickname: this.data.userForm.nickname,
/**
* Purpose: shopId supports index.js by holding or executing the shop id page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
shopId: selectedShop ? Number(selectedShop.id) : undefined,
/**
* Purpose: signature supports index.js by holding or executing the signature page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
signature: this.data.userForm.signature || undefined
})
wx.showToast({
/**
* Purpose: title supports index.js by holding or executing the title page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
title: this.data.mode === 'edit' ? '美甲师已更新' : '美甲师已创建',
/**
* Purpose: icon supports index.js by holding or executing the icon page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
icon: 'none'
})
navigation.goBack('/pages/artists/index')
} catch (error) {
wx.showToast({
/**
* Purpose: title supports index.js by holding or executing the title page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
title: error.message || '保存失败',
/**
* Purpose: icon supports index.js by holding or executing the icon page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
icon: 'none'
})
}
}
})
@@ -1,5 +0,0 @@
{
"usingComponents": {
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
}
}
@@ -1,82 +0,0 @@
<navigation-bar title="{{mode === 'edit' ? '编辑美甲师' : '新增美甲师'}}" back="{{true}}" color="#f6efe7" background="#081518"></navigation-bar>
<view class="page-shell">
<view class="page-stack">
<view class="surface-card">
<text class="section-title">账号信息</text>
<view class="field-group">
<text class="field-label">昵称</text>
<input class="field-input" value="{{userForm.nickname}}" data-field="nickname" bindinput="handleUserInput"></input>
</view>
<view class="field-group">
<text class="field-label">账号</text>
<input class="field-input" value="{{userForm.account}}" data-field="account" bindinput="handleUserInput"></input>
</view>
<view class="field-group">
<text class="field-label">手机号</text>
<input class="field-input" type="number" value="{{userForm.phone}}" data-field="phone" bindinput="handleUserInput"></input>
</view>
<view class="field-group">
<text class="field-label">{{mode === 'edit' ? '密码(留空则不修改)' : '登录密码'}}</text>
<input class="field-input" password value="{{userForm.password}}" data-field="password" bindinput="handleUserInput"></input>
</view>
<view class="field-group">
<text class="field-label">签名</text>
<textarea class="field-textarea" value="{{userForm.signature}}" data-field="signature" bindinput="handleUserInput"></textarea>
</view>
<view class="field-group">
<text class="field-label">所属店铺</text>
<picker mode="selector" range="{{shops}}" range-key="shopName" value="{{shopIndex}}" bindchange="handleShopChange">
<view class="field-picker">{{shopLabel || '请选择店铺'}}</view>
</picker>
</view>
</view>
<view class="surface-card">
<text class="section-title">职业信息</text>
<view class="field-group">
<text class="field-label">身份标签</text>
<input class="field-input" value="{{artistForm.identity}}" data-field="identity" bindinput="handleArtistInput"></input>
</view>
<view class="field-group">
<text class="field-label">从业年限</text>
<input class="field-input" type="number" value="{{artistForm.experience}}" data-field="experience" bindinput="handleArtistInput"></input>
</view>
<view class="field-group">
<text class="field-label">评分</text>
<input class="field-input" type="digit" value="{{artistForm.rating}}" data-field="rating" bindinput="handleArtistInput"></input>
</view>
<view class="field-group">
<text class="field-label">营业状态</text>
<picker mode="selector" range="{{statusOptions}}" value="{{statusIndex}}" bindchange="handleStatusChange">
<view class="field-picker">{{statusOptions[statusIndex]}}</view>
</picker>
</view>
<view class="field-group">
<text class="field-label">擅长标签</text>
<checkbox-group bindchange="handleTagChange">
<block wx:for="{{tags}}" wx:key="id">
<label class="checkbox-chip {{item.checked ? 'active' : ''}}">
<checkbox value="{{item.valueId}}" checked="{{item.checked}}" />
{{item.labelText}}
</label>
</block>
</checkbox-group>
</view>
<view class="field-group">
<text class="field-label">作品集</text>
<checkbox-group bindchange="handleProductChange">
<block wx:for="{{products}}" wx:key="id">
<label class="checkbox-chip {{item.checked ? 'active' : ''}}">
<checkbox value="{{item.valueId}}" checked="{{item.checked}}" />
{{item.labelText}}
</label>
</block>
</checkbox-group>
</view>
<view class="action-row">
<button class="primary-btn" bindtap="handleSubmit">保存美甲师</button>
</view>
</view>
</view>
</view>
@@ -1,5 +0,0 @@
@import "../../app.wxss";
checkbox {
transform: scale(0.75);
margin-right: 8rpx;
}
@@ -1,119 +0,0 @@
/**
* Purpose: artistApi supports index.js by holding or executing the artist api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const artistApi = require('../../api/nail-artist')
/**
* Purpose: navigation supports index.js by holding or executing the navigation page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const navigation = require('../../utils/navigation')
const { setTempRecord, clearTempRecord } = require('../../utils/storage')
Page({
/**
* Purpose: data supports index.js by holding or executing the data page or API role.
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
*/
data: {
/**
* Purpose: list supports index.js by holding or executing the list page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
list: [],
/**
* Purpose: canCreate supports index.js by holding or executing the can create page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
canCreate: false
},
/**
* Purpose: onShow supports index.js by holding or executing the on show page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
onShow() {
if (!navigation.ensureLogin('进入美甲师管理')) {
return
}
const permissionCodes = getApp().globalData.permissionCodes || []
this.setData({
/**
* Purpose: canCreate supports index.js by holding or executing the can create page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
canCreate: permissionCodes.includes('user:create') || permissionCodes.includes('nail_artist:edit')
})
this.loadArtists()
},
async loadArtists() {
try {
const list = await artistApi.listNailArtists()
this.setData({
/**
* Purpose: list supports index.js by holding or executing the list page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
list: (Array.isArray(list) ? list : []).map(item => ({
...item,
/**
* Purpose: displayStatusText supports index.js by holding or executing the display status text page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
displayStatusText: Number(item.status) === 0 ? '休息中' : '营业中'
}))
})
} catch (error) {
wx.showToast({
/**
* Purpose: title supports index.js by holding or executing the title page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
title: error.message || '美甲师列表加载失败',
/**
* Purpose: icon supports index.js by holding or executing the icon page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
icon: 'none'
})
}
},
/**
* Purpose: handleCreate supports index.js by holding or executing the handle create page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleCreate() {
clearTempRecord('currentArtist')
navigation.navigate('/pages/artist-form/index', {
/**
* Purpose: mode supports index.js by holding or executing the mode page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
mode: 'create'
}).catch(() => undefined)
},
/**
* Purpose: handleEdit supports index.js by holding or executing the handle edit page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
handleEdit(event) {
const artist = event.currentTarget.dataset.artist
setTempRecord('currentArtist', artist)
navigation.navigate('/pages/artist-form/index', {
/**
* Purpose: mode supports index.js by holding or executing the mode page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
mode: 'edit',
/**
* Purpose: userId supports index.js by holding or executing the user id page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
userId: artist.userId
}).catch(() => undefined)
}
})
@@ -1,5 +0,0 @@
{
"usingComponents": {
"navigation-bar": "/admin/components/navigation-bar/navigation-bar"
}
}
@@ -1,42 +0,0 @@
<navigation-bar title="美甲师管理" back="{{true}}" color="#f6efe7" background="#081518"></navigation-bar>
<view class="page-shell">
<view class="page-stack">
<view class="surface-card">
<text class="section-title">美甲师列表</text>
<text class="section-desc">店长只能看到并管理自己门店的美甲师;平台管理员可跨店查看,移动端表单集中处理账号和档案两部分信息。</text>
</view>
<block wx:for="{{list}}" wx:key="id">
<view class="list-card">
<view class="list-head">
<view>
<text class="list-title">{{item.nickname}}</text>
<text class="list-subtitle">{{item.identity || '未设置身份'}} · {{item.shopName || '当前店铺'}}</text>
</view>
<text class="{{item.status === 0 ? 'soft-badge' : 'badge'}}">{{item.displayStatusText}}</text>
</view>
<view class="meta-grid">
<view class="meta-item">
<text class="meta-label">从业年限</text>
<text class="meta-value">{{item.experience || 0}} 年</text>
</view>
<view class="meta-item">
<text class="meta-label">评分</text>
<text class="meta-value">{{item.rating || 0}}</text>
</view>
</view>
<view class="list-actions">
<view class="mini-btn primary" data-artist="{{item}}" bindtap="handleEdit">编辑</view>
</view>
</view>
</block>
<view wx:if="{{!list.length}}" class="empty-state">
<text class="empty-title">还没有美甲师</text>
<text class="empty-desc">可以先新增一个美甲师账号,再补充技能、作品集和营业状态。</text>
</view>
<view wx:if="{{canCreate}}" class="fab" bindtap="handleCreate">+</view>
</view>
</view>

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