163 Commits
Author SHA1 Message Date
xiaowang 583bace2e1 修复日程美甲师筛选消失与日视图泳道末端裁切
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 11s
2026-11-09 15:59:22 +08:00
xiaowang 69ea01eaa4 小程序预约详情支持图片预览、编辑预约与完成收款拆分
自动发布开发环境 Nacos 配置 / publish (push) Successful in 34s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 11s
2026-11-09 15:18:27 +08:00
xiaowang 6f6625bc0d 管理端图片上传:公告超过 5MB 自动切换分片,去除 5MB 提前拦截,仅在分片总量超 500MB 时提示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 12s
2026-11-08 22:54:02 +08:00
xiaowang 4bc7ddf08e 管理端实况照片上传:按需加载 heic2any 将 HEIC/HEIF 转 JPEG 后沿用原有上传链路,二维码继续排除 HEIC
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
2026-11-08 19:37:45 +08:00
xiaowang ae5bc3ef2b 回溯提交:ArtList 清理微信号必填遗留校验与前端提示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
2026-11-08 15:31:39 +08:00
xiaowang 2eefae834a test(salon): 清理微信号必填遗留用例,改为校验空值归一为 null
自动发布开发环境 Nacos 配置 / publish (push) Successful in 23s
2026-11-08 02:10:34 +08:00
xiaowang b8904d92d1 新建预约必填与默认值调整:款式名称必填加星标,价格空值默认0、时长空值默认60,移除名称为空回退客户姓名/散客款式,非必填标签统一(选填)
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
2026-11-08 02:08:54 +08:00
xiaowang 338283090b 实况照片上传:小程序选图恢复压缩模式,避免 iOS HEIC 转 JPEG 后体积超限
自动发布开发环境 Nacos 配置 / publish (push) Successful in 27s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 12s
2026-11-08 01:25:26 +08:00
xiaowang 0dfa3bc5a8 修复小程序日程页日视图末条内容被滚动容器底边裁切
自动发布开发环境 Nacos 配置 / publish (push) Successful in 46s
- 日视图滚动容器末尾新增留白(64rpx + 安全区),避免末条时间刻度与末个预约卡片贴边、滚到底仍缺一截
- 视口高度计算同步预留该留白,短时间轴不再因高度刚好等于内容高度而裁掉末条标签
- 时间刻度列加宽到 104rpx,刻度与泳道内容间距增至 20rpx,改善左侧呼吸感并避免刻度文字被截断
2026-11-08 00:28:17 +08:00
xiaowang daae69c6a0 图片上传支持 GIF:管理端上传白名单对齐 GIF,小程序图片选择保留原图避免动图被压成静态
自动发布开发环境 Nacos 配置 / publish (push) Successful in 47s
2026-11-08 00:27:37 +08:00
xiaowang 771625d8cf fix(salon): 取消微信号必填校验,允许店长与美甲师留空
自动发布开发环境 Nacos 配置 / publish (push) Successful in 44s
2026-11-08 00:26:49 +08:00
xiaowang e0154a9edb 预约时间选择改为1分钟粒度:小程序预约时间滚轮与时段列表由15分钟一档改为逐分钟候选,分钟可选00-59并原样提交回显
自动发布开发环境 Nacos 配置 / publish (push) Successful in 34s
2026-11-08 00:23:52 +08:00
xiaowang 419eccad79 补充 MinIO 预签名区域解析配置说明
自动发布开发环境 Nacos 配置 / publish (push) Successful in 27s
说明签名区域改为经内网端点解析、公网签名 URL 语义不变,并在配置总说明登记可选 minio.region。
2026-11-08 00:21:46 +08:00
xiaowang 98308928e2 回溯提交:MinIO 预签名区域改为从内网端点解析,避免公网域名 DNS 依赖
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
2026-11-08 00:17:04 +08:00
xiaowang fb27f94deb 运行参数改为分组切换显示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
运行参数下账号与登录、门店经营两组由纵向堆叠改为按钮切换,默认账号与登录;切换仅更新选中态与渲染内容,字段值均在页面级状态中,未保存内容不丢失。
2026-11-07 23:49:26 +08:00
xiaowang 60e9e1e9d0 修复对象存储探针签名读取二次编码并补充失败诊断
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 13s
签名 URL 改为以 URI 传入 RestTemplate,避免 DefaultUriBuilderFactory 的 URI_COMPONENT 把 %2B/%2F/%3D 二次编码导致 OSS、MinIO 验签失败。probeStorage 失败明细改为记录阶段、异常类型与脱敏后的简短原因,不再统一显示上传或读取失败。新增单测覆盖 URI 原样传参与失败明细含阶段、异常类型且不泄露签名参数。
2026-11-07 21:06:58 +08:00
xiaowang b1360d9552 接入诊断去重图片回调结论展示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 23s
检查项 detail 与结果 summary 文案完全相同时只保留 summary,避免同一结论重复渲染两次。
2026-11-07 20:21:03 +08:00
xiaowang 5dfea1a73b 接入诊断标题行调整刷新按钮
自动发布开发环境 Nacos 配置 / publish (push) Successful in 22s
将原有刷新最近结果入口改为刷新并移到汇总徽标左侧,补充请求期间禁用;仍复用只读配置查询,不重新发起外部探测。
2026-11-07 20:15:31 +08:00
xiaowang f01662b185 系统设置服务接入改为分组切换
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 9s
服务接入下五个分组由纵向平铺改为按钮切换,默认接入诊断;表单与测试状态均在页面级响应式状态中,切换不丢失未保存输入与最近测试结果。
2026-11-07 20:01:38 +08:00
xiaowang e870285300 微信审核回调改为先落库后应答并异步探测补偿
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 8s
- 回调到达即持久化解密报文与 trace_id,落库失败返回 500 让微信重试
- 异步执行器按环境顺序探测认领,状态机 PENDING/PROCESSING/SUCCESS/NO_ENV/FAILED/DEAD
- 定时补偿按 30/120/600/3600 秒退避,达到上限置 DEAD 并告警,启动时恢复未完成任务
- 数据库条件更新抢锁保证多实例只处理一次,新增 V22 迁移与管理端重试配置/明细
2026-11-07 13:02:26 +08:00
xiaowang 69a32672c9 补齐微信审核回调跨环境串行探测单测:三态认领、ERROR 告警与幂等防环
自动发布开发环境 Nacos 配置 / publish (push) Successful in 23s
2026-11-07 12:39:39 +08:00
xiaowang 7da346d3aa 隐私与内容复核:内容类型枚举统一映射中文并补充未知类型兜底
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
2026-11-07 12:35:43 +08:00
xiaowang 4d111d8257 回溯提交:隐私审核回调与系统设置并行改动快照 2026-11-07 12:34:30 +08:00
xiaowang 4f80a09619 修复微信图片异步审核 47001:移除不支持的 extra 字段并纠正 media_type/version
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
SIT 实测 media_check_async 携带 extra 时固定返回 47001 data format error,去掉 extra 后恢复正常;同时把图片类型改为 2、version 改为 1,并补充失败响应的脱敏日志。
2026-11-07 01:41:57 +08:00
xiaowang ed33066ef6 打通美甲师专属颜色持久化与日程即时刷新
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
2026-11-07 01:29:17 +08:00
xiaowang 3d73ac7db7 小程序页面的一些优化
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 10s
2026-11-07 01:10:02 +08:00
xiaowang 71ddf0210c 修复新建美甲师后日程筛选列表未即时刷新
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
2026-11-07 01:03:19 +08:00
xiaowang ae6317903a 新增美甲师手机号改为选填并跳过空值哈希索引
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
2026-11-07 00:57:23 +08:00
xiaowang 5fae5163ff 小程序剩余原生弹窗统一接入 action-modal
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
2026-11-07 00:50:04 +08:00
xiaowang 1482bda1fa 小程序浮层动作项按钮化并统一按钮样式
自动发布开发环境 Nacos 配置 / publish (push) Successful in 27s
2026-11-07 00:38:22 +08:00
xiaowang a5f050286b 新增美甲师页颜色选择抽屉与注册流程按钮样式同步设计稿 2026-11-07 00:31:33 +08:00
xiaowang 54215ffd50 回溯提交:员工创建页微信绑定与排班颜色文案调整 2026-11-07 00:21:23 +08:00
xiaowang c2c5c27453 日程页优化 0 单空态与休息日呈现
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
周视图 0 单不再渲染空量轨与 0单,改为次字色「暂无预约」;休息日仅显示休;月视图三种显示模式的空态由「空」统一为「暂无预约」并对休息日隐藏。

仅改动 0 单分支呈现,量轨归一、分段配色、数据与接口未改动。
2026-11-06 21:39:34 +08:00
xiaowang 380e7b42de 日程页周视图改为本周安排卡片纵向列表并同步月视图条色
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
周视图从七列卡片改为单卡片七行列表,行高 108rpx,行内依次为周几与日期、营业状态、396x28rpx 单量量轨、单量与待分配徽标;量轨按美甲师分段,1 单 75.2rpx、段间 4rpx,段内显示姓名与单量并单行裁切。

三色条更新为 #43789E/#96684B/#587959,旧默认员工色统一映射,月视图条与筛选 chip 色点同步;今日行浅绿底加左侧竖条,待分配使用琥珀徽标;顶部保留标题、日期范围、图例与周汇总。仅呈现层调整,接口、字段与状态流转未改动。
2026-11-06 17:07:17 +08:00
xiaowang c9ff29d048 订单数据页标题对齐设计稿
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-06 14:34:33 +08:00
xiaowang 60d9bba61a 小程序页面视觉对齐二期:预约图片轮播、订单数据预览、微信用户关联与请假管理
新增预约详情作品图片轮播字段与组装;新增订单预览与未关联微信用户候选接口;补齐请假记录查询接口;订单数据预览改为四列;请假管理接入真实排班例外并支持新增;日程、我的、美甲师详情与改派选择器按设计稿微调;注册结果页与申请提交时间对齐设计稿。
2026-11-06 14:34:02 +08:00
xiaowang 2ff83a5ec1 style(小程序): 新增预约表单字段与客户选择区、排班卡片描边对齐设计稿
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
2026-11-06 11:37:37 +08:00
xiaowang 70f5462d88 style(小程序): 我的页身份胶囊与菜单重组、审核面板重构、客户新增悬浮按钮等页面视觉对齐设计稿
自动发布开发环境 Nacos 配置 / publish (push) Successful in 22s
2026-11-06 11:36:04 +08:00
xiaowang 3e51247312 style(小程序): 关于系统补充协议入口与版本更新日志卡片,色盘中心环对齐设计稿 2026-11-06 11:23:27 +08:00
xiaowang 701b75e57f docs: 更新 Ardot 小程序端设计导出清单与缺失项 2026-11-06 11:22:44 +08:00
xiaowang 61b443ff0a chore: 补全 Ardot 设计稿导出 HTML 与资源 2026-11-06 11:18:23 +08:00
xiaowang 3bfc32777d chore: 归档 Ardot 设计稿导出产物与既有分析文档作为改造基线 2026-11-06 11:17:54 +08:00
xiaowang 7e16e1820a docs(artlist): 新增 ArtList 需求分析报告
- 以既定口径(ArtList 只做 C 端、Salon 承载履约大脑、券会员归 ArtList、线下支付、全场景脱敏与单次取号)为约束,基于三端源码与 Salon 只读核查产出可直接评审的需求分析
- 覆盖背景目标与用户、核心业务链路、端×模块功能清单、15 条需求问题(含证据/影响/建议)、优化建议、P0-P3 优先级与依赖、18 条可验证验收标准
- 全文区分【事实】【推断】【待确认】,附录提供源码文件与行号证据索引,并汇总 5 条待决策问题
- 仅新增文档,未修改任何业务代码、配置与 SQL
2026-11-06 11:17:35 +08:00
xiaowang 46e724334c docs: 建立项目级 Agent Skills 体系与开发规范
- AGENTS.md 扩充:项目概述、技术栈版本、架构、目录/数据库/API/开发验证/安全规范
- .agents/skills 新增 5 个项目技能:jayu-domain、jayu-database、jayu-api、jayu-devflow、jayu-release
- docs/agent 新增 4 份文档:PROJECT_CONTEXT、PROJECT_CONSTRAINTS、SKILLS_CATALOG、AGENT_SKILLS_GUIDE
- .gitignore 收窄 .agents 忽略规则,保留镜像忽略意图、纳入项目技能版本管理
2026-11-06 10:34:40 +08:00
xiaowang 6c2e094d58 docs(salon): 协议正文补充后台管理端豁免说明并新增 V21 迁移
自动发布开发环境 Nacos 配置 / publish (push) Successful in 17s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 7s
2026-11-05 17:00:12 +08:00
xiaowang 6848491678 style(salon-admin): 管理后台移除页面说明块并改造面包屑与侧栏折叠按钮
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-05 16:44:38 +08:00
xiaowang 3a91246e0c fix(salon): 后台管理端豁免协议版本校验并移除后台同意弹层
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-05 16:32:55 +08:00
xiaowang 385c4b06ec fix(wechat): 协议页切后台暂停超时计时并全量映射技术文案
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 5s
2026-11-05 11:32:29 +08:00
xiaowang 942718b8d9 fix(wechat): 协议挂起请求仅在离开页面时结算并集中映射错误文案
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
2026-11-05 10:51:40 +08:00
xiaowang 3f825682fb fix(wechat): 结算挂起的协议 4510 请求,避免页面 loading 卡死
自动发布开发环境 Nacos 配置 / publish (push) Successful in 21s
2026-11-05 10:39:34 +08:00
xiaowang 702c186f65 fix(wechat): 协议 4510 改为原地同意并自动重试原请求
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-05 10:29:10 +08:00
xiaowang fb19fcf05f feat(salon): 服务端拦截未同意最新协议的用户并补充端侧 4510 处理
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
2026-11-05 09:43:01 +08:00
xiaowang 88589e2575 feat(salon): 支持散客预约拨号并发布协议新版本强制重新同意
自动发布开发环境 Nacos 配置 / publish (push) Successful in 23s
2026-11-04 23:38:42 +08:00
xiaowang 114a8a423c fix: 跨环境转发配置项按 CONTENT_MODERATION_FORWARD 命名落库
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
2026-11-04 23:26:14 +08:00
xiaowang 90b07bf33e feat: 微信审核回调支持跨环境转发与补偿重试 2026-11-04 23:24:05 +08:00
xiaowang 99fa38f110 feat(artlist): 全场景脱敏与单次拨号取号,补齐账号加密与协议版本
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
- 手机号/账号全场景一律脱敏:SensitiveFieldPolicy 删除完整值分支与 ADMIN_EDIT,SELF_PROFILE 同样脱敏;convertToVO 全调用点统一脱敏
- 联系信息接口不再返回号码:toContact 置空 phone 并给出 phoneAvailable,补齐 ensureUserCanSeeShop 真实可见范围校验
- 新增 POST /contact-info/dial,按 scene(SHOP_MANAGER/ORDER_ARTIST/PRODUCT_ARTIST/PLATFORM) 一次一取;DialTargetProvider 抽象直连/隐私号,未配置隐私号返回 9001 且不回退真实号;/contact-info/** 按用户限流并记录审计
- 验证码与换绑手机号改为服务端按当前登录用户取号,客户端 phone/oldPhone 参数兼容忽略;前端与小程序同步去掉回传
- 消息发布人昵称兜底改为脱敏账号,避免 account 明文写入 publisher_name
- 新增 V5 账号加密与账号哈希、V6 协议文本改为全场景脱敏与单次拨号取号
2026-11-04 22:04:14 +08:00
xiaowang 05493923e4 Salon 侧全场景脱敏与拨号单次取号改造:收掉预约选择客户的完整手机号出口,新增按门店与订单上下文授权的拨号取号端点及隐私号占位渠道,前端改为脱敏展示加呼叫取号,并同步更新协议条款
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
2026-11-04 22:02:51 +08:00
xiaowang bbe1473b70 Salon 两个静态协议页改为运行时读取后台当前发布协议,保留内置正文快照兜底
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
2026-11-04 21:34:15 +08:00
xiaowang 80d187d23c 修订隐私政策与用户协议以对齐加密存储与场景化脱敏
自动发布开发环境 Nacos 配置 / publish (push) Successful in 22s
- 新增 Salon V17 协议版本 2026.11.04
- 新增 ArtList V4 协议版本 2026.11.04(V3 已被账号加密并行改造占用)
- 同步更新 Salon 静态隐私政策与用户协议页面
- 补充加密密钥管理、HMAC 索引、按场景脱敏、第三方清单、留存期限与用户权利条款
2026-11-04 20:18:12 +08:00
xiaowang e6ecca7d47 店长编辑手机号改为仅修改时提交
自动发布开发环境 Nacos 配置 / publish (push) Successful in 25s
编辑弹窗保留脱敏手机号展示,聚焦时清空并提示留空不修改;未修改或仍为脱敏值时不再提交 phone/contactPhone,避免脱敏串写库。
2026-11-04 20:08:45 +08:00
xiaowang 47fced8175 修复系统设置页分组导航:通用滚动定位并改为横排导航
自动发布开发环境 Nacos 配置 / publish (push) Successful in 23s
分组导航改为内容顶部横向胶囊导航并随页面滚动,取消 sticky 侧栏与双列布局;滚动定位改为自动识别滚动容器并计入顶部 sticky 头部高度,点击时立即高亮并对目标分组做短暂描边,移除会与平滑滚动冲突的滚动监听高亮。
2026-11-04 19:59:34 +08:00
xiaowang ac35984ca3 ArtList 短信验证码投递日志手机号脱敏,避免日志输出明文号码
自动发布开发环境 Nacos 配置 / publish (push) Successful in 22s
2026-11-04 19:55:25 +08:00
xiaowang 772835d80d ArtList 手机号加密改造:新增 V2 迁移与 PhoneCrypto,登录注册与查询统一走 phone_hash,对外输出脱敏
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-04 19:53:50 +08:00
xiaowang 6e4ee2cd54 调整 ArtList Flyway 口径为空库直接初始化:三环境关闭 baseline 并移除 baseline-version,同步更新配置说明
自动发布开发环境 Nacos 配置 / publish (push) Successful in 22s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 11s
2026-11-04 19:19:41 +08:00
xiaowang 544725f25e 补齐 SIT/PROD ArtList Flyway 与会话库隔离配置并新增配置说明文档
自动发布开发环境 Nacos 配置 / publish (push) Successful in 21s
2026-11-04 19:13:51 +08:00
xiaowang 8f57158eab 合并 dev-trae 到 dev:Salon 线下收款登记与完成校验、ArtList Flyway 底座与安全清理、Salon 系统设置页重排 2026-11-04 19:07:38 +08:00
xiaowang 7d37432f4c 重排系统设置页布局:顶部标签、页内分组导航与配置组合并
将左侧设置目录改为顶部横向标签,移除页头大标题与各页重复标题;运行参数四个配置组按业务含义合并为账号与登录、门店经营两组,字段仍按原接口独立保存;服务接入改为紧凑服务卡与状态芯片,保留诊断、排序与全部配置读写。
2026-11-04 18:58:35 +08:00
xiaowang 9ddc77415c ArtList 底座与安全:接入 Flyway 基线、下线 mock 支付、Redis 会话隔离并清理死代码 2026-11-04 18:10:45 +08:00
xiaowang a961cc4bb2 修复微信异步图片审核请求参数
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 11s
2026-11-04 17:28:04 +08:00
xiaowang 3c28fe5544 新增订单线下收款登记并强制完成前收款校验
新增 POST /admin/order/{orderId}/offline-payment,仅支持 OFFLINE,金额需与应付一致;t_order 增加 paid_by/paid_by_type/paid_remark(V16);订单完成前统一校验收款状态,补单订单因创建即为 PAID 不受影响。
2026-11-04 16:40:06 +08:00
xiaowang 0e4b8b1981 CORS 白名单中增加 http://localhost:3000 和 http://127.0.0.1:3000
自动发布开发环境 Nacos 配置 / publish (push) Successful in 21s
2026-11-04 15:35:17 +08:00
xiaowang d4fc48bc2a 完善系统接入诊断与审核状态展示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 20s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 6s
2026-11-04 12:39:47 +08:00
xiaowang 029b7cc578 增加系统接入诊断基础能力 2026-11-04 11:16:04 +08:00
xiaowang b3e33c9fb9 修复店员申请审核后昵称头像展示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 21s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 7s
2026-11-04 01:13:32 +08:00
xiaowang 4b4c1ddef5 完善店员申请关联与预约页面
自动发布开发环境 Nacos 配置 / publish (push) Successful in 21s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 8s
2026-11-03 23:29:40 +08:00
xiaowang 1fc46f3835 提交注册资料必填校验回溯点 2026-11-03 22:40:47 +08:00
xiaowang 92df97810a 完善注册资料必填校验与驳回重申流程
自动发布开发环境 Nacos 配置 / publish (push) Successful in 21s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 11s
2026-11-03 21:22:05 +08:00
xiaowang c626a1e6d6 完善审核来源标识与图片读取设置
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 6s
2026-11-03 17:57:12 +08:00
xiaowang 19e2cd2594 完善小程序登录排班与个人资料流程 2026-11-03 15:33:03 +08:00
xiaowang 6aafbd4eac 补充门店周排班与预约营业校验 2026-11-03 13:25:33 +08:00
xiaowang b08fe4b486 调整预约表单布局样式 2026-11-03 12:48:34 +08:00
xiaowang b2fc23cd34 完善系统设置密钥保护确认 2026-11-03 11:09:38 +08:00
xiaowang 6047348a21 已配置审核密钥显示圆点占位
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 5s
2026-11-03 10:23:28 +08:00
xiaowang db48259f1c 调整后台标题文案 2026-11-03 10:19:00 +08:00
xiaowang de014483a8 修复微信审核回调支持JSON格式 2026-11-03 10:11:13 +08:00
xiaowang 083ec972e3 记录Salon SIT首次Flyway初始化恢复
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 8s
2026-11-02 23:35:11 +08:00
xiaowang e7e340b780 增强Salon Nacos回退读回校验 2026-11-02 21:57:20 +08:00
xiaowang 506fd8273f 修复Salon订单审核Mapper重复映射 2026-11-02 21:48:18 +08:00
xiaowang eec4507aad 统一Gitea工作流仓库域名
自动发布开发环境 Nacos 配置 / publish (push) Successful in 22s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 5s
2026-11-02 20:50:11 +08:00
xiaowang 4e5c553b33 nacos本地认证信息补充
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 7s
2026-11-02 16:50:42 +08:00
xiaowang c3d9cd938d 修复Salon各环境JWT密钥配置
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-02 15:20:37 +08:00
xiaowang 19ca9e2965 接入微信订阅消息并完善预约通知
自动发布开发环境 Nacos 配置 / publish (push) Successful in 20s
2026-11-02 12:11:23 +08:00
xiaowang 3e439543bc 完成Salon SIT HTTPS入口配置记录
自动发布开发环境 Nacos 配置 / publish (push) Successful in 19s
2026-11-01 23:33:35 +08:00
xiaowang 71943092ae 记录Salon SIT Nginx入口实施结果 2026-11-01 22:35:53 +08:00
xiaowang fc3d38b247 完成Salon SIT整改并清理旧接口 2026-11-01 16:21:43 +08:00
xiaowang 9e47371442 清理Salon管理页面电商残留 2026-11-01 15:26:36 +08:00
xiaowang 52b7dcb7d3 清理Salon后台电商前端残留 2026-11-01 15:26:23 +08:00
xiaowang 203dac2370 提交Salon旧接口清理与安全配置基线 2026-11-01 14:43:04 +08:00
xiaowang f30abbc26c 修复Salon对象存储头像展示 2026-11-01 00:41:51 +08:00
xiaowang e52e04685d fix(salon): 完善预约草稿与表单重置 2026-10-31 23:03:13 +08:00
xiaowang 5426df3ef2 修复小程序令牌过期登录循环 2026-10-31 21:02:37 +08:00
xiaowang c8e0806c4d 统一历史补录与新建预约表单体验 2026-10-31 03:48:49 +08:00
xiaowang ddc04705e3 调整日程日期选择与预约入口 2026-10-31 03:03:34 +08:00
xiaowang 0e4043628e 修复MinIO对象存储Bean启动注入 2026-10-31 02:31:15 +08:00
xiaowang 506ee86436 整理Salon SIT域名与对象存储入口
自动发布开发环境 Nacos 配置 / publish (push) Successful in 20s
2026-10-31 02:18:37 +08:00
xiaowang 0e72050e3e 补充安全配置循环修复测试 2026-10-30 22:25:17 +08:00
xiaowang bdc425183a 修复安全配置服务循环依赖 2026-10-30 22:24:16 +08:00
xiaowang 8b205f3220 安全接入配置改造回溯点 2026-10-30 22:04:38 +08:00
xiaowang 9a2c158fdd 安全接入配置改造回溯点
自动发布开发环境 Nacos 配置 / publish (push) Successful in 27s
2026-10-30 17:08:00 +08:00
xiaowang 7b9a5e4d1c 修复Salon注册预约客户流程 2026-10-30 15:13:38 +08:00
xiaowang 53b6fcaa11 回溯点:保存注册预约客户流程修复进度 2026-10-30 13:02:38 +08:00
xiaowang 7b40ee1650 Salon美甲师注册申请关联微信账号
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
2026-10-30 03:46:24 +08:00
xiaowang 5a787a93f3 回溯点:保存美甲师账号关联改造进度 2026-10-30 02:03:49 +08:00
xiaowang eb1a41bfd1 规划页并排展示待分配预约 2026-10-29 21:01:01 +08:00
xiaowang 6697b7e193 对齐规划日视图时间刻度与横线 2026-10-29 18:35:02 +08:00
xiaowang 369f58d24e 保存客户资料与员工排班改造阶段成果 2026-10-29 18:32:45 +08:00
xiaowang 762be0d907 保存客户与员工排班改造阶段成果 2026-10-29 17:36:42 +08:00
xiaowang b3a8c7e01c 保存客户与美甲师表单改造检查点 2026-10-29 17:02:57 +08:00
xiaowang bb3d00c51e 保留预约暂不分配美甲师状态 2026-10-29 15:34:38 +08:00
xiaowang 6a278616a8 完善预约待分配状态与月历工具栏布局 2026-10-29 15:07:38 +08:00
xiaowang 48050fb985 将月历显示控件改为左对齐 2026-10-29 14:49:31 +08:00
xiaowang 47d8cf555b 对齐月历显示控制项 2026-10-29 14:43:40 +08:00
xiaowang f6b8f9b72a 调整预约款式图片排列 2026-10-29 14:36:54 +08:00
xiaowang 8f8f89e3b7 修复本地上传图片预览 2026-10-29 14:28:55 +08:00
xiaowang 5793bf2390 保存款式录入页面微调 2026-10-29 11:42:26 +08:00
xiaowang 976ca68687 优化预约款式录入表单 2026-10-28 17:55:42 +08:00
xiaowang 6fbcf9896e 提交当前工作区改动作为页面微调回溯点 2026-10-28 15:51:02 +08:00
xiaowang 6fb8ffd067 将门店有效期展示移至店铺设置 2026-10-27 17:46:40 +08:00
xiaowang ba118c514a 修复小程序门店有效期展示 2026-10-27 16:59:27 +08:00
xiaowang cf789b90b2 修复门店默认经营有效期为空 2026-10-27 15:46:43 +08:00
xiaowang d10161a583 修复小程序后台路由误判 2026-10-27 11:50:18 +08:00
xiaowang d24a6ac5b8 修复开发审核默认通过并展示全部注册记录 2026-10-27 09:25:32 +08:00
xiaowang 44dda21976 修复注册审核记录不可见问题 2026-10-26 23:58:51 +08:00
xiaowang 50af9b3fb0 后台地图配置添加Key获取链接 2026-10-26 22:11:03 +08:00
xiaowang fd9ff73c00 feat: 增加店长审核模式与门店经营有效期 2026-10-26 21:12:50 +08:00
xiaowang 0151367333 新增店长审核与门店有效期设计 2026-10-26 15:54:32 +08:00
xiaowang 433853c6a7 重构Salon后台七页紧凑操作台样式 2026-10-26 12:25:14 +08:00
xiaowang e4124d1e37 修复Salon Core启动缺失Mapper 2026-10-26 11:10:14 +08:00
xiaowang 525882f3c2 优化Salon后台侧边栏视觉 2026-10-26 10:42:52 +08:00
xiaowang b8327146cb 重构Salon后台单管理员与经营驾驶舱 2026-10-26 01:19:23 +08:00
xiaowang 17cf16db36 统一后台页面为全宽布局 2026-10-25 21:16:01 +08:00
xiaowang ed97bc0591 调整后台系统设置页为全宽布局 2026-10-25 20:53:58 +08:00
xiaowang 76917d92ad 重构Salon后台系统设置并整合个人账号信息 2026-10-25 20:34:15 +08:00
xiaowang c1b282d465 新增后台系统设置重构设计文档 2026-10-25 19:41:07 +08:00
xiaowang 9395d2781b 修复Salon V5迁移排序规则冲突 2026-10-25 13:48:24 +08:00
xiaowang 9a13f20691 接入Salon对外内容审核与发布门禁 2026-10-25 05:58:35 +08:00
xiaowang ed3daee8e5 补充Salon Flyway迁移管理规则 2026-10-24 15:31:19 +08:00
xiaowang 38caec77af 补充Flyway与MySQL版本兼容说明 2026-10-23 11:20:18 +08:00
xiaowang 2e2548d68f 更新Git服务域名配置
自动发布开发环境 Nacos 配置 / publish (push) Successful in 31s
2026-10-23 10:34:17 +08:00
xiaowang a923702578 接入Salon Flyway空库迁移并校验自动发布包 2026-10-22 18:29:57 +08:00
xiaowang 7cca502a98 修复Salon Core自动填充Bean冲突
自动发布开发环境 Nacos 配置 / publish (push) Successful in 35s
2026-10-22 11:08:52 +08:00
xiaowang da1f2d2cba 完成Salon小程序合规整改 2026-10-22 00:27:12 +08:00
xiaowang 1120f9d5a9 优化协议未勾选提示弹窗 2026-10-21 09:47:47 +08:00
xiaowang 6e9ad54e94 支持预约款式多图录入 2026-10-21 02:36:00 +08:00
xiaowang 9925c7f83b 对齐历史补录款式弹窗 2026-10-21 00:55:51 +08:00
xiaowang 8d3f092084 对齐历史补单页面样式 2026-10-20 18:42:27 +08:00
xiaowang 68533738e0 提交 Salon 小程序现有调整 2026-10-20 18:02:49 +08:00
xiaowang 527754af02 统一 Salon 全端薄荷绿主题 2026-10-20 17:54:09 +08:00
xiaowang 274c6af30b 对齐新增预约页面演示稿设计 2026-10-20 15:50:29 +08:00
xiaowang c952a913e8 优化预约表单并支持散客预约 2026-10-20 13:29:55 +08:00
xiaowang 4a7bd90088 优化预约客户输入与唯一性校验 2026-10-16 17:33:58 +08:00
xiaowang 3d18a1972b 新增预约客户输入与选择交互设计 2026-10-16 16:25:03 +08:00
xiaowang 94f3f3a4fa 整理运行发布配置说明
自动发布开发环境 Nacos 配置 / publish (push) Successful in 26s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-16 15:25:37 +08:00
1066 changed files with 152077 additions and 34826 deletions
+49
View File
@@ -0,0 +1,49 @@
---
name: jayu-api
description: JayuCloud 接口与权限规则:Gateway 路由前缀(/api、/api/admin、/internal)、白名单与 JWT 门禁、小程序与管理端基址差异、脱敏与授权取数出口、接口变更检查清单。用于新增/修改后端接口或前后端联调契约时;通用 API 设计方法用全局 $api-design
---
# JayuCloud 接口规则
本项目接口变更最常见的事故是**路由前缀与门禁错配**(管理接口暴露、小程序被误拦)。新增或修改接口必须按本技能核对。
## 路由与门禁基线
| 前缀 | 用途 | 门禁 |
|------|------|------|
| `/api/**` | 业务接口(小程序与前端业务路由) | Gateway JWT 初筛 + 白名单 |
| `/api/admin/**` | 管理端接口 | 管理员门禁(Core 按 URL 前缀判断) |
| `/internal/**` | 服务间内部接口 | 仅限内部调用,禁止暴露到公网路由 |
关键事实:
- Salon Core 的管理员门禁按 `/admin/**` URL 前缀判断:**小程序绝不能复用 `/api/admin` 基址**,否则店长/员工业务会被误拒;小程序用 `/api` 业务路由,需要时由 Core 提供非 `/admin` 路由别名。
- 给小程序提供别名时不得整控制器映射:只映射实际需要的端点(例如对象存储只映射上传端点,不映射列表/更新/删除)。
- 生产小程序请求走 `https://yunail.art/api/admin`(管理师小程序)与 `/api`(用户端);本地开发用 `utils/config.local.js`(不入 Git)。
- 匿名白名单:逐个端点枚举,禁止 `/wechat-mini/**` 这类宽泛前缀——后续新增认证端点会被静默暴露。白名单需同时核对服务拦截器与 Gateway 各份配置。
## 新增接口检查清单
1. 确定归属端与前缀(对照上表);拿不准时先看同域现有接口。
2. 认证与授权:匿名还是登录?管理端权限码?数据属主(门店作用域)校验写在 Service 层。
3. 请求/响应:统一 `Result<T>` 包装;参数校验注解;错误语义与现有错误码一致。
4. 隐私字段:默认脱敏返回;需要明文时走独立授权端点(一次一取,按门店/订单上下文授权),并记录审计。
5. 幂等与并发:写接口明确重复提交语义;金额/配额操作原子化。
6. 前端/小程序同步:`src/api/` 或 `api/` 封装、免登录路径、请求基址是否需要同步修改。
7. Gateway 白名单与路由是否需要同步(Nacos `gateway.yaml`)。
8. 涉及 SQL 时转 $jayu-database;涉及配置时转 $jayu-release。
## 联调约定
- 前端开发代理:`/admin/api` 与 `/api` → `VITE_DEV_PROXY_TARGET`(vite.config.ts)。
- 小程序:`utils/request.js` 统一封装;401 处理全局唯一,清会话要彻底(含 `wx.uploadFile` 路径)。
- 大数 ID:雪花 ID 传前端按字符串处理,避免 `JSON.parse` 精度丢失。
## 安全边界
- 不新增绕过门禁的「临时匿名接口」;确有需要必须逐个列出理由并提示安全评审。
- 不在接口返回中携带密钥、内部堆栈、完整隐私字段。
## 验收标准
- 清单 8 项逐一给出结论(含「不涉及」);前缀与门禁选择有依据;联调端同步修改已列出。
+59
View File
@@ -0,0 +1,59 @@
---
name: jayu-database
description: JayuCloud 数据库与迁移纪律:Flyway 版本文件规则(中文命名、已执行不可改、向前兼容补偿)、空库初始化基线、实体与迁移同步清单、MySQL 已知坑。用于新增/修改表结构、字段、索引或写 SQL 时;通用数据库设计方法用全局 $database-design
---
# JayuCloud 数据库纪律
本项目数据库变更是高危操作:DEV/SIT/PROD 由 Core 启动时 Flyway 自动执行,**没有人工补救窗口**。任何结构改动必须按本技能执行。
## 硬性规则(不可违反)
1. 结构变更只走 Flyway 版本文件:
- Salon:`JC-Salon-Core/src/main/resources/db/migration/V{n}__中文功能说明_YYYYMMDD.sql`
- ArtList:`JC-ArtList-Core/src/main/resources/db/migration/` 同规则
- 版本号取当前目录最大版本号 +1;文件名中文体现功能与日期;内容必须完整可执行。
2. 已在任一环境执行过的迁移文件**不得修改或删除**;撤销/修正必须新增向前兼容的补偿迁移。禁止 Flyway `clean`、自动 baseline、重跑初始化 SQL。
3. 空库初始化仅用 `docs/scripts/sql/init/jayucloud-salon.sql` / `jayucloud-artlist.sql`(0.0.1 基线);只有负责人明确要求重整基线时才把变更合并进初始化 SQL。
4. 生产已部署库升级不直接执行初始化 SQL,必须单独制定迁移方案。
5. Gitea 工作流不得直连数据库或绕过 Flyway;合并 SIT 前先在 DEV 验证迁移。
## 工作流程
### 1. 设计
- 先读现有表结构(初始化 SQL + 已有版本文件)与对应实体,遵循既有命名/主键/字符集约定。
- 字段类型注意:金额用 DECIMAL;时间遵循现有约定;枚举落库策略与现有一致。
- 索引从实际查询出发;唯一约束必须显式建唯一索引。
### 2. 实体与迁移同步清单(逐项核对)
- [ ] 实体类字段与 SQL 列一一对应(`@TableName`/`@TableField`)。
- [ ] 新 Mapper 包已加入 `MyBatisPlusConfig` 的 `@MapperScan` 清单(编译过≠启动过)。
- [ ] 自动填充逻辑合并进现有 `MetaObjectHandler`(只接受单例)。
- [ ] 所有插入入口都覆盖新字段(静态搜索该实体的全部保存入口)。
- [ ] 存量数据需要回填时,在同一版本文件或后续版本中写幂等回填。
- [ ] 历史迁移中不得夹带本次之外的变更。
### 3. 已知坑(写 SQL 前对照)
- 排序规则冲突:`utf8mb4_0900_ai_ci` 与旧列 `utf8mb4_unicode_ci` 混用会报 1267;跨 collation 比较显式 `CONVERT(... USING utf8mb4) COLLATE utf8mb4_unicode_ci`。
- MySQL 迁移失败不回滚已执行 DDL:可重试迁移要先检查字段/索引是否已存在(幂等)。
- `flyway repair` 只清失败历史记录,不回滚结构;独立调用 repair 必须显式设置完整 `locations`,否则可能误删历史。
- 整理/合并初始化 SQL 时检查脚本尾部 DROP 语句,别把运行必需表删掉。
- 雪花 ID:MyBatis-Plus `ASSIGN_ID` 在应用层分配,表定义可能仍是 `AUTO_INCREMENT`,判断主键策略要三处核对(注解/生成策略/SQL)。
- 无斜杠的 `test/` gitignore 规则会忽略任意层级的 test 目录,新增测试文件用 `git check-ignore -v` 确认。
### 4. 验证与交付
- 能在临时库执行就实际执行验证;不能执行时记录阻塞原因。
- 任务说明中写明:新增的版本文件路径、影响的表、是否需要回填、DEV 验证结果。
## 安全边界
- 不对任何真实环境数据库直接执行 DDL/DML;执行由 Core 启动的 Flyway 完成。
- 不在 SQL 中写入真实客户数据;种子数据只保留运行必需项(平台管理员 `xiaowang`、权限、协议、系统参数等)。
## 验收标准
- 版本文件命名与位置合规、可独立执行;实体与列一致;清单全部勾选;任务记录包含验证结论。
+54
View File
@@ -0,0 +1,54 @@
---
name: jayu-devflow
description: JayuCloud 开发与验证流程:各模块构建命令(Maven/npm/node 语法检查)、启动烟测要求、提交前检查(GitNexus detect_changes、中文提交)、常见陷阱清单。用于在本仓库写代码、构建、测试、提交时;TDD 方法论用全局 $test-driven-development,调试方法用 $systematic-debugging
---
# JayuCloud 开发流程
## 构建与验证命令(按改动范围选择)
| 改动范围 | 验证命令 | 说明 |
|----------|----------|------|
| Salon 后端 | `mvn -f JC-Salon-Core/pom.xml -DskipTests compile`(测试:`... test`) | 非聚合工程,必须 `-f` 指定模块;本机 Maven:`D:\software\apache-maven-3.9.12\bin\mvn.cmd` |
| ArtList 后端 | `mvn -f JC-ArtList-Core/pom.xml -DskipTests compile` | 同上 |
| Gateway | `mvn -f JC-Salon-Gateway/pom.xml -DskipTests compile`(ArtList 同理) | |
| 前端 | `JC-Salon-Frontend` / `JC-ArtList-Frontend` 下 `npm run build` | 开发 `npm run dev` |
| 小程序 | `node --check <改动文件>` 语法检查 | 有条件时微信开发者工具冒烟 |
| SQL | 临时库执行或记录阻塞原因 | 见 $jayu-database |
**升级规则**:涉及 Bean 装配、事务、拦截器、`@MapperScan`、自动填充的改动,编译通过后必须做一次 Core 启动烟测——编译通过不等于能启动。
## 开发节奏
1. 动手前:`git status` 确认工作区;有他人未提交改动时先按项目规则处理(中文回溯提交)。
2. 修改符号前:GitNexus impact 分析(AGENTS.md 文首规则);业务域不熟时先读 $jayu-domain。
3. 实施:遵循模块分层与命名约定;接口改动走 $jayu-api 清单;SQL 改动走 $jayu-database。
4. 验证:按上表执行对应命令;测试遵循红绿纪律,Mock 参数全字面量或全 matcher。
5. 提交前:GitNexus `detect_changes`(失败时记录原因,用 `git diff` + 测试结果兜底);只暂存本任务文件。
6. 提交:中文提交信息;任务记录写明新增/调整的版本化文件(SQL/配置说明)。
## 提交与分支纪律
- 每次任务完成后整理相关改动创建 git 提交,提交信息必须中文。
- 只暂存和提交本次任务涉及的文件,保留其他并行改动。
- 注意 `.gitignore` 陷阱:无斜杠的 `test/` 会忽略任意层级 test 目录,新增测试用 `git check-ignore -v` 确认,必要时 `git add -f`。
## 常见陷阱(改前对照,详见 references/pitfalls.md)
1. 编译过 ≠ 启动过(扫描清单、Bean 冲突在启动期暴露)。
2. 事务自调用失效;事务内远程调用不可回滚。
3. 多构造器时注入构造器要显式 `@Autowired`(Spring Boot 2.x)。
4. 共享基类字段(软删除等)并非所有实体都有,查询前先核对继承链。
5. 配置覆盖链:`secret.yaml`/环境变量可能覆盖 `infra.yaml` 与本地文件。
6. 旧 class 残留:移除组件后 clean 构建再验证。
7. 雪花 ID 传 JS 前端的精度问题(字符串传输)。
8. 小程序 401 清会话不彻底导致反复跳登录。
## 安全边界
- 不在本地验证中连接生产数据库/生产 Nacos;本地联调用 dev 环境或本机中间件。
- 验证失败如实报告,不以「应该没问题」代替证据(全局 $verification-before-completion 约束同样适用)。
## 验收标准
- 对应范围的验证命令已实际执行且输出通过;提交信息中文、范围干净;任务记录含版本化文件清单。
@@ -0,0 +1,43 @@
# JayuCloud 常见陷阱清单
来源:历史任务教训沉淀(全局 error-memory 与本项目复盘),仅保留与本项目技术栈相关的通用条目。
## Spring / MyBatis-Plus
- `MyBatisPlusConfig` 使用显式 `@MapperScan` 包清单:新增 `@Mapper` 模块包必须同步加入,否则编译通过但启动缺 Bean。
- MyBatis Mapper statement ID = namespace + 方法名(无参数类型):同一 Mapper 不能重载同名 SQL 方法,否则一条注解映射被忽略。
- MyBatis-Plus 自动填充只接受单个 `MetaObjectHandler`:新增填充逻辑合并进同一处理器;移除旧组件后 clean 构建,防止旧 class 被扫描。
- MyBatis lambda 查询共享基类字段(如 `isDelete`)前,确认具体实体继承链上确实有该字段。
- Spring Bean 多构造器时,注入构造器显式 `@Autowired`;用一次真实容器启动烟测确认。
- Mockito 验证不混用字面量与 `any()`,参数要么全字面量要么全 matcher。
- 事务:自调用不走代理;事务内不做远程调用/发消息等不可回滚操作。
## 配置与环境
- Nacos 配置写入成功后集群读回可能短暂落后:发布/回退都要做有限重试 + 内容摘要校验,失败要 fail closed。
- 排查配置问题不能只看单一文件:后加载的 `secret.yaml`、systemd `EnvironmentFile`、环境变量都可能覆盖。
- 本地 `application.yaml`/`bootstrap.yaml` 只放 Nacos 引导参数,运行配置改 Nacos 并同步 `nacos/` 仓库副本与说明文档。
## 前端 / 小程序
- 小程序不要复用 `/api/admin` 基址(管理门禁按前缀误拒业务);别名只映射需要的端点。
- 雪花 `Long` ID 经 `JSON.parse` 丢精度:前端回传按字符串保留,补回归测试。
- 上传到私有对象存储后不要直接拿响应 `fileUrl` 做预览:可能是私有桶/内网地址;先用本地临时路径预览,以服务端文件 ID 提交。
- 对象存储 URL 解析必须按环境配置处理 MinIO 内网端点、公共端点与 `oss://` 引用;签名失败不得把私有地址原样返回。
- 401 处理:清会话要覆盖 `wx.request` 与 `wx.uploadFile` 全部路径,防重状态保持到新登录成功,避免残留旧登录态反复跳登录。
- 提供 HTML demo 做参照时,实现前完整检查其 HTML/CSS/交互脚本再映射组件,不能只按截图复刻。
## 数据库 / 迁移
- 新增必需业务字段:静态搜索实体所有插入入口逐一补齐 + 幂等回填存量空值。
- 排序规则冲突(`utf8mb4_0900_ai_ci` vs `utf8mb4_unicode_ci`):跨 collation 比较显式 `CONVERT ... COLLATE`。
- MySQL 迁移失败不回滚已执行 DDL:可重试迁移先查字段/索引是否已存在。
- 独立调用 Flyway `repair` 必须显式完整 `locations`,执行后立即检查 `flyway_schema_history`。
- 整理初始化 SQL 时核对尾部 DROP 与实体表清单,防止误删运行必需表。
- 注册/申请类「取最新记录」查询:按创建时间排序后还要按雪花 ID 倒序,避免同秒提交取旧。
## 工具链
- 本机 `node`/`mvn` 可能不在 PATH:Node 在 `D:\software\nodejs`(PowerShell 用 `npm.cmd`/`npx.cmd`),Maven 在 `D:\software\apache-maven-3.9.12\bin\mvn.cmd`。
- GitNexus 特定版本在本机分析可能失败,优先用项目 `.gitnexus/run.cjs analyze --index-only` 或可用版本。
- GitNexus 对 Vue/Java 同名局部符号可能跨语言误关联:critical 风险提示先核对实际引用与构建结果再决策。
+42
View File
@@ -0,0 +1,42 @@
---
name: jayu-domain
description: JayuCloud 项目领域知识:Salon 店务与 ArtList 设计师两条产品线的模块地图、核心业务流程(预约/排班/订单/注册审核/协议/拨号/内容审核)、角色权限模型。用于理解或修改本项目业务功能前;通用需求分析方法用全局 $requirements-analysis
---
# JayuCloud 领域知识
JayuCloud 是双产品线仓库:**Salon(店务/指尖管理师)** 与 **ArtList(指尖设计师)**。修改业务代码前先读本技能与 [references/module-map.md](references/module-map.md),确认改动落在哪个业务域、影响哪些端。
## 产品线速览
| 产品线 | 服务对象 | 端 | 后端 |
|--------|----------|----|------|
| Salon | 美甲门店(平台管理员/店长/美甲师) | 管理端 Vue + 指尖管理师小程序 | JC-Salon-Core / JC-Salon-Gateway |
| ArtList | C 端用户 + 平台运营 | 用户端/管理端 Vue + 用户小程序 | JC-ArtList-Core / JC-ArtList-Gateway |
## 核心业务流程(改前必查上下游)
1. **预约与排班(Salon)**:门店每周营业排班 → 美甲师可约时段 → 客户预约(散客支持拨号联系)→ 订单履约。改动排班/预约时核对 `planning`、`order`、`shop` 三域。
2. **订单与收款**:下单 → 状态流转 → 收款(线上/线下收款登记)→ 完成。订单完成强制校验收款状态;补单创建即 PAID。
3. **注册与审核**:门店/美甲师注册申请 → 店长审核模式 → 门店经营有效期;驳回重申保留历史版本并新建申请。
4. **内容审核与协议**:对外内容审核(图片/作品)、协议版本管理、用户同意状态拦截(微信端 4510 流程)。
5. **隐私与拨号**:手机号/账号全链路加密存储(AES-GCM + hash 查询),所有接口默认脱敏返回;明文一次一取,走独立授权端点(按门店与订单上下文授权)。
6. **文件体系**:上传按 `MINIO → QINIU_KODO → ALIYUN_OSS` 优先级补副本,读取按配置的渠道优先级生成签名地址;历史数据可能存 MinIO 内网端点或 `oss://` 引用,统一 URL 工具按环境解析。
7. **ArtList 电商链路**:浏览 → 购物车 → 下单 → 评价/改派 → VIP/优惠券;订单镜像与 Salon 侧存在同步契约(事件/状态映射)。
## 角色与权限
- 角色:平台管理员(`xiaowang`)、店长、美甲师、普通用户 + 门店自定义角色。
- 权限码裁剪菜单与接口;数据属主校验(门店作用域)在 Service 层;管理端走 `/api/admin/**` 门禁。
- 新增权限/菜单种子后必须授权给平台管理员。
## 使用要求
- 修改业务功能前:先定位业务域(module-map)→ 按 AGENTS.md 要求做 GitNexus impact → 再动手。
- 涉及流程 1-7 的改动,完成后在任务说明中写明对上下游的影响。
- 本技能只提供项目知识,不替代开发流程技能($jayu-devflow)与数据库纪律($jayu-database)。
## 安全边界
- 不输出、不记录任何真实客户手机号/账号明文;示例一律用占位符。
- 隐私字段相关改动必须保持「默认脱敏、授权取明文」的基线,不得新开完整号码出口。
@@ -0,0 +1,50 @@
# JayuCloud 模块地图
> 依据 2026-11-05 源码目录核实;如有出入以源码为准。
## 后端业务域(Core `modules/`)
| 域 | Salon | ArtList | 职责 |
|----|:---:|:---:|------|
| auth | ✓ | ✓ | 登录、令牌、会话(微信登录/账号登录) |
| user | ✓ | ✓ | 用户资料、客户管理、隐私字段加密与脱敏出口 |
| shop | ✓ | ✓ | 门店/店铺、营业设置、有效期、主题 |
| artist | ✓ | ✓ | 美甲师/艺术家资料、注册申请关联 |
| product | ✓ | ✓ | 作品/服务项、分类标签、价格与时长 |
| order | ✓ | ✓ | 订单状态机、收款登记、完成校验 |
| payment | ✓ | ✓ | 支付/退款集成 |
| planning | ✓ | ✓ | 排班、预约占用、规划日历 |
| marketing | ✓ | ✓ | 优惠券、营销活动、VIP |
| message | ✓ | ✓ | 系统消息、订阅消息、跳转与弹窗 |
| content | ✓ | ✓ | 内容审核(图片/作品/对外文案) |
| file | ✓ | ✓ | 上传编排、对象存储三副本、签名地址 |
| integration | ✓ | ✓ | 第三方集成(微信审核回调、内容审核、短信等) |
| security | ✓ | ✓ | 审计日志、安全接入配置 |
| system | ✓ | ✓ | 系统参数、协议版本、诊断 |
| privacy | ✓ | — | 隐私政策、脱敏策略、拨号取号授权 |
| registration | ✓ | — | 门店/员工注册审核流 |
| manager | ✓ | — | 店长/管理端专属能力 |
| inventory | ✓ | — | 库存耗材 |
| analytics | ✓ | — | 经营分析、绩效统计 |
ArtList 已清理 inventory/manager/analytics/planning 实现等(保留订单容量校验所需依赖);新增 ArtList 功能前先确认该域仍存在。
## 端侧入口
| 端 | 页面/视图位置 | 请求封装 | 登录态 |
|----|--------------|----------|--------|
| JC-Salon-Frontend | `src/views/` | `src/api/*.ts` | Axios 拦截器 |
| JC-ArtList-Frontend | `src/views/` | `src/api/*.ts` | Axios 拦截器 |
| JC-Salon-WeChat | `pages/`(planning/customers/employees/appointment…) | `utils/request.js` | `utils/auth.js` |
| JC-ArtList-WeChat | `pages/`(home/products/cart/orders/vip-center…) | `utils/request.js` | `utils/auth.js` |
## 网关与公共件
- `JC-*-Gateway`:`filter/AuthGlobalFilter`(白名单 + JWT 初筛)、路由配置在 Nacos `gateway.yaml`。
- Core 公共:`common/`(`Result<T>`、DTO/VO 基类)、`config/`(MyBatis-Plus、加密组件、对象存储编排等)。
## 关键横切组件
- 手机号/账号加密:AES-GCM 加密组件 + `*_hash` 查询列;日志脱敏。
- 协议拦截:服务端拦截未同意最新协议用户,微信端 4510 原地同意后重试。
- 对象存储读取渠道优先级:配置项控制,历史数据多端点兼容解析。
+47
View File
@@ -0,0 +1,47 @@
---
name: jayu-release
description: JayuCloud 发布与配置管理:Nacos 配置分层(core/gateway/infra/secret/logging)、dev→sit→prod 晋级流程、Gitea 工作流边界、配置变更说明文档要求、发布回滚纪律。用于修改配置、发布环境、部署脚本或 Nacos 相关任务;线上故障排查用全局 $incident-troubleshooting
---
# JayuCloud 发布与配置管理
配置与发布是本项目的高风险动作:生产配置由 Nacos 管理、发布由 Gitea 工作流驱动、数据库迁移随应用启动自动执行。任何配置/发布改动按本技能执行。
## 配置体系
- 仓库副本:`nacos/namespaces/<environment>/<namespace>/DEFAULT_GROUP/`,environment ∈ dev/sit/prod,namespace ∈ `jayucloud-salon` / `jayucloud-artlist`。
- 每个命名空间五个 dataId:`core.yaml`(业务运行)、`gateway.yaml`(路由与网关)、`infra.yaml`(中间件地址/开关)、`secret.yaml`(敏感配置)、`logging.yaml`。
- 覆盖关系:后加载来源覆盖先加载来源;排查配置问题必须核对全部来源的最终生效值(含 systemd EnvironmentFile 与环境变量)。
- 仓库副本不得包含真实密钥;敏感值只存在于对应环境的 Nacos `secret.yaml`。
- dev 分支推送触发 Gitea 工作流自动发布 dev Nacos 配置(带失败自动回退);发布后有读回校验(SHA256 比对)。
## 发布流程(dev → sit → prod)
1. **先 DEV 验证**:迁移、配置、代码必须在 DEV 验证通过;迁移未过不得合并 SIT。
2. **SIT**:合并后由 SIT 部署流程发布;核对 Nacos 发布快照与读回校验结果。
3. **PROD**:走发布提交 + `自动部署prod环境` 工作流(构建发布包 → 部署脚本 → 记录部署,失败自动回退);生产发布前核对目标环境、备份状态与凭据注入方式,并取得确认。
4. 发布顺序契约:数据库迁移随 Core 启动由 Flyway 执行,变更设计必须向前兼容(先加后删),应用回退不会回滚数据库。
## 配置变更任务要求
1. 修改前先读取现有配置(Nacos 只读查询或仓库副本),备份原配置内容到任务记录。
2. 仓库 `nacos/` 副本与 Nacos 实际内容同步修改;dev 走分支推送自动发布,sit/prod 按既有发布流程。
3. **必须提供中文说明文档**:按「功能+日期」命名(如 `Salon××配置说明_20261105.md`),放在 `docs/scripts/`,写明变更内容、生效环境、验证方式、回退方式。
4. 涉及脚本/配置/SQL 的任务,先读 `docs/scripts/运行与发布配置总说明.md`。
5. 发布后验证:服务日志、Nacos 实例健康、读回校验结果。
## Gitea 工作流边界
- 工作流不得直连数据库、不得绕过 Flyway 执行 SQL。
- 不可绕过的分支保护检查必须由目标分支定义的工作流(`pull_request_target` 类)完成,且不得检出/执行来源分支代码。
- 修改工作流定义属于发布基础设施变更:先说明影响,单独提交。
## 安全边界
- 生产环境动作(发布、Nacos 生产写、生产 SQL)必须先取得明确确认;未授权只读。
- 不在仓库、日志、说明文档中写入密钥/口令/令牌;示例用占位符。
- 回滚优先使用工作流与发布脚本的既有回退机制;数据库问题用补偿迁移,不依赖 clean/baseline。
## 验收标准
- 配置变更有说明文档且命名合规;环境晋级顺序未跳级;发布后验证结果已记录;仓库副本与 Nacos 一致。
+110
View File
@@ -0,0 +1,110 @@
---
name: gitnexus-cli
description: "Use when the user needs to run GitNexus CLI commands like analyze/index a repo, check status, clean the index, generate a wiki, or list indexed repos. Examples: \"Index this repo\", \"Reanalyze the codebase\", \"Generate a wiki\""
---
# GitNexus CLI Commands
Commands below use `node .gitnexus/run.cjs <command>` — the project-local runner `gitnexus analyze` drops next to the index. It auto-selects an available runner at call time (global `gitnexus`, else `pnpm dlx`, else `bunx`, else `npx`), so no package-manager assumption and no global install is required — including on a bun-only machine, which has no npm, npx or pnpm at all.
> **Not analyzed yet, or `node .gitnexus/run.cjs` reports `Cannot find module`** (the gitignored runner is absent — e.g. a fresh clone or `git clean`)? (Re)generate it with `npx gitnexus analyze` from the project root, or `bunx gitnexus@latest analyze` on a bun-only machine. On **npm 11.x**, if `npx` crashes during install (`node.target is null`), install once with `npm i -g gitnexus` (then `gitnexus analyze`), or use `bunx gitnexus@latest analyze`, or `pnpm --allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx gitnexus@latest analyze`. See [#1939](https://github.com/abhigyanpatwari/GitNexus/issues/1939).
## Commands
### analyze — Build or refresh the index
```bash
node .gitnexus/run.cjs analyze
```
Run from the project root. This parses all source files, builds the knowledge graph, writes it to `.gitnexus/`, and generates CLAUDE.md / AGENTS.md context files.
| Flag | Effect |
| -------------- | ---------------------------------------------------------------- |
| `--watch` | Keep a Git repository index current with serialized refreshes |
| `--debounce <ms>` | Watch quiet period before refresh (default: 300 ms) |
| `--force` | Force full re-index even if up to date |
| `--embeddings` | Enable embedding generation for semantic search (off by default) |
| `--drop-embeddings` | Drop existing embeddings on rebuild. By default, an `analyze` without `--embeddings` preserves them. |
| `--pdg` | Build the program-dependence layers used by `explain` and `pdg_query` (taint, CDG, and REACHING_DEF). |
| `--spring-actuator <path>` | Import opt-in Spring Boot Actuator mappings, beans, conditions, configprops, and env snapshots. Forces a full rebuild; unsupported with `--watch`. |
| `--asyncapi-spec <path>` | Read opt-in AsyncAPI 3.x documents (directory or single file) and mint `Destination` nodes from their operations. 2.x is refused, not mapped. Unsupported with `--watch`. |
**When to run:** First time in a project, after major code changes, or when `gitnexus://repo/{name}/context` reports the index is stale. In Claude Code, a PostToolUse hook detects staleness after `git commit` and `git merge` and notifies the agent to run `analyze` — the hook does not run analyze itself, to avoid blocking the agent for up to 120s and risking KuzuDB corruption on timeout.
For Spring runtime enrichment, pass a JSON bundle, one endpoint JSON file, or a directory containing endpoint files. Route evidence is authoritative only when `runtimeConfirmed === true`; `runtimeSource` records provenance and may also accompany `handler-conflict`. Env/configprops values are never persisted.
## Index storage and retention
Default location is `<repo>/.gitnexus/`. Override with environment variables (also documented in README):
| Env | Effect |
| --- | ------ |
| `GITNEXUS_STORAGE_PATH` | One complete external index directory. Wins if both storage vars are set. |
| `GITNEXUS_STORAGE_ROOT` | Absolute root; GitNexus creates an isolated `<repo-basename>-<12-hex>/` slot per repository. |
| `GITNEXUS_CONTENT_RETENTION` | `full` (default) keeps file text; `symbol` keeps snippets; `none` keeps the graph only. |
`list_repos`, `gitnexus://repo/{name}/context`, and HTTP `GET /api/repos` / `GET /api/repo` expose `storagePath`, `contentRetention`, and `sourceAvailable`. HTTP `/api/file` and `/api/grep` return 410 unless retention is `full`. MCP `include_content` may still return symbol spans when retention is `symbol`.
Use `node .gitnexus/run.cjs analyze --watch` for a long-lived local Git repository. It performs an initial analysis, queues scanner-admitted file changes, and retries intact failed batches with bounded backoff. Watch refreshes update only the graph: they skip AGENTS.md / CLAUDE.md injection and standard skill installation, so run a one-shot `analyze` when those generated files need updating. Watch rejects one-shot or context-output flags including `--force`, embedding flags, `--skills`, `--default-branch`, `--skip-agents-md`, `--skip-skills`, `--no-stats`, `--self-commit`, `--index-only`, and `--skip-git`. It never pulls remotes. Scheduled remote clone/pull is a different command: `gitnexus auto-sync`. Bare `gitnexus watch` is reserved and does not start either job. Running MCP and `serve` processes periodically check for a published replacement and reopen it without a restart. MCP checks are throttled to once every five seconds, so a tool call before the next check can briefly use the previous index.
### status — Check index freshness
```bash
node .gitnexus/run.cjs status
```
Shows whether the current repo has a GitNexus index, when it was last updated, and symbol/relationship counts. Use this to check if re-indexing is needed.
### clean — Delete the index
```bash
node .gitnexus/run.cjs clean
```
Deletes the `.gitnexus/` directory and unregisters the repo from the global registry. Use before re-indexing if the index is corrupt or after removing GitNexus from a project.
| Flag | Effect |
| --------- | ------------------------------------------------- |
| `--force` | Skip confirmation prompt |
| `--all` | Clean all indexed repos, not just the current one |
### wiki — Generate documentation from the graph
```bash
node .gitnexus/run.cjs wiki
```
Generates repository documentation from the knowledge graph using an LLM. HTTP providers require an API key (saved to `~/.gitnexus/config.json` on first use). Local CLI providers (`--provider cursor|claude|codex|opencode|grok`) use your existing CLI login.
| Flag | Effect |
| ------------------- | ----------------------------------------- |
| `--force` | Force full regeneration, also required to re-generate an existing wiki in a different language |
| `--provider <name>` | LLM provider: minimax, openai, openrouter, azure, custom, cursor, claude, codex, opencode, or grok (default: minimax). Local CLIs (`cursor`, `claude`, `codex`, `opencode`, `grok`) use your existing CLI login and skip `--api-key`. |
| `--model <model>` | LLM model (default: MiniMax-M3) |
| `--base-url <url>` | LLM API base URL |
| `--api-key <key>` | LLM API key |
| `--concurrency <n>` | Parallel LLM calls (default: 3) |
| `--timeout <seconds>` | LLM request timeout in seconds (default: disabled) |
| `--retries <n>` | Max LLM retry attempts per request (default: 3) |
| `--lang <lang>` | Output language for generated documentation (e.g. english, chinese, spanish, japanese) |
| `--gist` | Publish wiki as a public GitHub Gist |
### list — Show all indexed repos
```bash
node .gitnexus/run.cjs list
```
Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information.
## After Indexing
1. **Read `gitnexus://repo/{name}/context`** to verify the index loaded
2. Use the other GitNexus skills (`exploring`, `debugging`, `impact-analysis`, `refactoring`) for your task
## Troubleshooting
- **"Not inside a git repository"**: Run from a directory inside a git repo
- **Index is stale after re-analyzing**: Wait for the next MCP tool call to reopen the published index; this normally takes no more than five seconds
- **Embeddings slow**: Omit `--embeddings` (it's off by default) or set `OPENAI_API_KEY` for faster API-based embedding
+131
View File
@@ -0,0 +1,131 @@
---
name: gitnexus-debugging
description: "Use when the user is debugging a bug, tracing an error, or asking why something fails. Examples: \"Why is X failing?\", \"Where does this error come from?\", \"Trace this bug\""
---
# Debugging with GitNexus
## When to Use
- "Why is this function failing?"
- "Trace where this error comes from"
- "Who calls this method?"
- "This endpoint returns 500"
- Investigating bugs, errors, or unexpected behavior
## Bind the repository first
A root cause traced in the wrong repository is a wrong root cause.
Call `list_repos {}` before the first tool call. With one indexed repository,
use the examples below as written. With more than one, pass `repo` on every
call: an omitted `repo` normally errors, but under an MCP policy with a
configured default it resolves to that default silently. If you cannot tell
which repository is meant, stop and ask. This matters most for `cypher`, whose
statement carries no in-band hint of which database it ran against.
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
`hasMore` is false before concluding a repository is absent.
A stale index describes the code from before your bug, so refresh before
trusting a trace, and state the repository and index freshness with the
diagnosis.
## Workflow
```
0. list_repos {} → Bind repo
1. query({search_query: "<error or symptom>"}) → Find related execution flows
2. context({name: "<suspect>"}) → See callers/callees/processes
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow
4. cypher({statement: "MATCH path..."}) → Custom traces if needed
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
## Checklist
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] Understand the symptom (error message, unexpected behavior)
- [ ] query for error text or related code
- [ ] Identify the suspect function from returned processes
- [ ] context to see callers and callees
- [ ] Trace execution flow via process resource if applicable
- [ ] cypher for custom call chain traces if needed
- [ ] Read source files to confirm root cause
- [ ] State the repository and index freshness with the diagnosis
```
## Debugging Patterns
| Symptom | GitNexus Approach |
| -------------------- | ---------------------------------------------------------- |
| Error message | `query` for error text → `context` on throw sites |
| Wrong return value | `context` on the function → trace callees for data flow |
| Intermittent failure | `context` → look for external calls, async deps |
| Performance issue | `context` → find symbols with many callers (hot paths) |
| Recent regression | `detect_changes` to see what your changes affect — pass `worktree` for a linked worktree |
| "How does A reach B?" | `trace` between the two symbols — shortest call chain in one call |
## Tools
**query** — find code related to error:
```
query({search_query: "payment validation error", repo: "my-app"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError, PaymentException
```
**context** — full context for a suspect:
```
context({name: "validatePayment", repo: "my-app"})
→ Incoming calls: processCheckout, webhookHandler
→ Outgoing calls: verifyCard, fetchRates (external API!)
→ Processes: CheckoutFlow (step 3/7)
```
**cypher** — custom call chain traces. Pass `repo` alongside the statement; the
Cypher text itself names no repository, so the result is unattributable without
it:
```cypher
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"})
RETURN [n IN nodes(path) | n.name] AS chain
```
**trace** — shortest call chain between two symbols ("how does A reach B?"), one call instead of chaining `context` hops:
```
trace({ from: "processCheckout", to: "fetchRates", repo: "my-app" })
→ status: ok, hopCount: 3
→ hops: processCheckout → validatePayment → verifyCard → fetchRates
→ edges: CALLS (1.0), CALLS (0.95), CALLS (1.0)
```
When no path exists, `trace` reports the furthest reachable node — exactly where the chain breaks (dynamic dispatch, reflection, or an external boundary).
## Example: "Payment endpoint returns 500 intermittently"
```
0. list_repos {}
→ total: 2 (my-app, billing-api) — bind my-app explicitly on every call
1. query({search_query: "payment error handling", repo: "my-app"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError
2. context({name: "validatePayment", repo: "my-app"})
→ Outgoing calls: verifyCard, fetchRates (external API!)
3. READ gitnexus://repo/my-app/process/CheckoutFlow
→ Step 3: validatePayment → calls fetchRates (external)
4. Root cause: fetchRates calls external API without proper timeout
Repository: my-app Index: current
```
With a single indexed repository, step 0 returns `total: 1` and the `repo`
argument drops out of every call above.
+100
View File
@@ -0,0 +1,100 @@
---
name: gitnexus-exploring
description: "Use when the user asks how code works, wants to understand architecture, trace execution flows, or explore unfamiliar parts of the codebase. Examples: \"How does X work?\", \"What calls this function?\", \"Show me the auth flow\""
---
# Exploring Codebases with GitNexus
## When to Use
- "How does authentication work?"
- "What's the project structure?"
- "Show me the main components"
- "Where is the database logic?"
- Understanding code you haven't seen before
## Bind the repository first
Step 1 discovers what is indexed; every call after it must say which of those
it means. With one indexed repository, use the examples below as written. With
more than one, pass `repo` on every call: an omitted `repo` normally errors,
but under an MCP policy with a configured default it resolves to that default
silently. If you cannot tell which repository is meant, stop and ask. Report
the bound repository and index freshness alongside your explanation.
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
`hasMore` is false before concluding a repository is absent.
## Workflow
```
1. list_repos {} or READ gitnexus://repos → Discover indexed repos
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
3. query({search_query: "<what you want to understand>"}) → Find related execution flows
4. context({name: "<symbol>"}) → Deep dive on specific symbol
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow
```
> If step 2 says "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
## Checklist
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] READ gitnexus://repo/{name}/context
- [ ] query for the concept you want to understand
- [ ] Review returned processes (execution flows)
- [ ] context on key symbols for callers/callees
- [ ] READ process resource for full execution traces
- [ ] Read source files for implementation details
- [ ] State the repository and index freshness with the explanation
```
## Resources
| Resource | What you get |
| --------------------------------------- | ------------------------------------------------------- |
| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) |
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores (~300 tokens) |
| `gitnexus://repo/{name}/cluster/{name}` | Area members with file paths (~500 tokens) |
| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) |
## Tools
**query** — find execution flows related to a concept:
```
query({search_query: "payment processing", repo: "my-app"})
→ Processes: CheckoutFlow, RefundFlow, WebhookHandler
→ Symbols grouped by flow with file locations
```
**context** — 360-degree view of a symbol:
```
context({name: "validateUser", repo: "my-app"})
→ Incoming calls: loginHandler, apiMiddleware
→ Outgoing calls: checkToken, getUserById
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3)
```
`repo` is required once more than one repository is indexed, and may be omitted
with a single one.
## Example: "How does payment processing work?"
```
1. list_repos {} → total: 1 (my-app) — bind it
READ gitnexus://repo/my-app/context → 918 symbols, 45 processes
2. query({search_query: "payment processing"})
→ CheckoutFlow: processPayment → validateCard → chargeStripe
→ RefundFlow: initiateRefund → calculateRefund → processRefund
3. context({name: "processPayment"})
→ Incoming: checkoutHandler, webhookHandler
→ Outgoing: validateCard, chargeStripe, saveTransaction
4. Read src/payments/processor.ts for implementation details
5. Answer, noting: Repository my-app, index current
```
Had step 1 returned two repositories, every call above would carry
`repo: "my-app"`.
+138
View File
@@ -0,0 +1,138 @@
---
name: gitnexus-guide
description: "Use when the user asks about GitNexus itself — available tools, how to query the knowledge graph, MCP resources, graph schema, or workflow reference. Examples: \"What GitNexus tools are available?\", \"How do I use GitNexus?\""
---
# GitNexus Guide
Quick reference for all GitNexus MCP tools, resources, and the knowledge graph schema.
## Always Start Here
For any task involving code understanding, debugging, impact analysis, or refactoring:
1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness
2. **Match your task to a skill below** and **read that skill file**
3. **Follow the skill's workflow and checklist**
> If step 1 warns the index is stale, run `node .gitnexus/run.cjs analyze` in the terminal first.
## Skills
| Task | Skill to read |
| -------------------------------------------- | ------------------- |
| Understand architecture / "How does X work?" | `gitnexus-exploring` |
| Blast radius / "What breaks if I change X?" | `gitnexus-impact-analysis` |
| Trace bugs / "Why is X failing?" | `gitnexus-debugging` |
| Rename / extract / split / refactor | `gitnexus-refactoring` |
| Tools, resources, schema reference | `gitnexus-guide` (this file) |
| Index, status, clean, wiki CLI commands | `gitnexus-cli` |
## Tools Reference
| Tool | What it gives you |
| ---------------- | ------------------------------------------------------------------------ |
| `query` | Process-grouped code intelligence — execution flows related to a concept |
| `context` | 360-degree symbol view — categorized refs, processes it participates in |
| `impact` | Symbol blast radius — what breaks at depth 1/2/3 with confidence |
| `trace` | Shortest path between two symbols — "how does A reach B?" in one call |
| `detect_changes` | Git-diff impact — what do your current changes affect |
| `rename` | Multi-file coordinated rename with confidence-tagged edits |
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) |
| `explain` | Persisted taint findings — source→sink data flows (needs `analyze --pdg`) |
| `pdg_query` | Control/data dependence — what gates X (CDG) / where Y flows (REACHING_DEF); needs `analyze --pdg` |
| `check` | Check graph invariants such as circular imports |
| `route_map` | API route map — which components/hooks fetch which endpoints, and the handler files that serve them |
| `shape_check` | Response-shape drift — keys each route returns vs keys its consumers access (flags MISMATCH) |
| `api_impact` | Pre-change report for an API route — consumers, middleware, shape mismatches, risk level |
| `tool_map` | MCP/RPC tool definitions and the files that handle them |
| `group_list` | List configured multi-repo groups, or one group's config |
| `group_sync` | Rebuild a group's Contract Registry (cross-repo HTTP contract links); run after `group.yaml` changes or member re-index |
| `list_repos` | Discover indexed repos (paginated — `limit`/`offset`) |
### Paginating `list_repos`
`list_repos` is paginated so a large registry is not truncated by MCP/LLM token limits. It takes optional `limit` (default **50**, max **200**) and `offset`, and returns:
```jsonc
{
"repositories": [
{ "name": "...", "path": "...", "indexedAt": "...", "lastCommit": "...", "stats": { } }
],
"pagination": {
"total": 437,
"limit": 50,
"offset": 0,
"returned": 50,
"hasMore": true,
"nextOffset": 50
}
}
```
To enumerate **every** repository, keep calling with `offset` set to `pagination.nextOffset` until `hasMore` is `false`:
```text
list_repos {} → repos 1–50, nextOffset 50, hasMore true
list_repos { offset: 50 } → repos 51–100, nextOffset 100, hasMore true
…
list_repos { offset: 400 } → repos 401–437, hasMore false (done)
```
Notes: `offset` ≥ `total` returns an empty page (with `total` still reported). Out-of-range or malformed `limit`/`offset` (non-integer, `limit` outside `[1, 200]`, `offset < 0`) are rejected with a clear error — `limit` above the max is rejected, not silently capped. The order is deterministic (lower-cased name, then path), so paging never skips or duplicates an entry while the registry is unchanged.
### Taint findings (`explain`)
`explain` returns taint findings recorded by `gitnexus analyze --pdg` — intra-procedural `TAINTED` edges plus cross-function `TAINT_PATH` hops where the interprocedural taint phase found a function-level source→sink chain. Each finding includes a sink category (command-injection, code-injection, path-traversal, sql-injection, xss), source/sink lines, and the ordered hop path with the variable carried on each hop.
- `explain {}` — enumerate all findings for the repo (bounded by `limit`, deterministic order)
- `explain { target: "src/vuln.ts" }` — findings in a file (suffix path match accepted)
- `explain { target: "runUserCommand" }` — findings in a function (resolved like `context`; ambiguous names return ranked candidates)
A repo indexed without `--pdg` returns a clear "no taint layer" note. Caveats: closure/callback, property/field, and implicit flows are not modeled, and interprocedural findings are function-level `TAINT_PATH` hops rather than statement-level path proof, so the absence of a finding is **not** proof of safety. `SANITIZES` (sanitizer-kill) edges are queryable via `cypher`.
### Control & data dependence (`pdg_query`)
`pdg_query` reads the control/data-dependence layers `gitnexus analyze --pdg` records (CDG + REACHING_DEF, basic-block granular) — the control/data analog of `explain`. It is **always anchored** (a `target` file path or symbol, resolved like `context`) and has two modes:
- `pdg_query { mode: "controls", target: "..." }` — CDG: "under what condition does X run?". Each edge is a controlling predicate block → dependent block with the branch sense (`'T'`/`'F'`) in `reason`; an edge into an early `return`/`throw` is flagged `guard: true` (guard-clause discovery — the sense depends on the predicate, so don't filter guards by a fixed label).
- `pdg_query { mode: "flows", target: "...", variable?: "..." }` — REACHING_DEF def→use edges within the function; pass `variable` to trace one binding.
A repo indexed without `--pdg` returns a "no PDG layer" note (or "status unknown" when the layer can't be confirmed). Intra-procedural only — cross-function flow is taint's domain (`explain`). The raw CDG/REACHING_DEF edges are also queryable via `cypher`. See the `gitnexus-pdg-query` skill for the full query surface.
### Shortest path between two symbols (`trace`)
`trace` answers "how does A reach B?" in one call — the shortest directed path over `CALLS` (plus `HAS_METHOD`, so a class-rooted trace descends into its methods) instead of chaining 3–8 `context`/`impact` hops by hand.
- `trace { from: "validateUser", to: "executeQuery" }` — shortest path between two symbols.
- Disambiguate common names with `from_uid`/`to_uid` (zero-ambiguity) or `from_file`/`to_file`; an ambiguous name returns ranked candidates.
- `maxDepth` (default 10, max 30) bounds the search; `includeTests` (default false) lets the traversal pass through test-file symbols.
Returns ordered `hops` (each `{ name, filePath, startLine }`) and an aligned `edges[]` of `{ relType, confidence }`, so call hops and containment (`HAS_METHOD`) hops stay distinguishable. When no path exists it reports the **furthest** reachable node (where the chain breaks) and sets `truncated: true` if a traversal cap was hit first. Every result carries a `status`: `ok` / `no_path` / `ambiguous` / `not_found` / `error`.
Cross-repo (experimental): pass `repo: "@groupName"` to trace across a group's member repos — the path may cross **one** `ContractLink` boundary (reported as a `CONTRACT_LINK` hop with the bridged contract in `crossings[]`). Omit `to` entirely to follow `from`'s outgoing HTTP call to whatever provider endpoint it lands on. Groups are configured via `group_list` / `group_sync`.
## Resources Reference
Lightweight reads (~100-500 tokens) for navigation:
| Resource | Content |
| ---------------------------------------------- | ----------------------------------------- |
| `gitnexus://repo/{name}/context` | Stats, staleness check |
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores |
| `gitnexus://repo/{name}/cluster/{clusterName}` | Area members |
| `gitnexus://repo/{name}/processes` | All execution flows |
| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace |
| `gitnexus://repo/{name}/schema` | Graph schema for Cypher |
## Graph Schema
**Nodes:** File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, Route, Tool, plus language-specific types (Struct, Enum, Trait, Impl, Namespace, Module, …) and BasicBlock (`--pdg` indexes only). The full node list lives in `gitnexus://repo/{name}/schema`.
**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, CONTAINS, MEMBER_OF, HAS_METHOD, HAS_PROPERTY, ACCESSES, METHOD_OVERRIDES, METHOD_IMPLEMENTS, STEP_IN_PROCESS, HANDLES_ROUTE, FETCHES, HANDLES_TOOL, ENTRY_POINT_OF, WRAPS, QUERIES, INJECTS, plus `--pdg`-only types (CFG, REACHING_DEF, TAINTED, SANITIZES, TAINT_PATH, CDG — zero rows on a default index).
Read `gitnexus://repo/{name}/schema` before writing Cypher — it is the authoritative schema for the indexed repo.
```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"})
RETURN caller.name, caller.filePath
```
@@ -0,0 +1,167 @@
---
name: gitnexus-impact-analysis
description: "Use when the user wants to know what will break if they change something, or needs safety analysis before editing code. Examples: \"Is it safe to change X?\", \"What depends on this?\", \"What will break?\""
---
# Impact Analysis with GitNexus
## When to Use
- "Is it safe to change this function?"
- "What will break if I modify X?"
- "Show me the blast radius"
- "Who uses this code?"
- Before making non-trivial code changes
- Before committing — to understand what your changes affect
## Bind the repository first
Impact analysis is the gate that authorizes an edit, so it must answer for the
repository you are about to edit.
Call `list_repos {}` before the first tool call. With one indexed repository,
use the examples below as written. With more than one, pass `repo` on every
call: an omitted `repo` normally errors, but under an MCP policy with a
configured default it resolves to that default silently. If you cannot tell
which repository is meant, stop and ask — every result below an ambiguous
identity inherits the ambiguity. `list_repos` is paginated, so page with
`offset: pagination.nextOffset` until `hasMore` is false before concluding a
repository is absent.
`detect_changes` takes `worktree` when your changes are in a linked worktree
the MCP server was not launched from. The server auto-detects a worktree only
when it was launched from inside one; otherwise `git diff` runs in the wrong
checkout and reports zero changed symbols — a false clean check that carries
none of the degradation flags described below. In the CLI fallbacks, `--repo .`
means the current checkout; pass the intended repository path instead when you
are not standing in it.
State the bound identity with your risk report:
```
Repository: <name> (<path>) Worktree: <path> Index: <commit>, <n> behind HEAD
```
## Workflow
```
0. list_repos {} → Bind repo (and worktree)
1. impact({target: "X", direction: "upstream"}) or `node .gitnexus/run.cjs impact "X" --direction upstream --repo .`
2. READ gitnexus://repo/{name}/processes → Check affected execution flows
3. detect_changes({scope: "all"}) or `node .gitnexus/run.cjs detect-changes --scope all --repo .`
4. Assess risk and report to user, echoing repo/worktree/index identity
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
> If `.gitnexus/run.cjs` is missing, replace `node .gitnexus/run.cjs` with `npx gitnexus` in the fallback commands.
## Checklist
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] impact({target, direction: "upstream"}) or CLI fallback to find dependents
- [ ] Review d=1 items first (these WILL BREAK)
- [ ] Check high-confidence (>0.8) dependencies
- [ ] READ processes to check affected execution flows
- [ ] detect_changes({scope: "all"}) or CLI fallback for pre-commit check
- [ ] Confirm the checkout you edited is the checkout that was diffed
- [ ] Assess risk level and report, stating repo/worktree/index identity
```
## Understanding Output
| Depth | Risk Level | Meaning |
| ----- | ---------------- | ------------------------ |
| d=1 | **WILL BREAK** | Direct callers/importers |
| d=2 | LIKELY AFFECTED | Indirect dependencies |
| d=3 | MAY NEED TESTING | Transitive effects |
## Risk Assessment
| Affected | Risk |
| ------------------------------ | -------- |
| <5 symbols, few processes | LOW |
| 5-15 symbols, 2-5 processes | MEDIUM |
| >15 symbols or many processes | HIGH |
| Critical path (auth, payments) | CRITICAL |
| **Zero callers found** | **UNKNOWN** |
`UNKNOWN` is not a low rung on this scale — it means the walk could not answer.
An empty caller set is equally consistent with "genuinely unused" and "the
callers are not resolvable by the index" (plain-object property access, dynamic
dispatch, cross-language calls), so few-callers ⇒ LOW does **not** apply. The
result carries a `riskNote` saying so. Confirm with a text search before
treating the symbol as safe to change or delete.
`risk` is the edit gate: warn on HIGH/CRITICAL and stop on UNKNOWN until the
uncertainty is resolved. Within single-repo mode, compare File and symbol
targets with local `riskSharedAxes` (direct/total only). Within group mode,
compare only group results: their `riskSharedAxes` overlays resolved
cross-repo crossings on that local value. Never use either field to waive the
edit gate. Check `riskScale.unusedAxes` before comparing kinds: MCP File walks
omit process/module axes, while web Graph-RAG expands File targets to in-file
symbols before enrichment.
## Tools
**impact** — the primary tool for symbol blast radius. If MCP is unavailable, use `node .gitnexus/run.cjs impact <symbol> --direction upstream --repo .` instead:
```
impact({
target: "validateUser",
repo: "my-app", // required once >1 repository is indexed
direction: "upstream",
minConfidence: 0.8,
maxDepth: 3
})
→ d=1 (WILL BREAK):
- loginHandler (src/auth/login.ts:42) [CALLS, 100%]
- apiMiddleware (src/api/middleware.ts:15) [CALLS, 100%]
→ d=2 (LIKELY AFFECTED):
- authRouter (src/routes/auth.ts:22) [CALLS, 95%]
```
**detect_changes** — git-diff based impact analysis. If MCP is unavailable, use `node .gitnexus/run.cjs detect-changes --scope all --repo .` instead:
```
detect_changes({scope: "all"})
→ Changed: 5 symbols in 3 files
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
→ Risk: MEDIUM
```
Add `repo` once more than one repository is indexed, and `worktree: "<abs
path>"` when your changes are in a linked worktree the server was not launched
from.
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
listing was capped) means the result is short of the truth, and reads like
`UNKNOWN` above: a zero there means unseen, not unaffected. Re-run it rather
than tick the pre-commit check.
A wrong-worktree zero carries neither flag and is shape-identical to a genuine
clean result, so confirm the checkout you edited is the one that was diffed
before treating an empty change set as a passed check.
## Example: "What breaks if I change validateUser?"
```
0. list_repos {}
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
1. impact({target: "validateUser", repo: "my-app", direction: "upstream"}) or `node .gitnexus/run.cjs impact "validateUser" --direction upstream --repo .`
→ d=1: loginHandler, apiMiddleware (WILL BREAK)
→ d=2: authRouter, sessionManager (LIKELY AFFECTED)
2. READ gitnexus://repo/my-app/processes
→ LoginFlow and TokenRefresh touch validateUser
3. Risk: 2 direct callers, 2 processes = MEDIUM
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
```
With a single indexed repository, step 0 returns `total: 1` and the `repo`
argument drops out of every call above.
@@ -0,0 +1,164 @@
---
name: gitnexus-refactoring
description: "Use when the user wants to rename, extract, split, move, or restructure code safely. Examples: \"Rename this function\", \"Extract this into a module\", \"Refactor this class\", \"Move this to a separate file\""
---
# Refactoring with GitNexus
## When to Use
- "Rename this function safely"
- "Extract this into a module"
- "Split this service"
- "Move this to a new file"
- Any task involving renaming, extracting, splitting, or restructuring code
## Bind the repository first
Refactoring writes to disk. `rename` with `dry_run: false` edits files in
whichever repository was resolved, so binding identity here is a safety gate,
not bookkeeping.
Call `list_repos {}` before the first tool call. With one indexed repository,
use the examples below as written. With more than one, pass `repo` on every
call: an omitted `repo` normally errors, but under an MCP policy with a
configured default it resolves to that default silently. If you cannot tell
which repository is meant, stop and ask. Never run `rename` with
`dry_run: false` until the preview in the same bound repository has been
reviewed — its returned `file_path` values show which checkout is about to be
written, so read them as a confirmation of identity.
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
`hasMore` is false before concluding a repository is absent.
`detect_changes` takes `worktree` when you are editing a linked worktree the
MCP server was not launched from; otherwise `git diff` runs in the wrong
checkout and reports nothing changed, which reads as a verified refactor.
## Workflow
```
0. list_repos {} → Bind repo (and worktree)
1. impact({target: "X", direction: "upstream"}) → Map all dependents
2. query({search_query: "X"}) → Find execution flows involving X
3. context({name: "X"}) → See all incoming/outgoing refs
4. Plan update order: interfaces → implementations → callers → tests
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
## Checklists
### Rename Symbol
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
- [ ] Confirm the previewed file paths are in the bound repository/worktree
- [ ] Review graph edits (high confidence) and text_search edits (review carefully)
- [ ] If satisfied: rename({..., dry_run: false}) — apply edits
- [ ] detect_changes() — verify only expected files changed
- [ ] Run tests for affected processes
```
### Extract Module
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] context({name: target}) — see all incoming/outgoing refs
- [ ] impact({target, direction: "upstream"}) — find all external callers
- [ ] Define new module interface
- [ ] Extract code, update imports
- [ ] detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
### Split Function/Service
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] context({name: target}) — understand all callees
- [ ] Group callees by responsibility
- [ ] impact({target, direction: "upstream"}) — map callers to update
- [ ] Create new functions/services
- [ ] Update callers
- [ ] detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
## Tools
**rename** — automated multi-file rename:
```
rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
→ 12 edits across 8 files
→ 10 graph edits (high confidence), 2 text_search edits (review)
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}]
```
**impact** — map all dependents first:
```
impact({target: "validateUser", repo: "my-app", direction: "upstream"})
→ d=1: loginHandler, apiMiddleware, testUtils
→ Affected Processes: LoginFlow, TokenRefresh
```
**detect_changes** — verify your changes after refactoring:
```
detect_changes({scope: "all"})
→ Changed: 8 files, 12 symbols
→ Affected processes: LoginFlow, TokenRefresh
→ Risk: MEDIUM
```
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
listing was capped) means the result is short of the truth: a short or empty
list is not proof that only the expected files changed. Re-run it rather than
treat the refactor as verified.
A wrong-worktree zero carries neither flag and is indistinguishable from a
clean verification, so confirm the diffed checkout is the one you edited.
**cypher** — custom reference queries:
```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"})
RETURN caller.name, caller.filePath ORDER BY caller.filePath
```
## Risk Rules
| Risk Factor | Mitigation |
| ------------------- | ----------------------------------------- |
| Many callers (>5) | Use rename for automated updates |
| Cross-area refs | Use detect_changes after to verify scope |
| String/dynamic refs | query to find them |
| External/public API | Version and deprecate properly |
| Same name in another indexed repo | Bind `repo`; verify previewed paths before applying |
## Example: Rename `validateUser` to `authenticateUser`
```
0. list_repos {}
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
1. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
→ 12 edits: 10 graph (safe), 2 text_search (review)
→ Files: validator.ts, login.ts, middleware.ts, config.json...
2. Review text_search edits (config.json: dynamic reference!)
3. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: false})
→ Applied 12 edits across 8 files
4. detect_changes({scope: "all", repo: "my-app"})
→ Affected: LoginFlow, TokenRefresh
→ Risk: MEDIUM — run tests for these flows
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
```
With a single indexed repository, step 0 returns `total: 1` and the `repo`
argument drops out of every call above.
+1 -1
View File
@@ -3,7 +3,7 @@ const ref = process.argv[3] || process.env.GITHUB_REF_NAME;
if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs <workflow.yml> <ref>'); if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs <workflow.yml> <ref>');
const token = process.env.GITHUB_TOKEN; const token = process.env.GITHUB_TOKEN;
if (!token) throw new Error('缺少 GITHUB_TOKEN'); if (!token) throw new Error('缺少 GITHUB_TOKEN');
const server = process.env.GITHUB_SERVER_URL || 'http://192.168.5.15:3000'; const server = process.env.GITHUB_SERVER_URL || 'http://wcsrv.top:3000';
const repository = process.env.GITHUB_REPOSITORY || 'xiaowang/JayuCloud'; const repository = process.env.GITHUB_REPOSITORY || 'xiaowang/JayuCloud';
const inputs = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('DISPATCH_INPUT_')).map(([key, value]) => [key.slice('DISPATCH_INPUT_'.length).toLowerCase(), value])); const inputs = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('DISPATCH_INPUT_')).map(([key, value]) => [key.slice('DISPATCH_INPUT_'.length).toLowerCase(), value]));
if (process.env.AUTO_ROLLBACK === 'true') inputs.auto_rollback = 'true'; if (process.env.AUTO_ROLLBACK === 'true') inputs.auto_rollback = 'true';
+25
View File
@@ -0,0 +1,25 @@
import { createHash } from 'node:crypto';
export async function verifyConfigReadback(url, expectedContent, expectExists, options = {}) {
const request = options.request || fetch;
const attempts = options.attempts || 3;
const delayMs = options.delayMs ?? 1000;
const expectedHash = expectExists ? sha256(expectedContent) : null;
for (let attempt = 0; attempt < attempts; attempt += 1) {
const response = await request(url);
const actual = await response.text();
const matches = expectExists
? response.ok && sha256(actual) === expectedHash
: response.status === 404;
if (matches) return true;
if (attempt + 1 < attempts && delayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
return false;
}
function sha256(value) {
return createHash('sha256').update(value ?? '', 'utf8').digest('hex');
}
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { verifyConfigReadback } from './nacos-readback.mjs';
test('retries a stale read until the restored config is visible', async () => {
const responses = [
new Response('old config', { status: 200 }),
new Response('restored config', { status: 200 })
];
let calls = 0;
const verified = await verifyConfigReadback('http://nacos/config', 'restored config', true, {
request: async () => responses[calls++],
attempts: 3,
delayMs: 0
});
assert.equal(verified, true);
assert.equal(calls, 2);
});
test('fails closed when the config does not match after bounded retries', async () => {
let calls = 0;
const verified = await verifyConfigReadback('http://nacos/config', 'restored config', true, {
request: async () => {
calls += 1;
return new Response('different config', { status: 200 });
},
attempts: 3,
delayMs: 0
});
assert.equal(verified, false);
assert.equal(calls, 3);
});
test('confirms deletion only after the config is absent', async () => {
const verified = await verifyConfigReadback('http://nacos/config', null, false, {
request: async () => new Response(null, { status: 404 }),
attempts: 1,
delayMs: 0
});
assert.equal(verified, true);
});
+3 -3
View File
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
import { readFile, readdir, rm } from 'node:fs/promises'; import { readFile, readdir, rm } from 'node:fs/promises';
import { join } from 'node:path'; import { join } from 'node:path';
import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs'; import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
import { verifyConfigReadback } from './nacos-readback.mjs';
const environment = envName(process.env.NACOS_ENVIRONMENT); const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP'; const group = 'DEFAULT_GROUP';
@@ -40,9 +41,8 @@ for (const target of targets) {
? await fetch(`${base}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(target.token)}`, { method: 'POST', body: new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, type: 'yaml', content }) }) ? await fetch(`${base}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(target.token)}`, { method: 'POST', body: new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, type: 'yaml', content }) })
: await fetch(`${base}/nacos/v1/cs/configs?${query}`, { method: 'DELETE' }); : await fetch(`${base}/nacos/v1/cs/configs?${query}`, { method: 'DELETE' });
if (!response.ok || (exists && (await response.text()).trim() !== 'true')) throw new Error(`回退失败:${target.id}/${entry.namespace}/${entry.dataId}`); if (!response.ok || (exists && (await response.text()).trim() !== 'true')) throw new Error(`回退失败:${target.id}/${entry.namespace}/${entry.dataId}`);
const check = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`); const checkUrl = `${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`;
const actual = await check.text(); if (!(await verifyConfigReadback(checkUrl, content, exists))) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`);
if (exists ? (!check.ok || sha256(actual) !== sha256(content)) : check.status !== 404) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`);
} }
} }
} }
@@ -19,7 +19,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: prod RELEASE_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
NACOS_ENVIRONMENT: prod NACOS_ENVIRONMENT: prod
@@ -19,7 +19,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: sit RELEASE_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
NACOS_ENVIRONMENT: sit NACOS_ENVIRONMENT: sit
@@ -37,7 +37,7 @@ jobs:
shell: bash shell: bash
env: env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
run: | run: |
git init . git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
@@ -72,7 +72,7 @@ jobs:
run: node .gitea/scripts/rollback-nacos.mjs run: node .gitea/scripts/rollback-nacos.mjs
- name: 执行 SIT 应用回退 - name: 执行 SIT 应用回退
shell: pwsh shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -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 run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -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.salon.yunail.art
- name: 记录回退后的成功版本 - name: 记录回退后的成功版本
shell: bash shell: bash
run: node .gitea/scripts/record-rollback.mjs run: node .gitea/scripts/record-rollback.mjs
@@ -35,7 +35,7 @@ jobs:
shell: bash shell: bash
env: env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
run: | run: |
git init . git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
@@ -33,13 +33,13 @@ jobs:
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }} AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
steps: steps:
- name: 检出回退脚本 - name: 检出回退脚本
shell: bash shell: bash
env: env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
run: | run: |
git init . git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
@@ -30,13 +30,13 @@ jobs:
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }} AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
steps: steps:
- name: 检出回退脚本 - name: 检出回退脚本
shell: bash shell: bash
env: env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
run: | run: |
git init . git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
@@ -15,7 +15,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
NACOS_ENVIRONMENT: dev NACOS_ENVIRONMENT: dev
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: dev RELEASE_ENVIRONMENT: dev
@@ -15,7 +15,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
NACOS_ENVIRONMENT: prod NACOS_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: prod RELEASE_ENVIRONMENT: prod
@@ -15,7 +15,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
NACOS_ENVIRONMENT: sit NACOS_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: sit RELEASE_ENVIRONMENT: sit
+2 -2
View File
@@ -19,7 +19,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: prod RELEASE_ENVIRONMENT: prod
RELEASE_SHA: ${{ inputs.release_sha || github.sha }} RELEASE_SHA: ${{ inputs.release_sha || github.sha }}
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
@@ -48,7 +48,7 @@ jobs:
- name: 校验 PROD Nacos 发布记录 - name: 校验 PROD Nacos 发布记录
shell: bash shell: bash
run: node .gitea/scripts/assert-nacos-release.mjs run: node .gitea/scripts/assert-nacos-release.mjs
- name: 构建并固化 PROD 发布包 - name: 构建并校验含 Flyway 迁移的 PROD 发布包
shell: pwsh shell: pwsh
env: env:
VITE_API_BASE_URL: https://salon.yunail.art/api VITE_API_BASE_URL: https://salon.yunail.art/api
+5 -5
View File
@@ -19,7 +19,7 @@ jobs:
options: >- options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env: env:
GITHUB_SERVER_URL: http://192.168.5.15:3000 GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: sit RELEASE_ENVIRONMENT: sit
RELEASE_SHA: ${{ inputs.release_sha || github.sha }} RELEASE_SHA: ${{ inputs.release_sha || github.sha }}
RELEASE_STORE_ROOT: /salon-release RELEASE_STORE_ROOT: /salon-release
@@ -45,11 +45,11 @@ jobs:
- name: 校验 SIT Nacos 发布记录 - name: 校验 SIT Nacos 发布记录
shell: bash shell: bash
run: node .gitea/scripts/assert-nacos-release.mjs run: node .gitea/scripts/assert-nacos-release.mjs
- name: 构建 SIT 发布包 - name: 构建并校验含 Flyway 迁移的 SIT 发布包
shell: pwsh shell: pwsh
env: env:
VITE_API_BASE_URL: https://sit.yunail.art/api VITE_API_BASE_URL: https://sit.salon.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api VITE_ADMIN_API_BASE_URL: https://sit.salon.yunail.art/admin/api
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit
- name: 持久化已校验发布包 - name: 持久化已校验发布包
shell: bash shell: bash
@@ -69,7 +69,7 @@ jobs:
printf '[{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},{"Name":"salon-web-sit","Host":"%s","Port":%s,"User":"%s","Purpose":"Salon SIT NGINX","Environment":"sit"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-sit/servers.json" printf '[{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},{"Name":"salon-web-sit","Host":"%s","Port":%s,"User":"%s","Purpose":"Salon SIT NGINX","Environment":"sit"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-sit/servers.json"
- name: 执行 SIT 部署 - name: 执行 SIT 部署
shell: pwsh shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.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 run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.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.salon.yunail.art
- name: 记录成功部署 - name: 记录成功部署
shell: bash shell: bash
run: node .gitea/scripts/record-deploy.mjs run: node .gitea/scripts/record-deploy.mjs
+3 -2
View File
@@ -8,8 +8,9 @@
# Full-regression database backups may contain development user data. # Full-regression database backups may contain development user data.
artifacts/full-regression/*backup*.sql artifacts/full-regression/*backup*.sql
# Local Codex agent skill mirrors; canonical project skills live under .claude/. # Local agent skill mirrors stay ignored; project skills under .agents/skills/ are versioned.
.agents/ .agents/*
!.agents/skills/
# BlueJ files # BlueJ files
*.ctxt *.ctxt
@@ -0,0 +1,49 @@
# Ardot 图标补齐剩余步骤
## Context
用户反馈 Ardot 文件 `https://ardot.tencent.com/file/744106780552731` 中已复刻的 35 个页面(Web 11 页、小程序 24 页)图标缺失,要求用本地 MCP(`mcp_ardot_*`)补齐真实图标,不重建页面、不改页面名、不动布局文案、不删页面、不改仓库、不提交 Git。
已完成部分:
- 品牌 logo 4 页:`3:3`(`7:18`)、`3:8`(`10:40`)、`3:9`(`10:15`)、`35:4`(`35:17`),已用 `upload_images` 应用 `assets/images/app-icon.png` 并删除原文字占位。
- tabBar 4 页:`35:1`(`36:625/630/635/640`)、`35:2`(`38:81/86/91/96`)、`35:11`(`55:117/122/127/132`)、`35:9`(`48:118/123/128/133`),已用 `assets/tabbar/*.png` 替换内层 SVG 容器。
剩余问题:两个页面的缺省头像仍是字母/文字占位,需要替换为 `assets/images/default-user-avatar.png`。
## 执行步骤(均在本地 MCP,只读仓库)
### 1. 定位头像容器(只读)
- 对页面 `3:12`(salon-小程序端-个人信息)用 `batch_read` 搜索 `^管$`,已得 TEXT `15:21`(21×25,x=0,y=2)。再读取其父节点,确认 50×50 或等效头像框 id。
- 对页面 `35:3`(salon-小程序端-新增美甲师)用 `batch_read` 读取整页树(已有 JSONL:`C:\Users\21616\AppData\Local\Temp\.ardot\reads\batch_read-35_3-3987-20261105_175025311.jsonl`),定位 50×50 头像框 id。
### 2. 替换为真实头像
- `upload_images` 将 `e:\code\JayuCloud\JC-Salon-WeChat\assets\images\default-user-avatar.png` 应用到上述两个头像框。
- `batch_edit` 删除字母/文字子节点(`3:12` 的 `15:21`,以及 `35:3` 中对应占位文字),保持外框尺寸、圆角与位置不变。
### 3. Web 端图标核对(只读 + 汇报,不新增页面)
- 用 `batch_read` 抽查 `3:1`(登录)、`3:2`(首页)、`3:7` 等页面的 VECTOR 节点,确认侧栏菜单、header 刷新/审核/待处理、列表操作图标已导入并渲染(记录尺寸与描边)。
- 源码侧 `JC-Salon-Frontend/src/assets` 仅 `vue.svg`,图标全部来自 `@ant-design/icons-vue`;侧栏与登录页品牌标记源码本身是文字「S」,无图片使用 → 在汇报中标注「源码无图片使用,保持近似」。
- 整理「还原 / 近似 / 缺失」三类清单。
### 4. 最终复核
- `fetch_editor_state` 确认 pageList 仍为 35 页(`3:20` 不恢复,`0:1` 不恢复)。
- 抽查补图标页面节点(`3:3`、`3:8`、`3:9`、`35:4`、`35:1`、`35:2`、`35:9`、`35:11`、`3:12`、`35:3`),确认 fills 为 IMAGE。
### 5. 汇报
- 以「图标补齐已完成」开头,给出:
- 小程序端:品牌 logo、tabBar、缺省头像的还原清单与节点 id;
- Web 端:已存在的 Ant Design Vue 图标(近似还原)清单、源码无图片的说明;
- 仍有缺失:上传失败或工具不支持(SVG 不能 `register_assets`,必要时内联)的条目与原因。
## 验证方式
- `batch_read` 返回节点 `fills` 含 `type: "IMAGE"`;
- `fetch_editor_state` 页面数量与名称未变;
- 截图抽查 `capture_screenshot` 对应 pageId 的局部区域(可选)。
## 约束
- 只增补图标节点,不重建页面、不改页面名、不动布局文案;
- 不改仓库文件、不提交 Git、不导出;
- 上传失败贴原始错误并跳过,继续其余页面。
```
@@ -0,0 +1,161 @@
# Ardot 设计稿批次 5 收尾与批次 6 执行计划
## Summary
针对 Ardot 文件 `https://ardot.tencent.com/file/744106780552731`(当前 35 页)继续完成已确认的 8 项优化中剩余部分:
- **批次 5 收尾**:验证 `salon-小程序端-我的`(35:9)本批改动;为 `salon-小程序端-关于系统`(3:3)补「用户协议 / 隐私政策」入口与「版本更新日志」。
- **批次 6**:新增 4 个注册相关页面(`补充资料(店长)`、`补充资料(店员)`、`申请状态(店长)`、`申请状态(店员)`)。
- 全部完成后按用户要求以「任务完成」开头,按「改了什么 / 依据 / 与源码不一致处 / 推断项 / 新增页面 ID 与命名 / 截图验证结论」汇报。
约束:不重建已有页面、不改页面名、不删页;只改内容或新增页面;不改仓库文件、不提交 Git、不导出。
## Current State Analysis
### 已核实(只读读取结果)
**35:9 我的页(48:1)** — 编辑已执行,待截图验证:
- `48:28` 96×23 r11.5,内含 `69:277` 选中胶囊 42×19 #247B63、`69:278`「店长」11px Bold 白、`69:279`「美甲师」11px Regular #71807A;旧「管理端」节点 `48:29` 已删。
- 菜单卡 `48:70/48:113` 高 250,`48:73` 内 5 行 × 49:`48:74` 个人信息 → `48:80` 店铺信息 → `48:86` 账号安全 → `48:92` 订单数据 → `48:110` 关于系统(文案已按顺序改写,文案字体为 Sarasa Bold)。
- 退出登录 `48:114` 357×44 r10 #FBE9E7(r0.984,g0.914,b0.906),y=538;`48:115` 14px Sarasa Semi Bold #B3261E(r0.702,g0.149,b0.118),x=152、y=12。
**3:3 关于系统(7:1)** — 尚未修改:
- `7:1` 390×844,底色 #F5F7F4;`7:2` vertical gap 0 → `7:3` 状态栏 44、`7:8` 导航头 44(返回 18×18 @x16、标题「关于系统」17px SemiBold)、`7:16` 内容区 vertical gap 10 / padding-top 42。
- `7:16` 子节点:`7:17` 品牌卡 366×175(`7:18` logo 58×58 imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`、`7:20`「甲屿手纪」20px Black、`7:22` 描述 12.5px #908865);`7:24` 信息卡 366×112 r12 白底。
- `7:24` → `7:25` vertical,padding 1/1/13/15;行 `7:26`「版本 / 0.0.1」340×43、`7:29`「定位 / 日程 / 客户 / 美甲师 / 我的」340×43;行内 padding 6/6/12/12,标签 14.5px #17211F、值 14.5px #71807A。
**35:4 注册页(40:1)** — 仅含第 1 步「选择工作身份」,第 2/3 步无画板,作为批次 6 的复用样式源:
- 页面 390×844 #F5F7F4;`40:15` 内容层为 `layout:"none"`,子节点全部 ABSOLUTE 定位。
- 品牌头 `40:16`:360.8×47.1 @(15,19),logo 45.8×45.8 r13.5 @(6.5,0.65) 同 imageHash,brand 文案列 156 宽。
- 进度条 `40:24`:360.8×40 @(15,84),三步 40×40 @x0/160/321,圆点 21.8×21.8 r10.9(激活 #247B63 / 未激活 #E0E9E2),连线 108×1 #DCE6DE @y12。
- 卡片 `40:42`:360.8×283.6 @(15,137),r12.5,填充 #FBFDFB(0.984,0.992,0.984),描边 #E7ECE9,标题 17.7px ExtraBold,描述 12px #879792,角色项 58.2 高 r8.3 #F5F7F4 描边 #E7ECE9。
- 主按钮 `40:70`:329.6×43.7 r7.3 #247B63 @(16,221),文字 14.6px Bold 白。
- 页脚注 `40:72`:11px #9AA9A0,居中 x=44。
### 源码依据(只读)
- `JC-Salon-WeChat/pages/register/index.wxml`:
- 进度条三步:选择身份 / 补充资料 / 申请状态。
- 第 2 步店长:`店铺名称*`、`店铺地址(选填)+ 地图选点` + 提示「地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。」;副标题「提交后由平台管理员审核」。
- 第 2 步店员:`选择店铺*`(picker,占位「请选择要加入的店铺」)、`昵称*`(提示「可从微信昵称中选择,也可以手动填写,最多20个字。」)、`头像*`(默认头像 + 「点击选择微信头像」)、notice「审核通过前不会获得门店业务权限」;副标题「提交后由对应店长审核,昵称和头像为必填资料」。
- 第 2 步底部:主按钮「提交审核」+ 文字链「返回上一步」。
- 第 3 步:结果图标(…/✓/!)、标题(申请已提交 / 申请已通过 / 申请未通过)、描述、`当前状态:待审核`、详情行(申请门店、申请身份、[申请昵称]、[申请编号]、提交时间)、主按钮「返回登录」(驳回态为「返回登录并重新申请」)。
- `JC-Salon-WeChat/pages/profile/index.js`:`menus` 顺序为用户协议/隐私政策在第 5/6 位,并入「关于系统」后需在 3:3 提供入口。
- `JC-Salon-WeChat/pages/about/index.wxml`:仅「版本 / 定位」两行,无协议入口、无更新日志 —— 3:3 的两处补充均属「按用户要求新增」,需在汇报中标注与源码不一致。
## Proposed Changes
### 批次 5-A:35:9 我的页截图验证(不改内容)
1. `capture_screenshot(nodeIds:["48:1"])`,核对:
- 身份切换 chip 显示「店长(选中)/ 美甲师」,无溢出、无换行;
- 菜单五项顺序为 个人信息 → 店铺信息 → 账号安全 → 订单数据 → 关于系统,行高一致无重叠;
- 退出登录为低饱和红底按钮,文字居中。
2. `capture_layout({parentId:"48:1", problemsOnly:true})` 复核裁剪/重叠。
3. 如发现渲染问题,仅做最小修正(改宽度/坐标/字号),不改结构。
### 批次 5-B:3:3 关于系统补协议入口与版本更新日志(`batch_edit` 于 `7:1`)
1. 信息卡扩容:
- `U("7:24",{"height":200})`
- `U("7:25",{"height":200})`
2. 新增两行入口(父节点 `7:25`,行样式对齐 `7:26`):
- `I("7:25",{ FRAME 名称「用户协议」340×43, layout:"none" })` → 子项:`TEXT`「用户协议」14.5px #17211F @(6,12);`TEXT`「›」22.9px #B0A79A @(320,10)
- `I("7:25",{ FRAME 名称「隐私政策」340×43, layout:"none" })` → 同上,文字「隐私政策」
3. 新增「版本更新日志」卡片(父节点 `7:16`,插入在 `7:24` 之后,顺序即视觉顺序):
- 卡片 `366×190` r12 白底 `layout:"none"`
- 标题「版本更新日志」15px Bold #17211F @(16,16)
- 条目块(横向:版本胶囊 + 日期,随后三行说明,均 11.5px):
- 版本胶囊 `58×22` r11 #E5F4ED,「0.0.1」11px Bold #247B63 居中;日期「2026-11-05」11.5px #71807A @x=82,y≈4
- 说明行 1「新增补充资料与申请状态设计稿(店长 / 店员)」@y=52
- 说明行 2「我的页支持店长 / 美甲师身份切换」@y=74
- 说明行 3「用户协议与隐私政策入口并入关于系统」@y=96
- 底部说明「后续版本更新将在此处按时间倒序展示」11px #9AA9A0 @y=140
4. 校验内容总高:42 + 175 + 10 + 200 + 10 + 190 = 627 < 800(扣除状态栏与导航头后可用 756),无溢出。
### 批次 6:新增 4 个注册相关页面
**通用构造**(每页一张 390×844 画板,页面底色 #F5F7F4,`layout:"none"` + 子节点 ABSOLUTE):
- 状态栏 44:`9:41`(13px SemiBold #17211F @x28 垂直居中)、`●●●` 与 `▮`(13px SemiBold,#17211F,gap 5,右侧 @x≈332)。
- 品牌头(复用 35:4 `40:16` 几何):logo 45.8×45.8 r13.5 @(21.5,20.3) imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`;右侧文案列 @(77.2,19):主标题「Salon」20px Black #17211F,副标题「用微信身份申请门店工作权限」11.380px #879792。
- 进度条 @(15,84):三步圆点 21.8×21.8 r10.9;未激活 #E0E9E2、已激活 #247B63;完成步数字「✓」7.6px Bold 白,当前步白字「2」或「3」,未开始步 #6B7B74;步名 10px #6B7B74 / 当前步 #247B63 Bold(「选择身份」「补充资料」「申请状态」);连线 108×1 #DCE6DE @y12 @x46 与 @x207。
- 卡片 @(15,137):360.8 宽,r12.5,#FBFDFB 填充 + #E7ECE9 1px 描边。
**1) `salon-小程序端-补充资料(店长)`**
- 进度:第 1 步完成、第 2 步激活、第 3 步未开始。
- 卡片高 352:
- 标题「补充资料」17.7px ExtraBold @(16,19);副标题「提交后由平台管理员审核」12px #879792 @(16,48)
- 字段 1:标签「* 店铺名称」(`*` 6.9px #C0392B + 文案 14px #17211F)@(16,84);输入框 329.6×44 r8 #F5F7F4 描边 #E7ECE9 @(16,106),占位「请输入店铺名称」12px #9AA9A0 @(12,12)
- 字段 2:标签「店铺地址 选填」(「选填」10px #9AA9A0)@(16,166);输入框 238×44 @(16,188) 占位「可手动填写门店地址」;按钮 83.6×44 r8 #E5F4ED @(262,188),文字「地图选点」11.5px Bold #247B63
- 提示「地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。」11px #9AA9A0,宽 329.6 @(16,240),两行
- 主按钮 329.6×43.7 r7.3 #247B63 @(16,278),文字「提交审核」14.6px Bold 白
- 文字链「返回上一步」11.5px #71807A @(y=330) 居中
- 页脚注 11px #9AA9A0 居中:「OpenID 仅用于识别你的微信身份,不会在页面中展示。」
**2) `salon-小程序端-补充资料(店员)`**
- 进度同 1)。
- 卡片高 430:
- 标题「补充资料」@(16,19);副标题「提交后由对应店长审核,昵称和头像为必填资料」@(16,48)
- 字段 1「* 选择店铺」@(16,84);选择行 329.6×44 r8 @(16,106),占位「请选择要加入的店铺」12px #9AA9A0,右箭头「›」22.9px #B0A79A @x≈318
- 字段 2「* 昵称」@(16,166);输入框 329.6×44 @(16,188),占位「点击输入框选择或填写微信昵称」;提示「可从微信昵称中选择,也可以手动填写,最多20个字。」11px #9AA9A0 @(16,240)
- 字段 3「* 头像」@(16,266);头像行 @(16,288):圆形 56×56 r28 默认头像(复用 imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`,若该图为品牌图则改用首字占位「微」#E5F4ED/#247B63),右侧文字「点击选择微信头像」12px #71807A;提示「请选择头像,头像会先上传并完成资料登记,提交时只引用已上传的文件。」11px @(16,350)
- 提示条 329.6×34 r8 #FDF3E7(0.992,0.953,0.906),文字「审核通过前不会获得门店业务权限」11.5px #A9743B @(16,382)
- 主按钮「提交审核」@(16,428)——卡片高需同步扩为 500,避免按钮与文字链越界
- 文字链「返回上一步」11.5px #71807A @y=484 居中
- 页脚注同 1)。
> 说明:头像占位若不使用品牌图,需在汇报中标注为「推断的默认头像占位」。
**3) `salon-小程序端-申请状态(店长)`**
- 进度:第 1、2 步完成、第 3 步激活。
- 卡片高 396:
- 结果图标 72×72 r36 #E5F4ED @(144.4,24),内「…」20px Bold #247B63 居中
- 标题「申请已提交」17.7px ExtraBold 居中 @y=112
- 描述「申请由平台管理员处理,通过后即可使用快捷登录。」12px #879792 居中,宽 300 @(30,144),两行
- 状态行「当前状态:待审核」12.5px #17211F @(16,186),「待审核」#D59A52 Bold
- 详情区 @(16,212):三行 40 高(申请门店「甲屿手纪·望京店」/ 申请身份「店长」/ 提交时间「2026-11-05 14:32」),行内左侧 11.5px #71807A、右侧 11.5px #17211F 右对齐 @x≈250;每行底部 1px #EDEDED
- 主按钮「返回登录」329.6×43.7 @(16,336)
- 页脚注「申请进度会随审核结果更新,可在登录页重新进入查看。」11px #9AA9A0 居中 @y=392(卡片外)
**4) `salon-小程序端-申请状态(店员)`**
- 进度同 3)。
- 卡片高 436:
- 结果图标、标题、描述同 3),描述为「申请由门店店长处理,通过后即可使用快捷登录。」
- 详情四行(申请门店「甲屿手纪·望京店」/ 申请身份「店员」/ 申请昵称「小雨」/ 提交时间「2026-11-05 14:32」),y 起点 212,每行 40
- 主按钮「返回登录」@(16,376)
- 页脚注同 3) @y=432
**页面创建与定位步骤(每页)**:
1. `create_new_page({name:"salon-小程序端-补充资料(店长)"})` 等 4 次,按序创建。
2. `locate_available_space` 取该页可用区(page 级插入前必须调用)。
3. `batch_edit` 在该页插入 390×844 顶层画板,`layout:"none"`,`I(pageId,{...})` 逐节点构建(每批 ≤ 60 行,操作行换行分隔,不用分号)。
4. 数字/中文混排节点显式设置 `fontName:{family:"Sarasa Gothic SC", style:"Semi Bold"}`,避免缺字回退。
## Assumptions & Decisions
| # | 决策 | 理由 |
|---|---|---|
| A1 | 4 个注册页各自独立成页,不复用 35:4 页面 | 用户明确要求「新增页面 ID 与命名」,且命名按「补充资料(店长)」等给出 |
| A2 | 新页沿用 35:4 的品牌头 + 三步进度条,第 2/3 步高亮 | 与源码 `register` 单页三步结构一致,视觉连续 |
| A3 | 不画「已通过 / 已驳回」状态 | 用户只要求「补齐补充资料与申请状态」,默认展示提交后的待审核态;其余状态列入建议清单 |
| A4 | 3:3 版本更新日志内容用 0.0.1 / 2026-11-05 + 三条本次改动说明 | 与仓库 0.0.1 基线一致,且可追溯本次设计稿改动 |
| A5 | 3:3 协议入口以「›」行形式挂在信息卡内,不新增独立页面 | 用户要求「并入关于系统」,不新建协议页 |
| A6 | 申请状态详情中的门店名/昵称/时间为示意文案 | 设计稿无真实数据源,属推断示例 |
| A7 | 若渲染异常只做最小修正(宽/坐标/字号),不改结构、不删页、不改页名 | 用户通用约束 |
## Verification
1. **批次 5-A**:`capture_screenshot(["48:1"])` + `capture_layout({parentId:"48:1",problemsOnly:true})`;确认身份 chip、5 行菜单、红色退出按钮。
2. **批次 5-B**:`capture_screenshot(["7:1"])` + `capture_layout({parentId:"7:1",problemsOnly:true})`;确认 4 行信息卡与版本日志卡不重叠、不越界。
3. **批次 6**:一次性 `capture_screenshot([四个新页画板 id])`(单次配额内);确认 4 页各自 390×844、进度高亮正确、字段与按钮不裁剪。
4. **终检**:`fetch_editor_state` 复核页面总数 39、4 个新页名称唯一且无重复、无页面被改名/删除。
5. **汇报**:以「任务完成」开头,输出 改了什么 / 依据 / 与源码不一致处(日程不做月视图;35:3 手机号必填差异;3:3 协议入口与版本日志为新增;注册页仅覆盖待审核态)/ 推断项(微信登录未关联用户列表、申请状态示例数据、店员头像占位)/ 新增页面 ID 与命名 / 截图验证结论 / 建议清单。
@@ -0,0 +1,66 @@
# Ardot 设计稿优化:批次 3 收尾与批次 4–6 执行计划
## Context
目标文件 `https://ardot.tencent.com/file/744106780552731`(35 页基线),需按用户已确认的 8 项优化逐批落地,每批用 `capture_screenshot` 验证后再进下一批。批次 1(日程周/日视图)与批次 2(客户页、预约详情页)已完成并验证;批次 3 的改派美甲师页栅格对齐与美甲师页折叠按钮/折叠态画板已完成主体编辑,截图验证后只剩 1 个视觉小问题待修。
约束:不重建已有页面、不改已有页面名、不删页;只改内容或新增页面;仅使用本地 Ardot MCP;不改仓库文件、不提交 Git。
## 已完成(供上下文,不再重复)
- 35:1 日程:主画板改「周视图状态」(69:1 周条 + 7 日卡),新增 69:52「日视图状态」;删除浮层 37:43(取消预约),35:8 已有 53:3 同名浮层。
- 35:2 客户:删除「新增」文字按钮,搜索栏满宽,新增 69:167 悬浮加号;新增客户弹窗姓名加红星(69:168)。
- 35:8 预约详情:补「呼叫」按钮(69:170/69:171);修复基线遗留的 193×844 浅绿块与竖排「呼叫」占位;重排卡片高度,六字段栅格恢复可见。
- 35:13 改派美甲师:`61:39` 宽度设为 94,三行内容列统一到 x≈94。
- 35:11 美甲师:删除旧「2 项」(55:34),新增 69:173「列表标题右侧」→ 69:174「2 项」+ 69:175「折叠按钮」+ 69:176「︿」;新增 69:177「美甲师(折叠态)」画板(含状态栏、头部、工具栏、折叠审核卡、3 张美甲师卡、底部导航)。
## 剩余执行计划
### 步骤 0:批次 3 收尾修复
- `U("69:174",{width:30})`:修「2 项」在 20px 宽内换行的问题。
- 用 `capture_layout`(problemsOnly)确认 69:177 无重叠/溢出;不额外消耗截图配额。
### 步骤 1:批次 4 —— 35:3「新增美甲师档案页」
1. 只读读取 35:3 页面结构(主画板 + 浮层组),定位姓名、手机号、微信号/微信登录、专属颜色字段节点与星号节点。
2. 必填收敛:仅「姓名」「专属颜色」加红星(#D9534F,12.5px),其余字段星号删除;与源码 `JC-Salon-WeChat/pages/employee-create` 字段必填关系比对并记录差异。
3. 「微信登录」点击态:在 35:3 浮层组新增浮层画板「浮层:未关联微信用户列表」——底部面板,标题「选择微信用户」+ 说明「仅显示尚未关联门店账号的微信用户」+ 3 条用户行(头像/昵称/最近登录时间/「选择」按钮)+ 空列表态文案。**标注为推断设计,渲染结果需用户确认。**
4. 「专属颜色」点击态:新增浮层「浮层:专属颜色设置」——色板网格(复用设计已有美甲师色 #7BA7C7/#C7A58F/#A7BFA8 + 6 个扩展色)、当前选中预览、取消/确认按钮。
5. 截图验证 35:3 主画板 + 2 个新浮层。
### 步骤 2:批次 5 —— 35:9「我的」与 3:3「关于系统」
1. 读取 35:9 主画板,找到顶部「管理端」标识与菜单列表、退出登录按钮。
2. 身份态:同一画板内把「管理端」替换为「当前身份」切换控件(店长 / 美甲师 两个 chip,店长为选中态),并在下方菜单区同时满足两角色(菜单文案差异不大,采用同页切换,不拆画板);另加一行说明「切换身份仅影响可见菜单」。
3. 菜单顺序调整为:个人信息 → 店铺信息 → 账号安全 → 订单数据 → 关于系统。
4. 「退出登录」改为低饱和红色填充按钮(浅红底 #FBE9E7 + 深红字 #B3261E,保持原尺寸与圆角)。
5. 3:3「关于系统」:新增「用户协议」「隐私政策」两个入口行,新增「版本更新日志」区(版本号 + 日期 + 2–3 条更新说明)。
6. 截图验证 35:9 与 3:3。
### 步骤 3:批次 6 —— 注册相关 4 个新页面
1. 读取 `JC-Salon-WeChat/pages/register` 与 `WorkbenchRegistrationView.vue` 的补充资料、申请状态字段作为内容依据。
2. 用 `create_new_page` 新建 4 页,命名严格为:
- `salon-小程序端-补充资料(店长)`
- `salon-小程序端-补充资料(店员)`
- `salon-小程序端-申请状态(店长)`
- `salon-小程序端-申请状态(店员)`
3. 每页用 `locate_available_space` 后插入 390×844 画板:状态栏、标题、表单/状态卡、说明文案、主按钮,风格沿用既有 token(#247B63 / #F5F7F4 / #17211F)。
4. 截图验证 4 个新页;复核总页数 39、页面名无重复。
### 步骤 4:最终汇报
以「任务完成」开头,按:改了什么 / 依据 / 与源码不一致处(含「日程不做月视图——按用户要求」)/ 推断项(微信登录未关联用户列表)/ 新增页面 ID 与命名 / 截图验证结论 / 建议清单 逐项交付。
## 验证方式
- 每批:`capture_screenshot(nodeIds)` 一次覆盖该批所有改动节点;仅当截图暴露问题且已集中修复后才允许第二次。
- 结构类问题优先 `capture_layout(problemsOnly:true)`,不占用截图配额。
- 全部完成后只读复核页面数量与命名。
## 已知风险与处理
- 更新 `characters` 会把缺失字体重置为 Sarasa Gothic SC Regular,需显式 `U(fontName)` 恢复字重。
- TEXT 不支持 `textAlign`,居中/右对齐需手动 x 定位。
- 新增子级必须指定正确 parentId,避免文字堆叠在父容器顶部(本任务已出现过两次)。
@@ -0,0 +1,84 @@
# ArtList 账号加密与场景化脱敏执行清单
> 按项目规则不新增设计文档;本文件只是 plan 模式的执行清单,实施完成后不为它单独提交。
## 零、版本号自查结论(已核实)
- 查 dev 库 `jayucloud_artlist`:库内没有 `flyway_schema_history`,表数为 0 → **V3 从未在任何环境执行过**。
- 远端 `dev` 已被并行分支先推入 `V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql`(本地 HEAD `80d187d2` 已含);`core.yaml` 为 `out-of-order: false`。
- 因此把工作区里的 `V3__账号加密与账号哈希_20261104.sql` **改名为 `V5__账号加密与账号哈希_20261104.sql`**(V3 文件已删除,V5 未被占用),保证 V1→V2→V4→V5 顺序天然正确,无论 V4 是否已执行都能跑。
- 若后续发现 V3 曾执行过,则恢复 V3 命名且不改文件内容(不得改已执行迁移)。
## 一、前置结论:为什么保留 `account` 列名
- Salon 实际实现:`t_user.account` 列存密文 + `account_hash char(64) NULL` + `uk_user_account_hash`;没有 `account_cipher`。
- **不能**"新增 account_cipher 再 DROP account":V1 种子由 SQL 直接写 `account='xiaowang'`,SQL 层无密钥无法回填,DROP 会丢数据。
- 因此与 Salon 同构:`account` 改存 AES-GCM 密文(`varchar(128) NULL`)、新增 `account_hash`、删 `uk_account`、加 `uk_user_account_hash`。hash 输入 `trim()` + HMAC-SHA256 十六进制小写,与 Salon 逐字对齐。
- ArtList 唯一差异:账号允许字母数字自定义账号,**一律加密**(Salon 仅手机号形态加密)。`decryptAccount` 对无 `enc:v1:` 前缀的历史值原样返回,兼容 V1 种子。
## 二、V5 迁移(已落地)
`JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql`:
1. 幂等过程沿用 V2 风格:`sp_v5_add_column_if_not_exists`、`sp_v5_drop_index_if_exists`、`sp_v5_add_unique_index_if_not_exists`(`DELIMITER $$`,用后 DROP)。
2. `ALTER TABLE t_user MODIFY COLUMN account varchar(128) NULL COMMENT '账号AES-GCM密文(enc:v1: 前缀)'`。
3. 新增 `account_hash char(64) NULL COMMENT '账号HMAC-SHA256索引'`。
4. 删除 `uk_account`;新增 `uk_user_account_hash (account_hash)`(MySQL 唯一索引允许多行 NULL)。
5. 不做 SQL 数据迁移;历史/种子账号由启动时 `AccountHashBackfillRunner` 加密并回填 hash。
## 三、后端改造(已落地)
- `support/privacy/PhoneCrypto`:新增 `encryptAccount`(非空一律加密)、`decryptAccount`(仅 `enc:v1:` 前缀解密,legacy 明文原样返回);`index` 复用,输入仍 `trim()`;删除不再使用的 `maskIfMobile`。
- 新建 `support/privacy/AccountPhoneTypeHandler`:写 `encryptAccount`、读 `decryptAccount`。
- `UserDO`:`account` 挂 `AccountPhoneTypeHandler`;新增 `accountHash`(`@TableField("account_hash")`,与既有 phoneHash 一致,由 `MyMetaObjectHandler` 手工填充)。
- `MyMetaObjectHandler`:`fillPhoneHashes` 中补 account → accountHash。
- `UserServiceImpl`:
- 全部账号等值查询改 `.eq(UserDO::getAccountHash, phoneCrypto.index(x))`;**不在每条查询挂 legacy fallback**。
- `pageUsers` 删除 account LIKE,改 `account_hash` 精确匹配,保留 nickname like 与 phone/contactPhone hash。
- `deleteUser` 抽出包级静态 `buildSoftDeleteUpdate(...)`(供单测断言),显式 set 密文 account + accountHash,并清空 `phone`、`phoneHash`、**`contactPhone`、`contactPhoneHash`**(本次补齐的数据残留),再置 status=0、isDelete=1。
- `buildLoginFailKey` 改用 `phoneCrypto.index(account)`。
- `convertToVO(userDO, scenario)`:`getUserById`/`getUserByAccount` 传 `SELF_PROFILE`,列表/分页传 `ADMIN_LIST`。
- 新建 `support/privacy/AccountHashBackfillRunner`(`ApplicationRunner`):启动时对 `account_hash IS NULL AND account IS NOT NULL` 的行加密 account 并回填 hash,幂等。
- `UserController`、`OperationGuardService` 的账号查询/签名索引统一走 `account_hash` / `index`。
## 四、集中脱敏策略(核心,已落地)
`support/privacy/SensitiveFieldPolicy`:`Scenario` 枚举 `SELF_PROFILE / ADMIN_EDIT / ADMIN_LIST / THIRD_PARTY / DIAL / LOG`;`phone(value, scenario)`、`account(value, scenario)`。已支持先解密再处理。
| 场景 | 返回方式 | 依据 |
| --- | --- | --- |
| SELF_PROFILE(`/user/info`、本人资料回显) | 完整 | 本人查看/修改;小程序发验证码直接用 `userInfo.phone` |
| ADMIN_EDIT(`/user/get/{id}`、`/user/get/account/{account}`) | 完整 | 编辑表单需原值,配合前端"未修改不提交" |
| ADMIN_LIST(分页、列表、公告/消息作者) | 脱敏 | 批量浏览,无编辑/拨号需求 |
| DIAL(门店与客服联系方式) | 完整 | 拨号必需;受登录态、门店可见范围与 OperationGuard、限流约束 |
| THIRD_PARTY(评论昵称回退、公开主页、订单客户昵称回退) | 脱敏 | 公开/半公开场景 |
| LOG(审计、日志、短信投递记录) | 脱敏 | 多人可见的持久化介质 |
| 订单详情客户手机 | 脱敏(维持 `customerPhoneMasked`) | 拨号统一走联系方式接口,避免订单批量泄露 |
应用点:`UserServiceImpl.convertToVO`;`ContactInfoServiceImpl`(手机 DIAL 完整、姓名回退 THIRD_PARTY);`CommentServiceImpl` / `AnnouncementServiceImpl` / `SystemMessageServiceImpl` / `OrderServiceImpl`(账号回退 THIRD_PARTY 或 ADMIN_LIST);`SecurityAuditLogServiceImpl`(LOG)。
## 五、前端 / 小程序(已落地)
- `JC-ArtList-Frontend/src/views/ProfileView.vue`:打开编辑弹窗记录 `originalContactPhone`,提交时仅值变化才带 `contactPhone` 字段。
- `JC-ArtList-Frontend/src/views/AccountSettingsView.vue`:绑定/修改手机号均为用户新输入,旧号只展示不回传。
- `JC-ArtList-WeChat`:`pages/account-settings` 只提交 nickname/signature;`pages/settings`、`pages/password-settings` 的 `userInfo.phone` 仅展示/发码。
- 管理端用户编辑 UI 不在本仓库(`CreateUserRequest/UpdateUserRequest` 无页面使用)→ 未覆盖项。
## 六、验证(已执行部分)
1. `mvn -q clean test -Dtest="PhoneCryptoTest,SensitiveFieldPolicyTest,UserSoftDeleteUpdateTest,FlywayMigrationTempCheckTest"` → **EXIT=0**(含编译)。
2. 单测覆盖:account 加解密回环(含纯数字账号一律加密)、legacy `xiaowang` 原样读取 + hash trim 稳定、六场景矩阵断言、软删除 set 子句含 `account/account_hash/phone_cipher/phone_hash/contact_phone_cipher/contact_phone_hash`。
3. 临时库 `jayucloud_artlist_v5check_20261104`:V1→V2→V4→V5 四个迁移成功,二次 migrate "Schema is up to date",断言 `account_hash` 列、`uk_user_account_hash` 存在、`uk_account` 已删、`account` 长度 128;finally DROP DATABASE;临时测试文件已删除。
## 七、剩余步骤
1. 全仓检索确认无明文读写:`getAccount(`/`setAccount(`/`getPhone(`/`phone_cipher`/`account_hash`,结合上下文判断。
2. `node .gitnexus/run.cjs detect-changes --scope all --repo .`(提交前门禁;`partial/truncated` 需重跑)。
3. 中文提交,只含本次文件(V5 迁移、PhoneCrypto、AccountPhoneTypeHandler、SensitiveFieldPolicy、AccountHashBackfillRunner、UserDO、MyMetaObjectHandler、UserServiceImpl、UserController、ContactInfoServiceImpl、SecurityAuditLogServiceImpl、Comment/Announcement/SystemMessage/Order、OperationGuardService、3 个测试类、ProfileView.vue);不提交 `.trae/`、`docs/design/`。
4. `git push origin dev`(禁止 force);非快进 `git pull --rebase` 重试一次,仍失败原样报错停止。
## 八、风险与未覆盖项
- JWT claims 与 Redis 会话 value 仍含账号明文,本轮不改。
- `account` 一律加密与 Salon 条件加密存在行为差异,hash 语义一致。
- 管理端用户编辑页面不在本仓库,未覆盖。
@@ -0,0 +1,178 @@
# 散客预约拨号 + 协议新版本强制重新同意 实施计划
## Context
现有拨号取号端点 `POST /manager/customers/{customerId}/dial?orderId=...` 强制要求 `order.userId = customerId`。散客预约(`OrderDO.userId` 为空,客户信息只存在 `customerNameSnapshot` / `customerPhoneSnapshot`)无法取号,“呼叫”按钮也被前端按 `userId` 隐藏。
同时,V17 已发布 `2026.11.04` 协议,V18 只修订了该版本正文、不可再改。需要新增 V19 发布新版本 `2026.11.04-R2`,并让已登录但未同意新版本的用户强制重新同意。
目标:
1. 拨号接口支持 `appointmentId`(= 预约详情的 `orderItemId`)/ `orderId` 定位,`customerId` 可空;只校验预约/订单属于当前店铺,不要求客户有账号;号码来源优先订单快照、再客户档案;无号码返回明确业务码。
2. 发布 V19 新协议版本;复用现有 `t_user_agreement_consent` 同意记录表,新增 pending/accept 接口;前端登录后强制弹层。
3. 不修改 V18,不动 ArtList 与 `SystemSettingsView.vue`。
## 一、散客拨号(Salon Core)
### 1. 服务接口与实现
`JC-Salon-Core/src/main/java/.../modules/privacy/service/CustomerDialService.java`
- 改为 `CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request);`
`.../modules/privacy/service/impl/CustomerDialServiceImpl.java`
- 注入 `OrderItemMapper`(已有 `OrderMapper`、`UserService`)。
- 流程:
1. `adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号")`,取 `currentShopId`;`requestThrottleService.checkCustomerDial(...)`。
2. 三个定位参数全空 → `BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)")`。
3. `appointmentId` 存在:按 `orderItemMapper.selectById` 查 `OrderItemDO`(未删除),否则 `404 预约不存在`;由 `item.orderId` 取 `OrderDO`。
4. `orderId` 存在:若上一步已解析订单且不相等 → `403 预约与订单不匹配,或无权拨打`;否则按 `orderMapper.selectById` 取订单。
5. 订单存在时:未删除且 `order.shopId == currentShopId`,否则 `403 无权拨打其他店铺预约/订单客户`。
6. 客户解析:
- `customerId` 非空:加载并校验 `type=0`、未删除;`ensureUserAccessibleInCurrentShop`。
- 订单 `userId` 非空且 `customerId` 非空但不相等 → `403 该客户与订单不匹配`;订单 `userId` 为空但传了 `customerId` 同样视为不匹配 → 403。
- `customerId` 为空:若订单 `userId` 非空,用订单客户作档案兜底;散客则为 `null`。
7. `resolveProvider()` 取渠道,`provider.resolve(customer, order)`,审计 reason 固定包含 `customerId=;appointmentId=;orderId=;provider=;mode=;result=`,不含号码。
8. 成功/失败审计沿用 `SecurityAuditSupport`,失败记录 `errorCode`。
`.../modules/privacy/dial/DirectDialTargetProvider.java`
- 号码优先级改为:`order.customerPhoneSnapshot` → `customer.contactPhone` → `customer.phone`。
- 注:`OrderDO.customerPhoneSnapshot` 由 `PhoneEncryptionTypeHandler` 读取时已解密,`phoneCrypto.decrypt` 对明文是幂等 no-op,保留调用即可。
- 全部为空 → `BusinessException(422, "该预约/订单未登记可拨打的手机号(DIAL_NUMBER_UNAVAILABLE)")`,新增常量 `NUMBER_UNAVAILABLE_CODE = 422`、`NUMBER_UNAVAILABLE_BUSINESS_CODE`。
- `DialTargetProvider` / `DialTarget` / 隐私号占位实现保持不变。
### 2. 控制器
`.../modules/manager/controller/admin/AdminManagerController.java`
- 保留旧端点,参数放宽:
- `POST /manager/customers/{customerId}/dial`:`customerId` 路径参数;`orderId`、`appointmentId` 均 `required = false`。
- 新增 `POST /manager/customers/dial`:`customerId`、`appointmentId`、`orderId` 全部 `required = false`。
- 两个方法均 `@RequirePermission("user:view")`、设置 `Cache-Control: no-store`,调用新 service 签名。
### 3. 测试
`JC-Salon-Core/src/test/java/.../modules/privacy/service/impl/CustomerDialServiceImplTest.java`
- 适配 5 参数签名与新增 `OrderItemMapper` mock。
- 新增断言:
- 散客订单(`customerId=null`、`order.userId=null`、订单快照有号)取号成功,号码只来自快照。
- `appointmentId` 定位成功(订单项 → 订单)。
- `appointmentId` 与 `orderId` 归属不一致 → 403。
- 散客无快照且无客户档案 → 422 且含 `DIAL_NUMBER_UNAVAILABLE`。
- 现有“登录客户 + 订单”路径保持成功。
## 二、协议新版本 + 强制重新同意
### 1. Flyway V19(不改 V18)
新增 `JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql`:
```sql
-- 先停用当前生效的两个协议
UPDATE t_legal_agreement
SET status = 0, update_time = NOW()
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
AND is_delete = 0 AND status = 1;
-- 从停用前刚生效的正文复制新版本,不重复维护长文本
INSERT INTO t_legal_agreement
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
SELECT 313931273555140005, 'USER_TERMS', title, '2026.11.04-R2', content, 1,
'2026-11-04 00:00:00', NOW(), NOW(), 0
FROM t_legal_agreement
WHERE agreement_type = 'USER_TERMS' AND is_delete = 0
ORDER BY effective_time DESC, create_time DESC
LIMIT 1;
-- PRIVACY_POLICY 使用 id 313931273555140006,同样 INSERT ... SELECT
```
- `id` 显式常量(该表 id 无自增);`version = 2026.11.04-R2`;生效时间为本次修订日期;`status = 1`。
- 不修改 `V18__...sql`。
### 2. 同意机制:复用现有表
已确认仓库已有 `t_user_agreement_consent`(唯一键 `(user_id, agreement_type, version)`)与 `LegalAgreementServiceImpl.recordConsent/upsertConsent/getMyConsent`,**不新建 `t_user_agreement_acceptance`**。
`.../modules/system/service/LegalAgreementService.java` 新增:
- `AgreementPendingVO getPendingAgreements(Long userId);`
- `void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest request);`
新增 `.../modules/system/vo/AgreementPendingVO.java`:
- `Boolean pending`、`Map<String,String> currentVersions`、`Map<String,String> acceptedVersions`、`List<String> pendingTypes`。
`LegalAgreementServiceImpl`:
- `getPendingAgreements`:对 `USER_TERMS` / `PRIVACY_POLICY` 各取 `findCurrentAgreement`,与 `getMyConsent(userId).consentVersions` 比对;缺失或版本不同即 pending。
- `acceptCurrentAgreements`:读取两类当前发布版本,按 `upsertConsent(userId, type, version, "agreement-gate", clientType, ip)` 记录,不依赖客户端上报版本。
- 保留登录/注册链路现有 `requireAccepted` 不变。
`.../modules/system/controller/front/LegalAgreementController.java` 新增:
- `GET /legal-agreement/pending`:从 request attribute `userId` 取用户,`requestThrottleService.checkAgreementRead(request, "PENDING")`,返回 pending VO。
- `POST /legal-agreement/accept`:登录态,可选 body `{clientType}`(默认 `WEB`),记录当前版本同意。
- 两个端点**不加入** `WebMvcConfig` 白名单,因此必须登录;`/legal-agreement/current`、`/current/**` 仍免登录,协议阅读页不受影响。
### 3. 测试
新增 `JC-Salon-Core/src/test/java/.../modules/system/service/impl/LegalAgreementServiceImplTest.java`:
- 无同意记录 → `pending=true`,`pendingTypes` 含两类。
- 已同意旧版本、当前版本已变 → `pending=true`。
- 已同意当前版本 → `pending=false`。
- `acceptCurrentAgreements` 对两类各调用一次 `upsertConsent`(insert/update 均可)。
## 三、前端与小程序
### 1. 拨号按钮与参数
`JC-Salon-Frontend/src/api/user.ts`
- `dialCustomer(params: { customerId?: IdType; appointmentId?: IdType; orderId?: IdType })`,调用 `POST /manager/customers/dial`,仅传非空参数。
`JC-Salon-Frontend/src/views/ArtistOrderView.vue`
- 按钮条件:`v-if="order.customerPhoneMasked"`(去掉 `&& order.userId`)。
- `dialCustomer(order)`:只要求 `order.id`;调用 `userApi.dialCustomer({ customerId: order.userId || undefined, orderId: order.id })`。
`JC-Salon-WeChat/api/customers.js`
- `dialCustomer(params)`:`POST /manager/customers/dial`,透传 `customerId/appointmentId/orderId`。
`JC-Salon-WeChat/pages/appointment-detail/index.wxml`
- 条件改为 `appointment.customerPhoneAvailable && appointment.orderId`(去掉 `customerId`)。
`JC-Salon-WeChat/pages/appointment-detail/index.js`
- `dialCustomer()` 只要求 `customerPhoneAvailable && orderId`;传 `{ customerId: appointment.customerId, appointmentId: appointment.orderItemId, orderId: appointment.orderId }`。
### 2. Web 强制同意弹层
`JC-Salon-Frontend/src/api/auth.ts` 的 `legalAgreementApi` 新增:
- `getPending()` → `GET /legal-agreement/pending`
- `accept(clientType?)` → `POST /legal-agreement/accept`
新增 `JC-Salon-Frontend/src/utils/agreement-gate.ts`:
- 模块级 `pending` 标志与 `setAgreementPending/isAgreementPending`。
`JC-Salon-Frontend/src/api/index.ts` 请求拦截器:
- 若 `isAgreementPending()` 且 URL 不属于 `/legal-agreement/`、`/admin/auth/`、`/user/logout`,直接 reject 并提示“请先阅读并同意最新版用户协议与隐私政策”。
- 不改造鉴权链,只在现有 axios 拦截器加一个前置判断。
`JC-Salon-Frontend/src/views/admin/AdminLayout.vue`
- `onMounted` 调用 `legalAgreementApi.getPending()`;pending 时 `setAgreementPending(true)` 并显示不可关闭的 `a-modal`。
- 弹层内链接 `/legal/user-terms.html`、`/legal/privacy-policy.html`(静态页运行时读取后台当前协议)。
- “同意并继续”调用 `accept('WEB')`,成功后置 false 并关闭;不提供关闭/取消。
### 3. 小程序
- 现有 `app.js` 已在启动时用 `hasMatchingAgreementVersions(preference.agreementVersions, currentVersions)` 比对当前协议版本,不一致即清 session 并跳登录页重新勾选;登录页 `agreementPromptVisible` 弹层与 `agreementPayload()` 会把新版本写入登录请求并记录同意。V19 发布后该链路自动生效,无需改动鉴权链。
- `JC-Salon-WeChat/api/auth.js` 增加 `getPendingAgreements()` / `acceptCurrentAgreements(clientType)` 供后续页面使用(本次不改变现有登录流程)。
## 四、验证
1. 编译:`mvn -q -DskipTests compile`(`JC-Salon-Core`)。
2. 单测:`mvn -q "-Dtest=CustomerDialServiceImplTest,LegalAgreementServiceImplTest,PlanningServiceImplTest,UserServiceCustomerMatchingTest" test`。
3. 前端构建:`npm run build`(`JC-Salon-Frontend`)。
4. 微信端:`node JC-Salon-WeChat/app-login-flow.test.js`、`node JC-Salon-WeChat/employees-review.test.js`。
5. GitNexus:
- `impact` 检查 `dial`、`CustomerDialServiceImpl`、`DirectDialTargetProvider`、`LegalAgreementServiceImpl`、`LegalAgreementService`、`AdminManagerController.dialCustomer`、`LegalAgreementController`;`UNKNOWN` 用全仓文本检索交叉确认。
- `detect-changes --scope all` 必须非 partial/truncated。
6. 提交:仅暂存本次文件,中文提交;`git push origin dev`,非快进先 `git pull --rebase` 重试一次,仍失败原样报错停止。
## 五、约束与残余风险
- 不修改 `V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql`。
- 不动任何 ArtList 文件,不动 `SystemSettingsView.vue`。
- V19 假设库中存在现行协议行(V17 的 `2026.11.04`)。若某环境从未执行 V17/V18,则 `INSERT ... SELECT` 无数据可复制,新版本不会生成;需上线前确认该环境已执行到 V18。
- 散客号码优先取订单快照,可能与客户档案最新号码不一致;这是本次明确的产品口径。
- Web 同意拦截在 axios 层与弹层实现,属于前端强制;后端灰心接口仍可被直接调用,未改鉴权链。如需服务端硬拦截,后续单独增加受限路径的协议同意拦截器。
- 管理员登录本身不携带协议勾选,V19 后首次登录会出现强制同意弹层,属于预期行为。
+108 -19
View File
@@ -1,29 +1,30 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
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. This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
> 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). > Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
## Always Do ## Always Do
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user. - **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`. - **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits. - MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. - **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`. - **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
## Never Do ## Never Do
- NEVER edit a function, class, or method without first running `impact` on it. - NEVER edit a function, class, or method before MCP/CLI impact analysis.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis. - NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph. - NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit changes without running `detect_changes()` to check affected scope. - NEVER commit before MCP/CLI graph change analysis.
## Resources ## Resources
| Resource | Use for | | Resource | Use for |
|----------|---------| | --- | --- |
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness | | `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
| `gitnexus://repo/JayuCloud/clusters` | All functional areas | | `gitnexus://repo/JayuCloud/clusters` | All functional areas |
| `gitnexus://repo/JayuCloud/processes` | All execution flows | | `gitnexus://repo/JayuCloud/processes` | All execution flows |
@@ -32,27 +33,115 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat
## CLI ## CLI
| Task | Read this skill file | | Task | Read this skill file |
|------|---------------------| | --- | --- |
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | | Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | | Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | | Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | | Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | | Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | | Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
## Project Workflow Rules ## Project Workflow Rules
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
- 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。 - 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。
- 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。 - 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。
- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。 - 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。
- Salon Core 的数据库变更必须放在 `JC-Salon-Core/src/main/resources/db/migration/` 下,使用递增的 Flyway 版本文件(如 `V2__功能说明_20261024.sql`);已在任一环境成功执行的迁移文件不得修改或删除。
- DEV、SIT、PROD 的数据库迁移由 Core 启动时的 Flyway 自动执行,Gitea 工作流不得直接连接数据库或绕过 Flyway 执行 SQL;合并到 SIT 前必须先在 DEV 验证迁移。
- 应用回退不会自动回滚数据库;需要撤销或修正时,必须新增向前兼容的补偿迁移,禁止依赖 Flyway `clean`、自动 baseline 或重新执行初始化 SQL。
- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。 - 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。
- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。 - 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。
- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `scripts/0.0.1版本基线与后续迭代规则_20260628.md`,并在任务记录中写明新增或调整的版本化文件。 - 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `docs/scripts/运行与发布配置总说明.md`,并在任务记录中写明新增或调整的版本化文件。
- 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。 - 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。
## Browser MCP Preference ## Browser MCP Preference
- For any browser-related operation, including opening, navigating, clicking, typing, inspecting pages/devtools, taking screenshots, testing pages, or automating local/remote web targets, use the `edgedev` MCP server first. - For any browser-related operation, including opening, navigating, clicking, typing, inspecting pages/devtools, taking screenshots, testing pages, or automating local/remote web targets, use the `edgedev` MCP server first.
- Do not use other browser automation providers such as Browser, browser-use, Chrome, Playwright MCP, or generic web browsing for browser operations unless `edgedev` is unavailable or the user explicitly requests a different browser/MCP in that turn. - Do not use other browser automation providers such as Browser, browser-use, Chrome, Playwright MCP, or generic web browsing for browser operations unless `edgedev` is unavailable or the user explicitly requests a different browser/MCP in that turn.
## 项目概述
JayuCloud 是甲屿云双产品线仓库,包含两条业务线,各自拥有完整的端侧矩阵:
- **Salon(店务 / 指尖管理师)**:面向美甲门店经营的管理系统——门店与员工管理、排班规划、预约、订单履约、注册审核、协议与隐私合规。模块:`JC-Salon-Core`(后端)、`JC-Salon-Gateway`(网关)、`JC-Salon-Frontend`(Vue 管理端)、`JC-Salon-WeChat`(指尖管理师小程序)。
- **ArtList(指尖设计师)**:面向用户的设计师作品电商平台——作品浏览、购物车、下单、评价、VIP、优惠券。模块:`JC-ArtList-Core`、`JC-ArtList-Gateway`、`JC-ArtList-Frontend`(Vue 用户端+管理端)、`JC-ArtList-WeChat`(用户小程序)。
- 支撑目录:`nacos/`(各环境 Nacos 配置副本)、`scripts/` 与 `docs/scripts/`(部署脚本与中文配置说明)、`docs/`(文档)、`.gitea/`(Gitea Actions 工作流)。
项目背景、模块职责与关键业务流程详见 `docs/agent/PROJECT_CONTEXT.md`;不可违反的约束见 `docs/agent/PROJECT_CONSTRAINTS.md`。
## 技术栈与版本(已核实)
| 层 | 技术 | 版本 |
| --- | --- | --- |
| 后端语言 | Java | 17 |
| 后端框架 | Spring Boot / Spring Cloud / Spring Cloud Alibaba | 2.7.18 / 2021.0.8 / 2021.0.5.0 |
| ORM / 连接池 | MyBatis-Plus / Druid | 3.5.3.1 / 1.2.23 |
| 认证 | jjwt | 0.11.5 |
| 数据库 / 迁移 | MySQL / Flyway | 迁移文件在各 Core 的 `src/main/resources/db/migration/` |
| 缓存 / 消息 | Redis / RabbitMQ | 版本以 Nacos `infra.yaml` 为准 |
| 注册与配置中心 | Nacos | 命名空间按端侧划分(`jayucloud-salon` / `jayucloud-artlist`) |
| 对象存储 | MinIO → 七牛 Kodo → 阿里云 OSS 三副本编排 | 读取渠道优先级可配置 |
| 网关 | Spring Cloud Gateway + Reactive Redis | `AuthGlobalFilter` 负责白名单与 JWT 初筛 |
| 前端 | Vue 3 + Vite + Element Plus + Ant Design Vue(双组件库)+ Pinia + Vue Router + Axios | Vue 3.5.x |
| 小程序 | 微信原生小程序(非 Taro/uni-app) | 基础库 3.15.2 基线 |
| 构建 | Maven(各模块独立构建,非聚合工程)/ npm | Maven 3.9.x |
| CI/CD | Gitea Actions(dev Nacos 自动发布、prod 部署工作流) | 见 `.gitea/workflows/` |
不得把未经确认的目标版本写成当前使用版本;升级版本属于迁移任务,需单独方案。
## 项目架构
- 调用链:各端 → Gateway(路由、白名单、Token 初筛)→ Core(业务)→ MySQL / Redis / RabbitMQ / 对象存储;服务间内部接口走 `/internal/**`。
- Core 分层:`modules.<业务域>` 下 controller / service / mapper / entity / dto / vo;公共能力在 `common` 与 `config`;统一响应包装为 `common` 包的 `Result<T>`。
- Salon Core 业务域:`analytics、artist、auth、content、file、integration、inventory、manager、marketing、message、order、payment、planning、privacy、product、registration、security、shop、system、user`;ArtList Core 为其收敛子集(已清理 inventory/manager/analytics 等)。
- 配置体系:本地 `application.yaml`/`bootstrap.yaml` 只保留 Nacos 引导参数;运行配置在 Nacos 的 `core.yaml、gateway.yaml、infra.yaml、secret.yaml、logging.yaml`;`secret.yaml` 与 `infra.yaml` 的覆盖关系以实际加载顺序为准,敏感配置只放 Nacos,不入仓库。
- 路由与权限基线:管理端接口走 `/api/admin/**` 门禁;小程序业务走 `/api/**`;匿名白名单逐个端点枚举,禁止宽泛前缀。
## 目录与代码规范
- 新业务优先进入现有 `modules.<业务域>`;跨域引用走对方 Service,不直连他域 Mapper。
- Gateway 不承载业务写逻辑,只做路由、鉴权初筛与转发。
- 命名遵循现有风格:Java 包 `com.xiaowang.jayucloud.<salon|artlist>.<core|gateway>`;前端页面在 `src/views/`,请求封装在 `src/api/`;小程序请求封装在 `utils/request.js`、登录态在 `utils/auth.js`。
- 界面文案统一中文;前端保持现有双组件库用法与页面风格,改版式不改业务行为(接口调用、校验、权限逻辑原样保留)。
- 异常与日志:沿用现有统一异常处理与 Log4j2 配置;日志禁止输出手机号、口令、令牌等敏感明文。
## 数据库规范
- 结构变更一律走 Flyway 版本文件(规则见上方 Project Workflow Rules 与 `docs/agent/PROJECT_CONSTRAINTS.md`):`V{n}__中文功能说明_YYYYMMDD.sql`,完整可执行,已执行文件不得修改。
- 空库初始化仅用 `docs/scripts/sql/init/jayucloud-salon.sql` / `jayucloud-artlist.sql`;生产已部署库升级必须单独制定迁移方案。
- 主键与实体:遵循现有实体的主键策略与软删除/审计字段约定;新增实体需同步检查 `@MapperScan` 包清单与 MyBatis-Plus 自动填充处理器(单例合并)。
- 新增字段必须同时更新实体与版本迁移,并核对历史数据回填需求。
## API 规范
- 风格:REST 风格 + 统一 `Result<T>` 包装;URL 使用小写中划线资源名,遵循所在端既有前缀(`/api`、`/api/admin`、`/internal`)。
- 认证:Bearer JWT,Gateway 初筛 + Core 业务校验;匿名端点必须显式列入白名单并逐个说明理由。
- 权限:管理端按权限码裁剪菜单与接口;数据属主校验(门店作用域)在 Service 层完成。
- 敏感数据:手机号/账号等隐私字段默认脱敏返回,明文获取走独立授权端点(如单次拨号取号);不在列表接口返回完整隐私字段。
- 接口文档:以代码与 `docs/` 说明为准;新增对外契约需在任务说明中写明请求/响应/错误语义。
## 开发与验证要求
- 后端构建(非聚合工程,进对应模块):`mvn -f JC-Salon-Core/pom.xml -DskipTests compile`(ArtList 同理);本机 Maven 位于 `D:\software\apache-maven-3.9.12\bin\mvn.cmd`。
- 涉及 Bean 装配、事务、拦截器的改动:编译通过后还需启动烟测,编译通过不等于能启动。
- 前端:`JC-Salon-Frontend` / `JC-ArtList-Frontend` 下 `npm run build`;开发代理 `/admin/api` 与 `/api` 指向 `VITE_DEV_PROXY_TARGET`。
- 小程序:JS 改动后做 node 语法检查;有条件时用微信开发者工具冒烟。
- 测试:JUnit 5 + Mockito(spring-boot-starter-test);Mock 参数要么全字面量要么全 matcher。
- 修改符号前先做 GitNexus impact 分析,提交前做 detect_changes(见文首 GitNexus 规则);修改完成后按改动范围执行上述对应验证,并如实报告结果。
## 安全与变更保护
- 不擅自删除业务数据;不擅自操作生产环境(生产部署、Nacos 生产发布、生产 SQL 执行必须先核对环境、备份与凭据注入方式并取得确认)。
- 不擅自变更数据库结构(必须走 Flyway 版本文件);不覆盖用户已有配置;不将密钥、口令、令牌写入仓库、日志或文档。
- 重大变更(结构调整、迁移、发布)前先备份;破坏性操作必须先确认。
- 敏感配置只存放在 Nacos `secret.yaml`(按环境),仓库中的 `nacos/` 副本不得包含真实密钥。
## Agent 知识体系
- 项目级技能位于 `.agents/skills/`(`jayu-domain`、`jayu-database`、`jayu-api`、`jayu-devflow`、`jayu-release`),清单与触发条件见 `docs/agent/SKILLS_CATALOG.md`,使用说明见 `docs/agent/AGENT_SKILLS_GUIDE.md`。
- 通用能力(需求分析、架构设计、TDD、调试、评审、运维等)由全局 Skills 提供,项目级技能只承载本项目专属知识,两者不重复建设。
- 交接文档入口:`docs/handoff/`(PROJECT-MAP、CURRENT-STATE 等,部分内容滞后于代码,结论以源码为准);脚本与发布规则入口:`docs/scripts/运行与发布配置总说明.md`。
+24 -18
View File
@@ -1,29 +1,30 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
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. This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
> 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). > Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
## Always Do ## Always Do
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user. - **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`. - **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits. - MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. - **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`. - **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
## Never Do ## Never Do
- NEVER edit a function, class, or method without first running `impact` on it. - NEVER edit a function, class, or method before MCP/CLI impact analysis.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis. - NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph. - NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit changes without running `detect_changes()` to check affected scope. - NEVER commit before MCP/CLI graph change analysis.
## Resources ## Resources
| Resource | Use for | | Resource | Use for |
|----------|---------| | --- | --- |
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness | | `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
| `gitnexus://repo/JayuCloud/clusters` | All functional areas | | `gitnexus://repo/JayuCloud/clusters` | All functional areas |
| `gitnexus://repo/JayuCloud/processes` | All execution flows | | `gitnexus://repo/JayuCloud/processes` | All execution flows |
@@ -32,12 +33,17 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat
## CLI ## CLI
| Task | Read this skill file | | Task | Read this skill file |
|------|---------------------| | --- | --- |
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | | Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | | Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | | Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | | Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | | Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | | Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
## Project Workflow Rules
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
+9
View File
@@ -110,6 +110,15 @@
<artifactId>mysql-connector-j</artifactId> <artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- Spring Boot manages the Flyway version; migrations run against the Nacos-configured datasource. -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-mysql</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId> <artifactId>mybatis-plus-boot-starter</artifactId>
@@ -0,0 +1,19 @@
package com.xiaowang.jayucloud.artlist.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 拨号取号配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jayucloud-artlist.dial")
public class DialProperties {
/**
* 拨号提供方:direct(直拨真实号码)或 privacy-number(隐私号,未对接时明确报错)。
*/
private String provider = "direct";
}
@@ -25,7 +25,6 @@ import org.springframework.context.annotation.Configuration;
"com.xiaowang.jayucloud.artlist.core.modules.content.mapper", "com.xiaowang.jayucloud.artlist.core.modules.content.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.file.mapper", "com.xiaowang.jayucloud.artlist.core.modules.file.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.integration.mapper", "com.xiaowang.jayucloud.artlist.core.modules.integration.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper", "com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.message.mapper", "com.xiaowang.jayucloud.artlist.core.modules.message.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.order.mapper", "com.xiaowang.jayucloud.artlist.core.modules.order.mapper",
@@ -1,6 +1,7 @@
package com.xiaowang.jayucloud.artlist.core.config; package com.xiaowang.jayucloud.artlist.core.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -27,6 +28,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
log.info("start insert fill ...."); log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
fillPhoneHashes(metaObject);
} }
@Override @Override
@@ -37,5 +39,31 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
public void updateFill(MetaObject metaObject) { public void updateFill(MetaObject metaObject) {
log.info("start update fill ...."); log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
fillPhoneHashes(metaObject);
}
/**
* 实体写入时按明文手机号刷新哈希列。
* 注意:QueryWrapper/UpdateWrapper 的 set 不会经过这里,删除等场景需显式置空哈希。
*/
private void fillPhoneHashes(MetaObject metaObject) {
if (metaObject.hasSetter("accountHash")) {
Object account = getFieldValByName("account", metaObject);
if (account != null) {
setFieldValByName("accountHash", PhoneCrypto.current().index(String.valueOf(account)), metaObject);
}
}
if (metaObject.hasSetter("phoneHash")) {
Object phone = getFieldValByName("phone", metaObject);
if (phone != null) {
setFieldValByName("phoneHash", PhoneCrypto.current().index(String.valueOf(phone)), metaObject);
}
}
if (metaObject.hasSetter("contactPhoneHash")) {
Object contactPhone = getFieldValByName("contactPhone", metaObject);
if (contactPhone != null) {
setFieldValByName("contactPhoneHash", PhoneCrypto.current().index(String.valueOf(contactPhone)), metaObject);
}
}
} }
} }
@@ -0,0 +1,17 @@
package com.xiaowang.jayucloud.artlist.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 手机号加密配置。密钥口径与 JC-Salon-Core 完全一致,保证两条业务线的 phone_hash 可比对。
* 配置位置:Nacos jayucloud-artlist / DEFAULT_GROUP / secret.yaml。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jayucloud-artlist.privacy.phone-crypto")
public class PhoneCryptoProperties {
private String encryptionKey;
private String indexKey;
}
@@ -28,6 +28,16 @@ public class RateLimitProperties {
private LimitRule orderCreate = new LimitRule(10, 60); private LimitRule orderCreate = new LimitRule(10, 60);
/**
* 联系方式查询:按登录用户维度。
*/
private LimitRule contactInfoRead = new LimitRule(30, 60);
/**
* 单次拨号取号:按登录用户维度。
*/
private LimitRule contactDial = new LimitRule(10, 60);
@Data @Data
/** /**
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
@@ -1,450 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.controller.front;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.artlist.core.common.Result;
import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties;
import com.xiaowang.jayucloud.artlist.core.modules.content.entity.CommentDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.content.mapper.CommentMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.DashboardStatsVO;
import com.xiaowang.jayucloud.artlist.core.modules.product.vo.HotProductVO;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.RecentActivityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/admin/dashboard")
@RequiredArgsConstructor
/**
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class DashboardController {
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserMapper userMapper;
/**
* Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ProductMapper productMapper;
/**
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ShopMapper shopMapper;
/**
* Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentMapper commentMapper;
/**
* Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderMapper orderMapper;
/**
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderItemMapper orderItemMapper;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
/**
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final MultiLevelCacheService multiLevelCacheService;
/**
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AppCacheProperties appCacheProperties;
private final OperationsAnalyticsService operationsAnalyticsService;
@GetMapping("/stats")
@RequirePermission("dashboard:view")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<DashboardStatsVO> result consumed by the caller or returned to the frontend
*/
public Result<DashboardStatsVO> getDashboardStats(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope);
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
DashboardStatsVO stats = multiLevelCacheService.getOrLoad(
"cache:dashboard:stats:" + cacheScope,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<DashboardStatsVO>() {
},
() -> buildDashboardStats(currentUser, shopIdScope)
);
return Result.success(stats);
}
@GetMapping("/analytics")
@RequirePermission("analytics:view")
public Result<OperationsAnalyticsVO> getAnalytics(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope));
}
/**
* Run business method `buildDashboardStats`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @param shopIdScope parameter `shopIdScope` supplied by the caller
* @return private DashboardStatsVO result consumed by the caller or returned to the frontend
*/
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
DashboardStatsVO stats = new DashboardStatsVO();
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
if (currentUser != null) {
// 根据用户类型显示不同的数据
if (currentUser.getType() == 4) { // 管理员
stats.setTotalUsers(userMapper.selectCount(null));
stats.setTotalProducts(productMapper.selectCount(null));
stats.setTotalShops(shopMapper.selectCount(null));
stats.setTodayOrders(getTodayOrders(null));
stats.setTotalCustomers(countUsers(null, 0, null, null));
stats.setTotalArtists(countUsers(null, 3, null, null));
} else { // 店长或美甲师
Long shopId = currentUser.getShopId();
if (shopId != null) {
shopIdScope = shopId;
// 只显示当前店铺的数据
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
stats.setTotalCustomers(countUsers(shopId, 0, null, null));
stats.setTotalArtists(countUsers(shopId, 3, null, null));
} else {
// 没有店铺ID的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
}
} else {
// 无法获取用户信息的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
LocalDateTime weekStart = todayStart.minusDays(6);
stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null));
stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null));
stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null));
stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null));
stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null));
stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null));
long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null);
long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null);
stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders);
stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null));
stats.setHotProducts(getHotProducts(shopIdScope));
stats.setRecentActivities(getRecentActivities(shopIdScope));
return stats;
}
/**
* Run business method `resolveShopScope`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long resolveShopScope(UserDO currentUser) {
if (currentUser == null || currentUser.getType() == 4) {
return null;
}
return currentUser.getShopId();
}
/**
* Purpose: countUsers supports DashboardController.java by holding or executing the count users business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
if (type != null) {
wrapper.eq(UserDO::getType, type);
}
if (from != null) {
wrapper.ge(UserDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(UserDO::getCreateTime, to);
}
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
return 0L;
}
wrapper.in(UserDO::getId, userIds);
}
return userMapper.selectCount(wrapper);
}
/**
* Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
return (long) listScopedOrders(shopId, artistId, status, from, to).size();
}
/**
* Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) {
return listScopedOrders(shopId, artistId, null, from, to).stream()
.map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount())
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private List<OrderDO> listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<OrderDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(OrderDO::getShopId, shopId);
}
if (status != null) {
wrapper.eq(OrderDO::getStatus, status);
}
if (from != null) {
wrapper.ge(OrderDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(OrderDO::getCreateTime, to);
}
if (artistId != null) {
Set<Long> orderIds = listOrderIdsByArtist(artistId);
if (orderIds.isEmpty()) {
return Collections.emptyList();
}
wrapper.in(OrderDO::getId, orderIds);
}
return orderMapper.selectList(wrapper);
}
/**
* Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Set<Long> listOrderIdsByArtist(Long artistId) {
List<OrderItemDO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.select(OrderItemDO::getOrderId)
.eq(OrderItemDO::getArtistId, artistId));
return items.stream()
.map(OrderItemDO::getOrderId)
.filter(id -> id != null)
.collect(Collectors.toCollection(HashSet::new));
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long getTodayOrders(Long shopId) {
// 获取今天的开始时间
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
if (shopId != null) {
// 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺
java.util.Map<String, Object> result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
} else {
// 管理员查询所有订单
java.util.Map<String, Object> result = orderItemMapper.countTodayOrders(todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
}
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<HotProductVO> result consumed by the caller or returned to the frontend
*/
private List<HotProductVO> getHotProducts(Long shopId) {
// 通过订单商品表统计每个商品的订单数量,按订单数量排序
// 使用SQL查询获取商品及其订单数量
List<Map<String, Object>> productOrderCounts = orderItemMapper.selectMaps(
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrderItemDO>()
.select("product_id, COUNT(*) as order_count")
.groupBy("product_id")
.orderByDesc("order_count")
.last("LIMIT 5")
);
List<HotProductVO> hotProducts = new ArrayList<>();
// 遍历查询结果,获取商品详情
for (Map<String, Object> map : productOrderCounts) {
Long productId = Long.valueOf(map.get("product_id").toString());
ProductDO product = productMapper.selectById(productId);
if (product != null && (shopId == null || shopId.equals(product.getShopId()))) {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
hotProducts.add(vo);
}
}
// 如果按订单数量查询没有结果,使用点赞数作为备选
if (hotProducts.isEmpty()) {
LambdaQueryWrapper<ProductDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(ProductDO::getShopId, shopId);
}
wrapper.orderByDesc(ProductDO::getLikeCount)
.last("LIMIT 5");
List<ProductDO> products = productMapper.selectList(wrapper);
hotProducts = products.stream().map(product -> {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
return vo;
}).collect(Collectors.toList());
}
return hotProducts;
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<RecentActivityVO> result consumed by the caller or returned to the frontend
*/
private List<RecentActivityVO> getRecentActivities(Long shopId) {
List<RecentActivityVO> activities = new ArrayList<>();
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
userWrapper.eq(UserDO::getId, -1L);
} else {
userWrapper.in(UserDO::getId, userIds);
}
}
userWrapper.orderByDesc(UserDO::getCreateTime)
.last("LIMIT 3");
List<UserDO> recentUsers = userMapper.selectList(userWrapper);
for (UserDO user : recentUsers) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(user.getId());
vo.setType("user");
vo.setTitle("新用户注册");
vo.setDescription("用户\"" + user.getNickname() + "\"注册成功");
vo.setTime(user.getCreateTime());
vo.setColor("");
activities.add(vo);
}
LambdaQueryWrapper<ProductDO> productWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
productWrapper.eq(ProductDO::getShopId, shopId);
}
productWrapper.orderByDesc(ProductDO::getCreateTime)
.last("LIMIT 2");
List<ProductDO> recentProducts = productMapper.selectList(productWrapper);
for (ProductDO product : recentProducts) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(product.getId());
vo.setType("product");
vo.setTitle("新品上架");
vo.setDescription("新品\"" + product.getTitle() + "\"已上架");
vo.setTime(product.getCreateTime());
vo.setColor("blue");
activities.add(vo);
}
LambdaQueryWrapper<CommentDO> commentWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
commentWrapper.eq(CommentDO::getShopId, shopId);
}
commentWrapper.orderByDesc(CommentDO::getCreateTime)
.last("LIMIT 2");
List<CommentDO> recentComments = commentMapper.selectList(commentWrapper);
for (CommentDO comment : recentComments) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(comment.getId());
vo.setType("comment");
vo.setTitle("用户评论");
String content = comment.getCommentContent();
if (content != null && content.length() > 20) {
content = content.substring(0, 20) + "...";
}
vo.setDescription(content != null ? content : "用户发表了评论");
vo.setTime(comment.getCreateTime());
vo.setColor("green");
activities.add(vo);
}
activities.sort((a, b) -> b.getTime().compareTo(a.getTime()));
return activities.stream().limit(5).collect(Collectors.toList());
}
}
@@ -1,7 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO;
public interface OperationsAnalyticsService {
OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId);
}
@@ -1,7 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.StoreWorkbenchVO;
public interface WorkbenchService {
StoreWorkbenchVO getWorkbench(Long shopId, Long artistId);
}
@@ -1,66 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserGrowthRecordDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserGrowthRecordMapper;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final UserGrowthRecordMapper userGrowthRecordMapper;
@Override
public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId != null) {
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
OperationsAnalyticsVO vo = new OperationsAnalyticsVO();
vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setCartCount(0L);
vo.setOrderCount((long) orders.size());
vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count());
vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REVIEW")));
vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REBOOK")));
vo.setTotalAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
return vo;
}
}
@@ -1,145 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistChangeRequestDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.AfterSaleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistChangeRequestMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.WorkbenchService;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.StoreWorkbenchVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class WorkbenchServiceImpl implements WorkbenchService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final AfterSaleMapper afterSaleMapper;
private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
private final InventoryItemMapper inventoryItemMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final OrderArtistReviewMapper orderArtistReviewMapper;
@Override
public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) {
LocalDateTime todayStart = LocalDate.now().atStartOfDay();
LocalDateTime tomorrowStart = todayStart.plusDays(1);
List<OrderDO> orders = scopedOrders(shopId, artistId);
StoreWorkbenchVO vo = new StoreWorkbenchVO();
vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count());
vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count());
vo.setPendingAfterSaleCount(countAfterSales(shopId));
vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId));
vo.setLowStockItemCount(countLowStock(shopId));
vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate()));
vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart));
vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setServiceAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
vo.setAverageRating(resolveRating(artistId));
return vo;
}
private boolean isActionableOrder(OrderDO order) {
if (order == null || order.getStatus() == null) {
return false;
}
return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())
|| Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus());
}
private List<OrderDO> scopedOrders(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId == null) {
return orders;
}
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
return orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
private long countAfterSales(Long shopId) {
return afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
.eq(shopId != null, AfterSaleDO::getShopId, shopId)
.eq(AfterSaleDO::getStatus, "PENDING")
.eq(AfterSaleDO::getIsDelete, 0));
}
private long countArtistChanges(Long shopId, Long artistId) {
return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
.eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId)
.eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId)
.eq(OrderArtistChangeRequestDO::getStatus, "PENDING")
.eq(OrderArtistChangeRequestDO::getIsDelete, 0));
}
private long countLowStock(Long shopId) {
return inventoryItemMapper.selectList(new LambdaQueryWrapper<InventoryItemDO>()
.eq(shopId != null, InventoryItemDO::getShopId, shopId)
.eq(InventoryItemDO::getIsDelete, 0))
.stream()
.filter(item -> item.getStockQuantity() != null
&& item.getWarningThreshold() != null
&& item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0)
.count();
}
private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) {
return artistScheduleMapper.selectCount(new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(shopId != null, ArtistScheduleDO::getShopId, shopId)
.eq(artistId != null, ArtistScheduleDO::getArtistId, artistId)
.ge(ArtistScheduleDO::getWorkDate, today)
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(3))
.eq(ArtistScheduleDO::getIsDelete, 0));
}
private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) {
if (artistId == null) {
return 0L;
}
return orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.ge(OrderItemDO::getAppointmentTime, todayStart)
.lt(OrderItemDO::getAppointmentTime, tomorrowStart)
.eq(OrderItemDO::getIsDelete, 0))
.size();
}
private BigDecimal resolveRating(Long artistId) {
if (artistId == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP);
}
private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) {
return value != null && !value.isBefore(start) && value.isBefore(end);
}
}
@@ -1,89 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import com.xiaowang.jayucloud.artlist.core.modules.product.vo.HotProductVO;
@Data
/**
* DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class DashboardStatsVO {
/**
* Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalUsers;
/**
* Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalProducts;
/**
* Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalShops;
/**
* Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long todayOrders;
/**
* Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal totalOrderAmount;
/**
* Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal todayOrderAmount;
/**
* Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal weekOrderAmount;
/**
* Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalCustomers;
/**
* Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalArtists;
/**
* Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomersToday;
/**
* Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomers7Days;
/**
* Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newOrders7Days;
/**
* Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long pendingOrders;
/**
* Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long completedOrders;
/**
* Field `hotProducts` (List<HotProductVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<HotProductVO> hotProducts;
/**
* Field `recentActivities` (List<RecentActivityVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<RecentActivityVO> recentActivities;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class OperationsAnalyticsVO {
private Long viewCount;
private Long favoriteCount;
private Long cartCount;
private Long orderCount;
private Long paidOrderCount;
private Long completedOrderCount;
private Long reviewCount;
private Long rebookCount;
private BigDecimal totalAmount;
}
@@ -1,37 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
/**
* RecentActivityVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class RecentActivityVO {
/**
* Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long id;
/**
* Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String type;
/**
* Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String title;
/**
* Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String description;
/**
* Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime time;
/**
* Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String color;
}
@@ -1,19 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class StoreWorkbenchVO {
private Long todayOrderCount;
private Long pendingOrderCount;
private Long pendingAfterSaleCount;
private Long pendingArtistChangeCount;
private Long lowStockItemCount;
private Long scheduleReminderCount;
private Long todayServiceCount;
private Long completedServiceCount;
private BigDecimal serviceAmount;
private BigDecimal averageRating;
}
@@ -1,19 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private String remark;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleDTO {
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer status;
private String remark;
}
@@ -1,24 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.service;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.jayucloud.artlist.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,423 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ArtistScheduleServiceImpl implements ArtistScheduleService {
private static final int GENERATED_DAYS = 60;
private static final int DEFAULT_SLOT_MINUTES = 60;
private static final int DEFAULT_CAPACITY = 1;
private static final String PRESET_SINGLE_REST = "SINGLE_REST";
private static final String PRESET_DOUBLE_REST = "DOUBLE_REST";
private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE";
private static final String PRESET_LATE_SHIFT = "LATE_SHIFT";
private static final String PRESET_CUSTOM = "CUSTOM";
private static final String EXCEPTION_REST = "REST";
private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK";
private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT";
private final ArtistScheduleMapper artistScheduleMapper;
private final ArtistScheduleRuleMapper ruleMapper;
private final ArtistScheduleExceptionMapper exceptionMapper;
private final AppointmentReservationMapper reservationMapper;
@Override
@Transactional
public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null
|| dto.getStartTime() == null || dto.getEndTime() == null) {
throw new RuntimeException("排班信息不完整");
}
ArtistScheduleDO schedule = new ArtistScheduleDO();
BeanUtils.copyProperties(dto, schedule);
schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes());
schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity());
schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
schedule.setIsDelete(0);
ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime());
if (existing == null) {
artistScheduleMapper.insert(schedule);
} else {
schedule.setId(existing.getId());
artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(),
schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark());
}
return toVO(schedule);
}
@Override
public List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) {
LambdaQueryWrapper<ArtistScheduleDO> wrapper = new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(ArtistScheduleDO::getIsDelete, 0)
.orderByAsc(ArtistScheduleDO::getWorkDate)
.orderByAsc(ArtistScheduleDO::getStartTime);
if (shopId != null) {
wrapper.eq(ArtistScheduleDO::getShopId, shopId);
}
if (artistId != null) {
wrapper.eq(ArtistScheduleDO::getArtistId, artistId);
}
if (startDate != null) {
wrapper.ge(ArtistScheduleDO::getWorkDate, startDate);
}
if (endDate != null) {
wrapper.le(ArtistScheduleDO::getWorkDate, endDate);
}
return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList();
}
private ArtistScheduleVO toVO(ArtistScheduleDO schedule) {
ArtistScheduleVO vo = new ArtistScheduleVO();
BeanUtils.copyProperties(schedule, vo);
return vo;
}
@Override
public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) {
if (shopId == null || artistId == null) {
throw new RuntimeException("排班规则查询参数不完整");
}
ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO();
ArtistScheduleRuleDO rule = selectRule(shopId, artistId);
setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule));
setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L))
.stream()
.map(this::toExceptionVO)
.toList());
return setting;
}
@Override
@Transactional
public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) {
ArtistScheduleRuleDO normalized = normalizeRule(dto);
ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId());
if (existing == null) {
ruleMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
ruleMapper.updateById(normalized);
}
refreshGeneratedSchedules(normalized);
return toRuleVO(normalized);
}
@Override
@Transactional
public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) {
ArtistScheduleExceptionDO normalized = normalizeException(dto);
ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId());
if (rule == null) {
rule = defaultRule(normalized.getShopId(), normalized.getArtistId());
}
ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate());
if (existing == null) {
exceptionMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
exceptionMapper.updateById(normalized);
}
refreshScheduleForDate(rule, normalized, normalized.getWorkDate());
return toExceptionVO(normalized);
}
private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) {
throw new RuntimeException("排班规则信息不完整");
}
String presetType = normalizePresetType(dto.getPresetType());
LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime();
LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime();
validateTimeRange(startTime, endTime);
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(dto.getShopId());
rule.setArtistId(dto.getArtistId());
rule.setPresetType(presetType);
rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType)));
rule.setStartTime(startTime);
rule.setEndTime(endTime);
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
rule.setRemark(trimText(dto.getRemark()));
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) {
throw new RuntimeException("排班例外信息不完整");
}
String exceptionType = normalizeExceptionType(dto.getExceptionType());
LocalTime startTime = dto.getStartTime();
LocalTime endTime = dto.getEndTime();
if (!EXCEPTION_REST.equals(exceptionType)) {
if (startTime == null || endTime == null) {
throw new RuntimeException("临时上班或改班必须填写开始和结束时间");
}
validateTimeRange(startTime, endTime);
}
ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO();
exception.setShopId(dto.getShopId());
exception.setArtistId(dto.getArtistId());
exception.setWorkDate(dto.getWorkDate());
exception.setExceptionType(exceptionType);
exception.setStartTime(startTime);
exception.setEndTime(endTime);
exception.setSlotMinutes(DEFAULT_SLOT_MINUTES);
exception.setCapacity(DEFAULT_CAPACITY);
exception.setRemark(trimText(dto.getRemark()));
exception.setIsDelete(0);
return exception;
}
private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) {
return ruleMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleRuleDO>()
.eq(ArtistScheduleRuleDO::getShopId, shopId)
.eq(ArtistScheduleRuleDO::getArtistId, artistId)
.eq(ArtistScheduleRuleDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) {
return exceptionMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getWorkDate, workDate)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private List<ArtistScheduleExceptionDO> listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) {
return exceptionMapper.selectList(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.between(ArtistScheduleExceptionDO::getWorkDate, start, end)
.orderByAsc(ArtistScheduleExceptionDO::getWorkDate));
}
private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) {
LocalDate start = LocalDate.now();
LocalDate end = start.plusDays(GENERATED_DAYS - 1L);
Map<LocalDate, ArtistScheduleExceptionDO> exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end)
.stream()
.collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a));
LocalDate cursor = start;
while (!cursor.isAfter(end)) {
refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor);
cursor = cursor.plusDays(1L);
}
}
private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate);
if (!generated.working()) {
assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate);
upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark());
return;
}
assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime());
upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark());
}
private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
if (exception != null) {
if (EXCEPTION_REST.equals(exception.getExceptionType())) {
return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception));
}
if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) {
return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception));
}
}
boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue());
return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班");
}
private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime,
Integer slotMinutes, Integer capacity, Integer status, String remark) {
ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate);
if (schedule == null) {
schedule = new ArtistScheduleDO();
schedule.setShopId(rule.getShopId());
schedule.setArtistId(rule.getArtistId());
schedule.setWorkDate(workDate);
schedule.setStartTime(startTime);
schedule.setEndTime(endTime);
schedule.setSlotMinutes(slotMinutes);
schedule.setCapacity(capacity);
schedule.setStatus(status);
schedule.setRemark(remark);
schedule.setIsDelete(0);
artistScheduleMapper.insert(schedule);
return;
}
artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark);
}
private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) {
int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate);
if (count > 0) {
throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count);
}
}
private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) {
int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime);
if (count > 0) {
throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count);
}
}
private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) {
return toRuleVO(defaultRule(shopId, artistId));
}
private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) {
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(shopId);
rule.setArtistId(artistId);
rule.setPresetType(PRESET_DOUBLE_REST);
rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5)));
rule.setStartTime(LocalTime.of(9, 0));
rule.setEndTime(LocalTime.of(17, 0));
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(1);
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) {
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
BeanUtils.copyProperties(rule, vo);
vo.setWorkDays(decodeWorkDays(rule.getWorkDays()));
return vo;
}
private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) {
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
BeanUtils.copyProperties(exception, vo);
return vo;
}
private String normalizePresetType(String presetType) {
String value = trimText(presetType);
if (value == null || value.isBlank()) {
return PRESET_CUSTOM;
}
return value;
}
private String normalizeExceptionType(String exceptionType) {
String value = trimText(exceptionType);
if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) {
return value;
}
throw new RuntimeException("不支持的排班例外类型:" + value);
}
private List<Integer> resolveWorkDays(List<Integer> inputWorkDays, String presetType) {
List<Integer> presetDays = switch (presetType) {
case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5);
case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6);
default -> inputWorkDays;
};
Set<Integer> normalized = new LinkedHashSet<>();
for (Integer day : presetDays == null ? List.<Integer>of() : presetDays) {
if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) {
normalized.add(day);
}
}
if (normalized.isEmpty()) {
throw new RuntimeException("请至少选择一个工作日");
}
return normalized.stream().sorted().toList();
}
private String encodeWorkDays(List<Integer> workDays) {
return workDays.stream()
.sorted()
.map(String::valueOf)
.collect(Collectors.joining(","));
}
private List<Integer> decodeWorkDays(String workDays) {
if (workDays == null || workDays.isBlank()) {
return new ArrayList<>();
}
return List.of(workDays.split(",")).stream()
.map(String::trim)
.filter(value -> !value.isBlank())
.map(Integer::valueOf)
.sorted()
.toList();
}
private LocalTime presetStartTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(9, 0);
}
return LocalTime.of(10, 0);
}
private LocalTime presetEndTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(17, 0);
}
return LocalTime.of(22, 0);
}
private void validateTimeRange(LocalTime startTime, LocalTime endTime) {
if (startTime == null || endTime == null || !startTime.isBefore(endTime)) {
throw new RuntimeException("排班开始时间必须早于结束时间");
}
}
private String trimText(String value) {
return value == null ? null : value.trim();
}
private String exceptionRemark(ArtistScheduleExceptionDO exception) {
if (exception.getRemark() != null && !exception.getRemark().isBlank()) {
return exception.getRemark();
}
return "例外排班:" + exception.getExceptionType();
}
private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes,
Integer capacity, String remark) {
}
}
@@ -1,20 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private String remark;
private LocalDateTime createTime;
}
@@ -1,11 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.util.List;
@Data
public class ArtistScheduleRuleSettingVO {
private ArtistScheduleRuleVO rule;
private List<ArtistScheduleExceptionVO> exceptions;
}
@@ -1,21 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleVO {
private Long id;
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -1,22 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.artlist.core.modules.auth.service.impl;
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
@@ -51,6 +52,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
* Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final MessageHubClientService messageHubClientService; private final MessageHubClientService messageHubClientService;
private final PhoneCrypto phoneCrypto;
@Override @Override
/** /**
@@ -94,15 +96,16 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
public void sendVerificationCode(String phone, String sceneCode) { public void sendVerificationCode(String phone, String sceneCode) {
String code = generateVerificationCode(); String code = generateVerificationCode();
String codeKey = CODE_PREFIX + phone; String phoneKey = phoneCrypto.index(phone);
String sendTimeKey = SEND_TIME_PREFIX + phone; String codeKey = CODE_PREFIX + phoneKey;
String sendTimeKey = SEND_TIME_PREFIX + phoneKey;
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); log.info("验证码已发送,手机号: {}, sceneCode: {}", phoneCrypto.mask(phone), sceneCode);
} }
@Override @Override
@@ -114,21 +117,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
* @return boolean result consumed by the caller or returned to the frontend * @return boolean result consumed by the caller or returned to the frontend
*/ */
public boolean verifyCode(String phone, String code) { public boolean verifyCode(String phone, String code) {
String codeKey = CODE_PREFIX + phone; String codeKey = CODE_PREFIX + phoneCrypto.index(phone);
String storedCode = redisTemplate.opsForValue().get(codeKey); String storedCode = redisTemplate.opsForValue().get(codeKey);
if (storedCode == null) { if (storedCode == null) {
log.warn("验证码不存在或已过期,手机号: {}", phone); log.warn("验证码不存在或已过期,手机号: {}", phoneCrypto.mask(phone));
return false; return false;
} }
if (!storedCode.equals(code)) { if (!storedCode.equals(code)) {
log.warn("验证码错误,手机号: {}", phone); log.warn("验证码错误,手机号: {}", phoneCrypto.mask(phone));
return false; return false;
} }
redisTemplate.delete(codeKey); redisTemplate.delete(codeKey);
log.info("验证码验证成功,手机号: {}", phone); log.info("验证码验证成功,手机号: {}", phoneCrypto.mask(phone));
return true; return true;
} }
@@ -140,7 +143,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
* @return boolean result consumed by the caller or returned to the frontend * @return boolean result consumed by the caller or returned to the frontend
*/ */
public boolean canResend(String phone) { public boolean canResend(String phone) {
String sendTimeKey = SEND_TIME_PREFIX + phone; String sendTimeKey = SEND_TIME_PREFIX + phoneCrypto.index(phone);
String sendTime = redisTemplate.opsForValue().get(sendTimeKey); String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
return sendTime == null; return sendTime == null;
} }
@@ -1,4 +1,4 @@
package com.xiaowang.jayucloud.artlist.core.modules.content.service.impl; import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -489,7 +489,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) {
UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId());
if (user != null) { if (user != null) {
commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname()
: SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY));
} }
ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId()); ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId());
if (shop != null) { if (shop != null) {
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHub
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService;
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message; import org.springframework.amqp.core.Message;
@@ -51,6 +52,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
* 平台品牌文案配置。 * 平台品牌文案配置。
*/ */
private final BrandProperties brandProperties; private final BrandProperties brandProperties;
private final PhoneCrypto phoneCrypto;
@Value("${messagehub.client.sms-queue:smsQueue}") @Value("${messagehub.client.sms-queue:smsQueue}")
/** /**
@@ -123,7 +125,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
String queueName = config == null ? smsQueue : config.getQueueName(); String queueName = config == null ? smsQueue : config.getQueueName();
rabbitTemplate.convertAndSend(queueName, message); rabbitTemplate.convertAndSend(queueName, message);
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}", log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}",
sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); sceneCode, phoneCrypto.mask(phone), queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
} catch (Exception exception) { } catch (Exception exception) {
log.error("发送短信验证码失败", exception); log.error("发送短信验证码失败", exception);
throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
@@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLogi
import lombok.Data; import lombok.Data;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -87,6 +88,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
* Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final PhoneCrypto phoneCrypto;
@Override @Override
/** /**
@@ -350,7 +352,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
} }
return userMapper.selectOne( return userMapper.selectOne(
new LambdaQueryWrapper<UserDO>() new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getPhone, phone) .eq(UserDO::getPhoneHash, phoneCrypto.index(phone))
.eq(UserDO::getIsDelete, 0) .eq(UserDO::getIsDelete, 0)
.last("limit 1") .last("limit 1")
); );
@@ -1,12 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class InventoryAdjustDTO {
private String changeType;
private BigDecimal changeQuantity;
private String remark;
}
@@ -1,16 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class InventoryItemDTO {
private Long shopId;
private String category;
private String itemName;
private String unit;
private BigDecimal stockQuantity;
private BigDecimal warningThreshold;
private Integer status;
}
@@ -1,33 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_inventory_item")
public class InventoryItemDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("category")
private String category;
@TableField("item_name")
private String itemName;
@TableField("unit")
private String unit;
@TableField("stock_quantity")
private BigDecimal stockQuantity;
@TableField("warning_threshold")
private BigDecimal warningThreshold;
@TableField("status")
private Integer status;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -1,31 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_inventory_record")
public class InventoryRecordDO extends BaseEntity {
@TableField("inventory_item_id")
private Long inventoryItemId;
@TableField("shop_id")
private Long shopId;
@TableField("change_type")
private String changeType;
@TableField("change_quantity")
private BigDecimal changeQuantity;
@TableField("before_quantity")
private BigDecimal beforeQuantity;
@TableField("after_quantity")
private BigDecimal afterQuantity;
@TableField("operator_id")
private Long operatorId;
@TableField("remark")
private String remark;
}
@@ -1,9 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface InventoryItemMapper extends BaseMapper<InventoryItemDO> {
}
@@ -1,9 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryRecordDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface InventoryRecordMapper extends BaseMapper<InventoryRecordDO> {
}
@@ -1,14 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.service;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryAdjustDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryItemDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.vo.InventoryItemVO;
import com.xiaowang.jayucloud.artlist.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,99 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryAdjustDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryItemDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryRecordDO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryRecordMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.service.InventoryService;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.vo.InventoryItemVO;
import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
@RequiredArgsConstructor
public class InventoryServiceImpl implements InventoryService {
private final InventoryItemMapper inventoryItemMapper;
private final InventoryRecordMapper inventoryRecordMapper;
@Override
@Transactional
public InventoryItemVO saveItem(InventoryItemDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getItemName() == null || dto.getItemName().isBlank()) {
throw new RuntimeException("库存物料信息不完整");
}
InventoryItemDO item = new InventoryItemDO();
BeanUtils.copyProperties(dto, item);
item.setStockQuantity(dto.getStockQuantity() == null ? BigDecimal.ZERO : dto.getStockQuantity());
item.setWarningThreshold(dto.getWarningThreshold() == null ? BigDecimal.ZERO : dto.getWarningThreshold());
item.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
item.setIsDelete(0);
inventoryItemMapper.insert(item);
return toVO(item);
}
@Override
@Transactional
public InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto) {
InventoryItemDO item = inventoryItemMapper.selectById(itemId);
if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) {
throw new RuntimeException("库存物料不存在");
}
BigDecimal before = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity();
BigDecimal delta = dto == null || dto.getChangeQuantity() == null ? BigDecimal.ZERO : dto.getChangeQuantity();
BigDecimal after = before.add(delta);
if (after.compareTo(BigDecimal.ZERO) < 0) {
throw new RuntimeException("库存不能小于 0");
}
item.setStockQuantity(after);
inventoryItemMapper.updateById(item);
InventoryRecordDO record = new InventoryRecordDO();
record.setInventoryItemId(item.getId());
record.setShopId(item.getShopId());
record.setChangeType(dto == null ? null : dto.getChangeType());
record.setChangeQuantity(delta);
record.setBeforeQuantity(before);
record.setAfterQuantity(after);
record.setOperatorId(operatorId);
record.setRemark(dto == null ? null : dto.getRemark());
inventoryRecordMapper.insert(record);
return toVO(item);
}
@Override
public PageResultVO<InventoryItemVO> listItems(Long shopId, Integer page, Integer size) {
int current = page == null || page < 1 ? 1 : page;
int pageSize = size == null || size < 1 ? 10 : size;
LambdaQueryWrapper<InventoryItemDO> wrapper = new LambdaQueryWrapper<InventoryItemDO>()
.eq(InventoryItemDO::getIsDelete, 0)
.orderByDesc(InventoryItemDO::getCreateTime);
if (shopId != null) {
wrapper.eq(InventoryItemDO::getShopId, shopId);
}
Page<InventoryItemDO> result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper);
PageResultVO<InventoryItemVO> vo = new PageResultVO<>();
vo.setList(result.getRecords().stream().map(this::toVO).toList());
vo.setTotal(result.getTotal());
vo.setPage(current);
vo.setSize(pageSize);
return vo;
}
private InventoryItemVO toVO(InventoryItemDO item) {
InventoryItemVO vo = new InventoryItemVO();
BeanUtils.copyProperties(item, vo);
BigDecimal stock = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity();
BigDecimal warning = item.getWarningThreshold() == null ? BigDecimal.ZERO : item.getWarningThreshold();
vo.setWarning(stock.compareTo(warning) <= 0);
return vo;
}
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class InventoryItemVO {
private Long id;
private Long shopId;
private String category;
private String itemName;
private String unit;
private BigDecimal stockQuantity;
private BigDecimal warningThreshold;
private Boolean warning;
private Integer status;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.manager.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
@Data
public class ManagerCustomerCreateDTO {
@NotBlank(message = "客户姓名不能为空")
private String nickname;
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
private String phone;
}
@@ -1,4 +1,4 @@
package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl; import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -212,7 +212,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
vo.setId(user.getId()); vo.setId(user.getId());
vo.setNickname(user.getNickname()); vo.setNickname(user.getNickname());
vo.setAccount(user.getAccount()); vo.setAccount(SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.ADMIN_LIST));
vo.setShopId(user.getShopId()); vo.setShopId(user.getShopId());
vo.setShopName(shopNameMap.get(user.getShopId())); vo.setShopName(shopNameMap.get(user.getShopId()));
vo.setType(user.getType()); vo.setType(user.getType());
@@ -498,6 +498,8 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
* @return private String result consumed by the caller or returned to the frontend * @return private String result consumed by the caller or returned to the frontend
*/ */
private String resolvePublisherName(UserDO currentUser) { private String resolvePublisherName(UserDO currentUser) {
return StringUtils.hasText(currentUser.getNickname()) ? currentUser.getNickname() : currentUser.getAccount(); return StringUtils.hasText(currentUser.getNickname())
? currentUser.getNickname()
: SensitiveFieldPolicy.account(currentUser.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY);
} }
} }
@@ -1,4 +1,4 @@
package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl; import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -267,7 +267,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
vo.setId(user.getId()); vo.setId(user.getId());
vo.setNickname(user.getNickname()); vo.setNickname(user.getNickname());
vo.setAccount(user.getAccount()); vo.setAccount(SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.ADMIN_LIST));
vo.setShopId(user.getShopId()); vo.setShopId(user.getShopId());
vo.setShopName(shopNameMap.get(user.getShopId())); vo.setShopName(shopNameMap.get(user.getShopId()));
vo.setType(user.getType()); vo.setType(user.getType());
@@ -881,6 +881,6 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
if (StringUtils.hasText(currentUser.getNickname())) { if (StringUtils.hasText(currentUser.getNickname())) {
return currentUser.getNickname(); return currentUser.getNickname();
} }
return currentUser.getAccount(); return SensitiveFieldPolicy.account(currentUser.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY);
} }
} }
@@ -48,6 +48,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.artist.support.BookableArtist
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStateMachine; import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStateMachine;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus; import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistCalendarAppointmentVO; import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistCalendarAppointmentVO;
@@ -3733,7 +3734,7 @@ public class OrderServiceImpl implements OrderService {
return customer.getNickname(); return customer.getNickname();
} }
if (StringUtils.hasText(customer.getAccount())) { if (StringUtils.hasText(customer.getAccount())) {
return customer.getAccount(); return SensitiveFieldPolicy.account(customer.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY);
} }
return "用户"; return "用户";
} }
@@ -23,10 +23,4 @@ public class PaymentController {
Long userId = (Long) request.getAttribute("userId"); Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.prepareOrderPayment(userId, orderId)); return Result.success(paymentService.prepareOrderPayment(userId, orderId));
} }
@PostMapping("/order/{orderId}/mock-success")
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
}
} }
@@ -6,7 +6,5 @@ import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.RefundOrderVO;
public interface PaymentService { public interface PaymentService {
PaymentOrderVO prepareOrderPayment(Long userId, Long orderId); PaymentOrderVO prepareOrderPayment(Long userId, Long orderId);
PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark);
RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark); RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark);
} }
@@ -60,34 +60,6 @@ public class PaymentServiceImpl implements PaymentService {
return toVO(payment); return toVO(payment);
} }
@Override
@Transactional
public PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark) {
OrderDO order = requirePayableOrder(null, orderId);
PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId);
if (payment == null) {
prepareOrderPayment(order.getUserId(), orderId);
payment = paymentOrderMapper.selectLatestByOrderId(orderId);
}
if (payment == null) {
throw new RuntimeException("支付单创建失败");
}
payment.setStatus(STATUS_PAID);
payment.setPaidAmount(payment.getPayAmount());
payment.setPayTime(LocalDateTime.now());
payment.setOperatorId(operatorId);
payment.setRemark(remark);
paymentOrderMapper.updateById(payment);
order.setPaymentStatus(STATUS_PAID);
order.setPaidAmount(payment.getPayAmount());
order.setPayTime(payment.getPayTime());
order.setPaymentMethod(payment.getChannel());
order.setPaymentOrderNo(payment.getPayNo());
orderMapper.updateById(order);
return toVO(payment);
}
@Override @Override
@Transactional @Transactional
public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) { public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) {
@@ -1,28 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class PlanningAppointmentCreateDTO {
private Long customerUserId;
private String customerName;
private String phone;
private Long productId;
private Integer quantity;
private Long artistId;
private String appointmentDate;
private String appointmentTime;
private String appointmentStartTime;
private Integer durationMinutes;
private String manualProductTitle;
private BigDecimal manualProductPrice;
private String manualProductDescription;
private String manualProductTags;
private String manualProductTargetAudience;
private String manualProductPrecautions;
private String manualProductImageFileIds;
private String remark;
private String clientRequestId;
}
@@ -1,13 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.dto;
import lombok.Data;
@Data
public class PlanningAppointmentMoveDTO {
private Long artistId;
private String appointmentDate;
private String appointmentTime;
private String appointmentStartTime;
private Integer durationMinutes;
private String clientRequestId;
}
@@ -1,8 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.dto;
import lombok.Data;
@Data
public class PlanningAppointmentStatusDTO {
private Integer status;
}
@@ -1,22 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.service;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentCreateDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentMoveDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentStatusDTO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jayucloud.artlist.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);
}
@@ -1,901 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentCreateDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentMoveDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentStatusDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.artlist.core.modules.planning.service.AppointmentCapacityService;
import com.xiaowang.jayucloud.artlist.core.modules.order.service.OrderService;
import com.xiaowang.jayucloud.artlist.core.modules.planning.service.PlanningService;
import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.modules.planning.support.PlanningCalendarSupport;
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningArtistCountVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningArtistVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningCalendarVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningDaySummaryVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningScheduleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PlanningServiceImpl implements PlanningService {
private static final int DEFAULT_SLOT_MINUTES = 30;
private static final int DEFAULT_DURATION_MINUTES = 60;
private static final int MONTH_AVAILABLE_MINUTES = 90;
private static final String RESERVATION_PENDING_QUOTE = "PENDING_QUOTE";
private static final String RESERVATION_CONFIRMED = "CONFIRMED";
private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT";
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW";
private static final List<String> ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED);
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final List<String> ARTIST_COLORS = List.of(
"#7BA7C7", "#8FB89A", "#A894C7", "#D7A86E", "#D98DA5", "#79A6A3", "#B9A16B", "#9BA9C8"
);
private final AdminScopeHelper adminScopeHelper;
private final UserMapper userMapper;
private final NailArtistInfoMapper nailArtistInfoMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final AppointmentReservationMapper appointmentReservationMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final ShopMapper shopMapper;
private final AppointmentCapacityService appointmentCapacityService;
private final OrderService orderService;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
@Override
public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) {
LocalDate start = startDate == null ? LocalDate.now() : startDate;
LocalDate end = endDate == null ? start : endDate;
if (end.isBefore(start)) {
end = start;
}
if (start.plusDays(61).isBefore(end)) {
end = start.plusDays(61);
}
Long shopId = requirePlanningShopId(currentUser);
ShopDO shop = shopMapper.selectById(shopId);
PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours(
shop == null ? null : shop.getBusinessHours()
);
List<PlanningArtistVO> artists = listArtists(shopId, artistId);
List<ArtistScheduleDO> schedules = listSchedules(shopId, start, end, artistId);
List<PlanningScheduleVO> scheduleVos = schedules.stream()
.map(schedule -> toScheduleVO(schedule, artists))
.sorted(Comparator.comparing(PlanningScheduleVO::getDate)
.thenComparing(PlanningScheduleVO::getStartTime)
.thenComparing(PlanningScheduleVO::getArtistName, Comparator.nullsLast(String::compareTo)))
.toList();
LocalDateTime rangeStart = start.atStartOfDay();
LocalDateTime rangeEnd = end.plusDays(1).atStartOfDay();
List<PlanningAppointmentVO> appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists);
Map<Long, Long> countByArtist = appointments.stream()
.filter(appointment -> appointment.getArtistId() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting()));
artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue()));
PlanningCalendarVO vo = new PlanningCalendarVO();
vo.setBusinessStartTime(businessHours.start().toString());
vo.setBusinessEndTime(businessHours.end().toString());
vo.setSlotMinutes(DEFAULT_SLOT_MINUTES);
vo.setArtists(artists);
vo.setSchedules(scheduleVos);
vo.setAppointments(appointments);
vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments));
return vo;
}
@Override
@Transactional
public PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto) {
if (dto == null) {
throw new RuntimeException("预约信息不能为空");
}
if (Integer.valueOf(3).equals(currentUser.getType())) {
throw new RuntimeException("美甲师账号只能查看预约,不能新建预约");
}
Long shopId = requirePlanningShopId(currentUser);
requireAppointmentDuration(dto.getDurationMinutes());
ProductDO product = resolveAppointmentProduct(dto, shopId);
UserDO artist = requireActiveArtist(dto.getArtistId(), shopId);
UserDO customer = resolveCustomer(shopId, dto);
int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity();
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity;
LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime());
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
ensureWithinBusinessHours(shopId, startTime, endTime);
BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice();
BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity));
OrderDO order = new OrderDO();
order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString());
order.setUserId(customer.getId());
order.setShopId(shopId);
order.setTotalAmount(amount);
order.setActualAmount(amount);
order.setCustomerRemark(trimToNull(dto.getRemark()));
order.setQuoteStatus("CONFIRMED");
order.setQuoteUserConfirmed(1);
order.setQuoteShopConfirmed(1);
order.setQuoteConfirmedTime(LocalDateTime.now());
order.setPaymentStatus("UNPAID");
order.setPayAmount(amount);
order.setPaidAmount(BigDecimal.ZERO);
order.setStatus(OrderStatus.PENDING_SERVICE.getCode());
order.setIsDelete(0);
orderMapper.insert(order);
OrderItemDO item = new OrderItemDO();
item.setOrderId(order.getId());
item.setProductId(product.getId());
item.setQuantity(quantity);
item.setPrice(unitPrice);
item.setArtistId(artist.getId());
item.setAppointmentTime(startTime);
item.setIsDelete(0);
orderItemMapper.insert(item);
appointmentCapacityService.reserveConfirmedOrThrow(
order.getId(),
item.getId(),
shopId,
artist.getId(),
product.getTitle(),
startTime,
endTime,
trimToNull(dto.getClientRequestId())
);
return getAppointment(currentUser, item.getId());
}
@Override
public PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId) {
if (orderItemId == null) {
throw new RuntimeException("预约ID不能为空");
}
OrderItemDO item = orderItemMapper.selectById(orderItemId);
if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) {
throw new RuntimeException("预约不存在");
}
OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId());
ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId());
AppointmentReservationDO reservation = findActiveReservation(orderItemId);
Map<Long, PlanningArtistVO> artistMap = listArtists(order.getShopId(), item.getArtistId()).stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a));
Map<Long, UserDO> customerMap = loadUsers(Set.of(order.getUserId()));
return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap);
}
@Override
@Transactional
public PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto) {
if (orderItemId == null || dto == null) {
throw new RuntimeException("改派信息不能为空");
}
OrderItemDO item = orderItemMapper.selectByIdForUpdate(orderItemId);
if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) {
throw new RuntimeException("预约不存在");
}
OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId());
ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId());
Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId();
UserDO artist = requireActiveArtist(targetArtistId, order.getShopId());
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) *
Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity());
LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime())
? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime())
: item.getAppointmentTime();
if (startTime == null) {
throw new RuntimeException("预约时间不能为空");
}
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
ensureWithinBusinessHours(order.getShopId(), startTime, endTime);
appointmentCapacityService.moveReservationForArtistChange(
order.getId(),
item.getId(),
order.getShopId(),
item.getArtistId(),
artist.getId(),
product.getTitle(),
startTime,
endTime
);
item.setArtistId(artist.getId());
item.setAppointmentTime(startTime);
orderItemMapper.updateById(item);
return getAppointment(currentUser, item.getId());
}
@Override
@Transactional
public Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto) {
if (orderId == null || dto == null || dto.getStatus() == null) {
throw new RuntimeException("预约状态不能为空");
}
OrderDO order = requireAccessibleOrder(currentUser, orderId);
int targetStatus = dto.getStatus();
if (targetStatus == OrderStatus.PENDING_SERVICE.getCode()) {
if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) {
orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode());
}
return true;
}
orderService.processOrder(orderId, targetStatus);
return true;
}
private Long requirePlanningShopId(UserDO currentUser) {
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
if (shopId == null || shopId <= 0) {
throw new RuntimeException("请先选择店铺后再查看规划");
}
return shopId;
}
private List<PlanningArtistVO> listArtists(Long shopId, Long artistId) {
QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
wrapper.eq("shop_id", shopId)
.eq("type", 3)
.eq("is_delete", 0)
.orderByAsc("id");
if (artistId != null && artistId > 0) {
wrapper.eq("id", artistId);
}
List<UserDO> artists = userMapper.selectList(wrapper);
if (artists == null || artists.isEmpty()) {
return List.of();
}
Set<Long> artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new));
Map<Long, NailArtistInfoDO> infoMap = loadArtistInfo(artistIds);
List<PlanningArtistVO> result = new ArrayList<>();
for (int i = 0; i < artists.size(); i++) {
UserDO user = artists.get(i);
NailArtistInfoDO info = infoMap.get(user.getId());
PlanningArtistVO vo = new PlanningArtistVO();
vo.setId(user.getId());
vo.setName(firstNonBlank(user.getNickname(), user.getAccount(), "美甲师" + (i + 1)));
vo.setShortName(PlanningCalendarSupport.shortName(vo.getName()));
vo.setPhone(firstNonBlank(user.getContactPhone(), user.getPhone(), ""));
vo.setAvatar(user.getAvatar());
vo.setColor(colorForArtist(user.getId(), i));
vo.setStatus(info == null || info.getStatus() == null ? user.getStatus() : info.getStatus());
vo.setStatusText(Integer.valueOf(0).equals(vo.getStatus()) ? "休息" : "可预约");
vo.setWorkStartTime(info == null || info.getWorkStartTime() == null ? null : info.getWorkStartTime().toString());
vo.setWorkEndTime(info == null || info.getWorkEndTime() == null ? null : info.getWorkEndTime().toString());
vo.setRangeCount(0);
result.add(vo);
}
return result;
}
private Map<Long, NailArtistInfoDO> loadArtistInfo(Set<Long> artistIds) {
if (artistIds == null || artistIds.isEmpty()) {
return Map.of();
}
QueryWrapper<NailArtistInfoDO> wrapper = new QueryWrapper<>();
wrapper.in("user_id", artistIds).eq("is_delete", 0);
return nailArtistInfoMapper.selectList(wrapper).stream()
.collect(Collectors.toMap(NailArtistInfoDO::getUserId, Function.identity(), (a, b) -> a));
}
private List<ArtistScheduleDO> listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) {
QueryWrapper<ArtistScheduleDO> wrapper = new QueryWrapper<>();
wrapper.eq("shop_id", shopId)
.between("work_date", start, end)
.eq("is_delete", 0)
.orderByAsc("work_date")
.orderByAsc("start_time");
if (artistId != null && artistId > 0) {
wrapper.eq("artist_id", artistId);
}
return artistScheduleMapper.selectList(wrapper);
}
private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, List<PlanningArtistVO> artists) {
Map<Long, String> artistNames = artists.stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a));
PlanningScheduleVO vo = new PlanningScheduleVO();
vo.setId(schedule.getId());
vo.setArtistId(schedule.getArtistId());
vo.setArtistName(artistNames.get(schedule.getArtistId()));
vo.setDate(schedule.getWorkDate() == null ? null : schedule.getWorkDate().toString());
vo.setStartTime(schedule.getStartTime() == null ? null : schedule.getStartTime().toString());
vo.setEndTime(schedule.getEndTime() == null ? null : schedule.getEndTime().toString());
vo.setCapacity(schedule.getCapacity());
vo.setStatus(schedule.getStatus());
vo.setStatusText(Integer.valueOf(1).equals(schedule.getStatus()) ? "可预约" : "请假");
vo.setRemark(schedule.getRemark());
return vo;
}
private List<PlanningAppointmentVO> listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd,
Long artistId, List<PlanningArtistVO> artists) {
QueryWrapper<AppointmentReservationDO> reservationWrapper = new QueryWrapper<>();
reservationWrapper.eq("shop_id", shopId)
.eq("is_delete", 0)
.in("status", ACTIVE_RESERVATION_STATUS)
.lt("appointment_start_time", rangeEnd)
.gt("appointment_end_time", rangeStart)
.orderByAsc("appointment_start_time");
if (artistId != null && artistId > 0) {
reservationWrapper.eq("artist_id", artistId);
}
List<AppointmentReservationDO> reservations = appointmentReservationMapper.selectList(reservationWrapper);
QueryWrapper<OrderItemDO> itemWrapper = new QueryWrapper<>();
itemWrapper.eq("is_delete", 0)
.isNotNull("appointment_time")
.ge("appointment_time", rangeStart)
.lt("appointment_time", rangeEnd)
.orderByAsc("appointment_time");
if (artistId != null && artistId > 0) {
itemWrapper.eq("artist_id", artistId);
}
List<OrderItemDO> fallbackItems = orderItemMapper.selectList(itemWrapper);
return buildAppointmentList(shopId, reservations, fallbackItems, artists);
}
private List<PlanningAppointmentVO> buildAppointmentList(Long shopId, List<AppointmentReservationDO> reservations,
List<OrderItemDO> fallbackItems, List<PlanningArtistVO> artists) {
Set<Long> itemIds = new HashSet<>();
Set<Long> orderIds = new HashSet<>();
for (AppointmentReservationDO reservation : safeList(reservations)) {
if (reservation.getOrderItemId() != null) {
itemIds.add(reservation.getOrderItemId());
}
if (reservation.getOrderId() != null) {
orderIds.add(reservation.getOrderId());
}
}
for (OrderItemDO item : safeList(fallbackItems)) {
if (item.getId() != null) {
itemIds.add(item.getId());
}
if (item.getOrderId() != null) {
orderIds.add(item.getOrderId());
}
}
Map<Long, OrderItemDO> itemMap = loadOrderItems(itemIds);
Map<Long, OrderDO> orderMap = loadOrders(orderIds);
Set<Long> productIds = itemMap.values().stream()
.map(OrderItemDO::getProductId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Set<Long> customerIds = orderMap.values().stream()
.map(OrderDO::getUserId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Map<Long, ProductDO> productMap = loadProducts(productIds);
Map<Long, UserDO> customerMap = loadUsers(customerIds);
Map<Long, PlanningArtistVO> artistMap = artists.stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a));
List<PlanningAppointmentVO> result = new ArrayList<>();
Set<Long> reservationItemIds = new HashSet<>();
for (AppointmentReservationDO reservation : safeList(reservations)) {
OrderItemDO item = itemMap.get(reservation.getOrderItemId());
OrderDO order = orderMap.get(reservation.getOrderId());
if (!isVisibleOrder(order, shopId)) {
continue;
}
ProductDO product = item == null ? null : productMap.get(item.getProductId());
UserDO customer = customerMap.get(order.getUserId());
result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap));
if (reservation.getOrderItemId() != null) {
reservationItemIds.add(reservation.getOrderItemId());
}
}
for (OrderItemDO item : safeList(fallbackItems)) {
if (item.getId() != null && reservationItemIds.contains(item.getId())) {
continue;
}
OrderDO order = orderMap.get(item.getOrderId());
if (!isVisibleOrder(order, shopId)) {
continue;
}
ProductDO product = productMap.get(item.getProductId());
UserDO customer = customerMap.get(order.getUserId());
result.add(toAppointmentVO(null, item, order, product, customer, artistMap));
}
result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo))
.thenComparing(PlanningAppointmentVO::getArtistName, Comparator.nullsLast(String::compareTo)));
return result;
}
private PlanningAppointmentVO toAppointmentVO(AppointmentReservationDO reservation, OrderItemDO item, OrderDO order,
ProductDO product, UserDO customer, Map<Long, PlanningArtistVO> artistMap) {
LocalDateTime start = reservation == null ? null : reservation.getAppointmentStartTime();
if (start == null && item != null) {
start = item.getAppointmentTime();
}
int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity());
LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime();
if (end == null && start != null) {
end = start.plusMinutes(durationMinutes);
}
Long artistId = reservation != null && reservation.getArtistId() != null
? reservation.getArtistId()
: item == null ? null : item.getArtistId();
PlanningArtistVO artist = artistId == null ? null : artistMap.get(artistId);
PlanningAppointmentVO vo = new PlanningAppointmentVO();
vo.setOrderId(order == null ? null : order.getId());
vo.setOrderNo(order == null ? null : order.getOrderNo());
vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId());
vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId());
vo.setCustomerName(customer == null ? "到店客户" : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户"));
vo.setCustomerPhone(customer == null ? null : firstNonBlank(customer.getContactPhone(), customer.getPhone(), ""));
vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId());
vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle())
? reservation.getProductTitle()
: product == null ? "预约作品" : product.getTitle());
vo.setArtistId(artistId);
vo.setArtistName(artist == null ? "未分配" : artist.getName());
vo.setArtistColor(artist == null ? ARTIST_COLORS.get(0) : artist.getColor());
vo.setDate(start == null ? null : start.toLocalDate().toString());
vo.setStartTime(start == null ? null : DATE_TIME_FORMATTER.format(start));
vo.setEndTime(end == null ? null : DATE_TIME_FORMATTER.format(end));
vo.setStartMinute(start == null ? null : start.toLocalTime().toSecondOfDay() / 60);
vo.setDurationMinutes(start == null || end == null ? durationMinutes : Math.toIntExact(Duration.between(start, end).toMinutes()));
vo.setStatus(order == null ? null : order.getStatus());
vo.setStatusText(statusText(order == null ? null : order.getStatus()));
String occupancyStatus = resolveOccupancyStatus(reservation, order);
vo.setOccupancyStatus(occupancyStatus);
vo.setCanEdit(canEditAppointment(order, occupancyStatus));
vo.setCanCancel(canCancelAppointment(order, occupancyStatus));
vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus));
vo.setAmount(order == null ? null : order.getActualAmount());
vo.setRemark(order == null ? null : order.getCustomerRemark());
return vo;
}
private List<PlanningDaySummaryVO> buildDaySummaries(LocalDate start, LocalDate end, List<PlanningArtistVO> artists,
List<ArtistScheduleDO> schedules, List<PlanningAppointmentVO> appointments) {
Map<String, List<PlanningAppointmentVO>> appointmentsByDate = appointments.stream()
.filter(appointment -> appointment.getDate() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getDate));
Map<String, List<ArtistScheduleDO>> schedulesByDate = schedules.stream()
.filter(schedule -> schedule.getWorkDate() != null)
.collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString()));
List<PlanningDaySummaryVO> summaries = new ArrayList<>();
LocalDate cursor = start;
while (!cursor.isAfter(end)) {
String date = cursor.toString();
List<PlanningAppointmentVO> dayAppointments = appointmentsByDate.getOrDefault(date, List.of());
Map<Long, Long> countByArtist = dayAppointments.stream()
.filter(appointment -> appointment.getArtistId() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting()));
List<ArtistScheduleDO> daySchedules = schedulesByDate.getOrDefault(date, List.of());
Map<Long, ArtistScheduleDO> scheduleByArtist = daySchedules.stream()
.collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a));
List<PlanningArtistCountVO> artistCounts = new ArrayList<>();
int workingArtistCount = 0;
int fullWorkingArtistCount = 0;
for (PlanningArtistVO artist : artists) {
int count = countByArtist.getOrDefault(artist.getId(), 0L).intValue();
ArtistScheduleDO schedule = scheduleByArtist.get(artist.getId());
List<PlanningAppointmentVO> artistAppointments = dayAppointments.stream()
.filter(appointment -> Objects.equals(appointment.getArtistId(), artist.getId()))
.toList();
String artistStatus = resolveArtistDayStatus(artist, schedule, artistAppointments);
if (!"rest".equals(artistStatus)) {
workingArtistCount++;
if ("full".equals(artistStatus)) {
fullWorkingArtistCount++;
}
}
PlanningArtistCountVO countVO = new PlanningArtistCountVO();
countVO.setArtistId(artist.getId());
countVO.setArtistName(artist.getName());
countVO.setShortName(artist.getShortName());
countVO.setColor(artist.getColor());
countVO.setCount(count);
countVO.setStatus(artistStatus);
artistCounts.add(countVO);
}
int total = dayAppointments.size();
boolean hasWorkingSchedule = workingArtistCount > 0;
boolean allFull = workingArtistCount > 0 && fullWorkingArtistCount == workingArtistCount;
PlanningDaySummaryVO summary = new PlanningDaySummaryVO();
summary.setDate(date);
summary.setTotalCount(total);
summary.setArtistCounts(artistCounts);
summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull));
summaries.add(summary);
cursor = cursor.plusDays(1);
}
return summaries;
}
private String resolveArtistDayStatus(PlanningArtistVO artist, ArtistScheduleDO schedule, List<PlanningAppointmentVO> appointments) {
if (schedule != null && !Integer.valueOf(1).equals(schedule.getStatus())) {
return "rest";
}
if (schedule == null || Integer.valueOf(0).equals(artist.getStatus())) {
return "rest";
}
if (hasContinuousFreeWindow(schedule, appointments, MONTH_AVAILABLE_MINUTES)) {
return appointments.isEmpty() ? "free" : "working";
}
return "full";
}
private boolean hasContinuousFreeWindow(ArtistScheduleDO schedule, List<PlanningAppointmentVO> appointments, int requiredMinutes) {
if (schedule == null || schedule.getStartTime() == null || schedule.getEndTime() == null || requiredMinutes <= 0) {
return false;
}
int startMinute = schedule.getStartTime().toSecondOfDay() / 60;
int endMinute = schedule.getEndTime().toSecondOfDay() / 60;
if (endMinute - startMinute < requiredMinutes) {
return false;
}
int cursor = startMinute;
List<TimeRange> ranges = appointments.stream()
.map(this::toTimeRange)
.filter(Objects::nonNull)
.filter(range -> range.endMinute() > startMinute && range.startMinute() < endMinute)
.map(range -> new TimeRange(Math.max(range.startMinute(), startMinute), Math.min(range.endMinute(), endMinute)))
.sorted(Comparator.comparing(TimeRange::startMinute).thenComparing(TimeRange::endMinute))
.toList();
for (TimeRange range : ranges) {
if (range.startMinute() - cursor >= requiredMinutes) {
return true;
}
cursor = Math.max(cursor, range.endMinute());
}
return endMinute - cursor >= requiredMinutes;
}
private TimeRange toTimeRange(PlanningAppointmentVO appointment) {
if (appointment == null) {
return null;
}
Integer startMinute = appointment.getStartMinute();
Integer durationMinutes = appointment.getDurationMinutes();
if (startMinute == null || durationMinutes == null || durationMinutes <= 0) {
return null;
}
return new TimeRange(startMinute, startMinute + durationMinutes);
}
private record TimeRange(int startMinute, int endMinute) {
}
private ProductDO requireActiveProduct(Long productId, Long shopId) {
if (productId == null) {
throw new RuntimeException("请选择预约作品");
}
ProductDO product = productMapper.selectById(productId);
if (product == null || Integer.valueOf(1).equals(product.getIsDelete()) || !shopId.equals(product.getShopId())) {
throw new RuntimeException("预约作品不存在或不属于当前店铺");
}
return product;
}
private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) {
if (dto.getProductId() != null) {
return requireActiveProduct(dto.getProductId(), shopId);
}
return createManualAppointmentProduct(dto, shopId);
}
private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) {
String title = trimToNull(dto.getManualProductTitle());
if (!hasText(title)) {
throw new RuntimeException("请选择预约作品或填写手动作品名称");
}
BigDecimal price = dto.getManualProductPrice();
if (price == null || price.compareTo(BigDecimal.ZERO) < 0) {
throw new RuntimeException("手动作品价格不能小于0");
}
int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes());
ProductDO product = new ProductDO();
product.setShopId(shopId);
product.setTitle(title);
product.setDescription(trimToNull(dto.getManualProductDescription()));
product.setTags(trimToNull(dto.getManualProductTags()));
product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience()));
product.setPrecautions(trimToNull(dto.getManualProductPrecautions()));
product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds()));
product.setPrice(price);
product.setLikeCount(0);
product.setCollectCount(0);
product.setApproximateDuration(durationMinutes + "分钟");
product.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId()));
product.setFrontVisible(0);
product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT);
product.setIsDelete(0);
productMapper.insert(product);
return product;
}
private int requireAppointmentDuration(Integer durationMinutes) {
if (durationMinutes == null || durationMinutes <= 0) {
throw new RuntimeException("预约时长不能为空且必须大于0分钟");
}
return durationMinutes;
}
private UserDO requireActiveArtist(Long artistId, Long shopId) {
if (artistId == null) {
throw new RuntimeException("请选择美甲师");
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())
|| !Integer.valueOf(3).equals(artist.getType()) || !shopId.equals(artist.getShopId())) {
throw new RuntimeException("美甲师不存在或不属于当前店铺");
}
return artist;
}
private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) {
if (dto.getCustomerUserId() != null) {
UserDO customer = userMapper.selectById(dto.getCustomerUserId());
if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) {
throw new RuntimeException("客户不存在");
}
return customer;
}
if (!hasText(dto.getPhone())) {
throw new RuntimeException("客户手机号不能为空");
}
QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
wrapper.eq("is_delete", 0)
.and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone()))
.last("LIMIT 1");
UserDO existing = userMapper.selectOne(wrapper);
if (existing != null) {
return existing;
}
UserDO customer = new UserDO();
customer.setShopId(shopId);
customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone()));
customer.setPhone(dto.getPhone());
customer.setContactPhone(dto.getPhone());
customer.setAccount(dto.getPhone());
customer.setPassword(ENCODED_UNSET_PASSWORD);
customer.setType(0);
customer.setStatus(1);
customer.setIsDelete(0);
userMapper.insert(customer);
return customer;
}
private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("订单不存在");
}
adminScopeHelper.ensureShopAccessible(currentUser, order.getShopId(), "无权访问其他店铺预约");
return order;
}
private AppointmentReservationDO findActiveReservation(Long orderItemId) {
QueryWrapper<AppointmentReservationDO> wrapper = new QueryWrapper<>();
wrapper.eq("order_item_id", orderItemId)
.eq("is_delete", 0)
.in("status", ACTIVE_RESERVATION_STATUS)
.orderByDesc("id")
.last("LIMIT 1");
return appointmentReservationMapper.selectOne(wrapper);
}
private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) {
ShopDO shop = shopMapper.selectById(shopId);
PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours());
LocalTime start = startTime.toLocalTime();
LocalTime end = endTime.toLocalTime();
if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) {
throw new RuntimeException("预约时间超出店铺营业时间");
}
}
private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) {
if (hasText(appointmentStartTime)) {
String normalized = appointmentStartTime.trim().replace('T', ' ');
if (normalized.length() == 16) {
normalized = normalized + ":00";
}
try {
return LocalDateTime.parse(normalized, DATE_TIME_FORMATTER);
} catch (DateTimeParseException ignored) {
return LocalDateTime.parse(appointmentStartTime.trim());
}
}
if (!hasText(appointmentDate) || !hasText(appointmentTime)) {
throw new RuntimeException("请选择预约日期和时间");
}
LocalDate date = LocalDate.parse(appointmentDate.trim());
LocalTime time = LocalTime.parse(appointmentTime.trim().length() == 5 ? appointmentTime.trim() + ":00" : appointmentTime.trim());
return LocalDateTime.of(date, time);
}
private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) {
if (overrideMinutes != null && overrideMinutes > 0) {
return overrideMinutes;
}
return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES);
}
private boolean isVisibleOrder(OrderDO order, Long shopId) {
return order != null
&& !Integer.valueOf(1).equals(order.getIsDelete())
&& shopId.equals(order.getShopId())
&& !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus());
}
private Map<Long, OrderItemDO> loadOrderItems(Set<Long> itemIds) {
if (itemIds == null || itemIds.isEmpty()) {
return Map.of();
}
return orderItemMapper.selectBatchIds(itemIds).stream()
.collect(Collectors.toMap(OrderItemDO::getId, Function.identity(), (a, b) -> a));
}
private Map<Long, OrderDO> loadOrders(Set<Long> orderIds) {
if (orderIds == null || orderIds.isEmpty()) {
return Map.of();
}
return orderMapper.selectBatchIds(orderIds).stream()
.collect(Collectors.toMap(OrderDO::getId, Function.identity(), (a, b) -> a));
}
private Map<Long, ProductDO> loadProducts(Set<Long> productIds) {
if (productIds == null || productIds.isEmpty()) {
return Map.of();
}
return productMapper.selectBatchIds(productIds).stream()
.collect(Collectors.toMap(ProductDO::getId, Function.identity(), (a, b) -> a));
}
private Map<Long, UserDO> loadUsers(Set<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return Map.of();
}
return userMapper.selectBatchIds(userIds).stream()
.collect(Collectors.toMap(UserDO::getId, Function.identity(), (a, b) -> a));
}
private String colorForArtist(Long artistId, int index) {
if (artistId == null) {
return ARTIST_COLORS.get(index % ARTIST_COLORS.size());
}
int colorIndex = Math.abs(artistId.hashCode()) % ARTIST_COLORS.size();
return ARTIST_COLORS.get(colorIndex);
}
private String statusText(Integer status) {
if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(status)) {
return "已确认";
}
if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(status)) {
return "已完成";
}
if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status)) {
return "已取消";
}
if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(status)) {
return "待确认";
}
return "未知";
}
private String resolveOccupancyStatus(AppointmentReservationDO reservation, OrderDO order) {
if (reservation != null && hasText(reservation.getStatus())) {
return reservation.getStatus();
}
if (order != null && Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) {
return RESERVATION_PENDING_QUOTE;
}
if (order != null && Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) {
return RESERVATION_CONFIRMED;
}
if (order != null && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) {
return "CANCELLED";
}
if (order != null && Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) {
return "COMPLETED";
}
return "UNKNOWN";
}
private Boolean canEditAppointment(OrderDO order, String occupancyStatus) {
return order != null
&& (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus))
&& !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())
&& !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus());
}
private Boolean canCancelAppointment(OrderDO order, String occupancyStatus) {
return order != null
&& (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus))
&& !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())
&& !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus());
}
private String resolveAppointmentConflictReason(String occupancyStatus) {
if (RESERVATION_PENDING_QUOTE.equals(occupancyStatus)) {
return "该时段已有待报价预约占用";
}
if (RESERVATION_CONFIRMED.equals(occupancyStatus)) {
return "该时段已有已确认预约占用";
}
return null;
}
private <T> List<T> safeList(List<T> list) {
return list == null ? List.of() : list;
}
private String firstNonBlank(String... values) {
for (String value : values) {
if (hasText(value)) {
return value.trim();
}
}
return "";
}
private String trimToNull(String value) {
return hasText(value) ? value.trim() : null;
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
}
@@ -1,83 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.support;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class PlanningCalendarSupport {
private static final LocalTime DEFAULT_START = LocalTime.of(10, 0);
private static final LocalTime DEFAULT_END = LocalTime.of(22, 0);
private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?)");
private PlanningCalendarSupport() {
}
public static String shortName(String name) {
if (name == null || name.trim().isEmpty()) {
return "?";
}
String normalized = name.trim();
if (normalized.startsWith("小") && normalized.length() > 1) {
return normalized.substring(1, 2);
}
if (normalized.endsWith("老师") && normalized.length() > 2) {
return normalized.substring(0, 1);
}
return normalized.substring(0, 1).toUpperCase();
}
public static BusinessHours parseBusinessHours(String businessHours) {
if (businessHours == null || businessHours.trim().isEmpty()) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
String[] parts = businessHours.trim().split("-");
if (parts.length != 2) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
try {
LocalTime start = LocalTime.parse(parts[0].trim());
LocalTime end = LocalTime.parse(parts[1].trim());
if (!start.isBefore(end)) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
return new BusinessHours(start, end);
} catch (RuntimeException ignored) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
}
public static int parseDurationMinutes(String durationText, int defaultMinutes) {
if (durationText == null || durationText.trim().isEmpty()) {
return defaultMinutes;
}
Matcher matcher = NUMBER_PATTERN.matcher(durationText.trim());
if (!matcher.find()) {
return defaultMinutes;
}
BigDecimal amount = new BigDecimal(matcher.group(1));
if (durationText.contains("小时") || durationText.toLowerCase().contains("hour")) {
amount = amount.multiply(BigDecimal.valueOf(60));
}
int minutes = amount.setScale(0, RoundingMode.HALF_UP).intValue();
return minutes > 0 ? minutes : defaultMinutes;
}
public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) {
if (!hasWorkingSchedule) {
return "rest";
}
if (allWorkingArtistsBusy) {
return "full";
}
if (totalCount <= 0) {
return "free";
}
return "working";
}
public record BusinessHours(LocalTime start, LocalTime end) {
}
}
@@ -1,33 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class PlanningAppointmentVO {
private Long orderId;
private String orderNo;
private Long orderItemId;
private Long customerId;
private String customerName;
private String customerPhone;
private Long productId;
private String productTitle;
private Long artistId;
private String artistName;
private String artistColor;
private String date;
private String startTime;
private String endTime;
private Integer startMinute;
private Integer durationMinutes;
private Integer status;
private String statusText;
private String occupancyStatus;
private Boolean canEdit;
private Boolean canCancel;
private String conflictReason;
private BigDecimal amount;
private String remark;
}
@@ -1,13 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningArtistCountVO {
private Long artistId;
private String artistName;
private String shortName;
private String color;
private Integer count;
private String status;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningArtistVO {
private Long id;
private String name;
private String shortName;
private String phone;
private String avatar;
private String color;
private Integer status;
private String statusText;
private String workStartTime;
private String workEndTime;
private Integer rangeCount;
}
@@ -1,16 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
import java.util.List;
@Data
public class PlanningCalendarVO {
private String businessStartTime;
private String businessEndTime;
private Integer slotMinutes;
private List<PlanningArtistVO> artists;
private List<PlanningScheduleVO> schedules;
private List<PlanningAppointmentVO> appointments;
private List<PlanningDaySummaryVO> daySummaries;
}
@@ -1,13 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
import java.util.List;
@Data
public class PlanningDaySummaryVO {
private String date;
private Integer totalCount;
private List<PlanningArtistCountVO> artistCounts;
private String dayStatus;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningScheduleVO {
private Long id;
private Long artistId;
private String artistName;
private String date;
private String startTime;
private String endTime;
private Integer capacity;
private Integer status;
private String statusText;
private String remark;
}
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.security.entity.SecurityAudit
import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.SecurityAuditLogMapper; import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.SecurityAuditLogMapper;
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService;
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO; import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -38,7 +39,7 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
try { try {
SecurityAuditLogDO log = new SecurityAuditLogDO(); SecurityAuditLogDO log = new SecurityAuditLogDO();
log.setUserId(userId); log.setUserId(userId);
log.setAccount(limit(account, 80)); log.setAccount(limit(SensitiveFieldPolicy.account(account, SensitiveFieldPolicy.Scenario.LOG), 80));
log.setAction(limit(action, 80)); log.setAction(limit(action, 80));
log.setResult(limit(result, 20)); log.setResult(limit(result, 20));
log.setReason(limit(reason, 500)); log.setReason(limit(reason, 500));
@@ -1,8 +1,15 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front; package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front;
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
import com.xiaowang.jayucloud.artlist.core.common.Result; import com.xiaowang.jayucloud.artlist.core.common.Result;
import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService;
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService; import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialScene;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -20,6 +27,18 @@ public class ContactInfoController {
* Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final ContactInfoService contactInfoService; private final ContactInfoService contactInfoService;
/**
* Variable `contactDialService`: resolves a one-time dial number after scene authorization.
*/
private final ContactDialService contactDialService;
/**
* Variable `requestThrottleService`: per-user throttling for all contact endpoints.
*/
private final RequestThrottleService requestThrottleService;
/**
* Variable `securityAuditLogService`: records who dialed which scene and the result, without the number.
*/
private final SecurityAuditLogService securityAuditLogService;
@GetMapping("/shop/{shopId}/manager") @GetMapping("/shop/{shopId}/manager")
/** /**
@@ -30,7 +49,8 @@ public class ContactInfoController {
* @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend * @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend
*/ */
public Result<ContactInfoVO> shopManager(HttpServletRequest request, @PathVariable Long shopId) { public Result<ContactInfoVO> shopManager(HttpServletRequest request, @PathVariable Long shopId) {
Long userId = (Long) request.getAttribute("userId"); Long userId = requireLogin(request);
requestThrottleService.checkContactInfoRead(request, userId);
return Result.success(contactInfoService.getShopManagerContact(userId, shopId)); return Result.success(contactInfoService.getShopManagerContact(userId, shopId));
} }
@@ -44,7 +64,8 @@ public class ContactInfoController {
* @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend * @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend
*/ */
public Result<ContactInfoVO> productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) { public Result<ContactInfoVO> productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) {
Long userId = (Long) request.getAttribute("userId"); Long userId = requireLogin(request);
requestThrottleService.checkContactInfoRead(request, userId);
return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId)); return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId));
} }
@@ -54,7 +75,8 @@ public class ContactInfoController {
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/ */
public Result<ContactInfoVO> orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) { public Result<ContactInfoVO> orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) {
Long userId = (Long) request.getAttribute("userId"); Long userId = requireLogin(request);
requestThrottleService.checkContactInfoRead(request, userId);
return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId)); return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId));
} }
@@ -62,9 +84,50 @@ public class ContactInfoController {
/** /**
* Run business method `platform`. * Run business method `platform`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend * @return Result<ContactInfoVO> result consumed by the caller or returned to the frontend
*/ */
public Result<ContactInfoVO> platform() { public Result<ContactInfoVO> platform(HttpServletRequest request) {
Long userId = requireLogin(request);
requestThrottleService.checkContactInfoRead(request, userId);
return Result.success(contactInfoService.getPlatformContact()); return Result.success(contactInfoService.getPlatformContact());
} }
@PostMapping("/dial")
/**
* 单次拨号取号:按场景校验可见范围后返回一次可用号码,号码不落库、不进日志、不进缓存。
*/
public Result<DialResponseVO> dial(HttpServletRequest request, @RequestBody DialRequestDTO dialRequestDTO) {
Long userId = requireLogin(request);
String account = (String) request.getAttribute("account");
requestThrottleService.checkContactDial(request, userId);
String action = "CONTACT_DIAL_" + safeSceneCode(dialRequestDTO);
try {
DialResponseVO response = contactDialService.dial(userId, dialRequestDTO);
securityAuditLogService.record(userId, account, action, "SUCCESS", null, request);
return Result.success(response);
} catch (BusinessException exception) {
securityAuditLogService.record(userId, account, action, "FAIL", "code=" + exception.getCode(), request);
throw exception;
}
}
private Long requireLogin(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
if (userId == null) {
throw new BusinessException(403, "请先登录后再获取联系方式");
}
return userId;
}
private String safeSceneCode(DialRequestDTO dialRequestDTO) {
if (dialRequestDTO == null || dialRequestDTO.getScene() == null) {
return "UNKNOWN";
}
try {
return DialScene.fromCode(dialRequestDTO.getScene()).name();
} catch (BusinessException exception) {
return "UNKNOWN";
}
}
} }
@@ -0,0 +1,25 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.dto;
import lombok.Data;
/**
* 单次拨号取号请求。
*/
@Data
public class DialRequestDTO {
/**
* 拨号场景:SHOP_MANAGER / ORDER_ARTIST / PRODUCT_ARTIST / PLATFORM。
*/
private String scene;
/**
* 目标标识:SHOP_MANAGER=店铺ID,ORDER_ARTIST=订单ID,PRODUCT_ARTIST=作品ID,PLATFORM 忽略。
*/
private Long targetId;
/**
* 可选的美甲师ID,仅 PRODUCT_ARTIST 场景使用;不传时取作品可预约美甲师的第一位。
*/
private Long artistId;
}
@@ -0,0 +1,15 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.service;
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
/**
* 单次拨号取号服务:按场景校验可见范围后返回一次可用的拨号号码。
*/
public interface ContactDialService {
/**
* 按场景解析并返回拨号号码;号码不落库、不进日志、不进缓存。
*/
DialResponseVO dial(Long userId, DialRequestDTO request);
}
@@ -0,0 +1,200 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
import com.xiaowang.jayucloud.artlist.core.config.DialProperties;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialScene;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialTargetProvider;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List;
@Service
@RequiredArgsConstructor
/**
* 单次拨号取号实现:先按场景校验可见范围,再由配置的提供方生成拨号号码。
*/
public class ContactDialServiceImpl implements ContactDialService {
private static final int FORBIDDEN = 403;
private final UserMapper userMapper;
private final ShopMapper shopMapper;
private final ProductMapper productMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final UserShopBindingSupport userShopBindingSupport;
private final DialProperties dialProperties;
private final List<DialTargetProvider> dialTargetProviders;
@Override
public DialResponseVO dial(Long userId, DialRequestDTO request) {
if (userId == null) {
throw new BusinessException(FORBIDDEN, "请先登录后再获取联系方式");
}
DialScene scene = DialScene.fromCode(request == null ? null : request.getScene());
UserDO caller = userMapper.selectById(userId);
if (caller == null || Integer.valueOf(1).equals(caller.getIsDelete())) {
throw new BusinessException(FORBIDDEN, "用户不存在或已失效");
}
String rawPhone = switch (scene) {
case SHOP_MANAGER -> resolveShopManagerPhone(caller, request.getTargetId());
case ORDER_ARTIST -> resolveOrderArtistPhone(caller, request.getTargetId());
case PRODUCT_ARTIST -> resolveProductArtistPhone(request.getTargetId(), request.getArtistId());
case PLATFORM -> resolvePlatformPhone();
};
if (!StringUtils.hasText(rawPhone)) {
throw new BusinessException(404, "该联系人暂未配置可拨打电话");
}
DialTargetProvider provider = selectProvider();
return provider.resolve(rawPhone);
}
private String resolveShopManagerPhone(UserDO caller, Long shopId) {
if (shopId == null || shopId <= 0) {
throw new BusinessException(400, "店铺ID不能为空");
}
ensureShopVisible(caller, shopId);
UserDO manager = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getType, 2)
.eq(UserDO::getShopId, shopId)
.eq(UserDO::getIsDelete, 0)
.eq(UserDO::getStatus, 1)
.last("LIMIT 1"));
return resolveContactPhone(manager);
}
private String resolveOrderArtistPhone(UserDO caller, Long orderId) {
if (orderId == null || orderId <= 0) {
throw new BusinessException(400, "订单ID不能为空");
}
OrderDO order = orderMapper.selectById(orderId);
if (order == null
|| Integer.valueOf(1).equals(order.getIsDelete())
|| !caller.getId().equals(order.getUserId())) {
throw new BusinessException(FORBIDDEN, "订单不存在或无权查看");
}
OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getOrderId, orderId)
.eq(OrderItemDO::getIsDelete, 0)
.isNotNull(OrderItemDO::getArtistId)
.last("LIMIT 1"))
.stream()
.findFirst()
.orElseThrow(() -> new BusinessException(404, "订单暂无可联系美甲师"));
return resolveContactPhone(userMapper.selectById(item.getArtistId()));
}
private String resolveProductArtistPhone(Long productId, Long artistId) {
if (productId == null || productId <= 0) {
throw new BusinessException(400, "作品ID不能为空");
}
ProductDO product = productMapper.selectById(productId);
if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) {
throw new BusinessException(FORBIDDEN, "作品不存在或不可见");
}
Long targetArtistId = artistId;
if (targetArtistId == null || targetArtistId <= 0) {
targetArtistId = firstBookableArtistId(product.getBookableArtists());
}
if (targetArtistId == null) {
throw new BusinessException(404, "该作品暂未配置可联系美甲师");
}
ensureArtistAllowed(product.getBookableArtists(), targetArtistId);
return resolveContactPhone(userMapper.selectById(targetArtistId));
}
private String resolvePlatformPhone() {
UserDO admin = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getType, 4)
.eq(UserDO::getIsDelete, 0)
.eq(UserDO::getStatus, 1)
.isNotNull(UserDO::getPhone)
.last("LIMIT 1"));
return resolveContactPhone(admin);
}
/**
* 校验当前用户是否可拨打该店铺店长:平台管理员、本店用户、有绑定关系或门店公开可见。
*/
private void ensureShopVisible(UserDO caller, Long shopId) {
if (Integer.valueOf(4).equals(caller.getType())) {
return;
}
if (shopId.equals(caller.getShopId()) || userShopBindingSupport.hasActiveBinding(caller.getId(), shopId)) {
return;
}
ShopDO shop = shopMapper.selectById(shopId);
if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) {
throw new BusinessException(FORBIDDEN, "店铺不存在或不可见");
}
}
private void ensureArtistAllowed(String rawBookableArtists, Long artistId) {
if (!StringUtils.hasText(rawBookableArtists)) {
return;
}
boolean allowed = Arrays.stream(rawBookableArtists.split(","))
.map(String::trim)
.filter(StringUtils::hasText)
.anyMatch(id -> id.equals(String.valueOf(artistId)));
if (!allowed) {
throw new BusinessException(FORBIDDEN, "该美甲师不可联系当前作品");
}
}
private Long firstBookableArtistId(String rawBookableArtists) {
if (!StringUtils.hasText(rawBookableArtists)) {
return null;
}
return Arrays.stream(rawBookableArtists.split(","))
.map(String::trim)
.filter(StringUtils::hasText)
.map(value -> {
try {
return Long.valueOf(value);
} catch (NumberFormatException exception) {
return null;
}
})
.filter(java.util.Objects::nonNull)
.findFirst()
.orElse(null);
}
private String resolveContactPhone(UserDO contact) {
if (contact == null || Integer.valueOf(1).equals(contact.getIsDelete())) {
return null;
}
return StringUtils.hasText(contact.getContactPhone()) ? contact.getContactPhone() : contact.getPhone();
}
private DialTargetProvider selectProvider() {
String configured = StringUtils.hasText(dialProperties.getProvider())
? dialProperties.getProvider().trim()
: "direct";
return dialTargetProviders.stream()
.filter(provider -> provider.name().equalsIgnoreCase(configured))
.findFirst()
.orElseThrow(() -> new BusinessException(9002, "拨号号码提供方配置无效"));
}
}
@@ -1,6 +1,7 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
@@ -8,11 +9,13 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService; import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService;
import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO;
import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -40,6 +43,10 @@ public class ContactInfoServiceImpl implements ContactInfoService {
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final OrderItemMapper orderItemMapper; private final OrderItemMapper orderItemMapper;
/**
* Variable `shopMapper`: used to verify the target shop is visible before exposing contact actions.
*/
private final com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper shopMapper;
/** /**
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
@@ -160,11 +167,23 @@ public class ContactInfoServiceImpl implements ContactInfoService {
* @return private void result consumed by the caller or returned to the frontend * @return private void result consumed by the caller or returned to the frontend
*/ */
private void ensureUserCanSeeShop(Long userId, Long shopId) { private void ensureUserCanSeeShop(Long userId, Long shopId) {
if (userId == null) return; if (userId == null) {
throw new BusinessException(403, "请先登录后再获取联系方式");
}
UserDO user = userMapper.selectById(userId); UserDO user = userMapper.selectById(userId);
if (user != null && shopId.equals(user.getShopId())) return; if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) {
if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { throw new BusinessException(403, "用户不存在或已失效");
// 店铺详情是公开入口,未绑定用户仍允许看联系方式。 }
if (Integer.valueOf(4).equals(user.getType())) {
return;
}
if (shopId.equals(user.getShopId()) || userShopBindingSupport.hasActiveBinding(userId, shopId)) {
return;
}
// 普通用户仅可查看未删除的门店,与公开店铺详情可见范围一致。
ShopDO shop = shopMapper.selectById(shopId);
if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) {
throw new BusinessException(403, "店铺不存在或不可见");
} }
} }
@@ -202,9 +221,11 @@ public class ContactInfoServiceImpl implements ContactInfoService {
return vo; return vo;
} }
vo.setContactUserId(user.getId()); vo.setContactUserId(user.getId());
vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname()
: SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY));
String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone(); String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone();
vo.setPhone(contactPhone); // 全场景脱敏:联系信息接口不再返回号码,真实号码只通过 /contact-info/dial 单次取号。
vo.setPhone(null);
vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); vo.setPhoneAvailable(StringUtils.hasText(contactPhone));
vo.setWechatId(user.getWechatId()); vo.setWechatId(user.getWechatId());
vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); vo.setWechatAvailable(StringUtils.hasText(user.getWechatId()));
@@ -0,0 +1,41 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
import com.xiaowang.jayucloud.artlist.core.common.BusinessException;
import org.springframework.util.StringUtils;
/**
* 拨号场景及其入参含义。
*/
public enum DialScene {
/**
* 店铺店长:targetId 为店铺ID。
*/
SHOP_MANAGER,
/**
* 订单美甲师:targetId 为订单ID。
*/
ORDER_ARTIST,
/**
* 作品美甲师:targetId 为作品ID,可选 artistId 指定美甲师。
*/
PRODUCT_ARTIST,
/**
* 平台客服:targetId 忽略。
*/
PLATFORM;
/**
* 解析前端传入的场景值。
*/
public static DialScene fromCode(String code) {
if (!StringUtils.hasText(code)) {
throw new BusinessException(400, "拨号场景不能为空");
}
try {
return DialScene.valueOf(code.trim().toUpperCase());
} catch (IllegalArgumentException exception) {
throw new BusinessException(400, "不支持的拨号场景");
}
}
}
@@ -0,0 +1,19 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
/**
* 拨号号码提供方:直拨真实号码或隐私号。
*/
public interface DialTargetProvider {
/**
* 配置值标识,与 jayucloud-artlist.dial.provider 对应。
*/
String name();
/**
* 将已通过授权校验的真实号码转换为拨号响应。
*/
DialResponseVO resolve(String rawPhone);
}
@@ -0,0 +1,30 @@
package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial;
import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO;
import org.springframework.stereotype.Component;
/**
* 直拨真实号码的提供方。
*/
@Component
public class DirectDialTargetProvider implements DialTargetProvider {
/**
* 直拨号码的有效提示时长,仅用于前端控制展示,不做服务端缓存。
*/
private static final int EXPIRES_IN_SECONDS = 300;
@Override
public String name() {
return "direct";
}
@Override
public DialResponseVO resolve(String rawPhone) {
DialResponseVO vo = new DialResponseVO();
vo.setMode("DIRECT");
vo.setDialNumber(rawPhone);
vo.setExpiresInSeconds(EXPIRES_IN_SECONDS);
return vo;
}
}

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