diff --git a/.agents/skills/jayu-api/SKILL.md b/.agents/skills/jayu-api/SKILL.md new file mode 100644 index 00000000..8b603505 --- /dev/null +++ b/.agents/skills/jayu-api/SKILL.md @@ -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` 包装;参数校验注解;错误语义与现有错误码一致。 +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 项逐一给出结论(含「不涉及」);前缀与门禁选择有依据;联调端同步修改已列出。 diff --git a/.agents/skills/jayu-database/SKILL.md b/.agents/skills/jayu-database/SKILL.md new file mode 100644 index 00000000..4c4d102f --- /dev/null +++ b/.agents/skills/jayu-database/SKILL.md @@ -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`、权限、协议、系统参数等)。 + +## 验收标准 + +- 版本文件命名与位置合规、可独立执行;实体与列一致;清单全部勾选;任务记录包含验证结论。 diff --git a/.agents/skills/jayu-devflow/SKILL.md b/.agents/skills/jayu-devflow/SKILL.md new file mode 100644 index 00000000..f5ab8108 --- /dev/null +++ b/.agents/skills/jayu-devflow/SKILL.md @@ -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 约束同样适用)。 + +## 验收标准 + +- 对应范围的验证命令已实际执行且输出通过;提交信息中文、范围干净;任务记录含版本化文件清单。 diff --git a/.agents/skills/jayu-devflow/references/pitfalls.md b/.agents/skills/jayu-devflow/references/pitfalls.md new file mode 100644 index 00000000..12d2be4b --- /dev/null +++ b/.agents/skills/jayu-devflow/references/pitfalls.md @@ -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 风险提示先核对实际引用与构建结果再决策。 diff --git a/.agents/skills/jayu-domain/SKILL.md b/.agents/skills/jayu-domain/SKILL.md new file mode 100644 index 00000000..9fef6724 --- /dev/null +++ b/.agents/skills/jayu-domain/SKILL.md @@ -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)。 + +## 安全边界 + +- 不输出、不记录任何真实客户手机号/账号明文;示例一律用占位符。 +- 隐私字段相关改动必须保持「默认脱敏、授权取明文」的基线,不得新开完整号码出口。 diff --git a/.agents/skills/jayu-domain/references/module-map.md b/.agents/skills/jayu-domain/references/module-map.md new file mode 100644 index 00000000..a00ce5cf --- /dev/null +++ b/.agents/skills/jayu-domain/references/module-map.md @@ -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`、DTO/VO 基类)、`config/`(MyBatis-Plus、加密组件、对象存储编排等)。 + +## 关键横切组件 + +- 手机号/账号加密:AES-GCM 加密组件 + `*_hash` 查询列;日志脱敏。 +- 协议拦截:服务端拦截未同意最新协议用户,微信端 4510 原地同意后重试。 +- 对象存储读取渠道优先级:配置项控制,历史数据多端点兼容解析。 diff --git a/.agents/skills/jayu-release/SKILL.md b/.agents/skills/jayu-release/SKILL.md new file mode 100644 index 00000000..7a420fb5 --- /dev/null +++ b/.agents/skills/jayu-release/SKILL.md @@ -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///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 一致。 diff --git a/.claude/skills/gitnexus-cli/SKILL.md b/.claude/skills/gitnexus-cli/SKILL.md new file mode 100644 index 00000000..3a00ab54 --- /dev/null +++ b/.claude/skills/gitnexus-cli/SKILL.md @@ -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 ` — 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 ` | 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 ` | Import opt-in Spring Boot Actuator mappings, beans, conditions, configprops, and env snapshots. Forces a full rebuild; unsupported with `--watch`. | +| `--asyncapi-spec ` | 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 `/.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 `-<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 ` | 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 ` | LLM model (default: MiniMax-M3) | +| `--base-url ` | LLM API base URL | +| `--api-key ` | LLM API key | +| `--concurrency ` | Parallel LLM calls (default: 3) | +| `--timeout ` | LLM request timeout in seconds (default: disabled) | +| `--retries ` | Max LLM retry attempts per request (default: 3) | +| `--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 diff --git a/.claude/skills/gitnexus-debugging/SKILL.md b/.claude/skills/gitnexus-debugging/SKILL.md new file mode 100644 index 00000000..41fb568f --- /dev/null +++ b/.claude/skills/gitnexus-debugging/SKILL.md @@ -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: ""}) → Find related execution flows +2. context({name: ""}) → 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. diff --git a/.claude/skills/gitnexus-exploring/SKILL.md b/.claude/skills/gitnexus-exploring/SKILL.md new file mode 100644 index 00000000..46fc187c --- /dev/null +++ b/.claude/skills/gitnexus-exploring/SKILL.md @@ -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: ""}) → Find related execution flows +4. context({name: ""}) → 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"`. diff --git a/.claude/skills/gitnexus-guide/SKILL.md b/.claude/skills/gitnexus-guide/SKILL.md new file mode 100644 index 00000000..c9661613 --- /dev/null +++ b/.claude/skills/gitnexus-guide/SKILL.md @@ -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 +``` diff --git a/.claude/skills/gitnexus-impact-analysis/SKILL.md b/.claude/skills/gitnexus-impact-analysis/SKILL.md new file mode 100644 index 00000000..85d90c90 --- /dev/null +++ b/.claude/skills/gitnexus-impact-analysis/SKILL.md @@ -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: () Worktree: Index: , 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 --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: ""` 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. diff --git a/.claude/skills/gitnexus-refactoring/SKILL.md b/.claude/skills/gitnexus-refactoring/SKILL.md new file mode 100644 index 00000000..9d63eb6e --- /dev/null +++ b/.claude/skills/gitnexus-refactoring/SKILL.md @@ -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. diff --git a/.gitea/scripts/dispatch-workflow.mjs b/.gitea/scripts/dispatch-workflow.mjs index 1026707d..9a3782df 100644 --- a/.gitea/scripts/dispatch-workflow.mjs +++ b/.gitea/scripts/dispatch-workflow.mjs @@ -3,7 +3,7 @@ const ref = process.argv[3] || process.env.GITHUB_REF_NAME; if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs '); const token = process.env.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 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'; diff --git a/.gitea/scripts/nacos-readback.mjs b/.gitea/scripts/nacos-readback.mjs new file mode 100644 index 00000000..6644cdec --- /dev/null +++ b/.gitea/scripts/nacos-readback.mjs @@ -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'); +} diff --git a/.gitea/scripts/nacos-readback.test.mjs b/.gitea/scripts/nacos-readback.test.mjs new file mode 100644 index 00000000..5b7e09b7 --- /dev/null +++ b/.gitea/scripts/nacos-readback.test.mjs @@ -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); +}); diff --git a/.gitea/scripts/rollback-nacos.mjs b/.gitea/scripts/rollback-nacos.mjs index a990da6f..d8ce02ef 100644 --- a/.gitea/scripts/rollback-nacos.mjs +++ b/.gitea/scripts/rollback-nacos.mjs @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'; import { readFile, readdir, rm } from 'node:fs/promises'; import { join } from 'node:path'; import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs'; +import { verifyConfigReadback } from './nacos-readback.mjs'; const environment = envName(process.env.NACOS_ENVIRONMENT); 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?${query}`, { method: 'DELETE' }); 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 actual = await check.text(); - if (exists ? (!check.ok || sha256(actual) !== sha256(content)) : check.status !== 404) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`); + const checkUrl = `${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`; + if (!(await verifyConfigReadback(checkUrl, content, exists))) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`); } } } diff --git a/.gitea/workflows/prod环境回退上一个版本.yml b/.gitea/workflows/prod环境回退上一个版本.yml index 62abf469..cfdd1455 100644 --- a/.gitea/workflows/prod环境回退上一个版本.yml +++ b/.gitea/workflows/prod环境回退上一个版本.yml @@ -19,7 +19,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 RELEASE_ENVIRONMENT: prod RELEASE_STORE_ROOT: /salon-release NACOS_ENVIRONMENT: prod diff --git a/.gitea/workflows/sit环境回退上一个版本.yml b/.gitea/workflows/sit环境回退上一个版本.yml index 4c786543..1cef030d 100644 --- a/.gitea/workflows/sit环境回退上一个版本.yml +++ b/.gitea/workflows/sit环境回退上一个版本.yml @@ -19,7 +19,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 RELEASE_ENVIRONMENT: sit RELEASE_STORE_ROOT: /salon-release NACOS_ENVIRONMENT: sit @@ -37,7 +37,7 @@ jobs: shell: bash env: GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 run: | git init . git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" @@ -72,7 +72,7 @@ jobs: run: node .gitea/scripts/rollback-nacos.mjs - name: 执行 SIT 应用回退 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: 记录回退后的成功版本 shell: bash run: node .gitea/scripts/record-rollback.mjs diff --git a/.gitea/workflows/回退dev环境nacos配置.yml b/.gitea/workflows/回退dev环境nacos配置.yml index ff9b637e..2f2e01c5 100644 --- a/.gitea/workflows/回退dev环境nacos配置.yml +++ b/.gitea/workflows/回退dev环境nacos配置.yml @@ -35,7 +35,7 @@ jobs: shell: bash env: GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 run: | git init . git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" diff --git a/.gitea/workflows/回退prod环境nacos配置.yml b/.gitea/workflows/回退prod环境nacos配置.yml index b3ab8539..7bad0473 100644 --- a/.gitea/workflows/回退prod环境nacos配置.yml +++ b/.gitea/workflows/回退prod环境nacos配置.yml @@ -33,13 +33,13 @@ jobs: NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} AUTO_ROLLBACK: ${{ inputs.auto_rollback }} - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 steps: - name: 检出回退脚本 shell: bash env: GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 run: | git init . git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" diff --git a/.gitea/workflows/回退sit环境nacos配置.yml b/.gitea/workflows/回退sit环境nacos配置.yml index 79011776..66b94562 100644 --- a/.gitea/workflows/回退sit环境nacos配置.yml +++ b/.gitea/workflows/回退sit环境nacos配置.yml @@ -30,13 +30,13 @@ jobs: NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} AUTO_ROLLBACK: ${{ inputs.auto_rollback }} - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 steps: - name: 检出回退脚本 shell: bash env: GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 run: | git init . git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" diff --git a/.gitea/workflows/自动发布dev环境nacos配置.yml b/.gitea/workflows/自动发布dev环境nacos配置.yml index 85b769ef..f83f2207 100644 --- a/.gitea/workflows/自动发布dev环境nacos配置.yml +++ b/.gitea/workflows/自动发布dev环境nacos配置.yml @@ -15,7 +15,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 NACOS_ENVIRONMENT: dev RELEASE_STORE_ROOT: /salon-release RELEASE_ENVIRONMENT: dev diff --git a/.gitea/workflows/自动发布prod环境nacos.yml b/.gitea/workflows/自动发布prod环境nacos.yml index 8bcbfc32..4fda6cd6 100644 --- a/.gitea/workflows/自动发布prod环境nacos.yml +++ b/.gitea/workflows/自动发布prod环境nacos.yml @@ -15,7 +15,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 NACOS_ENVIRONMENT: prod RELEASE_STORE_ROOT: /salon-release RELEASE_ENVIRONMENT: prod diff --git a/.gitea/workflows/自动发布sit环境nacos配置.yml b/.gitea/workflows/自动发布sit环境nacos配置.yml index a8d9c6be..6ee4c7e9 100644 --- a/.gitea/workflows/自动发布sit环境nacos配置.yml +++ b/.gitea/workflows/自动发布sit环境nacos配置.yml @@ -15,7 +15,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 NACOS_ENVIRONMENT: sit RELEASE_STORE_ROOT: /salon-release RELEASE_ENVIRONMENT: sit diff --git a/.gitea/workflows/自动部署prod环境.yml b/.gitea/workflows/自动部署prod环境.yml index 2b6c4c51..882a0da7 100644 --- a/.gitea/workflows/自动部署prod环境.yml +++ b/.gitea/workflows/自动部署prod环境.yml @@ -19,7 +19,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 RELEASE_ENVIRONMENT: prod RELEASE_SHA: ${{ inputs.release_sha || github.sha }} RELEASE_STORE_ROOT: /salon-release @@ -48,7 +48,7 @@ jobs: - name: 校验 PROD Nacos 发布记录 shell: bash run: node .gitea/scripts/assert-nacos-release.mjs - - name: 构建并固化 PROD 发布包 + - name: 构建并校验含 Flyway 迁移的 PROD 发布包 shell: pwsh env: VITE_API_BASE_URL: https://salon.yunail.art/api diff --git a/.gitea/workflows/自动部署sit环境.yml b/.gitea/workflows/自动部署sit环境.yml index be7c88ca..2173a18c 100644 --- a/.gitea/workflows/自动部署sit环境.yml +++ b/.gitea/workflows/自动部署sit环境.yml @@ -19,7 +19,7 @@ jobs: options: >- -v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 + GITHUB_SERVER_URL: http://wcsrv.top:3000 RELEASE_ENVIRONMENT: sit RELEASE_SHA: ${{ inputs.release_sha || github.sha }} RELEASE_STORE_ROOT: /salon-release @@ -45,11 +45,11 @@ jobs: - name: 校验 SIT Nacos 发布记录 shell: bash run: node .gitea/scripts/assert-nacos-release.mjs - - name: 构建 SIT 发布包 + - name: 构建并校验含 Flyway 迁移的 SIT 发布包 shell: pwsh env: - VITE_API_BASE_URL: https://sit.yunail.art/api - VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api + VITE_API_BASE_URL: https://sit.salon.yunail.art/api + VITE_ADMIN_API_BASE_URL: https://sit.salon.yunail.art/admin/api run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit - name: 持久化已校验发布包 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" - name: 执行 SIT 部署 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: 记录成功部署 shell: bash run: node .gitea/scripts/record-deploy.mjs diff --git a/.github/workflows/sync-to-gitea.yml b/.github/workflows/sync-to-gitea.yml new file mode 100644 index 00000000..4366471a --- /dev/null +++ b/.github/workflows/sync-to-gitea.yml @@ -0,0 +1,71 @@ + +name: Sync GitHub dev to Gitea + +on: + push: + branches: + - dev + paths-ignore: + - ".github/workflows/sync-to-gitea.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: github-to-gitea-dev + cancel-in-progress: false + +jobs: + sync: + name: Push GitHub dev to Gitea dev + runs-on: ubuntu-latest + + steps: + - name: Checkout full history + uses: actions/checkout@v4 + with: + ref: dev + fetch-depth: 0 + + - name: Validate and push to Gitea + shell: bash + env: + GITEA_USERNAME: ${{ secrets.GITEA_USERNAME }} + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + GITHUB_SHA: ${{ github.sha }} + run: | + set -euo pipefail + + if [[ -z "$GITEA_USERNAME" || -z "$GITEA_TOKEN" ]]; then + echo "::error::Missing Gitea credentials." + exit 1 + fi + + AUTH="$(printf '%s' "$GITEA_USERNAME:$GITEA_TOKEN" | base64 -w 0)" + + git remote add gitea https://code.yunail.art/xiaowang/JayuCloud.git + + git -c http.extraheader="AUTHORIZATION: basic $AUTH" \ + fetch gitea refs/heads/dev:refs/remotes/gitea/dev + + GITEA_SHA="$(git rev-parse refs/remotes/gitea/dev)" + + echo "GitHub commit: $GITHUB_SHA" + echo "Gitea commit: $GITEA_SHA" + + if [[ "$GITEA_SHA" == "$GITHUB_SHA" ]]; then + echo "Both repositories are already synchronized." + exit 0 + fi + + if ! git merge-base --is-ancestor "$GITEA_SHA" "$GITHUB_SHA"; then + echo "::error::Gitea dev has diverged from or advanced beyond GitHub dev." + echo "::error::Refusing to overwrite Gitea." + exit 1 + fi + + git -c http.extraheader="AUTHORIZATION: basic $AUTH" \ + push gitea "$GITHUB_SHA:refs/heads/dev" + + echo "Successfully synchronized GitHub dev to Gitea dev." diff --git a/.gitignore b/.gitignore index d2da9ad8..13606505 100644 --- a/.gitignore +++ b/.gitignore @@ -8,8 +8,9 @@ # Full-regression database backups may contain development user data. artifacts/full-regression/*backup*.sql -# Local Codex agent skill mirrors; canonical project skills live under .claude/. -.agents/ +# Local agent skill mirrors stay ignored; project skills under .agents/skills/ are versioned. +.agents/* +!.agents/skills/ # BlueJ files *.ctxt diff --git a/.trae/documents/Ardot图标补齐剩余步骤.md b/.trae/documents/Ardot图标补齐剩余步骤.md new file mode 100644 index 00000000..1057a4f3 --- /dev/null +++ b/.trae/documents/Ardot图标补齐剩余步骤.md @@ -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、不导出; +- 上传失败贴原始错误并跳过,继续其余页面。 +``` diff --git a/.trae/documents/Ardot设计稿-批次5收尾与批次6执行计划.md b/.trae/documents/Ardot设计稿-批次5收尾与批次6执行计划.md new file mode 100644 index 00000000..cc9d8469 --- /dev/null +++ b/.trae/documents/Ardot设计稿-批次5收尾与批次6执行计划.md @@ -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 与命名 / 截图验证结论 / 建议清单。 diff --git a/.trae/documents/Ardot设计稿优化-批次3收尾与批次4至6执行计划.md b/.trae/documents/Ardot设计稿优化-批次3收尾与批次4至6执行计划.md new file mode 100644 index 00000000..9de615e7 --- /dev/null +++ b/.trae/documents/Ardot设计稿优化-批次3收尾与批次4至6执行计划.md @@ -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,避免文字堆叠在父容器顶部(本任务已出现过两次)。 diff --git a/.trae/documents/ArtList账号加密与场景化脱敏实施计划_20261104.md b/.trae/documents/ArtList账号加密与场景化脱敏实施计划_20261104.md new file mode 100644 index 00000000..5fc684c2 --- /dev/null +++ b/.trae/documents/ArtList账号加密与场景化脱敏实施计划_20261104.md @@ -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 语义一致。 +- 管理端用户编辑页面不在本仓库,未覆盖。 diff --git a/.trae/documents/散客预约拨号与协议新版本强制同意实施计划.md b/.trae/documents/散客预约拨号与协议新版本强制同意实施计划.md new file mode 100644 index 00000000..b99a3ac2 --- /dev/null +++ b/.trae/documents/散客预约拨号与协议新版本强制同意实施计划.md @@ -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 currentVersions`、`Map acceptedVersions`、`List 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 后首次登录会出现强制同意弹层,属于预期行为。 diff --git a/AGENTS.md b/AGENTS.md index cee9ecb9..238bbb26 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,29 +1,30 @@ # 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 -- **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 `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 warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits. -- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. -- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`. +- **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 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 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. +- **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. +- **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 edit a function, class, or method without first running `impact` on it. -- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis. +- NEVER edit a function, class, or method before MCP/CLI 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 commit changes without running `detect_changes()` to check affected scope. +- NEVER commit before MCP/CLI graph change analysis. ## Resources | Resource | Use for | -|----------|---------| +| --- | --- | | `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness | | `gitnexus://repo/JayuCloud/clusters` | All functional areas | | `gitnexus://repo/JayuCloud/processes` | All execution flows | @@ -32,27 +33,115 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat ## CLI | Task | Read this skill file | -|------|---------------------| -| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | -| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | -| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | -| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | -| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | -| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/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-impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` | +| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` | +| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` | ## Project Workflow Rules +- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。 +- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。 - 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。 - 后端修改如果涉及 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 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。 -- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `scripts/0.0.1版本基线与后续迭代规则_20260628.md`,并在任务记录中写明新增或调整的版本化文件。 +- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `docs/scripts/运行与发布配置总说明.md`,并在任务记录中写明新增或调整的版本化文件。 - 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。 ## 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. - 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`。 +- 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..`;前端页面在 `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` 包装;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`。 diff --git a/CLAUDE.md b/CLAUDE.md index b53a6048..26eaebc7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,29 +1,30 @@ # 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 -- **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 `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 warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits. -- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. -- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`. +- **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 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 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. +- **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. +- **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 edit a function, class, or method without first running `impact` on it. -- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis. +- NEVER edit a function, class, or method before MCP/CLI 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 commit changes without running `detect_changes()` to check affected scope. +- NEVER commit before MCP/CLI graph change analysis. ## Resources | Resource | Use for | -|----------|---------| +| --- | --- | | `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness | | `gitnexus://repo/JayuCloud/clusters` | All functional areas | | `gitnexus://repo/JayuCloud/processes` | All execution flows | @@ -32,12 +33,17 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat ## CLI | Task | Read this skill file | -|------|---------------------| -| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | -| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | -| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | -| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | -| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | -| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/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-impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` | +| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` | +| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` | + +## Project Workflow Rules + +- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。 +- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。 diff --git a/JC-ArtList-Core/pom.xml b/JC-ArtList-Core/pom.xml index 6cf3f2e1..b21a25c6 100644 --- a/JC-ArtList-Core/pom.xml +++ b/JC-ArtList-Core/pom.xml @@ -110,6 +110,15 @@ mysql-connector-j runtime + + + org.flywaydb + flyway-core + + + org.flywaydb + flyway-mysql + com.baomidou mybatis-plus-boot-starter diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java new file mode 100644 index 00000000..03d6ad88 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java @@ -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"; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java index 59e35b0f..394c1b78 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java @@ -25,7 +25,6 @@ import org.springframework.context.annotation.Configuration; "com.xiaowang.jayucloud.artlist.core.modules.content.mapper", "com.xiaowang.jayucloud.artlist.core.modules.file.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.message.mapper", "com.xiaowang.jayucloud.artlist.core.modules.order.mapper", diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java index b0745ddf..4e65a0e4 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java @@ -1,6 +1,7 @@ package com.xiaowang.jayucloud.artlist.core.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; @@ -27,6 +28,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler { log.info("start insert fill ...."); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + fillPhoneHashes(metaObject); } @Override @@ -37,5 +39,31 @@ public class MyMetaObjectHandler implements MetaObjectHandler { public void updateFill(MetaObject metaObject) { log.info("start update fill ...."); 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); + } + } } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/PhoneCryptoProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/PhoneCryptoProperties.java new file mode 100644 index 00000000..bcb36c6a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/PhoneCryptoProperties.java @@ -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; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java index 1eaaef16..ca29dc27 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java @@ -28,6 +28,16 @@ public class RateLimitProperties { private LimitRule orderCreate = new LimitRule(10, 60); + /** + * 联系方式查询:按登录用户维度。 + */ + private LimitRule contactInfoRead = new LimitRule(30, 60); + + /** + * 单次拨号取号:按登录用户维度。 + */ + private LimitRule contactDial = new LimitRule(10, 60); + @Data /** * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java deleted file mode 100644 index e6884f79..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java +++ /dev/null @@ -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 result consumed by the caller or returned to the frontend - */ - public Result 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() { - }, - () -> buildDashboardStats(currentUser, shopIdScope) - ); - return Result.success(stats); - } - - @GetMapping("/analytics") - @RequirePermission("analytics:view") - public Result 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().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 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 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 listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { - LambdaQueryWrapper 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 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 listOrderIdsByArtist(Long artistId) { - List items = orderItemMapper.selectList(new LambdaQueryWrapper() - .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 result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr); - return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; - } else { - // 管理员查询所有订单 - java.util.Map 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 result consumed by the caller or returned to the frontend - */ - private List getHotProducts(Long shopId) { - // 通过订单商品表统计每个商品的订单数量,按订单数量排序 - // 使用SQL查询获取商品及其订单数量 - List> productOrderCounts = orderItemMapper.selectMaps( - new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper() - .select("product_id, COUNT(*) as order_count") - .groupBy("product_id") - .orderByDesc("order_count") - .last("LIMIT 5") - ); - - List hotProducts = new ArrayList<>(); - - // 遍历查询结果,获取商品详情 - for (Map 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 wrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - wrapper.eq(ProductDO::getShopId, shopId); - } - wrapper.orderByDesc(ProductDO::getLikeCount) - .last("LIMIT 5"); - List 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 result consumed by the caller or returned to the frontend - */ - private List getRecentActivities(Long shopId) { - List activities = new ArrayList<>(); - - LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - List 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 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 productWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - productWrapper.eq(ProductDO::getShopId, shopId); - } - productWrapper.orderByDesc(ProductDO::getCreateTime) - .last("LIMIT 2"); - List 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 commentWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - commentWrapper.eq(CommentDO::getShopId, shopId); - } - commentWrapper.orderByDesc(CommentDO::getCreateTime) - .last("LIMIT 2"); - List 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()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java deleted file mode 100644 index 2927c955..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java +++ /dev/null @@ -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); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java deleted file mode 100644 index 2be03c97..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java +++ /dev/null @@ -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); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java deleted file mode 100644 index 72a022a6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java +++ /dev/null @@ -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 orders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, OrderDO::getShopId, shopId) - .eq(OrderDO::getIsDelete, 0)); - if (artistId != null) { - Set orderIds = new HashSet<>(); - orderItemMapper.selectList(new LambdaQueryWrapper() - .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() - .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() - .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() - .eq(UserGrowthRecordDO::getSourceType, "REVIEW"))); - vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() - .eq(UserGrowthRecordDO::getSourceType, "REBOOK"))); - vo.setTotalAmount(orders.stream() - .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java deleted file mode 100644 index 7641e43d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java +++ /dev/null @@ -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 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 scopedOrders(Long shopId, Long artistId) { - List orders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, OrderDO::getShopId, shopId) - .eq(OrderDO::getIsDelete, 0)); - if (artistId == null) { - return orders; - } - Set orderIds = new HashSet<>(); - orderItemMapper.selectList(new LambdaQueryWrapper() - .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() - .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() - .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() - .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() - .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() - .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); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java deleted file mode 100644 index edc5acc4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java +++ /dev/null @@ -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): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List hotProducts; - /** - * Field `recentActivities` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List recentActivities; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java deleted file mode 100644 index e794124c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java deleted file mode 100644 index bebca37f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java deleted file mode 100644 index 8839fc77..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java deleted file mode 100644 index 28da0150..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java deleted file mode 100644 index 7f43bf77..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java deleted file mode 100644 index b4d1f4ce..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java +++ /dev/null @@ -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 workDays; - private LocalTime startTime; - private LocalTime endTime; - private Integer status; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java deleted file mode 100644 index 5ad05a63..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java +++ /dev/null @@ -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 listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate); - - ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId); - - ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto); - - ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java deleted file mode 100644 index d68ee7d1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java +++ /dev/null @@ -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 listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .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() - .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() - .eq(ArtistScheduleExceptionDO::getShopId, shopId) - .eq(ArtistScheduleExceptionDO::getArtistId, artistId) - .eq(ArtistScheduleExceptionDO::getWorkDate, workDate) - .eq(ArtistScheduleExceptionDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - private List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { - return exceptionMapper.selectList(new LambdaQueryWrapper() - .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 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 resolveWorkDays(List inputWorkDays, String presetType) { - List 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 normalized = new LinkedHashSet<>(); - for (Integer day : presetDays == null ? List.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 workDays) { - return workDays.stream() - .sorted() - .map(String::valueOf) - .collect(Collectors.joining(",")); - } - - private List 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) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java deleted file mode 100644 index 2833e5e7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java deleted file mode 100644 index fdf82f63..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java +++ /dev/null @@ -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 exceptions; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java deleted file mode 100644 index 89096f7c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java +++ /dev/null @@ -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 workDays; - private LocalTime startTime; - private LocalTime endTime; - private Integer status; - private String remark; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java deleted file mode 100644 index 2e2a9091..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java index 9a95ec9f..dff3dffe 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -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.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; 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. */ private final MessageHubClientService messageHubClientService; + private final PhoneCrypto phoneCrypto; @Override /** @@ -94,15 +96,16 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { public void sendVerificationCode(String phone, String sceneCode) { String code = generateVerificationCode(); - String codeKey = CODE_PREFIX + phone; - String sendTimeKey = SEND_TIME_PREFIX + phone; + String phoneKey = phoneCrypto.index(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(sendTimeKey, String.valueOf(System.currentTimeMillis()), Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); - log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); + log.info("验证码已发送,手机号: {}, sceneCode: {}", phoneCrypto.mask(phone), sceneCode); } @Override @@ -114,21 +117,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * @return boolean result consumed by the caller or returned to the frontend */ 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); if (storedCode == null) { - log.warn("验证码不存在或已过期,手机号: {}", phone); + log.warn("验证码不存在或已过期,手机号: {}", phoneCrypto.mask(phone)); return false; } if (!storedCode.equals(code)) { - log.warn("验证码错误,手机号: {}", phone); + log.warn("验证码错误,手机号: {}", phoneCrypto.mask(phone)); return false; } redisTemplate.delete(codeKey); - log.info("验证码验证成功,手机号: {}", phone); + log.info("验证码验证成功,手机号: {}", phoneCrypto.mask(phone)); return true; } @@ -140,7 +143,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * @return boolean result consumed by the caller or returned to the frontend */ 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); return sendTime == null; } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java index ed42aed6..8f17d3c3 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java @@ -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.extension.service.impl.ServiceImpl; @@ -489,7 +489,8 @@ public class CommentServiceImpl extends ServiceImpl im private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); 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()); if (shop != null) { diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 9e4ab43d..14c7467c 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -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.MessageHubPushConfigService; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; @@ -51,6 +52,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { * 平台品牌文案配置。 */ private final BrandProperties brandProperties; + private final PhoneCrypto phoneCrypto; @Value("${messagehub.client.sms-queue:smsQueue}") /** @@ -123,7 +125,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { String queueName = config == null ? smsQueue : config.getQueueName(); rabbitTemplate.convertAndSend(queueName, message); 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) { log.error("发送短信验证码失败", exception); throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java index e854db38..3ecaf046 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLogi import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; 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. */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final PhoneCrypto phoneCrypto; @Override /** @@ -350,7 +352,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } return userMapper.selectOne( new LambdaQueryWrapper() - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java deleted file mode 100644 index 362ba0fd..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java deleted file mode 100644 index c8213b4f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java deleted file mode 100644 index e6bc0072..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java deleted file mode 100644 index 7e035965..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java deleted file mode 100644 index 6fecd165..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java +++ /dev/null @@ -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 { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java deleted file mode 100644 index 8e9c7022..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java +++ /dev/null @@ -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 { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java deleted file mode 100644 index c3b7931e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java +++ /dev/null @@ -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 listItems(Long shopId, Integer page, Integer size); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java deleted file mode 100644 index 52f9bcec..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java +++ /dev/null @@ -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 listItems(Long shopId, Integer page, Integer size) { - int current = page == null || page < 1 ? 1 : page; - int pageSize = size == null || size < 1 ? 10 : size; - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(InventoryItemDO::getIsDelete, 0) - .orderByDesc(InventoryItemDO::getCreateTime); - if (shopId != null) { - wrapper.eq(InventoryItemDO::getShopId, shopId); - } - Page result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper); - PageResultVO 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; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java deleted file mode 100644 index 79c35fc2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java deleted file mode 100644 index 977f35b8..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java index a994fa33..a692e919 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -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.extension.service.impl.ServiceImpl; @@ -212,7 +212,7 @@ public class AnnouncementServiceImpl extends ServiceImpl mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); - } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java index 87ed325a..76f019f8 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java @@ -6,7 +6,5 @@ import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.RefundOrderVO; public interface PaymentService { PaymentOrderVO prepareOrderPayment(Long userId, Long orderId); - PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark); - RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark); } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java index b31d0ad3..6960caff 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java @@ -60,34 +60,6 @@ public class PaymentServiceImpl implements PaymentService { 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 @Transactional public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) { diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java deleted file mode 100644 index adbf959a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java deleted file mode 100644 index c3b5aafb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java deleted file mode 100644 index 12d8b336..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.xiaowang.jayucloud.artlist.core.modules.planning.dto; - -import lombok.Data; - -@Data -public class PlanningAppointmentStatusDTO { - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java deleted file mode 100644 index e1de78fa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java +++ /dev/null @@ -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); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java deleted file mode 100644 index e8e19b27..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java +++ /dev/null @@ -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 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 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 artists = listArtists(shopId, artistId); - List schedules = listSchedules(shopId, start, end, artistId); - List 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 appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists); - Map 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 artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - Map 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 listArtists(Long shopId, Long artistId) { - QueryWrapper 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 artists = userMapper.selectList(wrapper); - if (artists == null || artists.isEmpty()) { - return List.of(); - } - Set artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new)); - Map infoMap = loadArtistInfo(artistIds); - List 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 loadArtistInfo(Set artistIds) { - if (artistIds == null || artistIds.isEmpty()) { - return Map.of(); - } - QueryWrapper 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 listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) { - QueryWrapper 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 artists) { - Map 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 listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd, - Long artistId, List artists) { - QueryWrapper 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 reservations = appointmentReservationMapper.selectList(reservationWrapper); - - QueryWrapper 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 fallbackItems = orderItemMapper.selectList(itemWrapper); - - return buildAppointmentList(shopId, reservations, fallbackItems, artists); - } - - private List buildAppointmentList(Long shopId, List reservations, - List fallbackItems, List artists) { - Set itemIds = new HashSet<>(); - Set 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 itemMap = loadOrderItems(itemIds); - Map orderMap = loadOrders(orderIds); - Set productIds = itemMap.values().stream() - .map(OrderItemDO::getProductId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Set customerIds = orderMap.values().stream() - .map(OrderDO::getUserId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Map productMap = loadProducts(productIds); - Map customerMap = loadUsers(customerIds); - Map artistMap = artists.stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - - List result = new ArrayList<>(); - Set 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 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 buildDaySummaries(LocalDate start, LocalDate end, List artists, - List schedules, List appointments) { - Map> appointmentsByDate = appointments.stream() - .filter(appointment -> appointment.getDate() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getDate)); - Map> schedulesByDate = schedules.stream() - .filter(schedule -> schedule.getWorkDate() != null) - .collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString())); - - List summaries = new ArrayList<>(); - LocalDate cursor = start; - while (!cursor.isAfter(end)) { - String date = cursor.toString(); - List dayAppointments = appointmentsByDate.getOrDefault(date, List.of()); - Map countByArtist = dayAppointments.stream() - .filter(appointment -> appointment.getArtistId() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); - List daySchedules = schedulesByDate.getOrDefault(date, List.of()); - Map scheduleByArtist = daySchedules.stream() - .collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a)); - - List 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 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 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 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 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 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 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 loadOrderItems(Set 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 loadOrders(Set 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 loadProducts(Set 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 loadUsers(Set 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 List safeList(List 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(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java deleted file mode 100644 index 4301d134..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java +++ /dev/null @@ -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) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java deleted file mode 100644 index f5186a2a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java deleted file mode 100644 index 8f20d1e5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java deleted file mode 100644 index 5b64ebc9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java deleted file mode 100644 index a91048ff..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java +++ /dev/null @@ -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 artists; - private List schedules; - private List appointments; - private List daySummaries; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java deleted file mode 100644 index ca253a1f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java +++ /dev/null @@ -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 artistCounts; - private String dayStatus; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java deleted file mode 100644 index 924cb55d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java index 4dd0ef8f..10cf7f43 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java @@ -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.service.SecurityAuditLogService; 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.modules.security.vo.SecurityAuditLogVO; import lombok.RequiredArgsConstructor; @@ -38,7 +39,7 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { try { SecurityAuditLogDO log = new SecurityAuditLogDO(); log.setUserId(userId); - log.setAccount(limit(account, 80)); + log.setAccount(limit(SensitiveFieldPolicy.account(account, SensitiveFieldPolicy.Scenario.LOG), 80)); log.setAction(limit(action, 80)); log.setResult(limit(result, 20)); log.setReason(limit(reason, 500)); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java index 8ef3b590..c70f4650 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java @@ -1,8 +1,15 @@ 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.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.support.dial.DialScene; 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 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. */ 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") /** @@ -30,7 +49,8 @@ public class ContactInfoController { * @return Result result consumed by the caller or returned to the frontend */ public Result 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)); } @@ -44,7 +64,8 @@ public class ContactInfoController { * @return Result result consumed by the caller or returned to the frontend */ public Result 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)); } @@ -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. */ public Result 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)); } @@ -62,9 +84,50 @@ public class ContactInfoController { /** * 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. + * @param request parameter `request` supplied by the caller * @return Result result consumed by the caller or returned to the frontend */ - public Result platform() { + public Result platform(HttpServletRequest request) { + Long userId = requireLogin(request); + requestThrottleService.checkContactInfoRead(request, userId); return Result.success(contactInfoService.getPlatformContact()); } + + @PostMapping("/dial") + /** + * 单次拨号取号:按场景校验可见范围后返回一次可用号码,号码不落库、不进日志、不进缓存。 + */ + public Result 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"; + } + } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java new file mode 100644 index 00000000..03a8c533 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java @@ -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; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java new file mode 100644 index 00000000..33cb95f2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java @@ -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); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java new file mode 100644 index 00000000..91802edd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java @@ -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 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() + .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() + .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() + .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, "拨号号码提供方配置无效")); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java index 43ac284e..7ae696c7 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java @@ -1,6 +1,7 @@ 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.modules.order.entity.OrderDO; import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; 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.OrderMapper; 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.shop.service.ContactInfoService; 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.vo.ContactInfoVO; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; 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. */ 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. */ @@ -160,11 +167,23 @@ public class ContactInfoServiceImpl implements ContactInfoService { * @return private void result consumed by the caller or returned to the frontend */ private void ensureUserCanSeeShop(Long userId, Long shopId) { - if (userId == null) return; + if (userId == null) { + throw new BusinessException(403, "请先登录后再获取联系方式"); + } UserDO user = userMapper.selectById(userId); - if (user != null && shopId.equals(user.getShopId())) return; - if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { - // 店铺详情是公开入口,未绑定用户仍允许看联系方式。 + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + 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; } 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(); - vo.setPhone(contactPhone); + // 全场景脱敏:联系信息接口不再返回号码,真实号码只通过 /contact-info/dial 单次取号。 + vo.setPhone(null); vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); vo.setWechatId(user.getWechatId()); vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java new file mode 100644 index 00000000..62b21a7f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java @@ -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, "不支持的拨号场景"); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java new file mode 100644 index 00000000..48d5137c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java @@ -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); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java new file mode 100644 index 00000000..527ff2df --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java @@ -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; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java new file mode 100644 index 00000000..3a0b5a8f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; +import org.springframework.stereotype.Component; + +/** + * 隐私号提供方占位实现:未对接隐私号平台时明确报错,绝不回退成真实号码。 + */ +@Component +public class PlaceholderPrivacyNumberProvider implements DialTargetProvider { + + /** + * 隐私号未配置的业务码。 + */ + public static final int NOT_CONFIGURED_CODE = 9001; + + @Override + public String name() { + return "privacy-number"; + } + + @Override + public DialResponseVO resolve(String rawPhone) { + throw new BusinessException(NOT_CONFIGURED_CODE, "隐私号码服务未配置,暂时无法拨号"); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java new file mode 100644 index 00000000..7124e526 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.vo; + +import lombok.Data; + +/** + * 单次拨号取号响应。号码本身不进审计、日志与缓存。 + */ +@Data +public class DialResponseVO { + + /** + * 拨号模式:DIRECT=直拨真实号码,PRIVACY_NUMBER=隐私号码。 + */ + private String mode; + + /** + * 拨号号码;PRIVACY_NUMBER 未对接时不会返回真实号码。 + */ + private String dialNumber; + + /** + * 本次号码的有效时长(秒),供前端控制缓存时间。 + */ + private Integer expiresInSeconds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java index c5feab86..52a50ccc 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java @@ -9,7 +9,6 @@ import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.content.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.file.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.*; -import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.message.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.order.dto.*; @@ -39,6 +38,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; @@ -90,6 +90,7 @@ public class UserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; + private final PhoneCrypto phoneCrypto; /** * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -139,6 +140,10 @@ public class UserController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final LegalAgreementService legalAgreementService; + /** + * Variable `jwtUtil`: resolves the optional logged-in user on endpoints excluded from authentication. + */ + private final com.xiaowang.jayucloud.artlist.core.utils.JwtUtil jwtUtil; /** * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -360,7 +365,7 @@ public class UserController { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) ); boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); String message = available ? "账号可用" : "账号已被注册"; @@ -378,7 +383,7 @@ public class UserController { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -422,7 +427,7 @@ public class UserController { public Result checkPhoneAvailability(@PathVariable String phone) { UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) ); boolean available = userDO == null; @@ -551,7 +556,7 @@ public class UserController { boolean success = userService.register(registerRequestDTO); UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) + .eq(UserDO::getAccountHash, phoneCrypto.index(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()))) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -598,8 +603,9 @@ public class UserController { @PostMapping("/send-verification-code") @OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试") public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { - requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); - if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { + String phone = resolveSendCodePhone(request, sendVerificationCodeRequestDTO); + requestThrottleService.checkSendCode(request, phone); + if (!verificationCodeService.canResend(phone)) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -608,10 +614,41 @@ public class UserController { */ throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); } - verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); + verificationCodeService.sendVerificationCode(phone, sendVerificationCodeRequestDTO.getSceneCode()); return Result.success(true); } + /** + * 修改密码等"发给自己"的验证码场景:号码由服务端按当前登录用户取,客户端传参忽略。 + */ + private String resolveSendCodePhone(HttpServletRequest request, SendVerificationCodeRequestDTO dto) { + String sceneCode = dto.getSceneCode(); + if (!"USER_CHANGE_PASSWORD_SMS_CODE".equals(sceneCode)) { + return dto.getPhone(); + } + Long userId = resolveOptionalUserId(request); + if (userId == null) { + return dto.getPhone(); + } + return userService.getBoundPhone(userId); + } + + private Long resolveOptionalUserId(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId != null) { + return userId; + } + String authorization = request.getHeader("Authorization"); + if (authorization == null || !authorization.startsWith("Bearer ")) { + return null; + } + String token = authorization.substring("Bearer ".length()).trim(); + if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) { + return null; + } + return jwtUtil.getUserIdFromToken(token); + } + /** * 通过手机号验证码重置密码 * diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java index cc7940bb..166dbadd 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java @@ -12,6 +12,8 @@ import lombok.EqualsAndHashCode; import java.time.LocalDate; import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +import com.xiaowang.jayucloud.artlist.core.support.privacy.AccountPhoneTypeHandler; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneEncryptionTypeHandler; /** * 系统用户信息表 DO * 对应数据库表 t_user @@ -22,7 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; @Getter @Setter @EqualsAndHashCode(callSuper = true) -@TableName("t_user") +@TableName(value = "t_user", autoResultMap = true) public class UserDO extends BaseEntity { /** @@ -44,23 +46,41 @@ public class UserDO extends BaseEntity { private String nickname; /** - * 用户账号(登录用) + * 用户账号(登录用,AES-GCM 密文,落库列 account;实体中保持明文,便于业务使用) */ - @TableField("account") + @TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class) private String account; /** - * 手机号 + * 账号哈希(HMAC-SHA256,十六进制小写),所有账号等值查询统一使用 */ - @TableField("phone") + @TableField("account_hash") + private String accountHash; + + /** + * 手机号(AES-GCM 密文,落库列 phone_cipher;实体中保持明文,便于业务使用) + */ + @TableField(value = "phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class) private String phone; /** - * 联系电话 + * 手机号哈希(HMAC-SHA256,十六进制小写),用于等值查询与唯一去重 */ - @TableField("contact_phone") + @TableField("phone_hash") + private String phoneHash; + + /** + * 联系电话(AES-GCM 密文,落库列 contact_phone_cipher;实体中保持明文) + */ + @TableField(value = "contact_phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class) private String contactPhone; + /** + * 联系电话哈希(HMAC-SHA256,十六进制小写),用于等值查询 + */ + @TableField("contact_phone_hash") + private String contactPhoneHash; + /** * 生日 */ diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java index 950a1ad0..88ac5275 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java @@ -394,4 +394,9 @@ public interface UserService extends IService { * @return boolean result consumed by the caller or returned to the frontend */ boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO); + + /** + * 获取当前登录用户已绑定的手机号(明文,仅用于服务端发码,不返回前端)。 + */ + String getBoundPhone(Long userId); } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java index 18d98347..d75fdfe0 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java @@ -6,13 +6,13 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.jayucloud.artlist.core.config.BrandProperties; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; import com.xiaowang.jayucloud.artlist.core.common.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.content.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.file.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.*; -import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.message.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.order.dto.*; @@ -49,6 +49,8 @@ import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPa import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog; import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy; import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; @@ -119,10 +121,10 @@ public class UserServiceImpl extends ServiceImpl implements private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5); /** - * Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role. + * Purpose: DELETED_ACCOUNT_MARKER supports UserServiceImpl.java by holding or executing the deleted account marker business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ - private static final String DELETED_PHONE_MARKER = "_deleted_"; + private static final String DELETED_ACCOUNT_MARKER = "_deleted_"; /** * Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -171,6 +173,7 @@ public class UserServiceImpl extends ServiceImpl implements */ private final UserInviteCodeMapper userInviteCodeMapper; private final BrandProperties brandProperties; + private final PhoneCrypto phoneCrypto; /** * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -370,7 +373,7 @@ public class UserServiceImpl extends ServiceImpl implements // 检查账号是否已存在 UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(validatedAccount)) .eq(UserDO::getIsDelete, 0) ); if (existingUser != null) { @@ -387,7 +390,6 @@ public class UserServiceImpl extends ServiceImpl implements String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); Integer userType = userDTO.getType(); String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); - UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); /** * Run business method `ensureShopBindingRequirement`. @@ -535,7 +537,7 @@ public class UserServiceImpl extends ServiceImpl implements if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) ); if (existingUser != null) { @@ -595,7 +597,6 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setVipId(userDTO.getVipId()); } Integer targetUserType = userDO.getType(); - UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); List validatedShopIds = null; boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; if (shopBindingChanged) { @@ -654,19 +655,34 @@ public class UserServiceImpl extends ServiceImpl implements .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) ); LocalDateTime now = LocalDateTime.now(); + String deletedAccount = buildDeletedAccount(userDO); return userMapper.update( null, - new LambdaUpdateWrapper() - .eq(UserDO::getId, id) - .eq(UserDO::getIsDelete, 0) - .set(UserDO::getAccount, buildDeletedAccount(userDO)) - .set(UserDO::getPhone, buildDeletedPhone(userDO)) - .set(UserDO::getStatus, 0) - .set(UserDO::getIsDelete, 1) - .set(UserDO::getUpdateTime, now) + buildSoftDeleteUpdate(id, + phoneCrypto.encryptAccount(deletedAccount), + phoneCrypto.index(deletedAccount), + now) ) > 0; } + /** + * 构造账号注销更新条件:账号改为占位值,手机号/联系电话的密文与哈希一并清空,避免数据残留。 + */ + static LambdaUpdateWrapper buildSoftDeleteUpdate(Long id, String encryptedAccount, String accountHash, LocalDateTime now) { + return new LambdaUpdateWrapper() + .eq(UserDO::getId, id) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getAccount, encryptedAccount) + .set(UserDO::getAccountHash, accountHash) + .set(UserDO::getPhone, null) + .set(UserDO::getPhoneHash, null) + .set(UserDO::getContactPhone, null) + .set(UserDO::getContactPhoneHash, null) + .set(UserDO::getStatus, 0) + .set(UserDO::getIsDelete, 1) + .set(UserDO::getUpdateTime, now); + } + /** * 根据ID获取用户信息 * @param id 用户ID @@ -684,7 +700,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return convertToVO(userDO); + return convertToVO(userDO, SensitiveFieldPolicy.Scenario.SELF_PROFILE); } /** @@ -698,7 +714,7 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getIsDelete, 0) ); return userDOs.stream() - .map(this::convertToVO) + .map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)) .collect(Collectors.toList()); } @@ -719,7 +735,7 @@ public class UserServiceImpl extends ServiceImpl implements .in(UserDO::getId, userIds) ); return userDOs.stream() - .map(this::convertToVO) + .map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)) .collect(Collectors.toList()); } @@ -736,7 +752,7 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getType, type) ); return userDOs.stream() - .map(this::convertToVO) + .map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)) .collect(Collectors.toList()); } @@ -750,7 +766,7 @@ public class UserServiceImpl extends ServiceImpl implements String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) ); if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { @@ -762,7 +778,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return convertToVO(userDO); + return convertToVO(userDO, SensitiveFieldPolicy.Scenario.SELF_PROFILE); } /** @@ -771,7 +787,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO 用户DO * @return 用户VO */ - private UserVO convertToVO(UserDO userDO) { + private UserVO convertToVO(UserDO userDO, SensitiveFieldPolicy.Scenario scenario) { UserVO userVO = new UserVO(); userVO.setId(userDO.getId()); List shopOptions = resolveShopOptions(userDO, true, false); @@ -792,9 +808,9 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userVO.setNickname(userDO.getNickname()); - userVO.setAccount(userDO.getAccount()); - userVO.setPhone(userDO.getPhone()); - userVO.setContactPhone(userDO.getContactPhone()); + userVO.setAccount(SensitiveFieldPolicy.account(userDO.getAccount(), scenario)); + userVO.setPhone(SensitiveFieldPolicy.phone(userDO.getPhone(), scenario)); + userVO.setContactPhone(SensitiveFieldPolicy.phone(userDO.getContactPhone(), scenario)); userVO.setBirthday(userDO.getBirthday()); userVO.setWechatId(userDO.getWechatId()); userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); @@ -870,7 +886,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -920,7 +936,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(normalizedPhone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -975,7 +991,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -1023,7 +1039,7 @@ public class UserServiceImpl extends ServiceImpl implements String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) ); /** @@ -1086,7 +1102,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phoneLoginRequestDTO.getPhone())) .eq(UserDO::getIsDelete, 0) ); @@ -1127,7 +1143,7 @@ public class UserServiceImpl extends ServiceImpl implements public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -1240,7 +1256,7 @@ public class UserServiceImpl extends ServiceImpl implements String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) ); /** @@ -1449,7 +1465,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(validatedAccount)) ); if (existingUser != null) { @@ -1472,7 +1488,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO existingPhoneUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, registerRequestDTO.getPhone()) + .eq(UserDO::getPhoneHash, phoneCrypto.index(registerRequestDTO.getPhone())) .eq(UserDO::getIsDelete, 0) ); @@ -1542,7 +1558,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, phone) + .eq(UserDO::getAccountHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -1714,7 +1730,6 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getWechatQrCode() != null) { userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); } - UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); userDO.setUpdateTime(LocalDateTime.now()); boolean updated = userMapper.updateById(userDO) > 0; @@ -1897,10 +1912,17 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.eq(UserDO::getIsDelete, 0); // 不再过滤普通用户,由前端根据用户角色进行过滤 if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(UserDO::getAccount, keyword) - .or().like(UserDO::getNickname, keyword) - .or().like(UserDO::getPhone, keyword) - .or().like(UserDO::getContactPhone, keyword)); + String keywordPhoneHash = phoneCrypto.isMobilePhone(keyword) ? phoneCrypto.index(keyword) : null; + String keywordAccountHash = phoneCrypto.index(keyword); + wrapper.and(w -> { + // 账号落库为密文,不能模糊检索,统一走 account_hash 精确匹配 + w.eq(UserDO::getAccountHash, keywordAccountHash).or().like(UserDO::getNickname, keyword); + // 手机号只做精确匹配:密文不可模糊检索,统一走 phone_hash + if (keywordPhoneHash != null) { + w.or().eq(UserDO::getPhoneHash, keywordPhoneHash) + .or().eq(UserDO::getContactPhoneHash, keywordPhoneHash); + } + }); } if (shopId != null && shopId > 0) { List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); @@ -1952,7 +1974,7 @@ public class UserServiceImpl extends ServiceImpl implements Page userPage = userMapper.selectPage(pageParam, wrapper); PageResultVO result = new PageResultVO<>(); - result.setList(userPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setList(userPage.getRecords().stream().map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)).collect(Collectors.toList())); result.setTotal(userPage.getTotal()); result.setPage(page); result.setSize(size); @@ -2212,7 +2234,7 @@ public class UserServiceImpl extends ServiceImpl implements * @return boolean result consumed by the caller or returned to the frontend */ public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { - String oldPhone = updatePhoneDTO.getOldPhone(); + // 原手机号由服务端按当前登录用户读取,客户端传入的 oldPhone 仅为兼容旧协议,不参与校验。 String newPhone = updatePhoneDTO.getNewPhone(); String verificationCode = updatePhoneDTO.getVerificationCode(); @@ -2232,14 +2254,6 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("当前账号未绑定手机号"); } - if (!userDO.getPhone().equals(oldPhone)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("原手机号不匹配"); - } /** * Run business method `validateVerificationCode`. @@ -2264,6 +2278,19 @@ public class UserServiceImpl extends ServiceImpl implements return userMapper.updateById(userDO) > 0; } + @Override + /** + * 获取当前登录用户已绑定手机号的明文,仅用于服务端发码。 + */ + public String getBoundPhone(Long userId) { + UserDO userDO = userMapper.selectById(userId); + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone())) { + throw new BusinessException(400, "当前账号未绑定手机号"); + } + return userDO.getPhone(); + } + @Override /** * Run business method `resetPasswordByPhone`. @@ -2285,9 +2312,9 @@ public class UserServiceImpl extends ServiceImpl implements */ validateVerificationCode(phone, verificationCode); - // 根据手机号查找用户 + // 根据手机号哈希查找用户 LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); - wrapper.eq(UserDO::getPhone, phone); + wrapper.eq(UserDO::getPhoneHash, phoneCrypto.index(phone)); wrapper.eq(UserDO::getIsDelete, 0); UserDO userDO = userMapper.selectOne(wrapper); @@ -2335,26 +2362,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param 50 parameter `50` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); - } - - /** - * Run business method `buildDeletedPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildDeletedPhone(UserDO userDO) { - String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); - String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone"; - /** - * Run business method `trimDeletedPlaceholder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param suffix parameter `suffix` supplied by the caller - * @param 50 parameter `50` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); + return trimDeletedPlaceholder(base + DELETED_ACCOUNT_MARKER + suffix, 50); } /** @@ -2500,7 +2508,8 @@ public class UserServiceImpl extends ServiceImpl implements * @return private String result consumed by the caller or returned to the frontend */ private String buildLoginFailKey(String account) { - return LOGIN_FAIL_KEY_PREFIX + account.trim(); + String indexedAccount = StringUtils.hasText(account) ? phoneCrypto.index(account) : null; + return LOGIN_FAIL_KEY_PREFIX + (indexedAccount == null ? "anonymous" : indexedAccount); } /** @@ -2970,9 +2979,6 @@ public class UserServiceImpl extends ServiceImpl implements } return null; } - if (isDeletedPlaceholderPhone(normalizedPhone)) { - return normalizedPhone; - } if (!normalizedPhone.matches(PHONE_REGEX)) { /** * Run business method `RuntimeException`. @@ -2992,16 +2998,6 @@ public class UserServiceImpl extends ServiceImpl implements return normalizedPhone; } - /** - * Run business method `isDeletedPlaceholderPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isDeletedPlaceholderPhone(String phone) { - return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER); - } - /** * Run business method `ensurePhoneNotUsed`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -3011,7 +3007,7 @@ public class UserServiceImpl extends ServiceImpl implements */ private void ensurePhoneNotUsed(String phone, Long currentUserId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0); if (currentUserId != null) { wrapper.ne(UserDO::getId, currentUserId); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java index 7be4d5a8..0282564c 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java @@ -13,11 +13,4 @@ public final class UserProfileFieldSupport { } return value.trim(); } - - public static void requireWechatIdForServiceUser(Integer userType, String wechatId) { - if ((Integer.valueOf(2).equals(userType) || Integer.valueOf(3).equals(userType)) - && !StringUtils.hasText(wechatId)) { - throw new IllegalArgumentException("店长和美甲师的微信号不能为空"); - } - } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java new file mode 100644 index 00000000..a6a57e7a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.List; + +/** + * V5 迁移之后的账号补写:把 account_hash 为空的历史行(如 V1 种子账号 xiaowang) + * 加密 account 并回填 account_hash,之后所有账号查询可统一走哈希等值条件。 + * + *

只处理无哈希的行,幂等;已处理行不会重复更新。

+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class AccountHashBackfillRunner implements ApplicationRunner { + + private final UserMapper userMapper; + private final PhoneCrypto phoneCrypto; + + @Override + public void run(ApplicationArguments args) { + List candidates = userMapper.selectList(Wrappers.lambdaQuery() + .isNull(UserDO::getAccountHash) + .isNotNull(UserDO::getAccount)); + if (candidates.isEmpty()) { + return; + } + int updated = 0; + for (UserDO user : candidates) { + String plainAccount = user.getAccount(); + if (!StringUtils.hasText(plainAccount)) { + continue; + } + userMapper.update(null, new LambdaUpdateWrapper() + .eq(UserDO::getId, user.getId()) + .set(UserDO::getAccount, phoneCrypto.encryptAccount(plainAccount)) + .set(UserDO::getAccountHash, phoneCrypto.index(plainAccount))); + updated++; + } + log.info("账号加密回填完成,共处理 {} 条", updated); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java new file mode 100644 index 00000000..b511b47b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * 账号 TypeHandler:写库时一律 AES-GCM 加密,读库时仅解密 enc:v1: 前缀的密文。 + * 与 JC-Salon-Core 的 AccountPhoneTypeHandler 同名同结构。 + */ +public class AccountPhoneTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encryptAccount(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(cs.getString(columnIndex)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCrypto.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCrypto.java new file mode 100644 index 00000000..3d28e1be --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCrypto.java @@ -0,0 +1,141 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PostConstruct; +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; + +/** + * 手机号加密与索引组件,算法与 JC-Salon-Core 的 PhoneCrypto 逐字对齐: + *
    + *
  • 加密:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag,前缀 {@code enc:v1:},载荷为 Base64(IV||密文);
  • + *
  • 索引:HMAC-SHA256,输入为 {@code value.trim()},输出十六进制小写;
  • + *
  • 手机号识别:{@code 1[3-9]\d{9}}。
  • + *
+ * 两条线使用同一把 index-key,phone_hash 才可跨线比对;密文因随机 IV 各自独立,不要求可比。 + */ +@Component +public class PhoneCrypto { + private static final String CIPHER_PREFIX = "enc:v1:"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static volatile PhoneCrypto current; + + private final PhoneCryptoProperties properties; + private byte[] encryptionKey; + private byte[] indexKey; + + public PhoneCrypto(PhoneCryptoProperties properties) { + this.properties = properties; + } + + @PostConstruct + public void initialize() { + encryptionKey = decodeKey(properties.getEncryptionKey(), "phone-crypto.encryption-key"); + indexKey = decodeKey(properties.getIndexKey(), "phone-crypto.index-key"); + if (encryptionKey.length != 32 || indexKey.length < 32) { + throw new IllegalStateException("手机号加密与索引密钥必须分别配置为至少32字节的Base64密钥"); + } + if (Arrays.equals(encryptionKey, indexKey)) { + throw new IllegalStateException("手机号加密密钥与索引密钥必须独立"); + } + current = this; + } + + public String encrypt(String value) { + if (!StringUtils.hasText(value) || value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] iv = new byte[12]; + RANDOM.nextBytes(iv); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); + byte[] payload = new byte[iv.length + encrypted.length]; + System.arraycopy(iv, 0, payload, 0, iv.length); + System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length); + return CIPHER_PREFIX + Base64.getEncoder().encodeToString(payload); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("手机号加密失败", exception); + } + } + + public String decrypt(String value) { + if (!StringUtils.hasText(value) || !value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] payload = Base64.getDecoder().decode(value.substring(CIPHER_PREFIX.length())); + if (payload.length < 29) throw new IllegalArgumentException("手机号密文格式无效"); + byte[] iv = Arrays.copyOfRange(payload, 0, 12); + byte[] encrypted = Arrays.copyOfRange(payload, 12, payload.length); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (GeneralSecurityException | IllegalArgumentException exception) { + throw new IllegalStateException("手机号解密失败,请检查密钥或数据完整性", exception); + } + } + + /** + * 账号加密:ArtList 允许字母数字自定义账号,因此非空账号一律加密。 + */ + public String encryptAccount(String value) { + return encrypt(value); + } + + /** + * 账号解密:仅对 {@code enc:v1:} 前缀的密文解密,历史明文账号原样返回。 + */ + public String decryptAccount(String value) { + return decrypt(value); + } + + public boolean isEncrypted(String value) { + return value != null && value.startsWith(CIPHER_PREFIX); + } + + public boolean isMobilePhone(String value) { + return value != null && value.trim().matches("1[3-9]\\d{9}"); + } + + public String mask(String value) { + if (!StringUtils.hasText(value)) return value; + String plain = isEncrypted(value) ? decrypt(value) : value; + return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain; + } + + public String index(String value) { + if (!StringUtils.hasText(value)) return null; + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(indexKey, "HmacSHA256")); + byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("敏感字段索引生成失败", exception); + } + } + + public static PhoneCrypto current() { + PhoneCrypto instance = current; + if (instance == null) throw new IllegalStateException("手机号加密组件尚未初始化"); + return instance; + } + + private byte[] decodeKey(String value, String name) { + if (!StringUtils.hasText(value)) throw new IllegalStateException("缺少Nacos配置: jayucloud-artlist.privacy." + name); + try { + return Base64.getDecoder().decode(value.trim()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneEncryptionTypeHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneEncryptionTypeHandler.java new file mode 100644 index 00000000..e90d750d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneEncryptionTypeHandler.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * 手机号密文列的类型处理器,与 JC-Salon-Core 的 PhoneEncryptionTypeHandler 一致。 + * 仅作用于实体读写;QueryWrapper 条件不会经过类型处理器,按手机号查询必须使用 phone_hash。 + */ +public class PhoneEncryptionTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encrypt(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(cs.getString(columnIndex)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java new file mode 100644 index 00000000..e472aa15 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import org.springframework.util.StringUtils; + +/** + * 手机号 / 账号的集中脱敏策略。 + * + *

后端始终完整保存明文语义(落库为 AES-GCM 密文),但返回前端、写日志、写审计时一律脱敏: + * 不再存在任何"返回完整号码"的场景。需要真实号码时只走 {@code POST /contact-info/dial} 单次取号。

+ */ +public final class SensitiveFieldPolicy { + + /** + * 调用场景,仅用于表达调用方语义;所有场景的输出均为脱敏值。 + */ + public enum Scenario { + SELF_PROFILE, + ADMIN_LIST, + THIRD_PARTY, + DIAL, + LOG + } + + private SensitiveFieldPolicy() { + } + + /** + * 手机号按场景返回脱敏值(138****0000)。 + */ + public static String phone(String value, Scenario scenario) { + if (!StringUtils.hasText(value)) { + return value; + } + String plain = PhoneCrypto.current().isEncrypted(value) ? PhoneCrypto.current().decrypt(value) : value; + return PhoneCrypto.current().mask(plain); + } + + /** + * 账号按场景返回脱敏值;手机号形态账号按手机号规则脱敏,其余保留前两位。 + */ + public static String account(String value, Scenario scenario) { + if (!StringUtils.hasText(value)) { + return value; + } + String plain = PhoneCrypto.current().isEncrypted(value) ? PhoneCrypto.current().decryptAccount(value) : value; + if (PhoneCrypto.current().isMobilePhone(plain)) { + return PhoneCrypto.current().mask(plain); + } + return plain.length() <= 2 ? "***" : plain.substring(0, 2) + "***"; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java index 89239fff..da20c366 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.artlist.core.support.security; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; @@ -55,6 +56,10 @@ public class OperationGuardService { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final ObjectMapper objectMapper; + /** + * Purpose: phoneCrypto supports OperationGuardService.java by hashing phone numbers before they become Redis key segments. + */ + private final PhoneCrypto phoneCrypto; /** * Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role. @@ -186,7 +191,8 @@ public class OperationGuardService { readBodyField(request, key) ); if (StringUtils.hasText(value)) { - return sanitize(value); + // 手机号/账号不落 Redis 键:统一替换为哈希 + return ("phone".equals(key) || "account".equals(key)) ? phoneCrypto.index(value) : sanitize(value); } } return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java index c6d0b117..4861910f 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java @@ -107,6 +107,22 @@ public class RequestThrottleService { assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); } + /** + * 联系方式查询限流:按登录用户维度。 + */ + public void checkContactInfoRead(HttpServletRequest request, Long userId) { + assertAllowed("contact-info-read", request, userId == null ? "" : String.valueOf(userId), + rateLimitProperties.getContactInfoRead(), "联系方式查询过于频繁,请稍后再试"); + } + + /** + * 单次拨号取号限流:按登录用户维度,避免批量撞取号码。 + */ + public void checkContactDial(HttpServletRequest request, Long userId) { + assertAllowed("contact-dial", request, userId == null ? "" : String.valueOf(userId), + rateLimitProperties.getContactDial(), "拨号取号过于频繁,请稍后再试"); + } + /** * Purpose: recordLoginFailure supports RequestThrottleService.java by holding or executing the record login failure business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java index 70c3feae..9afbc2b8 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java @@ -28,12 +28,12 @@ public class UserSessionService { * Purpose: SESSION_KEY_PREFIX supports UserSessionService.java by holding or executing the session key prefix business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ - private static final String SESSION_KEY_PREFIX = "auth:session:"; + private static final String SESSION_KEY_PREFIX = "artlist:auth:session:"; /** * Purpose: USER_SESSION_SET_PREFIX supports UserSessionService.java by holding or executing the user session set prefix business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ - private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:"; + private static final String USER_SESSION_SET_PREFIX = "artlist:auth:user:sessions:"; /** * Purpose: stringRedisTemplate supports UserSessionService.java by holding or executing the string redis template business role. diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql new file mode 100644 index 00000000..94e1ed7d --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql @@ -0,0 +1,2275 @@ +-- ============================================================ +-- ArtList 基线冻结(Flyway V1) +-- 来源:docs/scripts/sql/init/jayucloud-artlist.sql +-- +-- 语义: +-- 1. 空库首次初始化:Flyway 从 V1 开始执行,建立全部基础表、索引与种子数据。 +-- 2. 已存在业务数据的库:由 spring.flyway.baseline-on-migrate=true + +-- baseline-version=1 自动 baseline 到版本 1,只执行 V2 及以后的迁移, +-- 不会重放本文件。 +-- 3. 本文件本身可安全重放:建表使用 IF NOT EXISTS,索引经存储过程幂等创建, +-- 种子数据使用 ON DUPLICATE KEY UPDATE / WHERE NOT EXISTS。 +-- +-- 规范化处理(相对初始化脚本): +-- - 移除 CREATE DATABASE / USE,库名由 Flyway schemas 配置决定; +-- - 建表统一 CREATE TABLE IF NOT EXISTS; +-- - 独立 CREATE INDEX / CREATE UNIQUE INDEX 改为 sp_add_index_if_not_exists / +-- sp_add_unique_index_if_not_exists 调用,保留原索引名、表名与列顺序, +-- 丢弃索引 COMMENT(MySQL 索引注释仅为元数据); +-- - 删除重复 DDL:t_order_artist_review、t_order_artist_change_request 各只保留一份; +-- - 修复原脚本中孤立字符导致的语法错误('索引';s); +-- - 不包含手机号加密、订单镜像字段等业务改造,后续按版本增量迁移。 +-- ============================================================ + +-- 幂等辅助存储过程(建表/索引重放时复用) +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_balance +( + id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' + primary key comment '余额表主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) default 0.00 not null comment '当前余额', + total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', + last_recharge_time datetime null comment '最近一次充值时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', + last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_user_id + unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' +) + comment '用户余额信息表'; + + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_balance_change_detail +( + id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' + primary key comment '余额变动明细主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', + type varchar(20) not null comment '变动类型(如充值、消费、退款)', + current_balance decimal(10, 2) not null comment '变动后的当前余额', + before_balance decimal(10, 2) null comment '变动前余额', + after_balance decimal(10, 2) null comment '变动后余额', + change_scene varchar(32) null comment '余额变动场景', + related_order_id bigint unsigned null comment '关联系统订单ID', + related_order_no varchar(64) null comment '关联系统订单号', + external_order_no varchar(64) null comment '手工录入的外部订单号', + operator_id bigint unsigned null comment '操作人ID', + remark varchar(255) null comment '备注', + change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' +) + comment '用户余额变动明细表'; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_change_time', '(change_time)'); + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_cart +( + id bigint unsigned auto_increment comment '购物车主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned default 1 not null comment '商品数量', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '购物车表'; + +CALL sp_add_index_if_not_exists('t_cart', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_comment +( + id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' + primary key comment '评论主键索引', + user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', + shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', + product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', + comment_content text not null comment '评论内容', + parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', + rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', + image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', + like_count int unsigned default 0 null comment '评论点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '用户评论信息表'; + +CALL sp_add_index_if_not_exists('t_comment', 'idx_parent_comment_id', '(parent_comment_id)'); + +CALL sp_add_index_if_not_exists('t_comment', 'idx_product_id', '(product_id)'); + +CALL sp_add_index_if_not_exists('t_comment', 'idx_shop_id', '(shop_id)'); + +CALL sp_add_index_if_not_exists('t_comment', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_coupon +( + id bigint unsigned auto_increment comment '优惠券主键索引' + primary key, + coupon_code varchar(50) not null comment '优惠券编码', + coupon_name varchar(100) not null comment '优惠券名称', + coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', + discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', + min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', + reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', + total_count int unsigned default 100 not null comment '优惠券总数量', + used_count int unsigned default 0 not null comment '已使用数量', + start_time datetime not null comment '开始时间', + end_time datetime not null comment '结束时间', + status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '所属店铺ID', + coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', + required_vip_level varchar(20) null comment '要求的VIP等级', + auto_match tinyint unsigned default 0 not null comment '是否自动匹配', + constraint uk_coupon_code + unique (coupon_code) comment '优惠券编码唯一索引' +) + comment '优惠券信息表'; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_status', '(status)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_coupon_tag +( + id bigint unsigned auto_increment comment '优惠券标签关联主键索引' + primary key, + coupon_id bigint unsigned not null comment '关联优惠券表主键', + tag_id bigint unsigned not null comment '关联标签表主键', + is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_coupon_tag + unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' +) + comment '优惠券标签关联表'; + +CALL sp_add_index_if_not_exists('t_coupon_tag', 'idx_coupon_id', '(coupon_id)'); + +CALL sp_add_index_if_not_exists('t_coupon_tag', 'idx_tag_id', '(tag_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_effect_diagram +( + id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' + primary key comment '效果图主键索引', + product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', + category varchar(50) default '' null comment '效果图类别', + image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', + description text null comment '效果图描述', + price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', + duration varchar(50) default '' null comment '效果图对应服务耗时', + tag varchar(50) default '' null comment '效果图标签', + like_count int unsigned default 0 null comment '效果图点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '商品效果图信息表'; + +CALL sp_add_index_if_not_exists('t_effect_diagram', 'idx_product_id', '(product_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_login_identity +( + id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' + primary key comment '登录标识主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', + input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', + input_time datetime not null comment '输入时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' +) + comment '用户登录标识信息表'; + +CALL sp_add_index_if_not_exists('t_login_identity', 'idx_login_method', '(login_method)'); + +CALL sp_add_index_if_not_exists('t_login_identity', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_wechat_mini_binding +( + id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' + primary key, + user_id bigint unsigned not null comment '关联用户ID', + app_id varchar(64) not null comment '微信小程序appId', + openid varchar(100) not null comment '微信小程序openid', + unionid varchar(100) null comment '微信开放平台unionid', + status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_wechat_mini_app_openid + unique (app_id, openid), + constraint uk_wechat_mini_app_user + unique (app_id, user_id) +) + comment '微信小程序账号绑定表'; + +CALL sp_add_index_if_not_exists('t_wechat_mini_binding', 'idx_wechat_mini_unionid', '(unionid)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_nail_artist_info +( + id bigint unsigned auto_increment comment '美甲师信息主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', + identity varchar(50) default '' null comment '身份', + experience int unsigned default 0 null comment '从业年限', + skills text null comment '技能标签ID集合,多个ID以逗号分隔', + rating decimal(3, 1) default 4.5 null comment '评分', + status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', + portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_id + unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' +) + comment '美甲师信息表'; + +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_user_id', '(user_id)'); + +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(participate_production, status)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_object_storage_file +( + id bigint unsigned auto_increment comment '????ID' + primary key comment '????????', + file_name varchar(100) not null comment '????', + file_url text not null comment '??????', + object_name varchar(512) null comment '????Key', + primary_provider varchar(64) null comment '??????', + primary_url text null comment '???????', + backup_provider varchar(64) null comment '???????', + backup_url text null comment '????????', + content_type varchar(128) null comment '??Content-Type', + file_size bigint unsigned null comment '?????????', + primary_upload_status tinyint unsigned default 0 not null comment '????????0????1???2??', + backup_upload_status tinyint unsigned default 0 not null comment '?????????0????1???2??', + backup_retry_count int unsigned default 0 not null comment '??????', + backup_last_error varchar(500) null comment '??????????', + backup_uploaded_at datetime null comment '??????', + backup_last_retry_time datetime null comment '??????????', + create_time datetime default CURRENT_TIMESTAMP not null comment '??????', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '??????', + status tinyint unsigned default 1 null comment '?????1???0????2???', + delete_time datetime null comment '??????', + recycle_time datetime null comment '?????????' +) + comment '?????????'; + +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(backup_upload_status, primary_upload_status, status)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS `t_object_storage_file_replica` +( + `id` bigint unsigned NOT NULL COMMENT '副本ID', + `file_id` bigint unsigned NOT NULL COMMENT '文件ID', + `provider` varchar(64) NOT NULL COMMENT '对象存储提供方', + `object_name` varchar(512) NOT NULL COMMENT '对象Key', + `object_url` text NULL COMMENT '对象访问地址', + `upload_status` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '上传状态:0-待上传,1-成功,2-失败', + `retry_count` int unsigned NOT NULL DEFAULT 0 COMMENT '重试次数', + `last_error` varchar(500) NULL COMMENT '最近一次错误', + `uploaded_at` datetime NULL COMMENT '上传成功时间', + `last_retry_time` datetime NULL COMMENT '最近一次重试时间', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_object_storage_file_replica_file_provider` (`file_id`, `provider`), + KEY `idx_object_storage_file_replica_retry` (`upload_status`, `provider`, `file_id`), + KEY `idx_object_storage_file_replica_file_status` (`file_id`, `upload_status`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci + COMMENT = '对象存储文件副本表'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_order +( + id bigint unsigned auto_increment comment '订单主键索引' + primary key, + order_no varchar(50) not null comment '订单编号', + user_id bigint unsigned not null comment '关联用户表主键', + shop_id bigint unsigned null comment '所属店铺ID', + total_amount decimal(10, 2) not null comment '订单总金额', + actual_amount decimal(10, 2) not null comment '实际支付金额', + coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', + user_coupon_id bigint unsigned null comment '用户券ID', + coupon_source_type varchar(32) null comment '优惠来源类型', + status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_order_no + unique (order_no) comment '订单编号唯一索引' +) + comment '订单表'; + +CALL sp_add_index_if_not_exists('t_order', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_order', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_order_item +( + id bigint unsigned auto_increment comment '订单商品主键索引' + primary key, + order_id bigint unsigned not null comment '关联订单表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned not null comment '商品数量', + price decimal(10, 2) not null comment '商品单价', + artist_id bigint unsigned null comment '关联美甲师ID', + appointment_time datetime null comment '预约开始时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单商品表'; + +CALL sp_add_index_if_not_exists('t_order_item', 'idx_order_id', '(order_id)'); + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(order_item_id, is_delete)'); + +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(customer_id, status, create_time)'); + +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(artist_id, status)'); + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(customer_id, status, create_time)'); + +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(from_artist_id, to_artist_id, status)'); + +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(shop_id, status, create_time)'); + +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(pending_key)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_permission +( + id bigint unsigned auto_increment comment '权限唯一主键ID' + primary key, + permission_code varchar(100) not null comment '权限编码(唯一标识)', + permission_name varchar(100) not null comment '权限名称', + permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', + description varchar(255) null comment '权限描述', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_permission_code + unique (permission_code) comment '权限编码唯一索引' +) + comment '系统权限表'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_product +( + id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' + primary key comment '商品主键索引', + shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', + title varchar(100) not null comment '商品标题', + description text null comment '商品描述', + target_audience text null comment '适合人群说明', + precautions text null comment '注意事项说明', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', + price decimal(10, 2) not null comment '商品价格,保留2位小数', + tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', + like_count int unsigned default 0 null comment '商品点赞数', + collect_count int unsigned default 0 null comment '商品收藏数', + approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', + bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', + available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', + front_visible tinyint unsigned default 1 not null comment '前台是否展示:0-隐藏,1-展示', + source_type varchar(64) default 'BACKEND' not null comment '来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约', + create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '商品信息表'; + +CALL sp_add_index_if_not_exists('t_product', 'idx_price', '(price)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_shop_id', '(shop_id)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_tags', '(tags)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_title', '(title)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_t_product_front_visible', '(shop_id, front_visible, source_type)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_product_like +( + id bigint unsigned auto_increment comment '商品点赞主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product_like + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品点赞记录表'; + +CALL sp_add_index_if_not_exists('t_product_like', 'idx_product_id_like', '(product_id)'); + +CALL sp_add_index_if_not_exists('t_product_like', 'idx_user_id_like', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_shop +( + id bigint unsigned auto_increment comment '店铺唯一主键ID' + primary key comment '店铺主键索引', + shop_name varchar(100) not null comment '店铺名称', + description text null comment '店铺描述', + address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', + business_hours varchar(100) default '' null comment '店铺营业时间', + cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', + theme_primary_color varchar(20) null comment '前台主题主色', + theme_secondary_color varchar(20) null comment '前台主题辅色', + theme_accent_color varchar(20) null comment '前台主题强调色', + theme_page_bg_color varchar(20) null comment '前台主题页面背景色', + theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', + theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', + status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', + authorization_start_date date null comment '店铺授权起始日', + authorization_days int null comment '店铺授权有效天数', + authorization_expire_time datetime null comment '店铺授权到期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' +) + comment '店铺信息表'; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_shop_name', '(shop_name)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_tag +( + id bigint unsigned auto_increment comment '标签唯一主键ID' + primary key comment '标签主键索引', + tag_name varchar(50) not null comment '标签名称', + text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', + bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', + border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', + scene_group varchar(50) null comment '前台场景筛选分组', + display_name varchar(80) null comment '前台展示名称', + sort_order int default 100 null comment '前台筛选排序', + front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '店铺ID', + constraint uk_tag_shop_name + unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' +) + comment '系统标签信息表'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_user +( + id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' + primary key comment '用户主键索引', + shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', + nickname varchar(50) not null comment '用户昵称', + account varchar(50) not null comment '用户账号(登录用)', + phone varchar(50) null comment '手机号', + contact_phone varchar(50) null comment '联系电话', + birthday date null comment '生日', + wechat_id varchar(100) null comment '微信号', + wechat_qr_code varchar(512) null comment '微信二维码', + email varchar(100) null comment '邮箱', + phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', + email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', + password varchar(100) not null comment '用户密码(加密存储)', + signature varchar(200) default '' null comment '用户签名', + level varchar(20) default '普通' null comment '用户等级', + type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', + vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', + avatar varchar(512) null comment '头像链接', + constraint uk_account + unique (account) comment '用户账号唯一索引' +) + comment '系统用户信息表'; + +CALL sp_add_index_if_not_exists('t_user', 'idx_email', '(email)'); + +CALL sp_add_index_if_not_exists('t_user', 'idx_phone', '(phone)'); + +CALL sp_add_index_if_not_exists('t_user', 'idx_shop_id', '(shop_id)'); + +CALL sp_add_index_if_not_exists('t_user', 'idx_type', '(type)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_user_coupon +( + id bigint unsigned auto_increment comment '用户优惠券关联主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + coupon_id bigint unsigned not null comment '关联优惠券表主键', + status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', + obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', + use_time datetime null comment '使用时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_coupon + unique (user_id, coupon_id) comment '用户-优惠券唯一索引' +) + comment '用户优惠券关联表'; + +CALL sp_add_index_if_not_exists('t_user_coupon', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_user_coupon', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_user_permission +( + id bigint unsigned auto_increment comment '关联ID' + primary key, + user_id bigint unsigned not null comment '用户ID', + permission_id bigint unsigned not null comment '权限ID', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + create_by bigint unsigned null comment '创建人ID', + update_by bigint unsigned null comment '更新人ID', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_permission + unique (user_id, permission_id) comment '用户-权限唯一索引' +) + comment '用户权限关联表'; + +CALL sp_add_index_if_not_exists('t_user_permission', 'idx_permission_id', '(permission_id)'); + +CALL sp_add_index_if_not_exists('t_user_permission', 'idx_user_id', '(user_id)'); + +CREATE TABLE IF NOT EXISTS t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + business_type varchar(64) null comment '业务类型', + business_id bigint unsigned null comment '业务ID', + action_path varchar(255) null comment '业务跳转路径', + idempotency_key varchar(160) null comment '业务消息幂等键', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +CALL sp_add_index_if_not_exists('t_system_message', 'idx_t_system_message_publish_time', '(publish_time)'); + +CALL sp_add_index_if_not_exists('t_system_message', 'idx_t_system_message_target', '(target_type, status)'); + +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(idempotency_key)'); + +CREATE TABLE IF NOT EXISTS t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +CALL sp_add_index_if_not_exists('t_system_message_user_state', 'idx_t_system_message_user_state_user', '(user_id, read_status, popup_shown)'); + +CREATE TABLE IF NOT EXISTS t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +CALL sp_add_index_if_not_exists('t_announcement', 'idx_t_announcement_target', '(target_type, status)'); + +CALL sp_add_index_if_not_exists('t_announcement', 'idx_t_announcement_sort_time', '(sort_order, publish_time)'); + +CREATE TABLE IF NOT EXISTS t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +CALL sp_add_index_if_not_exists('t_vip_recharge_plan', 'idx_t_vip_recharge_plan_shop_status', '(shop_id, status, sort_order)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_vip_benefit +( + id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' + primary key comment 'VIP权益主键索引', + benefit_info text not null comment '权益详情(如折扣、专属服务)', + required_vip_level varchar(20) not null comment '所需VIP等级', + level_rank int default 0 not null comment '等级序号', + recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', + status tinyint unsigned default 1 not null comment '状态', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment 'VIP权益信息表'; + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_required_vip_level', '(required_vip_level)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_vip_info +( + id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' + primary key comment 'VIP信息主键索引', + user_id bigint unsigned null comment '所属用户ID', + vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', + start_time datetime not null comment 'VIP开通时间', + expire_time datetime null comment 'VIP到期时间', + activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', + benefit_id bigint unsigned null comment '关联VIP权益信息表主键', + manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment '用户VIP信息表'; + +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_vip_level', '(vip_level)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_wishlist_group +( + id bigint unsigned auto_increment comment '收藏分组主键' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', + sort_order int default 100 not null comment '分组排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' +) + comment '商品收藏分组表'; + +CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_sort', '(user_id, sort_order, create_time)'); + +CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_user', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_wishlist +( + id bigint unsigned auto_increment comment '商品收藏主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + group_id bigint unsigned null comment '收藏分组ID', + note varchar(500) null comment '收藏灵感备注', + sort_order int default 100 not null comment '分组内排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品收藏表'; + +CALL sp_add_index_if_not_exists('t_wishlist', 'idx_product_id', '(product_id)'); + +CALL sp_add_index_if_not_exists('t_wishlist', 'idx_user_id', '(user_id)'); + +CALL sp_add_index_if_not_exists('t_wishlist', 'idx_t_wishlist_user_group_sort', '(user_id, group_id, sort_order, create_time)'); + +-- ======================================== +-- 首次部署整合区:用户资产 / VIP / 优惠券补丁 +-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); +CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); +CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); + +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''????Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_provider', 'varchar(64) NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_url', 'text NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_provider', 'varchar(64) NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_url', 'text NULL COMMENT ''????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''??Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''?????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''?????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_error', 'varchar(500) NULL COMMENT ''??????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_uploaded_at', 'datetime NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_retry_time', 'datetime NULL COMMENT ''??????????'''); +UPDATE t_object_storage_file +SET primary_provider = COALESCE(primary_provider, 'QINIU_KODO'), + primary_url = COALESCE(primary_url, file_url), + backup_provider = COALESCE(backup_provider, 'ALIYUN_OSS'), + primary_upload_status = CASE WHEN primary_upload_status IS NULL OR primary_upload_status = 0 THEN 1 ELSE primary_upload_status END, + backup_upload_status = COALESCE(backup_upload_status, 0), + backup_retry_count = COALESCE(backup_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(`backup_upload_status`, `primary_upload_status`, `status`)'); +UPDATE t_balance +SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) +WHERE total_recharge_amount IS NULL; + +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); +CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); + +CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); +CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); + +UPDATE t_balance_change_detail +SET before_balance = COALESCE(before_balance, current_balance - amount), + after_balance = COALESCE(after_balance, current_balance), + change_scene = COALESCE(NULLIF(change_scene, ''), type) +WHERE before_balance IS NULL + OR after_balance IS NULL + OR change_scene IS NULL + OR change_scene = ''; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); + +CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); +CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); + +CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); + +SET @drop_old_tag_unique_sql = ( + SELECT IF( + EXISTS( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_tag' + AND INDEX_NAME = 'uk_tag_name' + ), + 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', + 'SELECT 1' + ) +); +PREPARE stmt FROM @drop_old_tag_unique_sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); +CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); +CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); +CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); +CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); +UPDATE t_tag +SET front_visible = 1 +WHERE front_visible IS NULL; +CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); + +CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); +CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); +CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); + +UPDATE t_coupon +SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), + auto_match = COALESCE(auto_match, 0) +WHERE coupon_scene IS NULL + OR coupon_scene = '' + OR auto_match IS NULL; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); + +CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); + +UPDATE t_vip_benefit +SET level_rank = CASE required_vip_level + WHEN '普通' THEN 0 + WHEN '青铜' THEN 1 + WHEN '白银' THEN 2 + WHEN '黄金' THEN 3 + ELSE level_rank + END, + recharge_threshold = CASE required_vip_level + WHEN '普通' THEN 0.00 + WHEN '青铜' THEN 500.00 + WHEN '白银' THEN 1000.00 + WHEN '黄金' THEN 2000.00 + ELSE recharge_threshold + END, + status = COALESCE(status, 1) +WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); + +CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); +CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); + +ALTER TABLE t_vip_info + MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', + MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; + +UPDATE t_vip_info vi +INNER JOIN t_user u ON u.vip_id = vi.id +SET vi.user_id = u.id +WHERE (vi.user_id IS NULL OR vi.user_id = 0) + AND u.vip_id IS NOT NULL + AND u.vip_id <> 0; + +UPDATE t_vip_info +SET start_time = COALESCE(start_time, create_time, NOW()), + activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), + manual_override = COALESCE(manual_override, 0); + +CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); + +UPDATE t_user u +LEFT JOIN t_vip_info vi ON vi.id = u.vip_id +SET u.level = CASE + WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level + WHEN u.type = 0 THEN '普通' + ELSE u.level + END, + u.vip_id = CASE + WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 + ELSE u.vip_id + END, + u.update_time = NOW() +WHERE u.is_delete = 0 + AND u.type = 0 + AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); + +UPDATE t_vip_benefit +SET benefit_info = '普通用户,无额外VIP折扣', + level_rank = 0, + recharge_threshold = 0.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '普通'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '普通' +); + +UPDATE t_vip_benefit +SET benefit_info = '青铜VIP,系统自动匹配9.5折券', + level_rank = 1, + recharge_threshold = 500.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '青铜'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '青铜' +); + +UPDATE t_vip_benefit +SET benefit_info = '白银VIP,系统自动匹配9.2折券', + level_rank = 2, + recharge_threshold = 1000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '白银'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '白银' +); + +UPDATE t_vip_benefit +SET benefit_info = '黄金VIP,系统自动匹配9.0折券', + level_rank = 3, + recharge_threshold = 2000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '黄金'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '黄金' +); + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 +-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); + +UPDATE t_shop +SET status = 1 +WHERE status IS NULL; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); + +CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', + `user_id` bigint unsigned NOT NULL COMMENT '用户ID', + `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', + `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (`id`) +) COMMENT='用户与店铺绑定关系表'; + +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); + +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); +CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); + +INSERT INTO t_user_shop_binding ( + user_id, + shop_id, + status, + create_time, + update_time, + is_delete +) +SELECT + u.id, + u.shop_id, + CASE + WHEN COALESCE(u.status, 1) = 1 THEN 1 + ELSE 0 + END AS binding_status, + COALESCE(u.create_time, NOW()), + COALESCE(u.update_time, NOW()), + 0 +FROM t_user u +INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 +LEFT JOIN t_user_shop_binding b + ON b.user_id = u.id + AND b.shop_id = u.shop_id + AND COALESCE(b.is_delete, 0) = 0 +WHERE COALESCE(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 + AND b.id IS NULL; + +UPDATE t_user_shop_binding b +INNER JOIN t_user u ON u.id = b.user_id +SET b.status = CASE + WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END + ELSE b.status + END, + b.is_delete = COALESCE(b.is_delete, 0), + b.update_time = COALESCE(b.update_time, NOW()) +WHERE b.status IS NULL + OR b.is_delete IS NULL + OR b.update_time IS NULL; + +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); +CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); +CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); +CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); +CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_business_event_outbox +( + id bigint unsigned auto_increment comment '事件ID' + primary key, + event_key varchar(160) not null comment '事件幂等键', + event_type varchar(64) not null comment '事件类型', + business_type varchar(64) not null comment '业务类型', + business_id bigint unsigned not null comment '业务ID', + payload_json text null comment '事件载荷', + status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', + retry_count int unsigned default 0 not null comment '重试次数', + next_retry_time datetime null comment '下次重试时间', + last_error varchar(500) null comment '最近错误', + claimed_at datetime null comment '认领时间', + processed_at datetime null comment '处理完成时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除' +) + comment '业务事件Outbox表'; + +CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); +CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); + +-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. +-- EXPIRED + +-- ======================================== +-- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth +-- ======================================== + +CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); +CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_artist_schedule +( + id bigint unsigned NOT NULL COMMENT '排班ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + work_date date NOT NULL COMMENT '工作日期', + start_time time NOT NULL COMMENT '班次开始时间', + end_time time NOT NULL COMMENT '班次结束时间', + slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', + capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', + remark varchar(255) NULL COMMENT '排班备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '美甲师排班表'; + +CREATE TABLE IF NOT EXISTS t_appointment_reservation +( + id bigint unsigned NOT NULL COMMENT '预约占用ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + product_title varchar(200) NULL COMMENT '预约作品标题快照', + appointment_start_time datetime NOT NULL COMMENT '预约开始时间', + appointment_end_time datetime NOT NULL COMMENT '预约结束时间', + status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', + client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单预约时段占用表'; + +CREATE TABLE IF NOT EXISTS t_payment_order +( + id bigint unsigned NOT NULL COMMENT '支付单ID', + pay_no varchar(64) NOT NULL COMMENT '支付单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_no varchar(64) NOT NULL COMMENT '订单号快照', + user_id bigint unsigned NOT NULL COMMENT '支付用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', + status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', + pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', + paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', + pay_time datetime NULL COMMENT '支付完成时间', + expire_time datetime NULL COMMENT '支付单过期时间', + operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', + remark varchar(255) NULL COMMENT '支付备注', + idempotency_key varchar(160) NULL COMMENT '支付幂等键', + raw_payload text NULL COMMENT '支付渠道原始载荷', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单支付单表'; + +CREATE TABLE IF NOT EXISTS t_refund_order +( + id bigint unsigned NOT NULL COMMENT '退款单ID', + refund_no varchar(64) NOT NULL COMMENT '退款单号', + after_sale_id bigint unsigned NULL COMMENT '售后单ID', + payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', + refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + refund_time datetime NULL COMMENT '退款完成时间', + channel varchar(32) NULL COMMENT '退款渠道', + external_refund_no varchar(64) NULL COMMENT '外部退款单号', + fail_reason varchar(255) NULL COMMENT '失败原因或备注', + idempotency_key varchar(160) NULL COMMENT '退款幂等键', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单退款单表'; + +CREATE TABLE IF NOT EXISTS t_after_sale +( + id bigint unsigned NOT NULL COMMENT '售后单ID', + after_sale_no varchar(64) NOT NULL COMMENT '售后单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NULL COMMENT '订单项ID', + user_id bigint unsigned NOT NULL COMMENT '申请用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + type varchar(32) NOT NULL COMMENT '售后类型', + reason varchar(1000) NULL COMMENT '申请原因', + refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', + audit_user_id bigint unsigned NULL COMMENT '审核人ID', + audit_reason varchar(500) NULL COMMENT '审核说明', + audit_time datetime NULL COMMENT '审核时间', + refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单售后申请表'; + +CREATE TABLE IF NOT EXISTS t_after_sale_log +( + id bigint unsigned NOT NULL COMMENT '售后日志ID', + after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', + action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', + from_status varchar(20) NULL COMMENT '变更前状态', + to_status varchar(20) NULL COMMENT '变更后状态', + operator_id bigint unsigned NULL COMMENT '操作人ID', + operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', + remark varchar(500) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '订单售后流转日志表'; + +CREATE TABLE IF NOT EXISTS t_inventory_item +( + id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + category varchar(50) NULL COMMENT '物料分类', + item_name varchar(100) NOT NULL COMMENT '物料名称', + unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', + stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', + warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '门店库存物料表'; + +CREATE TABLE IF NOT EXISTS t_inventory_record +( + id bigint unsigned NOT NULL COMMENT '库存流水ID', + inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', + change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', + before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', + after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', + operator_id bigint unsigned NULL COMMENT '操作人ID', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '门店库存变动流水表'; + +CREATE TABLE IF NOT EXISTS t_campaign +( + id bigint unsigned NOT NULL COMMENT '营销活动ID', + shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', + title varchar(120) NOT NULL COMMENT '活动标题', + description varchar(1000) NULL COMMENT '活动说明', + scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', + product_ids text NULL COMMENT '关联作品ID集合', + coupon_ids text NULL COMMENT '关联优惠券ID集合', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', + start_time datetime NULL COMMENT '开始时间', + end_time datetime NULL COMMENT '结束时间', + sort_order int NOT NULL DEFAULT 100 COMMENT '排序', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '营销活动配置表'; + +CREATE TABLE IF NOT EXISTS t_user_growth_record +( + id bigint unsigned NOT NULL COMMENT '成长值记录ID', + user_id bigint unsigned NOT NULL COMMENT '用户ID', + source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', + source_id bigint unsigned NULL COMMENT '来源业务ID', + growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '用户成长值流水表'; + +CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); +CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), + (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), + (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), + (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), + (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), + (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), + (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), + (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), + (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), + (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), + (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), + (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), + (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), + (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), + (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), + (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); + +CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); +CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); +CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); + +CREATE TABLE IF NOT EXISTS t_order_quote_message +( + id bigint unsigned auto_increment comment '报价交互消息主键' + primary key, + order_id bigint unsigned not null comment '订单ID', + actor_id bigint unsigned null comment '操作人ID', + actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', + action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', + remark varchar(500) null comment '备注', + items_snapshot text null comment '订单项报价快照JSON', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单询价报价交互消息表'; + +CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'jayucloud-artlist' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='JayuCloud ArtList按业务场景投递MessageHub的配置'; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 +-- 来源:2026-03-20_init_admin_permission_template.sql +-- ======================================== + +SET NAMES utf8mb4; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136626, 'home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + (313931273555136627, 'dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + (313931273555136628, 'user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + (313931273555136629, 'user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + (313931273555136630, 'user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + (313931273555136631, 'user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + (313931273555136632, 'user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + (313931273555136633, 'user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + (313931273555136634, 'user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + (313931273555136635, 'user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + (313931273555136636, 'user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + (313931273555136637, 'user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + (313931273555136638, 'product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + (313931273555136639, 'product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + (313931273555136640, 'product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + (313931273555136641, 'product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + (313931273555136642, 'product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + (313931273555136643, 'shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + (313931273555136644, 'shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + (313931273555136645, 'shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + (313931273555136646, 'shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + (313931273555136647, 'shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + (313931273555136648, 'permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + (313931273555136649, 'permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + (313931273555136650, 'permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + (313931273555136651, 'permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + (313931273555136652, 'permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + (313931273555136653, 'tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + (313931273555136654, 'tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + (313931273555136655, 'tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + (313931273555136656, 'tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + (313931273555136657, 'tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + (313931273555136658, 'coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + (313931273555136659, 'coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + (313931273555136660, 'coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + (313931273555136661, 'coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + (313931273555136662, 'coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + (313931273555136663, 'comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + (313931273555136664, 'comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + (313931273555136665, 'order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + (313931273555136666, 'order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + (313931273555136667, 'order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + (313931273555136668, 'order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + (313931273555136669, 'nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + (313931273555136670, 'nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + (313931273555136671, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (313931273555136672, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (313931273555136673, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + (313931273555136674, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (313931273555136675, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (313931273555136676, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES (313931273555136677, 'order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_user ( + shop_id, + nickname, + account, + phone_verified, + email_verified, + password, + signature, + level, + type, + vip_id, + create_time, + update_time, + is_delete, + status +) +SELECT + 0, + '系统管理员', + 'xiaowang', + 0, + 0, + '$2a$10$3ZC5HHVK6EYIfkjcU9IHZulGXwNZhy.6LU85HRJC9A.3LHm0IEdMO', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +-- ======================================== +-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT +-- 说明: +-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 +-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 +-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 +-- ======================================== + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) +BEGIN + DECLARE v_column_type VARCHAR(128) DEFAULT NULL; + DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; + DECLARE v_extra VARCHAR(128) DEFAULT NULL; + + SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA + INTO v_column_type, v_column_comment, v_extra + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = 'id' + LIMIT 1; + + IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN + SET @alter_sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', + v_column_type, + ' NOT NULL' + ); + + IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN + SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); + END IF; + + PREPARE stmt FROM @alter_sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); +CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); +CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); +CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); +CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); +CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); +CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); +CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); +CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); +CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); +CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NOT NULL COMMENT '用户ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + device_id varchar(128) NULL COMMENT '设备ID', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + device_id varchar(128) NULL COMMENT '设备ID', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +SET @system_parameter_enabled_missing := ( + SELECT COUNT(1) = 0 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_system_parameter_config' + AND COLUMN_NAME = 'enabled' +); +SET @system_parameter_enabled_sql := IF( + @system_parameter_enabled_missing, + 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', + 'SELECT 1' +); +PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; +EXECUTE stmt_system_parameter_enabled; +DEALLOCATE PREPARE stmt_system_parameter_enabled; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), + (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), + (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), + (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), + is_delete = 0, + update_time = NOW(); + +-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + 313931273556000000 + p.id, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 最终权限兜底:确保平台管理员拥有当前权限目录中的全部基础权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + (CAST(u.id AS UNSIGNED) << 20) + (CAST(p.id AS UNSIGNED) & 1048575), + u.id, + p.id, + NOW(), + NOW(), + 0, + 0, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +-- 排班规则与例外 +CREATE TABLE IF NOT EXISTS t_artist_schedule_rule ( + id bigint unsigned NOT NULL COMMENT '排班规则ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', preset_type varchar(32) NOT NULL COMMENT '预设类型', work_days varchar(32) NOT NULL COMMENT '工作星期,1-7逗号分隔', start_time time NOT NULL COMMENT '常规开始时间', end_time time NOT NULL COMMENT '常规结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1启用,0停用', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_rule_artist (shop_id, artist_id, is_delete), KEY idx_artist_schedule_rule_shop_status (shop_id, status, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师常规排班规则表'; +CREATE TABLE IF NOT EXISTS t_artist_schedule_exception ( + id bigint unsigned NOT NULL COMMENT '排班例外ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', work_date date NOT NULL COMMENT '例外日期', exception_type varchar(32) NOT NULL COMMENT '例外类型:REST/EXTRA_WORK/CHANGE_SHIFT', start_time time NULL COMMENT '例外开始时间', end_time time NULL COMMENT '例外结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_exception_date (shop_id, artist_id, work_date, is_delete), KEY idx_artist_schedule_exception_artist_date (artist_id, work_date, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师排班例外表'; + +-- 历史命名兼容修正:整合已部署库迁移所需的数据修正,空库执行时无副作用。 +START TRANSACTION; +UPDATE t_messagehub_push_config +SET source_system = 'jayucloud-artlist' +WHERE source_system IN ('fingertipdesigner', 'fingertip-designer', 'FingertipDesigner'); +UPDATE t_legal_agreement +SET content = REPLACE(content, 'Fingertip Designer', 'JayuCloud ArtList') +WHERE content LIKE '%Fingertip Designer%'; +ALTER TABLE t_messagehub_push_config +COMMENT = 'JayuCloud ArtList 按业务场景投递 MessageHub 的配置'; +COMMIT; diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V2__手机号加密与手机号哈希_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V2__手机号加密与手机号哈希_20261104.sql new file mode 100644 index 00000000..6cde0091 --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V2__手机号加密与手机号哈希_20261104.sql @@ -0,0 +1,123 @@ +-- ============================================================================= +-- V2 手机号加密与手机号哈希(ArtList) +-- 日期:2026-11-04 +-- 口径:不做数据迁移,空库初始化。本迁移只调整结构,不回填历史数据。 +-- 说明: +-- - t_user.phone / t_user.contact_phone 改为密文列 phone_cipher / contact_phone_cipher; +-- - 新增 phone_hash / contact_phone_hash,用于等值查询与去重; +-- - 哈希算法与 Salon 一致:HMAC-SHA256(规范化手机号),规范化为 trim; +-- - 加密算法与 Salon 一致:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag。 +-- 可重复执行:所有 DDL 均先查 information_schema 再执行。 +-- ============================================================================= + +DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_v2_add_column_if_not_exists( + IN p_table VARCHAR(64), + IN p_column VARCHAR(64), + IN p_definition VARCHAR(500) +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column + ) THEN + SET @ddl = CONCAT('ALTER TABLE `', p_table, '` ADD COLUMN `', p_column, '` ', p_definition); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_drop_column_if_exists( + IN p_table VARCHAR(64), + IN p_column VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column + ) THEN + SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP COLUMN `', p_column, '`'); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_drop_index_if_exists( + IN p_table VARCHAR(64), + IN p_index VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.statistics + WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index + ) THEN + SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`'); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_add_index_if_not_exists( + IN p_table VARCHAR(64), + IN p_index VARCHAR(64), + IN p_columns VARCHAR(255) +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.statistics + WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index + ) THEN + SET @ddl = CONCAT('CREATE INDEX `', p_index, '` ON `', p_table, '` ', p_columns); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_add_unique_index_if_not_exists( + IN p_table VARCHAR(64), + IN p_index VARCHAR(64), + IN p_columns VARCHAR(255) +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.statistics + WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index + ) THEN + SET @ddl = CONCAT('CREATE UNIQUE INDEX `', p_index, '` ON `', p_table, '` ', p_columns); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +DELIMITER ; + +CALL sp_v2_add_column_if_not_exists('t_user', 'phone_cipher', 'varchar(255) NULL COMMENT ''手机号密文(AES-GCM)'''); +CALL sp_v2_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号哈希(HMAC-SHA256,十六进制小写)'''); +CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_cipher', 'varchar(255) NULL COMMENT ''联系电话密文(AES-GCM)'''); +CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话哈希(HMAC-SHA256,十六进制小写)'''); + +CALL sp_v2_drop_index_if_exists('t_user', 'idx_phone'); +CALL sp_v2_drop_column_if_exists('t_user', 'phone'); +CALL sp_v2_drop_column_if_exists('t_user', 'contact_phone'); + +-- MySQL 唯一索引允许多行 NULL,因此未绑定手机号的用户不受影响。 +CALL sp_v2_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(phone_hash)'); +CALL sp_v2_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(contact_phone_hash)'); + +DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists; diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql new file mode 100644 index 00000000..8dfb4456 --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql @@ -0,0 +1,110 @@ +-- 隐私政策与用户协议条款修订:对齐手机号/账号 AES-GCM 加密存储、HMAC 不可逆索引与按场景脱敏展示 +-- 版本:2026.11.04 +-- 说明:仅停用旧版本并新增协议版本,不修改已在任一环境执行的 V1 协议正文。 +-- 版本号说明:并行改造已占用 V3(账号加密与账号哈希),本次协议修订顺延为 V4。 + +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) +VALUES + (313931273555138003, 'USER_TERMS', '用户协议', '2026.11.04', + '欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。本协议与《隐私政策》共同构成你使用本服务的基础规则。 + +一、协议接受与版本 +你在登录或注册前应完整阅读本协议和《隐私政策》并主动选择同意;不同意时不能完成注册或继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。 + +二、账号与安全 +1. 你应使用本人手机号注册和登录,手机号用于身份识别、验证码校验、订单联系和账号找回。 +2. 手机号与账号按《隐私政策》所述采用 AES-GCM 加密存储,并以 phone_hash/account_hash 不可逆索引支持登录与去重;客户端页面按场景展示脱敏或完整号码,完整号码仅限权限校验通过的必要业务场景。 +3. 你应妥善保管账号、验证码和登录设备,不得转借、出租、出售账号,不得绕过权限校验访问他人信息。 +4. 发现账号异常、手机号被冒用或验证码泄露时,应及时修改资料、解绑手机号并联系客服。 + +三、预约、订单与会员 +1. 预约与订单信息应真实、准确;你应确保填写的联系人手机号已获得联系人授权。 +2. 订单金额、会员余额、优惠券和售后规则以页面展示和门店确认为准;本平台当前不发起在线支付,充值档位仅作展示,实际充值、退款和余额变动由门店按线下流程处理。 +3. 不得利用订单、优惠券、会员权益进行虚假交易、套现、刷单或欺诈。 + +四、用户内容 +你上传的头像、作品图片、评价等内容应来源合法,不得包含违法、侵权、暴力、色情、欺诈或侵害他人权益的信息。你授予平台为提供服务所必需的展示、存储和处理权限;平台可对违规内容采取删除、屏蔽或限制功能等措施。 + +五、个人信息与保密 +1. 你不得收集、导出、转卖或向无关第三方提供通过平台获取的他人手机号、订单或会员信息。 +2. 完整手机号仅在本人资料维护、管理端编辑、门店或客服拨号等必要业务场景,且权限校验通过时由服务端使用,任何客户端页面不得作为批量获取完整号码的工具。 + +六、账号注销与数据留存 +1. 你可在小程序设置中申请注销;注销后账号不可登录,系统清除账号手机号密文和 phone_hash 索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。 +3. 法律法规另有强制留存要求的,按法定期限保存。 + +七、未成年人 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,不得注册或下单。 + +八、服务调整、责任与联系 +1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。 +2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。 +3. 隐私相关申请可从设置发起或联系在线客服;其他问题请联系运营方公布的客服渠道【待业务确认】。 + +本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555138004, 'PRIVACY_POLICY', '隐私政策', '2026.11.04', + 'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。本政策说明我们如何处理这些个人信息。 + +一、处理的信息及用途 +1. 登录与账号:你通过微信登录授权获取 OpenID 与 UnionID,用于识别和绑定账号;你主动授权手机号或输入手机号完成注册登录,手机号用于注册登录、验证码校验、订单联系、售后处理和账号找回,不用于营销。 +2. 账号标识:账号用于身份识别、权限校验和操作归属记录;账号与手机号均使用 AES-GCM 加密存储。 +3. 资料:昵称、头像仅在你主动补充或更新时处理。 +4. 业务信息:预约、订单、会员余额与余额变动、优惠券、售后、消息和客服记录,用于履行交易和服务。 +5. 安全运行:服务端处理网络地址、登录会话、客户端本地生成的随机设备标识和操作审计信息,用于登录安全、风险控制和审计;不采集 IMEI、MAC、通讯录、麦克风或持续定位。 +6. 内容与图片:你主动上传的头像、作品图片等文件存储于对象存储,用于资料展示和服务履约;本服务当前不接入第三方内容安全审核平台和地图服务,如后续启用将更新本政策并另行告知。 + +二、加密存储与检索索引 +1. 手机号与账号使用 AES-GCM 加密后落库,不以明文存入数据库;密文带版本标识。 +2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供。 +3. 为支持登录、去重和查询匹配,系统以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引;该索引不能反推手机号或账号原文,不对外展示。 +4. 备份、导出和迁移沿用同等加密要求。 + +三、按场景脱敏展示 +1. 订单、预约、售后、消息、客户服务和后台列表等常规场景展示脱敏号码。 +2. 本人资料维护、管理端编辑、门店或客服拨号等必要业务联系场景,在登录态、门店或订单可见范围和权限校验通过时展示完整号码;完整号码不向无权限页面批量返回。 +3. 脱敏由服务端集中策略执行;客户端不得缓存、截屏传播或向无关第三方提供完整号码。 + +四、第三方共享 +我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的: +1. 微信:微信登录、手机号授权和订阅消息。 +2. 短信服务商:通过部署环境配置的 MessageHub 短信通道发送验证码、绑定/解绑和必要业务通知。 +3. 消息通道:通过 MessageHub 等已配置通道推送站内或订阅消息。 +4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。 +我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。 + +五、保存期限与删除 +1. 账号注销:可在小程序设置中提交注销申请;注销后账号不可登录,系统清除账号手机号密文和 phone_hash 索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。 +3. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。 +4. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。 + +六、你的权利 +1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在设置中更换。 +2. 删除与注销:可在设置中申请注销;也可请求删除非交易必需的资料。 +3. 撤回同意:可在设置或联系客服撤回授权;撤回后不影响撤回前已进行的处理。 +4. 投诉与咨询:可联系在线客服或运营方公布的客服渠道【待业务确认】;我们将在收到请求后按适用法律规定的期限响应。 +5. 请注意:为保障交易安全,订单、余额和售后记录在法定或约定留存期内可能无法立即删除。 + +七、未成年人保护 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,我们不会处理其个人信息。如发现误收集,将停止处理并删除。 + +八、安全措施与安全事件响应 +我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。 + +九、跨境传输 +目前我们不涉及向境外提供个人信息。如未来发生跨境传输,将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。 + +十、政策更新与联系 +本政策版本为 2026.11.04,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在设置中查看当前版本;其他问题请联系在线客服或运营方公布的客服渠道【待业务确认】。 + +本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。', + 1, NOW(), NOW(), NOW(), 0); diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql new file mode 100644 index 00000000..aca85eaf --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql @@ -0,0 +1,118 @@ +-- ============================================================ +-- ArtList V5:账号加密与账号哈希 +-- 日期:2026-11-04 +-- +-- 版本号说明:V3 从未在任何环境执行过;并行分支已先占用 V4 +-- (V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql), +-- 在 out-of-order:false 前提下本文件使用 V5,保证 V1→V2→V4→V5 顺序天然正确。 +-- +-- 语义: +-- 1. t_user.account 列改为存放 AES-GCM 密文(enc:v1: 前缀),列名与 Salon 保持一致; +-- 2. 新增 account_hash(HMAC-SHA256 十六进制),并建立唯一索引 uk_user_account_hash, +-- 所有账号等值查询统一走 account_hash; +-- 3. 删除依赖明文 account 的唯一索引 uk_account; +-- 4. 不做 SQL 数据迁移:历史/种子账号(如 xiaowang)由应用启动时 +-- AccountHashBackfillRunner 加密并回填 hash。 +-- +-- 幂等:information_schema 判存在 + 存储过程,沿用 V2 风格;可安全重放。 +-- ============================================================ + +DROP PROCEDURE IF EXISTS sp_v5_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v5_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v5_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_v5_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_v5_drop_index_if_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` DROP INDEX `', p_index_name, '`' + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_v5_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +-- 1. 账号列改为密文容器(与 Salon 对齐:varchar(128) NULL) +ALTER TABLE t_user + MODIFY COLUMN account varchar(128) NULL COMMENT '账号AES-GCM密文(enc:v1: 前缀)'; + +-- 2. 新增账号 HMAC 索引列 +CALL sp_v5_add_column_if_not_exists( + 't_user', + 'account_hash', + "char(64) NULL COMMENT '账号HMAC-SHA256索引'" +); + +-- 3. 删除依赖明文账号的唯一索引 +CALL sp_v5_drop_index_if_exists('t_user', 'uk_account'); + +-- 4. 新增账号哈希唯一索引(MySQL 唯一索引允许多行 NULL) +CALL sp_v5_add_unique_index_if_not_exists( + 't_user', + 'uk_user_account_hash', + '(account_hash)' +); + +DROP PROCEDURE IF EXISTS sp_v5_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v5_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v5_add_unique_index_if_not_exists; diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql new file mode 100644 index 00000000..b568cffd --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql @@ -0,0 +1,119 @@ +-- V6:协议文本改为全场景脱敏与单次拨号取号 +-- 版本:2026.11.04-R2 +-- 说明:V4 已发布 2026.11.04 版本协议文本;本次仅新增修订版本并停用旧版本,不修改 V1/V2/V4 文件内容。 +-- 变更点:所有推送前端的号码一律脱敏;电话联系改为按需单次拨号取号,可对接隐私号码且未配置时明确不可用。 + +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) +VALUES + (313931273555138005, 'USER_TERMS', '用户协议', '2026.11.04-R2', + '欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。本协议与《隐私政策》共同构成你使用本服务的基础规则。 + +一、协议接受与版本 +你在登录或注册前应完整阅读本协议和《隐私政策》并主动选择同意;不同意时不能完成注册或继续使用。本协议版本为 2026.11.04-R2,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。 + +二、账号与安全 +1. 你应使用本人手机号注册和登录,手机号用于身份识别、验证码校验、订单联系和账号找回。 +2. 手机号与账号按《隐私政策》所述采用 AES-GCM 加密存储,并以 phone_hash/account_hash 不可逆索引支持登录与去重;客户端页面一律展示脱敏号码,需要电话联系时通过单次拨号取号接口按需获取当次可拨号码,该接口可对接隐私号码且不会回退为真实号码。 +3. 你应妥善保管账号、验证码和登录设备,不得转借、出租、出售账号,不得绕过权限校验访问他人信息。 +4. 发现账号异常、手机号被冒用或验证码泄露时,应及时修改资料、解绑手机号并联系客服。 + +三、预约、订单与会员 +1. 预约与订单信息应真实、准确;你应确保填写的联系人手机号已获得联系人授权。 +2. 订单金额、会员余额、优惠券和售后规则以页面展示和门店确认为准;本平台当前不发起在线支付,充值档位仅作展示,实际充值、退款和余额变动由门店按线下流程处理。 +3. 不得利用订单、优惠券、会员权益进行虚假交易、套现、刷单或欺诈。 + +四、用户内容 +你上传的头像、作品图片、评价等内容应来源合法,不得包含违法、侵权、暴力、色情、欺诈或侵害他人权益的信息。你授予平台为提供服务所必需的展示、存储和处理权限;平台可对违规内容采取删除、屏蔽或限制功能等措施。 + +五、个人信息与保密 +1. 你不得收集、导出、转卖或向无关第三方提供通过平台获取的他人手机号、订单或会员信息。 +2. 任何客户端页面均不展示完整手机号;需要电话联系时,仅在登录态与可见范围、权限校验通过后通过单次拨号取号接口获取当次可拨号码,平台不向客户端批量返回、缓存或提供长期有效的号码。 + +六、账号注销与数据留存 +1. 你可在小程序设置中申请注销;注销后账号不可登录,系统清除账号手机号密文、联系电话密文及相关哈希索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。 +3. 法律法规另有强制留存要求的,按法定期限保存。 + +七、未成年人 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,不得注册或下单。 + +八、服务调整、责任与联系 +1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。 +2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。 +3. 隐私相关申请可从设置发起或联系在线客服;其他问题请联系运营方公布的客服渠道【待业务确认】。 + +本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555138006, 'PRIVACY_POLICY', '隐私政策', '2026.11.04-R2', + 'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。本政策说明我们如何处理这些个人信息。 + +一、处理的信息及用途 +1. 登录与账号:你通过微信登录授权获取 OpenID 与 UnionID,用于识别和绑定账号;你主动授权手机号或输入手机号完成注册登录,手机号用于注册登录、验证码校验、订单联系、售后处理和账号找回,不用于营销。 +2. 账号标识:账号用于身份识别、权限校验和操作归属记录;账号与手机号均使用 AES-GCM 加密存储。 +3. 资料:昵称、头像仅在你主动补充或更新时处理。 +4. 业务信息:预约、订单、会员余额与余额变动、优惠券、售后、消息和客服记录,用于履行交易和服务。 +5. 安全运行:服务端处理网络地址、登录会话、客户端本地生成的随机设备标识和操作审计信息,用于登录安全、风险控制和审计;不采集 IMEI、MAC、通讯录、麦克风或持续定位。 +6. 内容与图片:你主动上传的头像、作品图片等文件存储于对象存储,用于资料展示和服务履约;本服务当前不接入第三方内容安全审核平台和地图服务,如后续启用将更新本政策并另行告知。 + +二、加密存储与检索索引 +1. 手机号与账号使用 AES-GCM 加密后落库,不以明文存入数据库;密文带版本标识。 +2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供。 +3. 为支持登录、去重和查询匹配,系统以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引;该索引不能反推手机号或账号原文,不对外展示。 +4. 备份、导出和迁移沿用同等加密要求。 + +三、全场景脱敏与单次拨号取号 +1. 本人资料、管理端列表与编辑、订单、预约、售后、消息、客户服务和后台列表等所有返回客户端的场景,一律展示脱敏号码与脱敏账号;服务端不对客户端返回完整手机号。 +2. 需要电话联系时,客户端在点击联系入口后调用单次拨号取号接口;服务端按场景校验登录态、订单归属、门店可见范围与权限后,返回当次可拨号码或隐私号码,响应带有效期标识,前端不缓存、不落库、不写入日志。 +3. 平台可对接隐私号码服务;未配置隐私号码时接口明确返回不可用错误,不会回退为真实号码。 +4. 日志、审计、消息记录与缓存不得保存完整手机号或完整账号;审计仅记录操作人、时间、场景与结果。 + +四、第三方共享 +我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的: +1. 微信:微信登录、手机号授权和订阅消息。 +2. 短信服务商:通过部署环境配置的 MessageHub 短信通道发送验证码、绑定/解绑和必要业务通知。 +3. 消息通道:通过 MessageHub 等已配置通道推送站内或订阅消息。 +4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。 +我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。 + +五、保存期限与删除 +1. 账号注销:可在小程序设置中提交注销申请;注销后账号不可登录,系统清除账号手机号密文、联系电话密文及相关哈希索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。 +3. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。 +4. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。 + +六、你的权利 +1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在设置中更换,展示值为脱敏值。 +2. 删除与注销:可在设置中申请注销;也可请求删除非交易必需的资料。 +3. 撤回同意:可在设置或联系客服撤回授权;撤回后不影响撤回前已进行的处理。 +4. 投诉与咨询:可联系在线客服或运营方公布的客服渠道【待业务确认】;我们将在收到请求后按适用法律规定的期限响应。 +5. 请注意:为保障交易安全,订单、余额和售后记录在法定或约定留存期内可能无法立即删除。 + +七、未成年人保护 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,我们不会处理其个人信息。如发现误收集,将停止处理并删除。 + +八、安全措施与安全事件响应 +我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。 + +九、跨境传输 +目前我们不涉及向境外提供个人信息。如未来发生跨境传输,将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。 + +十、政策更新与联系 +本政策版本为 2026.11.04-R2,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在设置中查看当前版本;其他问题请联系在线客服或运营方公布的客服渠道【待业务确认】。 + +本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。', + 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java new file mode 100644 index 00000000..dd039d27 --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java @@ -0,0 +1,92 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +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.vo.DialResponseVO; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ContactDialControllerTest { + @Mock + private ContactInfoService contactInfoService; + @Mock + private ContactDialService contactDialService; + @Mock + private RequestThrottleService requestThrottleService; + @Mock + private SecurityAuditLogService securityAuditLogService; + + private ContactInfoController controller; + private MockHttpServletRequest request; + + @BeforeEach + void setUp() { + controller = new ContactInfoController(contactInfoService, contactDialService, requestThrottleService, + securityAuditLogService); + request = new MockHttpServletRequest(); + } + + @Test + void rejectsAnonymousCallerWith403() { + DialRequestDTO dialRequestDTO = new DialRequestDTO(); + dialRequestDTO.setScene("PLATFORM"); + + BusinessException exception = assertThrows(BusinessException.class, () -> + controller.dial(request, dialRequestDTO)); + + assertEquals(403, exception.getCode()); + verify(contactDialService, never()).dial(any(), any()); + } + + @Test + void successRecordsAuditWithoutNumber() { + request.setAttribute("userId", 1L); + request.setAttribute("account", "xiaowang"); + DialRequestDTO dialRequestDTO = new DialRequestDTO(); + dialRequestDTO.setScene("SHOP_MANAGER"); + dialRequestDTO.setTargetId(88L); + DialResponseVO response = new DialResponseVO(); + response.setMode("DIRECT"); + response.setDialNumber("13800000000"); + response.setExpiresInSeconds(300); + when(contactDialService.dial(eq(1L), any())).thenReturn(response); + + controller.dial(request, dialRequestDTO); + + verify(requestThrottleService).checkContactDial(request, 1L); + verify(securityAuditLogService).record(eq(1L), eq("xiaowang"), eq("CONTACT_DIAL_SHOP_MANAGER"), + eq("SUCCESS"), eq(null), eq(request)); + } + + @Test + void throttledRequestDoesNotReachDialService() { + request.setAttribute("userId", 1L); + DialRequestDTO dialRequestDTO = new DialRequestDTO(); + dialRequestDTO.setScene("PLATFORM"); + org.mockito.Mockito.doThrow(new RuntimeException("拨号取号过于频繁,请稍后再试")) + .when(requestThrottleService).checkContactDial(request, 1L); + + RuntimeException exception = assertThrows(RuntimeException.class, () -> + controller.dial(request, dialRequestDTO)); + + assertEquals("拨号取号过于频繁,请稍后再试", exception.getMessage()); + verify(contactDialService, never()).dial(any(), any()); + } +} diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java new file mode 100644 index 00000000..25ae3f82 --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java @@ -0,0 +1,131 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; + +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.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.dto.DialRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialTargetProvider; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DirectDialTargetProvider; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.PlaceholderPrivacyNumberProvider; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ContactDialServiceTest { + + @Mock + private UserMapper userMapper; + @Mock + private ShopMapper shopMapper; + @Mock + private ProductMapper productMapper; + @Mock + private OrderMapper orderMapper; + @Mock + private OrderItemMapper orderItemMapper; + @Mock + private UserShopBindingSupport userShopBindingSupport; + + private DialProperties dialProperties; + private ContactDialServiceImpl contactDialService; + + @BeforeEach + void setUp() { + dialProperties = new DialProperties(); + dialProperties.setProvider("direct"); + DialTargetProvider[] providers = { + new DirectDialTargetProvider(), + new PlaceholderPrivacyNumberProvider() + }; + contactDialService = new ContactDialServiceImpl(userMapper, shopMapper, productMapper, orderMapper, + orderItemMapper, userShopBindingSupport, dialProperties, Arrays.asList(providers)); + } + + @Test + void rejectsAnonymousCallerWith403() { + BusinessException exception = assertThrows(BusinessException.class, () -> + contactDialService.dial(null, platformRequest())); + assertEquals(403, exception.getCode()); + } + + @Test + void platformSceneReturnsDirectNumber() { + UserDO caller = user(1L, 1); + UserDO admin = user(9L, 4); + admin.setPhone("13800000000"); + when(userMapper.selectById(1L)).thenReturn(caller); + when(userMapper.selectOne(any())).thenReturn(admin); + + DialResponseVO response = contactDialService.dial(1L, platformRequest()); + + assertEquals("DIRECT", response.getMode()); + assertEquals("13800000000", response.getDialNumber()); + } + + @Test + void orderArtistRejectsOrderOfOtherUser() { + UserDO caller = user(1L, 1); + OrderDO order = new OrderDO(); + order.setId(100L); + order.setUserId(2L); + order.setIsDelete(0); + when(userMapper.selectById(1L)).thenReturn(caller); + when(orderMapper.selectById(100L)).thenReturn(order); + + DialRequestDTO request = new DialRequestDTO(); + request.setScene("ORDER_ARTIST"); + request.setTargetId(100L); + + BusinessException exception = assertThrows(BusinessException.class, () -> + contactDialService.dial(1L, request)); + assertEquals(403, exception.getCode()); + } + + @Test + void privacyNumberProviderNeverFallsBackToRealNumber() { + dialProperties.setProvider("privacy-number"); + UserDO caller = user(1L, 1); + UserDO admin = user(9L, 4); + admin.setPhone("13800000000"); + when(userMapper.selectById(1L)).thenReturn(caller); + when(userMapper.selectOne(any())).thenReturn(admin); + + BusinessException exception = assertThrows(BusinessException.class, () -> + contactDialService.dial(1L, platformRequest())); + + assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, exception.getCode()); + } + + private DialRequestDTO platformRequest() { + DialRequestDTO request = new DialRequestDTO(); + request.setScene("PLATFORM"); + return request; + } + + private UserDO user(Long id, Integer type) { + UserDO user = new UserDO(); + user.setId(id); + user.setType(type); + user.setIsDelete(0); + user.setStatus(1); + return user; + } +} diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCryptoTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCryptoTest.java new file mode 100644 index 00000000..51221fda --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCryptoTest.java @@ -0,0 +1,88 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PhoneCryptoTest { + + private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM="; + private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU="; + + private PhoneCrypto phoneCrypto; + + @BeforeEach + void setUp() { + PhoneCryptoProperties properties = new PhoneCryptoProperties(); + properties.setEncryptionKey(ENCRYPTION_KEY); + properties.setIndexKey(INDEX_KEY); + phoneCrypto = new PhoneCrypto(properties); + phoneCrypto.initialize(); + } + + @Test + void encryptAndDecryptRoundTrip() { + String phone = "13800000000"; + String cipher = phoneCrypto.encrypt(phone); + assertTrue(cipher.startsWith("enc:v1:")); + assertEquals(phone, phoneCrypto.decrypt(cipher)); + assertNotEquals(cipher, phoneCrypto.encrypt(phone), "随机IV使同一明文的密文不同"); + } + + @Test + void hashIsStableForSamePhone() { + String phone = "13800000000"; + String first = phoneCrypto.index(phone); + String second = phoneCrypto.index(phone); + assertEquals(first, second); + assertEquals(64, first.length()); + assertEquals(first, first.toLowerCase()); + } + + @Test + void normalizationOnlyTrimsToMatchSalon() { + assertEquals(phoneCrypto.index("13800000000"), phoneCrypto.index(" 13800000000 ")); + assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("+8613800000000")); + assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("138-0000-0000")); + assertFalse(phoneCrypto.isMobilePhone("+8613800000000")); + assertFalse(phoneCrypto.isMobilePhone("138-0000-0000")); + assertTrue(phoneCrypto.isMobilePhone("13800000000")); + } + + @Test + void hashOfUnknownPhoneDoesNotMatchRegisteredPhone() { + assertNotEquals(phoneCrypto.index("13900000000"), phoneCrypto.index("13800000000")); + } + + @Test + void maskKeepsPrefixAndSuffix() { + assertEquals("138****0000", phoneCrypto.mask("13800000000")); + assertEquals("138****0000", phoneCrypto.mask(phoneCrypto.encrypt("13800000000"))); + assertEquals("zhangsan", phoneCrypto.mask("zhangsan")); + } + + @Test + void accountIsAlwaysEncryptedAndDecryptsBack() { + String account = "xiaowang"; + String cipher = phoneCrypto.encryptAccount(account); + assertTrue(cipher.startsWith("enc:v1:")); + assertEquals(account, phoneCrypto.decryptAccount(cipher)); + // 数值型自定义账号同样加密,不采用 Salon 的"仅手机号形态加密"条件 + String digitAccount = "20261104"; + assertTrue(phoneCrypto.encryptAccount(digitAccount).startsWith("enc:v1:")); + assertEquals(digitAccount, phoneCrypto.decryptAccount(phoneCrypto.encryptAccount(digitAccount))); + } + + @Test + void legacyPlainAccountIsReadableAndHashIsStable() { + // V1 种子账号历史上是明文,无 enc:v1: 前缀时原样返回 + assertEquals("xiaowang", phoneCrypto.decryptAccount("xiaowang")); + assertEquals(phoneCrypto.index("xiaowang"), phoneCrypto.index(" xiaowang ")); + assertEquals(64, phoneCrypto.index("xiaowang").length()); + } +} diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java new file mode 100644 index 00000000..521b76de --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java @@ -0,0 +1,55 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SensitiveFieldPolicyTest { + + private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM="; + private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU="; + private static final String PHONE = "13800000000"; + + @BeforeEach + void setUp() { + PhoneCryptoProperties properties = new PhoneCryptoProperties(); + properties.setEncryptionKey(ENCRYPTION_KEY); + properties.setIndexKey(INDEX_KEY); + PhoneCrypto crypto = new PhoneCrypto(properties); + crypto.initialize(); + } + + @Test + void phoneIsMaskedInEveryScenario() { + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.SELF_PROFILE)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.THIRD_PARTY)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.DIAL)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.LOG)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PhoneCrypto.current().encrypt(PHONE), SensitiveFieldPolicy.Scenario.DIAL)); + } + + @Test + void accountIsMaskedInEveryScenario() { + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.SELF_PROFILE)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.THIRD_PARTY)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.DIAL)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.LOG)); + assertEquals("138****0000", SensitiveFieldPolicy.account(PHONE, SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + assertEquals("***", SensitiveFieldPolicy.account("ab", SensitiveFieldPolicy.Scenario.LOG)); + } + + @Test + void encryptedAccountIsMaskedAfterDecrypt() { + assertEquals("xi***", SensitiveFieldPolicy.account(PhoneCrypto.current().encryptAccount("xiaowang"), SensitiveFieldPolicy.Scenario.SELF_PROFILE)); + } + + @Test + void nullAndBlankValuesStayUnchanged() { + assertEquals(null, SensitiveFieldPolicy.phone(null, SensitiveFieldPolicy.Scenario.LOG)); + assertEquals("", SensitiveFieldPolicy.account("", SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + } +} diff --git a/JC-ArtList-Frontend/src/api/order.ts b/JC-ArtList-Frontend/src/api/order.ts index 015c9875..e4a09dae 100644 --- a/JC-ArtList-Frontend/src/api/order.ts +++ b/JC-ArtList-Frontend/src/api/order.ts @@ -158,9 +158,6 @@ export interface GrowthSummaryVO { export const paymentApi = { prepareOrderPayment: async (orderId: IdType): Promise => { return await api.post(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO - }, - mockSuccess: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO } } diff --git a/JC-ArtList-Frontend/src/api/user.ts b/JC-ArtList-Frontend/src/api/user.ts index 4c6fc5df..d7de3af3 100644 --- a/JC-ArtList-Frontend/src/api/user.ts +++ b/JC-ArtList-Frontend/src/api/user.ts @@ -202,7 +202,8 @@ export interface InviteCodeVO { * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface UpdatePhoneRequest { - oldPhone: string + /** 兼容旧协议保留;服务端按当前登录用户取原手机号,不再使用该字段。 */ + oldPhone?: string newPhone: string verificationCode: string } @@ -319,6 +320,20 @@ export interface ContactInfoVO { platformContactText?: string } +/** + * 拨号场景:与后端 /contact-info/dial 的 scene 取值一致。 + */ +export type ContactDialScene = 'SHOP_MANAGER' | 'ORDER_ARTIST' | 'PRODUCT_ARTIST' | 'PLATFORM' + +/** + * 单次拨号取号结果;DIRECT 为直拨真实号码,PRIVACY_NUMBER 为隐私号码。 + */ +export interface DialContactResult { + mode: 'DIRECT' | 'PRIVACY_NUMBER' + dialNumber: string + expiresInSeconds: number +} + /** * userApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. @@ -385,7 +400,7 @@ export const userApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. * @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }` */ - sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { + sendVerificationCode: (data: { phone?: string; sceneCode?: string }) => { return api.post('/user/send-verification-code', data) }, /** @@ -459,6 +474,10 @@ export const userApi = { getPlatformContact: async (): Promise => { return await api.get('/contact-info/platform') as unknown as ContactInfoVO }, + // 单次拨号取号:号码不缓存到本地,拨号完成后即丢弃。 + dialContact: async (scene: ContactDialScene, targetId?: IdType, artistId?: IdType): Promise => { + return await api.post('/contact-info/dial', { scene, targetId, artistId }) as unknown as DialContactResult + }, /** * `deactivateAccount` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. diff --git a/JC-ArtList-Frontend/src/views/AccountSettingsView.vue b/JC-ArtList-Frontend/src/views/AccountSettingsView.vue index 712fb84c..6fa473f1 100644 --- a/JC-ArtList-Frontend/src/views/AccountSettingsView.vue +++ b/JC-ArtList-Frontend/src/views/AccountSettingsView.vue @@ -625,8 +625,8 @@ const handleChangePhoneSubmit = async () => { changePhoneLoading.value = true try { await runWithGlobalLoading(async () => { + // 原手机号由服务端按当前登录用户读取,前端不再回传可能已脱敏的号码。 await userApi.updatePhone({ - oldPhone: userInfo.value.phone!, newPhone: changePhoneForm.newPhone, verificationCode: changePhoneForm.verificationCode }) diff --git a/JC-ArtList-Frontend/src/views/HelpView.vue b/JC-ArtList-Frontend/src/views/HelpView.vue index 3e503e01..e19c4656 100644 --- a/JC-ArtList-Frontend/src/views/HelpView.vue +++ b/JC-ArtList-Frontend/src/views/HelpView.vue @@ -9,6 +9,20 @@ import { BRAND_CONFIG } from '@/config/brand' const router = useRouter() const loading = ref(false) const contact = ref(null) +const dialing = ref(false) + +/** 平台客服拨号:点击后才单次取号,号码不落页面状态。 */ +const dialPlatform = async () => { + dialing.value = true + try { + const result = await userApi.dialContact('PLATFORM') + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '获取客服号码失败') + } finally { + dialing.value = false + } +} const loadContact = async () => { loading.value = true @@ -46,7 +60,9 @@ onMounted(loadContact)

平台联系信息

{{ contact.contactName }} {{ contact.roleLabel || '' }}

-

电话:{{ contact.phone }}

+

+ 拨打客服电话 +

微信:{{ contact.wechatId }}

{{ contact.platformContactText }}

暂无可展示的客服信息,请稍后重试或通过订单详情联系服务人员。

diff --git a/JC-ArtList-Frontend/src/views/OrderDetailView.vue b/JC-ArtList-Frontend/src/views/OrderDetailView.vue index 1367717a..6b9fb014 100644 --- a/JC-ArtList-Frontend/src/views/OrderDetailView.vue +++ b/JC-ArtList-Frontend/src/views/OrderDetailView.vue @@ -19,6 +19,7 @@ const reviews = ref([]) const changeRequests = ref([]) const afterSales = ref([]) const contact = ref(null) +const dialing = ref(false) const quoteReply = ref('') const quoteSubmitting = ref(false) const quoteConfirming = ref(false) @@ -37,7 +38,6 @@ const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status)) const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending' const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID' const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value)) -const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING') const canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value))) const timeline = computed(() => { @@ -131,6 +131,20 @@ const loadRelated = async () => { contact.value = contactInfo } +/** 单次取号后立即拨号:不缓存号码,仅使用本次返回的 dialNumber。 */ +const dialArtist = async () => { + if (!orderId.value) return + dialing.value = true + try { + const result = await userApi.dialContact('ORDER_ARTIST', orderId.value) + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '获取拨号号码失败') + } finally { + dialing.value = false + } +} + const loadOrder = async () => { if (!orderId.value) { order.value = null @@ -206,15 +220,6 @@ const preparePayment = async () => { message.success('支付单已准备') } -const mockPay = async () => { - if (!order.value?.id) return - await runWithGlobalLoading(async () => { - await paymentApi.mockSuccess(order.value.id) - await loadOrder() - }) - message.success('模拟支付成功') -} - const cancelOrder = () => { if (!order.value?.id) return Modal.confirm({ @@ -344,7 +349,9 @@ onMounted(loadOrder)

联系信息

{{ contact.contactName || contact.roleLabel || '服务联系人' }}

-

电话:{{ contact.phone }}

+

+ 拨打美甲师电话 +

微信:{{ contact.wechatId }}

{{ contact.platformContactText }}

@@ -358,7 +365,6 @@ onMounted(loadOrder)
准备支付 - 模拟支付 申请售后 取消订单
diff --git a/JC-ArtList-Frontend/src/views/OrderView.vue b/JC-ArtList-Frontend/src/views/OrderView.vue index b765db9c..37a08fad 100644 --- a/JC-ArtList-Frontend/src/views/OrderView.vue +++ b/JC-ArtList-Frontend/src/views/OrderView.vue @@ -201,7 +201,6 @@
- @@ -471,7 +470,6 @@ const orderPaymentStatus = (order: any) => String(order.paymentStatus || order.p const isOrderPaid = (order: any) => orderPaymentStatus(order) === 'PAID' const orderNeedsPayment = (order: any) => Number(order.status) === 1 && !isOrderPaid(order) const canPreparePayment = (order: any) => orderNeedsPayment(order) && orderPaymentStatus(order) !== 'PAYING' -const canMockPay = (order: any) => Number(order.status) === 1 && orderPaymentStatus(order) === 'PAYING' const canApplyAfterSale = (order: any) => !isQuoteConfirming(order) && (Number(order.status) === 2 || isOrderPaid(order)) /** @@ -779,18 +777,6 @@ const preparePayment = async (order: any) => { } } -const mockPay = async (order: any) => { - try { - await runWithGlobalLoading(async () => { - await paymentApi.mockSuccess(order.id) - await loadOrders() - }) - message.success('支付成功') - } catch (error: any) { - message.error(error?.message || '支付失败') - } -} - const submitQuoteReply = async (order: any) => { const key = quoteOrderKey(order) const remark = String(quoteReplyForms[key] || '').trim() diff --git a/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue b/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue index 82d3c055..65819edd 100644 --- a/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue +++ b/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue @@ -238,7 +238,7 @@ const handleSendVerificationCode = async () => { try { await runWithGlobalLoading(() => userApi.sendVerificationCode({ - phone: userPhone.value, + // 号码由服务端按当前登录用户读取,前端只传场景,避免回传已脱敏的展示值。 sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' })) message.success('验证码发送成功') diff --git a/JC-ArtList-Frontend/src/views/ProfileView.vue b/JC-ArtList-Frontend/src/views/ProfileView.vue index 37eb972e..7a298a4d 100644 --- a/JC-ArtList-Frontend/src/views/ProfileView.vue +++ b/JC-ArtList-Frontend/src/views/ProfileView.vue @@ -193,8 +193,8 @@ - - + +
@@ -211,7 +211,7 @@ 删除二维码 - 店长和美甲师需填写微信号,二维码可选。 + 微信号与二维码均为选填。
@@ -373,6 +373,9 @@ const editForm = reactive({ wechatQrCode: '' }) +/** 打开编辑弹窗时的联系电话原值,用于判断用户是否真实修改过(未修改则不提交该字段)。 */ +const originalContactPhone = ref('') + /** getDraftKey is a local helper used by this page script. */ const getDraftKey = () => buildDraftStorageKey('profile-edit') @@ -596,6 +599,7 @@ const handleEditProfile = () => { editForm.avatar = userInfo.value.avatar || '' editForm.signature = userInfo.value.signature || '' editForm.contactPhone = userInfo.value.contactPhone || '' + originalContactPhone.value = editForm.contactPhone editForm.birthday = userInfo.value.birthday || '' editForm.wechatId = userInfo.value.wechatId || '' editForm.wechatQrCode = userInfo.value.wechatQrCode || '' @@ -734,23 +738,20 @@ const handleSaveProfile = async () => { return } - if (isServiceUser.value && !editForm.wechatId.trim()) { - message.error('店长和美甲师必须填写微信号') - return - } - saving.value = true try { await runWithGlobalLoading(async () => { - await userApi.updateUserInfo({ + const payload = { nickname: editForm.nickname, avatar: editForm.avatar, signature: editForm.signature, - contactPhone: editForm.contactPhone, birthday: editForm.birthday || undefined, wechatId: editForm.wechatId, - wechatQrCode: editForm.wechatQrCode - }) + wechatQrCode: editForm.wechatQrCode, + // 只有联系电话真实变更时才提交,避免把接口回填值(可能已脱敏)原样写回 + ...(editForm.contactPhone !== originalContactPhone.value ? { contactPhone: editForm.contactPhone } : {}) + } + await userApi.updateUserInfo(payload) await fetchUserInfo() }) message.success('资料更新成功') diff --git a/JC-ArtList-Frontend/src/views/ShopDetailView.vue b/JC-ArtList-Frontend/src/views/ShopDetailView.vue index afa5215c..739f5999 100644 --- a/JC-ArtList-Frontend/src/views/ShopDetailView.vue +++ b/JC-ArtList-Frontend/src/views/ShopDetailView.vue @@ -226,16 +226,12 @@

{{ contactInfo.contactName || contactInfo.roleLabel || '联系人' }}

联系电话 - {{ contactInfo.phoneAvailable ? contactInfo.phone : '暂无电话' }} + {{ contactInfo.phoneAvailable ? '点击下方按钮获取当次号码' : '暂无电话' }}
- + - 拨号 - - - - 复制电话 + 拨打店长电话
@@ -372,6 +368,7 @@ const contactOpen = ref(false) * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const contactInfo = ref({}) +const dialing = ref(false) /** * Purpose: mapOpen supports ShopDetailView.vue by holding or executing the map open page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -617,11 +614,24 @@ const openWechatContact = async () => { window.location.href = 'weixin://' } -/** copyContactInfo copies all available contact channels in one action. */ +/** 单次取号后立即拨号:页面不缓存号码,仅使用本次返回的 dialNumber。 */ +const dialManager = async () => { + if (!shopInfo.value.id) return + dialing.value = true + try { + const result = await userApi.dialContact('SHOP_MANAGER', shopInfo.value.id) + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '获取拨号号码失败') + } finally { + dialing.value = false + } +} + +/** copyContactInfo copies the WeChat channel only; phone numbers are no longer rendered or cached. */ const copyContactInfo = async () => { const lines = [ contactInfo.value.contactName || contactInfo.value.roleLabel || '联系人', - contactInfo.value.phoneAvailable && contactInfo.value.phone ? `电话:${contactInfo.value.phone}` : '', contactInfo.value.wechatAvailable && contactInfo.value.wechatId ? `微信:${contactInfo.value.wechatId}` : '' ].filter(Boolean) await copyToClipboard(lines.join('\n'), '联系方式') diff --git a/JC-ArtList-Frontend/vite.config.ts b/JC-ArtList-Frontend/vite.config.ts index e1fc04bd..b439431f 100644 --- a/JC-ArtList-Frontend/vite.config.ts +++ b/JC-ArtList-Frontend/vite.config.ts @@ -57,7 +57,7 @@ export default defineConfig(({ mode }) => { 'localhost', '127.0.0.1', '2666.online', - 'wcy111.top' + 'wcsrv.top' ] }, build: { diff --git a/JC-ArtList-WeChat/api/payment.js b/JC-ArtList-WeChat/api/payment.js index b551479f..89caf52d 100644 --- a/JC-ArtList-WeChat/api/payment.js +++ b/JC-ArtList-WeChat/api/payment.js @@ -7,13 +7,5 @@ module.exports = { method: 'POST', data: {} }) - }, - - mockOrderPaymentSuccess(orderId) { - return request({ - url: `/payment/order/${orderId}/mock-success`, - method: 'POST', - data: {} - }) } } diff --git a/JC-ArtList-WeChat/api/user.js b/JC-ArtList-WeChat/api/user.js index f7662e43..d186dae7 100644 --- a/JC-ArtList-WeChat/api/user.js +++ b/JC-ArtList-WeChat/api/user.js @@ -144,6 +144,18 @@ module.exports = { }) }, + /** + * 单次拨号取号:号码不缓存,仅用于本次拨号。 + * scene: SHOP_MANAGER / ORDER_ARTIST / PRODUCT_ARTIST / PLATFORM + */ + dialContact(scene, targetId, artistId) { + return request({ + url: '/contact-info/dial', + method: 'POST', + data: { scene, targetId, artistId } + }) + }, + /** * Purpose: getShopManagerContact supports user.js by holding or executing the get shop manager contact page or API role. * Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow. diff --git a/JC-ArtList-WeChat/api/vnext.test.js b/JC-ArtList-WeChat/api/vnext.test.js index 95d3a12a..154b78bc 100644 --- a/JC-ArtList-WeChat/api/vnext.test.js +++ b/JC-ArtList-WeChat/api/vnext.test.js @@ -19,7 +19,6 @@ const afterSaleApi = require('./after-sale') const growthApi = require('./growth') paymentApi.prepareOrderPayment(12) -paymentApi.mockOrderPaymentSuccess(12) afterSaleApi.applyAfterSale({ orderId: 12, reason: 'need refund' }) afterSaleApi.getMyAfterSales({ page: 2, size: 5 }) growthApi.getGrowthSummary() @@ -32,19 +31,14 @@ assert.deepStrictEqual(calls[0], { data: {} }) assert.deepStrictEqual(calls[1], { - url: '/payment/order/12/mock-success', - method: 'POST', - data: {} -}) -assert.deepStrictEqual(calls[2], { url: '/after-sale/apply', method: 'POST', data: { orderId: 12, reason: 'need refund' } }) -assert.deepStrictEqual(calls[3], { +assert.deepStrictEqual(calls[2], { url: '/after-sale/my', params: { page: 2, size: 5 } }) -assert.deepStrictEqual(calls[4], { +assert.deepStrictEqual(calls[3], { url: '/growth/summary' }) diff --git a/JC-ArtList-WeChat/app.json b/JC-ArtList-WeChat/app.json index 945da678..64a16f58 100644 --- a/JC-ArtList-WeChat/app.json +++ b/JC-ArtList-WeChat/app.json @@ -7,7 +7,6 @@ "pages/profile/index", "pages/auth/index", "pages/product-detail/index", - "pages/artist-profile/index", "pages/shop-detail/index", "pages/orders/index", "pages/order-detail/index", @@ -15,8 +14,6 @@ "pages/after-sale-apply/index", "pages/service-progress/index", "pages/help/index", - "pages/artist-orders/index", - "pages/artist-calendar/index", "pages/account-settings/index", "pages/password-settings/index", "pages/wishlist/index", diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.js b/JC-ArtList-WeChat/pages/artist-calendar/index.js deleted file mode 100644 index 5d32fb83..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.js +++ /dev/null @@ -1,76 +0,0 @@ -const orderApi = require('../../api/order') -const auth = require('../../utils/auth') -const navigation = require('../../utils/navigation') -const theme = require('../../utils/theme') -const { formatDateTime, formatPrice } = require('../../utils/format') -const { runWithLoading } = require('../../utils/loading') - -function safeList(value) { - return Array.isArray(value) ? value : [] -} - -function formatClock(value) { - return value ? String(value).replace('T', ' ').slice(11, 16) : '--' -} - -function formatAppointment(item) { - return { - ...item, - dayText: String(item.appointmentStartTime || '').slice(5, 10), - timeText: `${formatClock(item.appointmentStartTime)}-${formatClock(item.appointmentEndTime)}`, - amountText: `¥${formatPrice(item.actualAmount || item.totalAmount)}`, - dateTimeText: formatDateTime(item.appointmentStartTime) - } -} - -Page({ - data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), { - loading: false, - isLoggedIn: false, - appointments: [] - }), - - onShow() { - this.loadAppointments() - }, - - handleBack() { - navigation.goBack('/pages/artist-orders/index') - }, - - async loadAppointments() { - const isLoggedIn = auth.isLoggedIn() - this.setData({ isLoggedIn }) - if (!isLoggedIn) { - navigation.openAuth(navigation.getCurrentPageUrl()) - return - } - this.setData({ loading: true }) - try { - const list = safeList(await orderApi.getArtistCalendarRecent(7)) - this.setData({ - appointments: list.map(formatAppointment) - }) - } catch (error) { - wx.showToast({ title: error.message || '预约日历加载失败', icon: 'none' }) - } finally { - this.setData({ loading: false }) - } - }, - - openArtistOrders() { - navigation.navigate('/pages/artist-orders/index') - }, - - async completeOrder(event) { - const orderId = event.currentTarget.dataset.orderId - if (!orderId) return - try { - await runWithLoading(() => orderApi.completeArtistOrder(orderId)) - wx.showToast({ title: '服务已完成', icon: 'none' }) - await this.loadAppointments() - } catch (error) { - wx.showToast({ title: error.message || '完成服务失败', icon: 'none' }) - } - } -}) diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.json b/JC-ArtList-WeChat/pages/artist-calendar/index.json deleted file mode 100644 index 8632c9b0..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "usingComponents": { - "navigation-bar": "/components/navigation-bar/navigation-bar" - } -} diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.wxml b/JC-ArtList-WeChat/pages/artist-calendar/index.wxml deleted file mode 100644 index 52ab222e..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.wxml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - 未来 7 天 - {{appointments.length}} 个预约 - 按时间查看即将服务的客户与项目 - - 订单列表 - - - - - 正在加载日历 - - - - - - {{item.dayText}} - {{item.timeText}} - - - {{item.customerNickname || '客户'}} · {{item.productTitle}} - {{item.orderStatusText}} · {{item.shopName || '门店'}} - {{item.amountText}} - 完成服务 - - - - - - 未来 7 天暂无预约 - - - diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.wxss b/JC-ArtList-WeChat/pages/artist-calendar/index.wxss deleted file mode 100644 index 77c57625..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.wxss +++ /dev/null @@ -1,49 +0,0 @@ -.appointment-card { - display: flex; - gap: 18rpx; - margin-top: 22rpx; - padding: 24rpx; -} - -.day-box { - width: 136rpx; - flex: 0 0 auto; - display: flex; - flex-direction: column; - justify-content: center; - gap: 8rpx; - padding: 20rpx 12rpx; - border-radius: 24rpx; - background: var(--theme-primary-soft); - color: var(--theme-primary); - text-align: center; - font-weight: 800; -} - -.appointment-main { - flex: 1; - min-width: 0; -} - -.appointment-title, -.appointment-line { - display: block; -} - -.appointment-title { - color: var(--text-primary); - font-size: 29rpx; - font-weight: 800; - line-height: 1.45; -} - -.appointment-line { - margin-top: 8rpx; - color: #504444; - font-size: 24rpx; - line-height: 1.6; -} - -.ghost-btn { - margin-top: 16rpx; -} diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.js b/JC-ArtList-WeChat/pages/artist-orders/index.js deleted file mode 100644 index 6142f28b..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.js +++ /dev/null @@ -1,92 +0,0 @@ -const orderApi = require('../../api/order') -const auth = require('../../utils/auth') -const navigation = require('../../utils/navigation') -const theme = require('../../utils/theme') -const { resolveLegacyImage } = require('../../utils/file') -const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format') -const { runWithLoading } = require('../../utils/loading') - -function safeList(value) { - return Array.isArray(value) ? value : [] -} - -async function formatOrder(order) { - return { - ...order, - statusText: getOrderStatusText(order), - statusClass: getOrderStatusClass(order), - amountText: `¥${formatPrice(order && order.actualAmount)}`, - items: await Promise.all(safeList(order && order.items).map(async item => ({ - ...item, - productImageUrl: await resolveLegacyImage(item.productImage), - priceText: `¥${formatPrice(item.price)}`, - appointmentText: formatDateTime(item.appointmentTime) - }))) - } -} - -Page({ - data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), { - loading: false, - isLoggedIn: false, - orders: [], - focusOrderId: '' - }), - - onLoad(options) { - this.setData({ - focusOrderId: (options && options.orderId) || '' - }) - }, - - onShow() { - this.loadOrders() - }, - - handleBack() { - navigation.goBack('/pages/profile/index') - }, - - async loadOrders() { - const isLoggedIn = auth.isLoggedIn() - this.setData({ isLoggedIn }) - if (!isLoggedIn) { - navigation.openAuth(navigation.getCurrentPageUrl()) - return - } - this.setData({ loading: true }) - try { - const list = safeList(await orderApi.getArtistOrders()) - const orders = await Promise.all(list.map(formatOrder)) - this.setData({ orders }) - } catch (error) { - wx.showToast({ title: error.message || '美甲师订单加载失败', icon: 'none' }) - } finally { - this.setData({ loading: false }) - } - }, - - openCalendar() { - navigation.navigate('/pages/artist-calendar/index') - }, - - async completeOrder(event) { - const orderId = event.currentTarget.dataset.orderId - if (!orderId) return - const confirmed = await new Promise(resolve => { - wx.showModal({ - title: '完成服务', - content: '确认这笔订单已经完成服务吗?', - success: res => resolve(Boolean(res.confirm)) - }) - }) - if (!confirmed) return - try { - await runWithLoading(() => orderApi.completeArtistOrder(orderId)) - wx.showToast({ title: '服务已完成', icon: 'none' }) - await this.loadOrders() - } catch (error) { - wx.showToast({ title: error.message || '完成订单失败', icon: 'none' }) - } - } -}) diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.json b/JC-ArtList-WeChat/pages/artist-orders/index.json deleted file mode 100644 index 8632c9b0..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "usingComponents": { - "navigation-bar": "/components/navigation-bar/navigation-bar" - } -} diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.wxml b/JC-ArtList-WeChat/pages/artist-orders/index.wxml deleted file mode 100644 index 777e3522..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.wxml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - 服务订单 - {{orders.length}} 笔相关订单 - 查看客户预约、项目和服务完成状态 - - 预约日历 - - - - - 正在加载订单 - - - - - - - {{item.orderNo}} - {{item.customerNickname || '客户'}} {{item.customerPhoneMasked || ''}} - - {{item.statusText}} - - - - - {{orderItem.productTitle}} - {{orderItem.priceText}} x {{orderItem.quantity}} - 预约:{{orderItem.appointmentText}} - - - - {{item.amountText}} - 完成服务 - - - - - - 暂无相关订单 - 有客户预约你服务的项目后会出现在这里 - - - diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.wxss b/JC-ArtList-WeChat/pages/artist-orders/index.wxss deleted file mode 100644 index 8e46a19c..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.wxss +++ /dev/null @@ -1,70 +0,0 @@ -.order-card { - margin-top: 22rpx; - padding: 26rpx; -} - -.order-card.focus-target { - border-color: var(--theme-primary); -} - -.order-head, -.order-foot { - display: flex; - align-items: center; - justify-content: space-between; - gap: 18rpx; -} - -.order-no, -.order-line, -.order-amount { - display: block; -} - -.order-no { - color: var(--text-primary); - font-size: 28rpx; - font-weight: 800; -} - -.order-line { - margin-top: 8rpx; - color: #504444; - font-size: 24rpx; - line-height: 1.6; -} - -.item-row { - display: flex; - gap: 18rpx; - margin-top: 22rpx; -} - -.item-thumb { - width: 116rpx; - height: 116rpx; - border-radius: 22rpx; - background: var(--theme-primary-soft); -} - -.item-main { - flex: 1; - min-width: 0; -} - -.item-title { - display: block; - color: var(--text-primary); - font-size: 28rpx; - font-weight: 800; -} - -.order-foot { - margin-top: 24rpx; -} - -.order-amount { - color: var(--text-primary); - font-size: 28rpx; - font-weight: 800; -} diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.js b/JC-ArtList-WeChat/pages/artist-profile/index.js deleted file mode 100644 index 848d8c7b..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.js +++ /dev/null @@ -1,136 +0,0 @@ -const nailArtistApi = require('../../api/nail-artist') -const navigation = require('../../utils/navigation') -const { DEFAULT_PRODUCT_IMAGE } = require('../../utils/config') - -function formatPrice(price) { - const value = Number(price || 0) - return value > 0 ? `¥${value.toFixed(2)}` : '到店确认' -} - -function formatDateTime(value) { - if (!value) { - return '' - } - return String(value).replace('T', ' ').slice(0, 16) -} - -Page({ - data: { - loading: true, - loadError: '', - artistId: '', - profile: null, - works: [], - reviews: [], - availability: [], - heroImage: DEFAULT_PRODUCT_IMAGE, - artistName: '美甲师', - artistDesc: '专注细节与稳定出品', - shopName: '门店待确认', - styleTags: [], - ratingText: '0.0', - serviceCountText: '0', - workTimeText: '到店确认' - }, - - onLoad(options) { - this.setData({ - artistId: options && options.id ? options.id : '' - }) - this.loadArtistProfile() - }, - - async onPullDownRefresh() { - await this.loadArtistProfile() - wx.stopPullDownRefresh() - }, - - async loadArtistProfile() { - if (!this.data.artistId) { - this.setData({ - loading: false, - loadError: '缺少美甲师信息' - }) - return - } - - this.setData({ - loading: true, - loadError: '' - }) - - try { - const [profile, availability, reviews] = await Promise.all([ - nailArtistApi.getPublicProfile(this.data.artistId), - nailArtistApi.getAvailability(this.data.artistId), - nailArtistApi.listReviews(this.data.artistId) - ]) - const works = (profile.works || []).map(work => ({ - ...work, - title: work.title || '美甲作品', - coverImageUrl: work.coverImageUrl || DEFAULT_PRODUCT_IMAGE, - priceText: formatPrice(work.price) - })) - const formattedReviews = (reviews || profile.reviews || []).map(review => ({ - ...review, - customerName: review.customerName || '匿名用户', - content: review.content || '这位用户没有填写文字评价', - submittedAtText: formatDateTime(review.submittedAt), - ratingText: Number(review.rating || 0).toFixed(1) - })) - const start = profile.workStartTime ? String(profile.workStartTime).slice(0, 5) : '' - const end = profile.workEndTime ? String(profile.workEndTime).slice(0, 5) : '' - - this.setData({ - profile, - works, - reviews: formattedReviews, - availability: availability || profile.availability || [], - heroImage: (works.find(work => work.coverImageUrl) || {}).coverImageUrl || DEFAULT_PRODUCT_IMAGE, - artistName: profile.artistName || '美甲师', - artistDesc: profile.identity || profile.signature || '专注细节与稳定出品', - shopName: profile.shopName || '门店待确认', - styleTags: (profile.styleTags || []).filter(Boolean), - ratingText: Number(profile.rating || 0).toFixed(1), - serviceCountText: String(profile.serviceCount || 0), - workTimeText: start && end ? `${start}-${end}` : '到店确认' - }) - } catch (error) { - this.setData({ - loadError: error.message || '美甲师个人页加载失败' - }) - } finally { - this.setData({ - loading: false - }) - } - }, - - handleBack() { - navigation.goBack('/pages/home/index') - }, - - handleRetry() { - this.loadArtistProfile() - }, - - handleOpenShop() { - const profile = this.data.profile - if (!profile || !profile.shopId) { - return - } - wx.navigateTo({ - url: `/pages/shop-detail/index?id=${profile.shopId}` - }) - }, - - handleOpenWork(event) { - const id = event.currentTarget.dataset.id - if (!id) { - return - } - wx.navigateTo({ - url: `/pages/product-detail/index?id=${id}` - }) - } -}) diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.json b/JC-ArtList-WeChat/pages/artist-profile/index.json deleted file mode 100644 index b16ef3e3..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "navigationStyle": "custom", - "usingComponents": {} -} diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.wxml b/JC-ArtList-WeChat/pages/artist-profile/index.wxml deleted file mode 100644 index 8386784f..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.wxml +++ /dev/null @@ -1,98 +0,0 @@ - - - ‹ - {{artistName}} - - - - - 加载中... - - - - 暂时无法查看个人页 - {{loadError}} - 重试 - - - - - - - - - 艺 - - {{artistName}} - {{artistDesc}} - {{shopName}} - - - - - - - 评分 - {{ratingText}} - - - 服务 - {{serviceCountText}} - - - 工时 - {{workTimeText}} - - - - - 擅长风格 - - {{item}} - - 暂未设置风格标签 - - - - 近期可预约 - - - {{item.dateText}} - {{item.timeText}} - - - 近期暂未放出可预约时间 - - - - 作品 - - - - {{item.title}} - {{item.priceText}} - - - 作品正在整理中 - - - - 评价 {{reviews.length}} - - - - - 客 - - {{item.customerName}} - {{item.submittedAtText}} - - {{item.ratingText}} - - {{item.content}} - - - 还没有公开评价 - - - diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.wxss b/JC-ArtList-WeChat/pages/artist-profile/index.wxss deleted file mode 100644 index 5c153ac2..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.wxss +++ /dev/null @@ -1,336 +0,0 @@ -.artist-page { - min-height: 100vh; - background: #f6f7fb; - color: #1f2933; -} - -.page-header { - position: sticky; - top: 0; - z-index: 5; - display: flex; - align-items: center; - justify-content: space-between; - height: 96rpx; - padding: 0 24rpx; - background: rgba(255, 255, 255, 0.95); - border-bottom: 1rpx solid #e6e9ef; -} - -.back-btn, -.header-spacer { - width: 64rpx; - height: 64rpx; - line-height: 58rpx; - text-align: center; - font-size: 48rpx; -} - -.page-title { - flex: 1; - overflow: hidden; - text-align: center; - font-size: 32rpx; - font-weight: 700; - text-overflow: ellipsis; - white-space: nowrap; -} - -.content-scroll { - height: calc(100vh - 96rpx); -} - -.state-box { - display: flex; - min-height: 60vh; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 20rpx; - padding: 40rpx; - color: #65717f; -} - -.state-title { - color: #1f2933; - font-size: 34rpx; - font-weight: 700; -} - -.state-desc { - text-align: center; - line-height: 1.6; -} - -.primary-btn { - padding: 18rpx 36rpx; - color: #fff; - background: var(--theme-primary-action); - border-radius: 12rpx; -} - -.hero { - position: relative; - height: 520rpx; - margin: 20rpx; - overflow: hidden; - background: #222831; - border-radius: 16rpx; -} - -.hero-image, -.hero-mask { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - width: 100%; - height: 100%; -} - -.hero-mask { - background: linear-gradient(180deg, rgba(10, 14, 20, 0.08), rgba(10, 14, 20, 0.72)); -} - -.artist-card { - position: absolute; - right: 28rpx; - bottom: 28rpx; - left: 28rpx; - display: flex; - gap: 22rpx; - align-items: center; - color: #fff; -} - -.avatar { - width: 112rpx; - height: 112rpx; - flex: 0 0 auto; - overflow: hidden; - border: 3rpx solid rgba(255, 255, 255, 0.8); - border-radius: 56rpx; -} - -.placeholder { - display: flex; - align-items: center; - justify-content: center; - background: #d8dde6; - color: #5f6b7a; - font-weight: 700; -} - -.artist-main { - min-width: 0; -} - -.artist-name, -.artist-desc, -.shop-link { - display: block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.artist-name { - font-size: 44rpx; - font-weight: 800; -} - -.artist-desc { - margin-top: 10rpx; - color: rgba(255, 255, 255, 0.88); - font-size: 26rpx; -} - -.shop-link { - max-width: 440rpx; - margin-top: 16rpx; - padding: 12rpx 18rpx; - background: rgba(255, 255, 255, 0.18); - border: 1rpx solid rgba(255, 255, 255, 0.28); - border-radius: 12rpx; -} - -.metrics { - display: grid; - grid-template-columns: repeat(3, 1fr); - gap: 16rpx; - margin: 0 20rpx 20rpx; -} - -.metric-item { - display: flex; - min-height: 132rpx; - flex-direction: column; - justify-content: center; - gap: 10rpx; - padding: 20rpx; - background: #fff; - border: 1rpx solid #e6e9ef; - border-radius: 16rpx; -} - -.metric-item text:first-child { - color: #65717f; - font-size: 24rpx; -} - -.metric-value { - overflow-wrap: anywhere; - font-size: 34rpx; - font-weight: 800; -} - -.section { - margin: 20rpx; - padding: 28rpx; - background: #fff; - border: 1rpx solid #e6e9ef; - border-radius: 16rpx; -} - -.section-head { - margin-bottom: 20rpx; - font-size: 32rpx; - font-weight: 800; -} - -.tag-list { - display: flex; - flex-wrap: wrap; - gap: 14rpx; -} - -.tag { - padding: 10rpx 18rpx; - color: #394554; - background: #eef1f5; - border-radius: 999rpx; -} - -.empty-text { - color: #7b8794; - line-height: 1.6; -} - -.slot-grid, -.work-grid { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 16rpx; -} - -.slot { - display: flex; - min-height: 104rpx; - flex-direction: column; - justify-content: center; - gap: 8rpx; - padding: 18rpx; - background: #f6f7fb; - border: 1rpx solid #dfe4ea; - border-radius: 14rpx; -} - -.slot text:first-child { - color: #65717f; - font-size: 24rpx; -} - -.slot-time { - font-size: 32rpx; - font-weight: 800; -} - -.work-card { - overflow: hidden; - background: #fff; - border: 1rpx solid #e6e9ef; - border-radius: 14rpx; -} - -.work-card image { - width: 100%; - height: 210rpx; - background: #eef1f5; -} - -.work-title, -.work-price { - display: block; - overflow: hidden; - padding: 0 16rpx; - text-overflow: ellipsis; - white-space: nowrap; -} - -.work-title { - margin-top: 14rpx; - font-weight: 700; -} - -.work-price { - margin: 8rpx 0 16rpx; - color: var(--theme-primary-action); - font-weight: 800; -} - -.review-list { - display: flex; - flex-direction: column; - gap: 18rpx; -} - -.review-card { - padding: 22rpx; - background: #f8fafc; - border: 1rpx solid #e6e9ef; - border-radius: 14rpx; -} - -.review-top { - display: flex; - align-items: center; - gap: 16rpx; -} - -.review-avatar { - width: 72rpx; - height: 72rpx; - border-radius: 36rpx; -} - -.review-meta { - flex: 1; - min-width: 0; -} - -.review-meta text { - display: block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.review-meta text:last-child { - margin-top: 4rpx; - color: #7b8794; - font-size: 22rpx; -} - -.review-score { - color: var(--theme-primary-action); - font-weight: 800; -} - -.review-content { - display: block; - margin-top: 18rpx; - color: #3f4a56; - line-height: 1.7; - white-space: pre-wrap; -} diff --git a/JC-ArtList-WeChat/pages/help/index.js b/JC-ArtList-WeChat/pages/help/index.js index c266d5dd..bf2d8a53 100644 --- a/JC-ArtList-WeChat/pages/help/index.js +++ b/JC-ArtList-WeChat/pages/help/index.js @@ -30,6 +30,18 @@ Page({ } }, + /** + * 平台客服拨号:点击后才单次取号,号码不保存。 + */ + async handleDialPlatform() { + try { + const dial = await userApi.dialContact('PLATFORM') + wx.makePhoneCall({ phoneNumber: dial.dialNumber }) + } catch (error) { + wx.showToast({ title: error.message || '获取客服号码失败', icon: 'none' }) + } + }, + openRoute(event) { const route = event.currentTarget.dataset.route const pureRoute = String(route || '').split('?')[0] diff --git a/JC-ArtList-WeChat/pages/help/index.wxml b/JC-ArtList-WeChat/pages/help/index.wxml index 457dfa80..18b8da83 100644 --- a/JC-ArtList-WeChat/pages/help/index.wxml +++ b/JC-ArtList-WeChat/pages/help/index.wxml @@ -12,7 +12,9 @@ 平台联系信息 {{contact.contactName}} {{contact.roleLabel || ''}} - 电话:{{contact.phone}} + + 拨打客服电话 + 微信:{{contact.wechatId}} {{contact.platformContactText}} diff --git a/JC-ArtList-WeChat/pages/order-detail/index.js b/JC-ArtList-WeChat/pages/order-detail/index.js index e30653cb..9c397660 100644 --- a/JC-ArtList-WeChat/pages/order-detail/index.js +++ b/JC-ArtList-WeChat/pages/order-detail/index.js @@ -131,6 +131,21 @@ Page({ navigation.navigate('/pages/after-sales/index', { orderId: this.data.id }) }, + /** + * 点击后才单次取号并拨号,页面不保存号码。 + */ + async handleDialArtist() { + if (!this.data.id) { + return + } + try { + const dial = await userApi.dialContact('ORDER_ARTIST', this.data.id) + wx.makePhoneCall({ phoneNumber: dial.dialNumber }) + } catch (error) { + wx.showToast({ title: error.message || '获取拨号号码失败', icon: 'none' }) + } + }, + async handleCancelOrder() { const confirmed = await new Promise(resolve => { wx.showModal({ diff --git a/JC-ArtList-WeChat/pages/order-detail/index.wxml b/JC-ArtList-WeChat/pages/order-detail/index.wxml index ae54d8fd..bad7d21b 100644 --- a/JC-ArtList-WeChat/pages/order-detail/index.wxml +++ b/JC-ArtList-WeChat/pages/order-detail/index.wxml @@ -51,7 +51,9 @@ 联系信息 {{contact.contactName || contact.roleLabel || '服务联系人'}} - 电话:{{contact.phone}} + + 拨打美甲师电话 + 微信:{{contact.wechatId}} {{contact.platformContactText}} diff --git a/JC-ArtList-WeChat/pages/orders/index.js b/JC-ArtList-WeChat/pages/orders/index.js index f2a444cd..c92e8e46 100644 --- a/JC-ArtList-WeChat/pages/orders/index.js +++ b/JC-ArtList-WeChat/pages/orders/index.js @@ -862,23 +862,8 @@ Page({ await runWithLoading(() => paymentApi.prepareOrderPayment(orderId), { title: '准备支付' }) - const confirmed = await new Promise(resolve => { - wx.showModal({ - title: '模拟支付', - content: `本次需支付 ${order.paymentInfo.amountText},确认模拟支付成功吗?`, - confirmText: '确认支付', - success: res => resolve(Boolean(res.confirm)), - fail: () => resolve(false) - }) - }) - if (!confirmed) { - return - } - await runWithLoading(() => paymentApi.mockOrderPaymentSuccess(orderId), { - title: '确认支付' - }) wx.showToast({ - title: '支付已确认', + title: '支付单已准备,请完成支付', icon: 'none' }) await this.loadOrders() diff --git a/JC-ArtList-WeChat/pages/settings/index.js b/JC-ArtList-WeChat/pages/settings/index.js index 882b0571..fb749df4 100644 --- a/JC-ArtList-WeChat/pages/settings/index.js +++ b/JC-ArtList-WeChat/pages/settings/index.js @@ -739,22 +739,9 @@ Page({ }, async handleChangePhoneSubmit() { - const userInfo = this.data.userInfo || {} - const oldPhone = String(userInfo.phone || '').trim() const newPhone = String(this.data.changePhoneForm.newPhone || '').trim() const verificationCode = String(this.data.changePhoneForm.verificationCode || '').trim() - - /** - * `if` page method. Use this from WXML event bindings or lifecycle hooks. - * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. - */ - if (!oldPhone) { - wx.showToast({ - title: '请先绑定手机号', - icon: 'none' - }) - return - } + // 原手机号由服务端按当前登录用户取,页面展示的是脱敏值,不再回传。 if (!phoneRegex.test(newPhone)) { wx.showToast({ @@ -782,7 +769,6 @@ Page({ try { await runWithLoading(() => userApi.updatePhone({ - oldPhone, newPhone, verificationCode })) @@ -829,8 +815,8 @@ Page({ } try { + // 号码由服务端按当前登录用户读取,前端只传场景。 await runWithLoading(() => authApi.sendVerificationCode({ - phone, sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' })) wx.showToast({ diff --git a/JC-ArtList-WeChat/pages/shop-detail/index.js b/JC-ArtList-WeChat/pages/shop-detail/index.js index fb89de0e..ec368046 100644 --- a/JC-ArtList-WeChat/pages/shop-detail/index.js +++ b/JC-ArtList-WeChat/pages/shop-detail/index.js @@ -180,8 +180,8 @@ Page({ }, /** - * Purpose: handleContactManager retrieves and shows the current shop manager contact. - * Usage: bind it to the contact button and require login before exposing phone data. + * Purpose: handleContactManager 点击后才单次取号并拨号,页面不再保存或展示号码。 + * Usage: 绑定到联系按钮,要求登录后由服务端按场景鉴权。 */ async handleContactManager() { const shopInfo = this.data.shopInfo @@ -191,20 +191,9 @@ Page({ try { const contact = await userApi.getShopManagerContact(shopInfo.id) this.setData({ managerContact: contact }) - if (contact && contact.phoneAvailable && contact.phone) { - wx.showModal({ - title: contact.contactName || '店长联系方式', - content: `${contact.roleLabel || '店长'}:${contact.phone}`, - confirmText: '拨打', - cancelText: '复制', - success: res => { - if (res.confirm) { - wx.makePhoneCall({ phoneNumber: contact.phone }) - } else { - wx.setClipboardData({ data: contact.phone }) - } - } - }) + if (contact && contact.phoneAvailable) { + const dial = await userApi.dialContact('SHOP_MANAGER', shopInfo.id) + wx.makePhoneCall({ phoneNumber: dial.dialNumber }) return } wx.showToast({ diff --git a/JC-ArtList-WeChat/pages/shop-detail/index.wxml b/JC-ArtList-WeChat/pages/shop-detail/index.wxml index 3f740ca1..d72805f2 100644 --- a/JC-ArtList-WeChat/pages/shop-detail/index.wxml +++ b/JC-ArtList-WeChat/pages/shop-detail/index.wxml @@ -67,7 +67,7 @@ 联系店长 - {{managerContact.contactName || '店长'}} · {{managerContact.phoneAvailable ? managerContact.phone : (managerContact.platformContactText || '暂无电话')}} + {{managerContact.contactName || '店长'}} · {{managerContact.phoneAvailable ? '点击“联系店长”获取当次号码' : (managerContact.platformContactText || '暂无电话')}} diff --git a/JC-ArtList-WeChat/utils/navigation.js b/JC-ArtList-WeChat/utils/navigation.js index 46ca891c..8b823d0e 100644 --- a/JC-ArtList-WeChat/utils/navigation.js +++ b/JC-ArtList-WeChat/utils/navigation.js @@ -113,14 +113,6 @@ function normalizeActionPath(value) { return `/pages/help/index${query}` } - if (pathOnly === '/artist-orders') { - return `/pages/artist-orders/index${query}` - } - - if (pathOnly === '/artist-calendar') { - return `/pages/artist-calendar/index${query}` - } - if (pathOnly === '/settings/account') { return `/pages/account-settings/index${query}` } diff --git a/JC-Salon-Core/pom.xml b/JC-Salon-Core/pom.xml index 5e00698b..1e6901cd 100644 --- a/JC-Salon-Core/pom.xml +++ b/JC-Salon-Core/pom.xml @@ -110,6 +110,15 @@ mysql-connector-j runtime + + + org.flywaydb + flyway-core + + + org.flywaydb + flyway-mysql + com.baomidou mybatis-plus-boot-starter diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java index 47955e0f..fd9885f8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java @@ -79,6 +79,15 @@ public class PermissionAspect { return Result.error(404, "用户不存在"); } + // Salon 后台只有平台管理员,登录后台后的数据范围统一为全平台。 + // 权限表继续保留给小程序和兼容接口使用,但不再阻断管理员后台请求。 + String requestPath = request.getRequestURI(); + boolean adminPath = requestPath != null + && (requestPath.startsWith("/admin/") || requestPath.startsWith("/order/admin/")); + if (adminPath && Integer.valueOf(4).equals(userDO.getType())) { + return joinPoint.proceed(); + } + String permissionCode = requirePermission.value(); Long currentShopId = parseShopId(request.getAttribute("currentShopId")); if (Integer.valueOf(4).equals(userDO.getType()) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptor.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptor.java new file mode 100644 index 00000000..a09bab7f --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptor.java @@ -0,0 +1,97 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * 协议同意校验拦截器:在身份解析之后、业务方法之前阻断未同意当前协议版本的已登录用户。 + * 未登录请求不在此校验;判定组件故障时放行并告警,避免协议缓存/数据库异常导致全站不可用。 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class AgreementAcceptanceInterceptor implements HandlerInterceptor { + + public static final int AGREEMENT_VERSION_REQUIRED_CODE = 4510; + + public static final String AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE = "AGREEMENT_VERSION_REQUIRED"; + + private final AgreementVersionCacheService agreementVersionCacheService; + + private final ObjectMapper objectMapper; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + // 后台管理端不参与协议版本校验:平台管理人员登录后台即视为已知悉协议,不产生同意记录、不弹更新提示。 + if (isAdminRequestPath(request.getRequestURI())) { + return true; + } + Object userIdAttribute = request.getAttribute("userId"); + if (!(userIdAttribute instanceof Number)) { + return true; + } + Long userId = ((Number) userIdAttribute).longValue(); + try { + Map currentVersions = agreementVersionCacheService.currentVersions(); + Map acceptedVersions = agreementVersionCacheService.acceptedVersions(userId); + List pendingTypes = new ArrayList<>(); + for (Map.Entry entry : currentVersions.entrySet()) { + if (!Objects.equals(entry.getValue(), acceptedVersions.get(entry.getKey()))) { + pendingTypes.add(entry.getKey()); + } + } + if (pendingTypes.isEmpty()) { + return true; + } + writeAgreementRequired(response, currentVersions, pendingTypes); + return false; + } catch (Exception exception) { + // 可用性优先:协议校验只是附加门禁,Redis/DB 故障时放行主业务,记录告警供监控排查。 + log.warn("协议同意校验失败,已放行请求 path={} userId={}", request.getRequestURI(), userId, exception); + return true; + } + } + + /** + * 判断请求是否属于后台管理端。 + * 网关会把 {@code /api/admin/**} 与 {@code /admin/api/**} 统一改写为 {@code /admin/**} 转发到 Core; + * 另有部分管理端接口以业务前缀 + {@code /admin/**} 暴露(如 {@code /order/admin/**})。 + * 因此只要路径包含 {@code /admin/} 段即视为管理端请求,直接放行。 + */ + private boolean isAdminRequestPath(String path) { + return path != null && path.contains("/admin/"); + } + + private void writeAgreementRequired(HttpServletResponse response, + Map currentVersions, + List pendingTypes) throws Exception { + String versionText = currentVersions.values().stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.joining("/")); + String message = "用户协议与隐私政策已更新(当前版本 " + versionText + "),请阅读并同意后继续使用"; + Map data = new LinkedHashMap<>(); + data.put("businessCode", AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE); + data.put("currentVersions", currentVersions); + data.put("pendingTypes", pendingTypes); + Result> result = new Result<>(AGREEMENT_VERSION_REQUIRED_CODE, message, data); + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType("application/json;charset=UTF-8"); + response.setHeader("Cache-Control", "no-store"); + response.getWriter().write(objectMapper.writeValueAsString(result)); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java index a5c15828..4fb2635a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java @@ -117,10 +117,13 @@ public class AuthInterceptor implements HandlerInterceptor { } boolean adminPath = isAdminPath(path); - if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限"); + if (adminPath && !Integer.valueOf(4).equals(currentUser.getType())) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "仅平台管理员可以访问后台管理系统"); return false; } + if (adminPath && Integer.valueOf(4).equals(currentUser.getType())) { + currentShopId = null; + } boolean canAccessShop = userShopBindingSupport.canUserAccessShop( userId, @@ -139,14 +142,6 @@ public class AuthInterceptor implements HandlerInterceptor { return false; } - if (adminPath - && !Integer.valueOf(4).equals(currentUser.getType()) - && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) - && !isExpiredAdminAllowedPath(path)) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员"); - return false; - } - if (requiresSignature(request)) { try { requestSignatureService.validateRequest(request, token, userId); @@ -205,19 +200,6 @@ public class AuthInterceptor implements HandlerInterceptor { return path.startsWith("/admin/") || path.startsWith("/order/admin/"); } - /** - * Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isExpiredAdminAllowedPath(String path) { - return path.startsWith("/admin/auth/") - || path.equals("/admin/user/info") - || path.equals("/permission/list/user/current") - || path.equals("/api/permission/list/user/current") - || path.startsWith("/admin/planning/") - || path.startsWith("/admin/shops/"); - } - /** * Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java index 27018ef0..20d49713 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java @@ -4,6 +4,8 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; +import javax.annotation.PostConstruct; + /** * JWT 配置。 */ @@ -15,7 +17,7 @@ public class JwtProperties { /** * HS512 密钥,生产环境请通过 Nacos 覆盖。 */ - private String secret = "jayucloud-salon-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + private String secret; /** * Token 发行者。 @@ -41,4 +43,11 @@ public class JwtProperties { * 时钟偏移容忍,单位秒。 */ private long clockSkewSeconds = 30; + + @PostConstruct + public void validate() { + if (secret == null || secret.trim().length() < 64) { + throw new IllegalStateException("jayucloud-salon.security.jwt.secret 未配置或长度不足 64 位"); + } + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java index 28153d12..ab15be83 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java @@ -21,6 +21,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @MapperScan({ "com.xiaowang.jayucloud.salon.core.modules.artist.mapper", + "com.xiaowang.jayucloud.salon.core.modules.analytics.mapper", "com.xiaowang.jayucloud.salon.core.modules.auth.mapper", "com.xiaowang.jayucloud.salon.core.modules.content.mapper", "com.xiaowang.jayucloud.salon.core.modules.file.mapper", @@ -32,6 +33,7 @@ import org.springframework.context.annotation.Configuration; "com.xiaowang.jayucloud.salon.core.modules.payment.mapper", "com.xiaowang.jayucloud.salon.core.modules.planning.mapper", "com.xiaowang.jayucloud.salon.core.modules.product.mapper", + "com.xiaowang.jayucloud.salon.core.modules.privacy.mapper", "com.xiaowang.jayucloud.salon.core.modules.registration.mapper", "com.xiaowang.jayucloud.salon.core.modules.security.mapper", "com.xiaowang.jayucloud.salon.core.modules.shop.mapper", diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java index 9db357b0..b3d2a5d8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java @@ -1,9 +1,11 @@ package com.xiaowang.jayucloud.salon.core.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; import java.time.LocalDateTime; @@ -27,6 +29,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler { log.info("start insert fill ...."); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + fillPhoneIndexes(metaObject); } @Override @@ -37,5 +40,36 @@ public class MyMetaObjectHandler implements MetaObjectHandler { public void updateFill(MetaObject metaObject) { log.info("start update fill ...."); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + fillPhoneIndexes(metaObject); + } + + /** + * Populate searchable HMAC indexes for encrypted phone fields while keeping + * this class as the single MyBatis-Plus MetaObjectHandler bean. + */ + private void fillPhoneIndexes(MetaObject metaObject) { + setAccountIndex(metaObject); + setIndex(metaObject, "phone", "phoneHash"); + setIndex(metaObject, "contactPhone", "contactPhoneHash"); + setIndex(metaObject, "customerPhoneSnapshot", "customerPhoneSnapshotHash"); + } + + private void setAccountIndex(MetaObject metaObject) { + if (!metaObject.hasGetter("account") || !metaObject.hasSetter("accountHash")) { + return; + } + Object value = metaObject.getValue("account"); + String account = value == null ? null : String.valueOf(value); + metaObject.setValue("accountHash", account == null ? null : PhoneCrypto.current().index(account)); + } + + private void setIndex(MetaObject metaObject, String source, String target) { + if (!metaObject.hasGetter(source) || !metaObject.hasSetter(target)) { + return; + } + Object value = metaObject.getValue(source); + String text = value == null ? null : String.valueOf(value).trim(); + String hash = !StringUtils.hasText(text) ? null : PhoneCrypto.current().index(text); + metaObject.setValue(target, hash); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/PhoneCryptoProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/PhoneCryptoProperties.java new file mode 100644 index 00000000..3ed1ee75 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/PhoneCryptoProperties.java @@ -0,0 +1,15 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-salon.privacy.phone-crypto") +public class PhoneCryptoProperties { + private String encryptionKey; + private String indexKey; + private boolean backfillEnabled; + private int backfillPageSize = 500; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java index 2784dc7c..30ce8c5f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java @@ -28,6 +28,8 @@ public class RateLimitProperties { private LimitRule orderCreate = new LimitRule(10, 60); + private LimitRule customerDial = new LimitRule(10, 60); + @Data /** * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java new file mode 100644 index 00000000..757f6b77 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +/** + * 部署环境标识。 + * 用于微信内容审核回调的跨环境路由,必须由各环境 Nacos 显式配置,缺失时启动失败。 + */ +@Data +@Component +@Validated +@ConfigurationProperties(prefix = "jayucloud-salon.deploy") +public class SalonDeployProperties { + + @NotBlank + @Pattern(regexp = "dev|sit|prod", message = "部署环境标识必须是 dev、sit 或 prod") + private String env; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java index 174cf00c..0daf8535 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java @@ -13,6 +13,86 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; */ public class WebMvcConfig implements WebMvcConfigurer { + private static final String[] AUTH_FREE_PATHS = { + "/user/login", + "/user/register", + "/user/check/**", + "/user/refresh-token", + "/user/send-verification-code", + "/user/phone-login", + "/user/wechat-mini/auto-login", + "/user/wechat-mini/phone-login", + "/user/wechat-mini/confirm-login", + "/user/wechat-mini/status", + "/user/wechat-mini/quick-login", + "/integration/wechat/content-moderation/callback", + "/user/workbench/register/**", + "/user/workbench/shops/available", + "/user/reset-password-by-phone", + "/legal-agreement/current", + "/legal-agreement/current/**", + "/legal-agreement/pending", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", + "/api/legal-agreement/pending", + "/product/get/**", + "/product/list/**", + "/comment/list/product/**", + "/api/comment/list/product/**", + "/nail-artist/profile/**", + "/nail-artist/*/availability", + "/nail-artist/*/reviews", + "/shop/get/**", + "/shop/trust-profile/**", + "/shop/list", + "/shop/list/public", + "/shop/list/simple", + "/tag/list/all", + "/tag/list/filter-options", + "/file/get-signed-url/**", + "/admin/auth/login", + "/admin/auth/refresh", + "/error", + "/health/**" + }; + + /** + * 协议同意门禁额外放行:同意接口、协议阅读页、账号认证类操作、外部回调与健康检查。 + * 这些路径不校验协议版本,避免版本发布后把已登录用户或外部回调锁在门外。 + */ + private static final String[] AGREEMENT_EXTRA_FREE_PATHS = { + "/legal-agreement/accept", + "/api/legal-agreement/accept", + "/legal-agreement/admin/**", + "/api/legal-agreement/admin/**", + "/user/logout", + "/user/info", + "/user/agreement-consent/**", + "/user/switch-shop", + "/user/relation/me", + "/user/invite-code/resolve", + "/user/bind-phone", + "/user/unbind-phone", + "/user/unbind-phone/**", + "/user/wechat-mini/bind-phone", + "/user/bind-email", + "/user/password", + "/user/phone", + "/user/send-current-password-code", + "/user/reset-password/**", + "/user/upload-avatar/**", + "/user/upload-profile-image/**", + "/user/deactivate", + "/legal/**", + "/integration/**", + "/api/integration/**", + "/actuator/**", + "/static/**", + "/assets/**", + "/index.html", + "/favicon.ico" + }; + /** * Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -23,6 +103,10 @@ public class WebMvcConfig implements WebMvcConfigurer { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor; + /** + * Purpose: agreementAcceptanceInterceptor 在鉴权之后校验协议同意状态。 + */ + private final AgreementAcceptanceInterceptor agreementAcceptanceInterceptor; @Override /** @@ -37,45 +121,12 @@ public class WebMvcConfig implements WebMvcConfigurer { registry.addInterceptor(authInterceptor) .addPathPatterns("/**") .order(0) - .excludePathPatterns( - "/user/login", - "/user/register", - "/user/check/**", - "/user/refresh-token", - "/user/send-verification-code", - "/user/phone-login", - "/user/wechat-mini/auto-login", - "/user/wechat-mini/phone-login", - "/user/wechat-mini/confirm-login", - "/user/wechat-mini/status", - "/user/wechat-mini/quick-login", - "/user/workbench/register/**", - "/user/workbench/shops/available", - "/user/reset-password-by-phone", - "/legal-agreement/current", - "/legal-agreement/current/**", - "/api/legal-agreement/current", - "/api/legal-agreement/current/**", - "/product/get/**", - "/product/list/**", - "/comment/list/product/**", - "/api/comment/list/product/**", - "/nail-artist/profile/**", - "/nail-artist/*/availability", - "/nail-artist/*/reviews", - "/shop/get/**", - "/shop/trust-profile/**", - "/shop/list", - "/shop/list/public", - "/shop/list/simple", - "/tag/list/all", - "/tag/list/filter-options", - "/file/get-signed-url/**", - "/admin/auth/login", - "/admin/auth/login-shops/**", - "/admin/auth/refresh", - "/error", - "/health/**" - ); + .excludePathPatterns(AUTH_FREE_PATHS); + + registry.addInterceptor(agreementAcceptanceInterceptor) + .addPathPatterns("/**") + .order(1) + .excludePathPatterns(AUTH_FREE_PATHS) + .excludePathPatterns(AGREEMENT_EXTRA_FREE_PATHS); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java index 9e69d4dc..351655d4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java @@ -37,4 +37,17 @@ public class WechatMiniProperties { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private Integer accessTokenBufferSeconds = 60; + + /** 订阅消息发送开关。 */ + private Boolean subscribeMessageEnabled = true; + /** DEV 使用 mock,SIT/PROD 使用 wechat。 */ + private String subscribeMessageProvider = "mock"; + /** 服务开始提醒提前分钟数。 */ + private Integer serviceStartReminderLeadMinutes = 30; + /** 订阅消息点击后的默认页面。 */ + private String subscribeMessagePage = "/pages/planning/index"; + /** 微信小程序消息跳转环境。 */ + private String subscribeMessageMiniprogramState = "developer"; + /** 发送失败后的最大重试次数。 */ + private Integer subscribeMessageMaxRetries = 3; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java index 1c15872b..7912bae6 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java @@ -15,6 +15,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.analytics.service.OperationsAnalyticsService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; @@ -25,16 +26,35 @@ import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.DashboardStatsVO; import com.xiaowang.jayucloud.salon.core.modules.product.vo.HotProductVO; import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.OperationsAnalyticsVO; import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.RecentActivityVO; +import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.SalonDashboardOverviewVO; +import com.xiaowang.jayucloud.salon.core.modules.analytics.mapper.SalonDashboardMapper; +import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus; +import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.AfterSaleDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistChangeRequestDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.AfterSaleMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistChangeRequestMapper; +import com.xiaowang.jayucloud.salon.core.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.salon.core.modules.inventory.entity.InventoryItemDO; +import com.xiaowang.jayucloud.salon.core.modules.inventory.mapper.InventoryItemMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; 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.LocalDate; import java.time.LocalDateTime; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -44,6 +64,7 @@ import java.util.stream.Collectors; @RestController @RequestMapping("/admin/dashboard") @RequiredArgsConstructor +@Slf4j /** * 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. @@ -90,6 +111,149 @@ public class DashboardController { */ private final AppCacheProperties appCacheProperties; private final OperationsAnalyticsService operationsAnalyticsService; + private final WorkbenchRegistrationApplicationMapper registrationMapper; + private final ContentModerationRecordMapper contentModerationRecordMapper; + private final AfterSaleMapper afterSaleMapper; + private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + private final AppointmentReservationMapper appointmentReservationMapper; + private final InventoryItemMapper inventoryItemMapper; + private final SalonDashboardMapper salonDashboardMapper; + + /** + * Salon 平台管理员专用驾驶舱。旧 stats/analytics 接口保留兼容,但首页只使用本接口。 + */ + @GetMapping("/overview") + public Result getOverview( + @RequestParam(required = false) String date, + @RequestParam(required = false, defaultValue = "7") Integer days) { + LocalDate targetDate = parseOverviewDate(date); + int rangeDays = days != null && days == 30 ? 30 : 7; + try { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard(); + String cacheKey = "cache:salon-dashboard:overview:" + targetDate + ":" + rangeDays; + return Result.success(multiLevelCacheService.getOrLoad( + cacheKey, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { }, + () -> buildSalonOverview(targetDate, rangeDays) + )); + } catch (Exception exception) { + log.warn("Salon 驾驶舱统计失败,返回空数据: date={}, days={}", targetDate, rangeDays, exception); + SalonDashboardOverviewVO empty = emptySalonOverview(targetDate, rangeDays); + empty.setDegraded(true); + empty.setDegradedMessage("部分经营数据暂时不可用,刷新后重试"); + return Result.success(empty); + } + } + + private LocalDate parseOverviewDate(String value) { + if (value == null || value.isBlank()) return LocalDate.now(); + try { + return LocalDate.parse(value); + } catch (DateTimeParseException exception) { + return LocalDate.now(); + } + } + + private SalonDashboardOverviewVO emptySalonOverview(LocalDate date, int days) { + SalonDashboardOverviewVO overview = new SalonDashboardOverviewVO(); + overview.setDate(date.toString()); + for (int index = days - 1; index >= 0; index--) { + SalonDashboardOverviewVO.TrendItem item = new SalonDashboardOverviewVO.TrendItem(); + item.setDate(date.minusDays(index).toString()); + overview.getTrend().add(item); + } + return overview; + } + + private SalonDashboardOverviewVO buildSalonOverview(LocalDate date, int days) { + SalonDashboardOverviewVO overview = emptySalonOverview(date, days); + SalonDashboardOverviewVO.Platform platform = overview.getPlatform(); + platform.setActiveShopCount(shopMapper.selectCount(new LambdaQueryWrapper() + .eq(ShopDO::getStatus, 1).eq(ShopDO::getIsDelete, 0))); + platform.setActiveManagerCount(countUsersByType(2)); + platform.setActiveStaffCount(countUsersByType(3)); + platform.setCustomerCount(countUsersByType(0)); + platform.setStyleCount(productMapper.selectCount(new LambdaQueryWrapper() + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, 1) + .eq(ProductDO::getModerationStatus, "APPROVED"))); + + LocalDate rangeStart = date.minusDays(days - 1); + List> trendRows = salonDashboardMapper.selectOrderTrend(rangeStart, date); + Map trendByDate = overview.getTrend().stream() + .collect(Collectors.toMap(SalonDashboardOverviewVO.TrendItem::getDate, item -> item, (left, right) -> left, LinkedHashMap::new)); + for (Map row : trendRows) { + String rowDate = stringValue(row, "date"); + SalonDashboardOverviewVO.TrendItem item = trendByDate.get(rowDate); + if (item == null) continue; + item.setAppointmentCount(longValue(row, "appointmentCount")); + item.setCompletedCount(longValue(row, "completedCount")); + item.setAmount(decimalValue(row, "amount")); + if (date.equals(LocalDate.parse(rowDate))) { + overview.getToday().setServiceInProgressCount(longValue(row, "serviceInProgressCount")); + overview.getToday().setPendingOrderCount(longValue(row, "pendingOrderCount")); + overview.getToday().setCompletedServiceCount(longValue(row, "completedCount")); + overview.getToday().setOrderAmount(decimalValue(row, "amount")); + overview.getToday().setAppointmentCount(longValue(row, "appointmentCount")); + } + } + List ranking = new ArrayList<>(); + for (Map row : salonDashboardMapper.selectShopRanking(rangeStart, date)) { + SalonDashboardOverviewVO.ShopRankingItem item = new SalonDashboardOverviewVO.ShopRankingItem(); + item.setShopId(numberValue(row, "shopId")); + item.setShopName(stringValue(row, "shopName")); + item.setAppointmentCount(longValue(row, "appointmentCount")); + item.setCompletedCount(longValue(row, "completedCount")); + item.setAmount(decimalValue(row, "amount")); + ranking.add(item); + } + overview.setShopRanking(ranking); + + overview.getAttention().setRegistrationReviewCount(registrationMapper.selectCount(new LambdaQueryWrapper() + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .in(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN, WorkbenchRegistrationStatus.PENDING_MANAGER))); + overview.getAttention().setContentReviewCount(contentModerationRecordMapper.selectCount(new LambdaQueryWrapper() + .in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY"))); + overview.getAttention().setAfterSaleCount(afterSaleMapper.selectCount(new LambdaQueryWrapper() + .eq(AfterSaleDO::getIsDelete, 0).eq(AfterSaleDO::getStatus, "PENDING"))); + overview.getAttention().setArtistChangeCount(orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper() + .eq(OrderArtistChangeRequestDO::getIsDelete, 0).eq(OrderArtistChangeRequestDO::getStatus, "PENDING"))); + overview.getAttention().setLowStockCount(inventoryItemMapper.selectCount(new LambdaQueryWrapper() + .eq(InventoryItemDO::getIsDelete, 0) + .apply("stock_quantity <= warning_threshold"))); + return overview; + } + + private String stringValue(Map row, String key) { + Object value = row.get(key); + return value == null ? "" : value.toString(); + } + + private long longValue(Map row, String key) { + Object value = row.get(key); + return value instanceof Number ? ((Number) value).longValue() : 0L; + } + + private Long numberValue(Map row, String key) { + Object value = row.get(key); + return value instanceof Number ? ((Number) value).longValue() : null; + } + + private BigDecimal decimalValue(Map row, String key) { + Object value = row.get(key); + if (value instanceof BigDecimal) return (BigDecimal) value; + if (value instanceof Number) return BigDecimal.valueOf(((Number) value).doubleValue()); + return BigDecimal.ZERO; + } + + private long countUsersByType(int type) { + return userMapper.selectCount(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getType, type) + .eq(UserDO::getStatus, 1)); + } @GetMapping("/stats") @RequirePermission("dashboard:view") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java new file mode 100644 index 00000000..83647b03 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java @@ -0,0 +1,42 @@ +package com.xiaowang.jayucloud.salon.core.modules.analytics.mapper; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +/** Salon 驾驶舱趋势和门店排行聚合查询。 */ +@Mapper +public interface SalonDashboardMapper { + + String BUSINESS_ORDERS = "(SELECT o.id, o.shop_id, o.status, o.order_source, " + + "CASE WHEN o.order_source = 'HISTORICAL_BACKFILL' " + + "THEN COALESCE(item.service_date, DATE(o.create_time)) " + + "ELSE COALESCE(DATE(item.appointment_time), DATE(o.create_time)) END AS business_date, " + + "item.appointment_time, COALESCE(o.actual_amount, o.total_amount, 0) AS amount " + + "FROM t_order o LEFT JOIN (SELECT order_id, MIN(appointment_time) AS appointment_time, " + + "MIN(service_date) AS service_date FROM t_order_item WHERE is_delete = 0 GROUP BY order_id) item " + + "ON item.order_id = o.id WHERE o.is_delete = 0 AND o.status <> 3)"; + + @Select("SELECT DATE_FORMAT(business_date, '%Y-%m-%d') AS date, " + + "SUM(CASE WHEN order_source <> 'HISTORICAL_BACKFILL' AND appointment_time IS NOT NULL AND status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, " + + "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS completedCount, " + + "SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS serviceInProgressCount, " + + "SUM(CASE WHEN status IN (0, 1) THEN 1 ELSE 0 END) AS pendingOrderCount, " + + "SUM(amount) AS amount FROM " + BUSINESS_ORDERS + " business_orders" + + " WHERE business_date BETWEEN #{startDate} AND #{endDate} GROUP BY business_date ORDER BY business_date") + List> selectOrderTrend(@Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + @Select("SELECT s.id AS shopId, s.shop_name AS shopName, " + + "SUM(CASE WHEN o.order_source <> 'HISTORICAL_BACKFILL' AND o.appointment_time IS NOT NULL AND o.status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, " + + "SUM(CASE WHEN o.status = 2 THEN 1 ELSE 0 END) AS completedCount, SUM(o.amount) AS amount " + + "FROM " + BUSINESS_ORDERS + " o JOIN t_shop s ON s.id = o.shop_id AND s.is_delete = 0 " + + "WHERE o.business_date BETWEEN #{startDate} AND #{endDate} " + + "GROUP BY s.id, s.shop_name ORDER BY amount DESC LIMIT 10") + List> selectShopRanking(@Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java new file mode 100644 index 00000000..ebecd94d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java @@ -0,0 +1,72 @@ +package com.xiaowang.jayucloud.salon.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * Salon 平台管理员驾驶舱数据。 + * 该 VO 只包含 Salon 经营口径,不复用 ArtList 的流量和电商指标。 + */ +@Data +public class SalonDashboardOverviewVO { + private String date; + private boolean degraded; + private String degradedMessage; + private Platform platform = new Platform(); + private Today today = new Today(); + private Attention attention = new Attention(); + private List trend = new ArrayList<>(); + private List shopRanking = new ArrayList<>(); + + @Data + public static class Platform { + private long activeShopCount; + private long activeManagerCount; + private long activeStaffCount; + private long customerCount; + private long styleCount; + } + + @Data + public static class Today { + private long appointmentCount; + private long serviceInProgressCount; + private long completedServiceCount; + private BigDecimal orderAmount = BigDecimal.ZERO; + private long pendingOrderCount; + } + + @Data + public static class Attention { + private long registrationReviewCount; + private long contentReviewCount; + private long afterSaleCount; + private long artistChangeCount; + private long lowStockCount; + + public long total() { + return registrationReviewCount + contentReviewCount + afterSaleCount + + artistChangeCount + lowStockCount; + } + } + + @Data + public static class TrendItem { + private String date; + private long appointmentCount; + private long completedCount; + private BigDecimal amount = BigDecimal.ZERO; + } + + @Data + public static class ShopRankingItem { + private Long shopId; + private String shopName; + private long appointmentCount; + private long completedCount; + private BigDecimal amount = BigDecimal.ZERO; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java index cadd683f..552d4aa3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java @@ -136,7 +136,7 @@ public class AdminNailArtistController { } } - NailArtistInfoDTO saved = nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + NailArtistInfoDTO saved = nailArtistInfoService.submitNailArtistInfo(nailArtistInfoDTO, currentUser.getId()); return Result.success(saved); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java index 7ec61a67..985cd848 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java @@ -39,7 +39,7 @@ public class NailArtistController { @GetMapping("/list/shop/{shopId}") public Result> listByShopId(@PathVariable Long shopId) { - return Result.success(nailArtistInfoService.getByShopId(shopId)); + return Result.success(nailArtistInfoService.listPublicByShopId(shopId)); } /** @@ -47,7 +47,7 @@ public class NailArtistController { */ @GetMapping("/get/{userId}") public Result getNailArtistInfo(@PathVariable Long userId) { - NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); + NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getPublicByUserId(userId); return Result.success(nailArtistInfoDTO); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/ArtistColorUpdateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/ArtistColorUpdateDTO.java new file mode 100644 index 00000000..448c68cf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/ArtistColorUpdateDTO.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.artist.dto; + +import lombok.Data; + +/** + * 美甲师专属颜色更新请求。 + */ +@Data +public class ArtistColorUpdateDTO { + /** + * 十六进制颜色值,格式 #RRGGBB;空值表示恢复默认色。 + */ + private String color; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java index ce46e421..ce20916d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java @@ -39,6 +39,9 @@ public class NailArtistInfoDTO { */ private String skills; + /** 规划页使用的专属颜色。 */ + private String color; + /** * 评分 */ @@ -79,6 +82,11 @@ public class NailArtistInfoDTO { */ private String portfolio; + /** + * 对外资料审核状态,仅用于后台展示当前发布版本状态。 + */ + private String moderationStatus; + /** * 美甲师姓名(从用户表获取) */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java index 039eadee..28f6ba48 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java @@ -37,6 +37,9 @@ public class NailArtistInfoDO extends BaseEntity { */ private String skills; + /** 规划页使用的专属颜色。 */ + private String color; + /** * 评分 */ @@ -70,6 +73,12 @@ public class NailArtistInfoDO extends BaseEntity { */ private String portfolio; + /** + * 对外资料审核状态:PENDING/APPROVED/REJECTED/RETRY。 + */ + @TableField("moderation_status") + private String moderationStatus; + /** * 逻辑删除:0-未删,1-已删 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/ArtistScheduleService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/ArtistScheduleService.java index d2c6fd55..af814ce6 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/ArtistScheduleService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/ArtistScheduleService.java @@ -21,4 +21,6 @@ public interface ArtistScheduleService { ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto); ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto); + + List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java index 4b5fc1a7..d2eed453 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java @@ -33,6 +33,11 @@ public interface NailArtistInfoService extends IService { */ List getByShopId(Long shopId); + /** + * 获取对外展示的指定门店美甲师,只返回个人资料和门店审核通过的记录。 + */ + List listPublicByShopId(Long shopId); + /** * 保存或更新美甲师信息 * @param nailArtistInfoDTO 美甲师信息DTO @@ -40,12 +45,28 @@ public interface NailArtistInfoService extends IService { */ NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO); + /** 保存运营字段,并将美甲师对外展示资料提交审核。 */ + NailArtistInfoDTO submitNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO, Long authorUserId); + + /** + * 更新美甲师在日程规划中使用的专属颜色。 + * @param userId 美甲师用户ID + * @param color 颜色值,空值表示恢复默认色 + * @return 更新后的美甲师信息 + */ + NailArtistInfoDTO updateArtistColor(Long userId, String color); + /** * 获取所有可用的美甲师信息(前台使用) * @return 美甲师信息列表 */ List getAllAvailableNailArtists(); + /** + * 获取对外展示的指定美甲师资料。 + */ + NailArtistInfoDTO getPublicByUserId(Long userId); + NailArtistProfileVO getPublicProfile(Long artistId); List getAvailability(Long artistId); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java index 9d0e764b..a1b48b39 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java @@ -112,10 +112,7 @@ public class ArtistScheduleServiceImpl implements ArtistScheduleService { 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()); + setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L))); return setting; } @@ -153,6 +150,26 @@ public class ArtistScheduleServiceImpl implements ArtistScheduleService { return toExceptionVO(normalized); } + @Override + public List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { + LocalDate begin = start == null ? LocalDate.now().withDayOfMonth(1) : start; + LocalDate finish = end == null ? begin.plusDays(30) : end; + if (finish.isBefore(begin)) { + finish = begin; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(ArtistScheduleExceptionDO::getShopId, shopId) + .eq(ArtistScheduleExceptionDO::getIsDelete, 0) + .between(ArtistScheduleExceptionDO::getWorkDate, begin, finish) + .orderByAsc(ArtistScheduleExceptionDO::getWorkDate); + if (artistId != null) { + wrapper.eq(ArtistScheduleExceptionDO::getArtistId, artistId); + } + return exceptionMapper.selectList(wrapper).stream() + .map(this::toExceptionVO) + .collect(Collectors.toList()); + } + private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) { if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) { throw new RuntimeException("排班规则信息不完整"); @@ -220,7 +237,7 @@ public class ArtistScheduleServiceImpl implements ArtistScheduleService { .last("LIMIT 1")); } - private List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { + private List listExceptionRecords(Long shopId, Long artistId, LocalDate start, LocalDate end) { return exceptionMapper.selectList(new LambdaQueryWrapper() .eq(ArtistScheduleExceptionDO::getShopId, shopId) .eq(ArtistScheduleExceptionDO::getArtistId, artistId) @@ -232,7 +249,7 @@ public class ArtistScheduleServiceImpl implements ArtistScheduleService { private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) { LocalDate start = LocalDate.now(); LocalDate end = start.plusDays(GENERATED_DAYS - 1L); - Map exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end) + Map exceptionByDate = listExceptionRecords(rule.getShopId(), rule.getArtistId(), start, end) .stream() .collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a)); LocalDate cursor = start; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java index e0aa81a4..3f69aaa8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -10,6 +10,8 @@ import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewD import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.TagMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; @@ -22,6 +24,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.common.BusinessException; import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; @@ -31,7 +34,11 @@ import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistProfileVO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistReviewVO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistWorkVO; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopSimpleVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -51,6 +58,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.LinkedHashMap; import java.util.stream.Collectors; @Service @@ -109,6 +117,15 @@ public class NailArtistInfoServiceImpl extends ServiceImpl listPublicByShopId(Long shopId) { + if (!isPublicShop(shopId)) { + return new ArrayList<>(); + } + List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (serviceUserIds.isEmpty()) { + return new ArrayList<>(); + } + List users = userMapper.selectList(new LambdaQueryWrapper() + .in(UserDO::getId, serviceUserIds) + .eq(UserDO::getType, 3) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getProfileModerationStatus, "APPROVED") + .orderByAsc(UserDO::getCreateTime) + .orderByAsc(UserDO::getId)); + List result = new ArrayList<>(); + ShopDO shop = shopMapper.selectById(shopId); + for (UserDO user : users) { + NailArtistInfoDTO dto = getByUserId(user.getId()); + if (dto == null) { + dto = buildFallbackArtistInfo(user); + } + if (!isVisibleServiceUser(dto) || !"APPROVED".equals(dto.getModerationStatus())) { + continue; + } + dto.setShopId(shopId); + dto.setShopName(shop == null ? null : shop.getShopName()); + result.add(dto); + } + enrichScheduleSummaries(result, shopId); + return result; + } + @Override /** * Save submitted data. @@ -196,16 +248,95 @@ public class NailArtistInfoServiceImpl extends ServiceImpl() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (entity == null) { + entity = new NailArtistInfoDO(); + entity.setUserId(userId); + entity.setIdentity(""); + entity.setExperience(0); + entity.setSkills(""); + entity.setPortfolio(""); + entity.setStatus(1); + entity.setParticipateProduction(1); + entity.setModerationStatus("APPROVED"); + } + entity.setColor(normalizedColor); + saveOrUpdate(entity); + return convertToDTO(entity); + } + + private String normalizeArtistColor(String color) { + if (!StringUtils.hasText(color)) { + return null; + } + String value = color.trim().toUpperCase(java.util.Locale.ROOT); + if (!value.matches("#[0-9A-F]{6}")) { + throw new BusinessException(400, "美甲师专属颜色格式不正确,应为 #RRGGBB"); + } + return value; + } + + private NailArtistInfoDTO saveNailArtistInfo(NailArtistInfoDTO dto, Long authorUserId, boolean moderatePublicProfile) { + if (dto == null || dto.getUserId() == null) { + throw new IllegalArgumentException("美甲师用户信息不能为空"); + } NailArtistInfoDO existing = getOne(new LambdaQueryWrapper() .eq(NailArtistInfoDO::getUserId, dto.getUserId()) .eq(NailArtistInfoDO::getIsDelete, 0) .last("LIMIT 1")); - if (existing != null) { - entity.setId(existing.getId()); + if (existing == null && moderatePublicProfile) { + UserDO user = userMapper.selectById(dto.getUserId()); + if (user == null || isDeleted(user.getIsDelete())) { + throw new IllegalArgumentException("美甲师信息不存在"); + } + existing = new NailArtistInfoDO(); + existing.setUserId(dto.getUserId()); + existing.setIdentity(""); + existing.setExperience(0); + existing.setSkills(""); + existing.setPortfolio(""); + existing.setStatus(1); + existing.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + existing.setModerationStatus("APPROVED"); + saveOrUpdate(existing); } + + NailArtistInfoDO entity = new NailArtistInfoDO(); + if (existing != null) { + // 后台编辑可能只提交部分资料。以已保存实体为基线,避免缺失字段被 BeanUtils 覆盖成 null。 + BeanUtils.copyProperties(existing, entity); + mergeSubmittedFields(dto, entity); + } else { + BeanUtils.copyProperties(dto, entity); + } + entity.setModerationStatus(existing == null || !StringUtils.hasText(existing.getModerationStatus()) + ? "APPROVED" : existing.getModerationStatus()); if (entity.getStatus() == null) { entity.setStatus(1); } @@ -214,12 +345,17 @@ public class NailArtistInfoServiceImpl extends ServiceImpl values = new ArrayList<>(); + if (StringUtils.hasText(profile.getIdentity())) values.add(profile.getIdentity().trim()); + if (profile.getExperience() != null) values.add(profile.getExperience() + "年从业经验"); + List tagIds = parseLongTokens(profile.getSkills()); + if (!tagIds.isEmpty()) { + tagMapper.selectBatchIds(tagIds).stream() + .filter(tag -> !isDeleted(tag.getIsDelete())) + .map(TagDO::getTagName) + .filter(StringUtils::hasText) + .forEach(values::add); + } + return String.join("\n", values); + } + + private String submitPublicProfileModeration(NailArtistInfoDO current, NailArtistInfoDO candidate, Long authorUserId) { + LinkedHashMap payload = new LinkedHashMap<>(); + payload.put("identity", candidate.getIdentity()); + payload.put("experience", candidate.getExperience()); + payload.put("skills", candidate.getSkills()); + payload.put("portfolio", candidate.getPortfolio()); + String text = buildArtistProfileModerationText(candidate); + try { + ContentModerationResultVO result = contentModerationService.assessVersion( + "NAIL_ARTIST_PROFILE", current.getId(), authorUserId, text, + objectMapper.writeValueAsString(payload), java.util.Collections.emptyList()); + return result == null || !StringUtils.hasText(result.getStatus()) ? "PENDING" : result.getStatus(); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("美甲师公开资料审核任务创建失败", exception); + } } @Override @@ -242,14 +444,25 @@ public class NailArtistInfoServiceImpl extends ServiceImpl(); } + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + if (artistInfo == null || !isPublicShop(artistInfo.getShopId())) { + return new ArrayList<>(); + } List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getShopId, artistInfo.getShopId()) .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .orderByDesc(OrderArtistReviewDO::getSubmittedAt) .orderByDesc(OrderArtistReviewDO::getId)); if (reviews == null || reviews.isEmpty()) { @@ -386,6 +605,12 @@ public class NailArtistInfoServiceImpl extends ServiceImpl productMap = loadProducts(limitedReviews.stream() .map(OrderArtistReviewDO::getProductId) .collect(Collectors.toCollection(LinkedHashSet::new))); + limitedReviews = limitedReviews.stream() + .filter(review -> { + ProductDO product = productMap.get(review.getProductId()); + return product != null && isFrontVisible(product) && "APPROVED".equals(product.getModerationStatus()); + }) + .collect(Collectors.toList()); Set imageIds = new LinkedHashSet<>(); for (OrderArtistReviewDO review : limitedReviews) { imageIds.addAll(parseLongTokens(review.getImageFileIds())); @@ -447,6 +672,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); if (!shopOptions.isEmpty()) { @@ -520,7 +746,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() + .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getShopId, artistInfo.getShopId()) + .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") + .isNotNull(OrderArtistReviewDO::getRatingScore)); + Map products = loadProducts(reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + BigDecimal averageRating = reviews.stream() + .filter(review -> products.containsKey(review.getProductId())) + .map(OrderArtistReviewDO::getRatingScore) + .filter(java.util.Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add); + long ratingCount = reviews.stream() + .filter(review -> products.containsKey(review.getProductId())) + .map(OrderArtistReviewDO::getRatingScore) + .filter(java.util.Objects::nonNull) + .count(); + if (ratingCount > 0) { + averageRating = averageRating.divide(BigDecimal.valueOf(ratingCount), 1, RoundingMode.HALF_UP); + } else { + averageRating = null; + } BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating; if (rating == null) { return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); @@ -822,7 +1093,8 @@ public class NailArtistInfoServiceImpl extends ServiceImpl register(@RequestBody PlanningManagerRegisterDTO registerDTO) { - return Result.success(userService.registerPlanningManager(registerDTO)); - } - - @GetMapping("/login-shops/{account}") - /** - * 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 account parameter `account` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getLoginShops(@PathVariable String account) { - return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account))); - } - - @PostMapping("/switch-shop") - @OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") - /** - * Run business method `switchShop`. - * 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 - * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); - } - @PostMapping("/logout") @OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) /** @@ -115,10 +83,9 @@ public class AdminAuthController { * @return Result result consumed by the caller or returned to the frontend */ public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { - LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); + LoginResponseVO loginResponseVO = userService.adminRefreshToken(refreshTokenRequestDTO.getRefreshToken()); if (loginResponseVO.getUserInfo() == null - || loginResponseVO.getUserInfo().getType() == null - || loginResponseVO.getUserInfo().getType() < 2) { + || !Integer.valueOf(4).equals(loginResponseVO.getUserInfo().getType())) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -128,4 +95,11 @@ public class AdminAuthController { } return Result.success(loginResponseVO); } + + @PostMapping("/password") + public Result changePassword(HttpServletRequest request, + @Valid @RequestBody AdminPasswordChangeRequestDTO passwordChangeRequest) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(adminAccountSecurityService.changePassword(userId, passwordChangeRequest)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java new file mode 100644 index 00000000..1b9a7ebf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.auth.dto; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Getter +@Setter +public class AdminPasswordChangeRequestDTO { + + @NotBlank(message = "当前密码不能为空") + @Size(max = 128, message = "当前密码长度不能超过 128 位") + private String currentPassword; + + @NotBlank(message = "新密码不能为空") + @Size(max = 128, message = "新密码长度不能超过 128 位") + private String newPassword; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java index e2234b69..76c65ec8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java @@ -13,7 +13,7 @@ import lombok.Data; public class UpdatePhoneRequestDTO { /** - * 原手机号 + * 兼容旧客户端的原手机号字段;服务端不使用该字段进行身份校验。 */ private String oldPhone; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java new file mode 100644 index 00000000..84ed1de5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java @@ -0,0 +1,57 @@ +package com.xiaowang.jayucloud.salon.core.modules.auth.service.admin; + +import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +@Service +@RequiredArgsConstructor +public class AdminAccountSecurityService { + + private final UserMapper userMapper; + private final UserSessionService userSessionService; + private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + + @Transactional(rollbackFor = Exception.class) + public boolean changePassword(Long userId, AdminPasswordChangeRequestDTO request) { + if (userId == null || request == null) { + throw new RuntimeException("管理员账号信息无效"); + } + + UserDO admin = userMapper.selectById(userId); + if (admin == null || Integer.valueOf(1).equals(admin.getIsDelete())) { + throw new RuntimeException("管理员账号不存在或已失效"); + } + if (!Integer.valueOf(4).equals(admin.getType())) { + throw new RuntimeException("仅平台管理员可以修改后台密码"); + } + if (!Integer.valueOf(1).equals(admin.getStatus())) { + throw new RuntimeException("管理员账号已被禁用"); + } + if (!StringUtils.hasText(request.getCurrentPassword()) + || !passwordEncoder.matches(request.getCurrentPassword(), admin.getPassword())) { + throw new RuntimeException("当前密码不正确"); + } + + String newPassword = request.getNewPassword(); + AdminDefaultPasswordSupport.validatePasswordStrength(newPassword); + if (passwordEncoder.matches(newPassword, admin.getPassword())) { + throw new RuntimeException("新密码不能与当前密码相同"); + } + + admin.setPassword(passwordEncoder.encode(newPassword)); + if (userMapper.updateById(admin) <= 0) { + throw new RuntimeException("密码保存失败,请重试"); + } + + userSessionService.revokeAllUserSessions(userId); + return true; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java index 8b78796f..ec76f1b7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.service.impl; import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; @@ -52,6 +53,10 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { */ private final MessageHubClientService messageHubClientService; + private String phoneKey(String phone) { + return PhoneCrypto.current().index(phone); + } + @Override /** * Run business method `generateVerificationCode`. @@ -94,14 +99,14 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { public void sendVerificationCode(String phone, String sceneCode) { String code = generateVerificationCode(); - String codeKey = CODE_PREFIX + phone; - String sendTimeKey = SEND_TIME_PREFIX + phone; + String codeKey = CODE_PREFIX + phoneKey(phone); + String sendTimeKey = SEND_TIME_PREFIX + phoneKey(phone); messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); - log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); + log.info("验证码已发送,手机号: {}, sceneCode: {}", PhoneCrypto.current().mask(phone), sceneCode); } @Override @@ -113,21 +118,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * @return boolean result consumed by the caller or returned to the frontend */ public boolean verifyCode(String phone, String code) { - String codeKey = CODE_PREFIX + phone; + String codeKey = CODE_PREFIX + phoneKey(phone); String storedCode = redisTemplate.opsForValue().get(codeKey); if (storedCode == null) { - log.warn("验证码不存在或已过期,手机号: {}", phone); + log.warn("验证码不存在或已过期,手机号: {}", PhoneCrypto.current().mask(phone)); return false; } if (!storedCode.equals(code)) { - log.warn("验证码错误,手机号: {}", phone); + log.warn("验证码错误,手机号: {}", PhoneCrypto.current().mask(phone)); return false; } redisTemplate.delete(codeKey); - log.info("验证码验证成功,手机号: {}", phone); + log.info("验证码验证成功,手机号: {}", PhoneCrypto.current().mask(phone)); return true; } @@ -139,7 +144,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * @return boolean result consumed by the caller or returned to the frontend */ public boolean canResend(String phone) { - String sendTimeKey = SEND_TIME_PREFIX + phone; + String sendTimeKey = SEND_TIME_PREFIX + phoneKey(phone); String sendTime = redisTemplate.opsForValue().get(sendTimeKey); return sendTime == null; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java index 1e418b46..b0533321 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java @@ -95,6 +95,9 @@ public class LoginResponseVO { * Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private Boolean shopAuthorizationExpired; + private LocalDateTime shopBusinessExpireTime; + private Boolean shopBusinessExpired; + private Integer shopBusinessRemainingDays; @JsonSerialize(contentUsing = ToStringSerializer.class) /** * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java index 8eecf13b..23bc1b4a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java @@ -71,4 +71,7 @@ public class CommentDO extends BaseEntity { */ @TableField("is_delete") private Integer isDelete; + + @TableField("moderation_status") + private String moderationStatus; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java index b22e4acd..0339d134 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java @@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.content.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; /** * 用户评论信息表 Mapper @@ -11,4 +13,12 @@ import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO; * @date 2026-02-13 */ public interface CommentMapper extends BaseMapper { + @Select("SELECT COUNT(1) FROM t_comment c " + + "LEFT JOIN t_product p ON p.id = NULLIF(c.product_id, 0) " + + "LEFT JOIN t_shop s ON s.id = COALESCE(NULLIF(c.shop_id, 0), p.shop_id) " + + "WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED' " + + "AND (NULLIF(c.product_id, 0) IS NULL OR (p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED')) " + + "AND (COALESCE(NULLIF(c.shop_id, 0), p.shop_id) IS NULL OR (s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED')) " + + "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java index 70a3cf98..7ee77356 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java @@ -14,6 +14,10 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.content.service.CommentService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.content.vo.CommentVO; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; @@ -57,6 +61,8 @@ public class CommentServiceImpl extends ServiceImpl im private final ProductMapper productMapper; private final ObjectStorageFileService objectStorageFileService; private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; @Override /** @@ -155,7 +161,9 @@ public class CommentServiceImpl extends ServiceImpl im } commentDO.setLikeCount(0); commentDO.setIsDelete(0); + commentDO.setModerationStatus("PENDING"); commentMapper.insert(commentDO); + moderateComment(commentDO, currentUserId); return commentDO.getId(); } @@ -172,9 +180,8 @@ public class CommentServiceImpl extends ServiceImpl im if (commentDO == null) { return false; } - commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); - commentDO.setUpdateTime(LocalDateTime.now()); - return commentMapper.updateById(commentDO) > 0; + moderateComment(commentDO, commentDO.getUserId(), sanitizeContent(commentDTO.getCommentContent()), commentDO.getImageFileIds()); + return true; } @Override @@ -204,7 +211,8 @@ public class CommentServiceImpl extends ServiceImpl im */ public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) { CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) + || !"APPROVED".equals(commentDO.getModerationStatus())) { return false; } if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { @@ -215,9 +223,10 @@ public class CommentServiceImpl extends ServiceImpl im */ throw new RuntimeException("只能修改自己的评论"); } - commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); - commentDO.setUpdateTime(LocalDateTime.now()); - return commentMapper.updateById(commentDO) > 0; + String nextContent = sanitizeContent(commentDTO.getCommentContent()); + String nextImages = joinImageFileIds(commentDTO.getImageFileIds()); + moderateComment(commentDO, currentUserId, nextContent, nextImages); + return true; } @Override @@ -230,7 +239,7 @@ public class CommentServiceImpl extends ServiceImpl im */ public boolean deleteComment(Long id, Long currentUserId) { CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) || !"APPROVED".equals(commentDO.getModerationStatus())) { return false; } if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { @@ -256,7 +265,8 @@ public class CommentServiceImpl extends ServiceImpl im */ public boolean adminDeleteComment(Long id, Long managedShopId) { CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) + || !"APPROVED".equals(commentDO.getModerationStatus())) { return false; } if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) { @@ -315,6 +325,8 @@ public class CommentServiceImpl extends ServiceImpl im Wrappers.lambdaQuery(CommentDO.class) .eq(CommentDO::getUserId, userId) .eq(CommentDO::getIsDelete, 0) + .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByDesc(CommentDO::getCreateTime) ); return commentDOs.stream() @@ -334,6 +346,8 @@ public class CommentServiceImpl extends ServiceImpl im Wrappers.lambdaQuery(CommentDO.class) .eq(CommentDO::getShopId, shopId) .eq(CommentDO::getIsDelete, 0) + .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByDesc(CommentDO::getCreateTime) ); return commentDOs.stream() @@ -353,6 +367,8 @@ public class CommentServiceImpl extends ServiceImpl im Wrappers.lambdaQuery(CommentDO.class) .eq(CommentDO::getProductId, productId) .eq(CommentDO::getIsDelete, 0) + .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByDesc(CommentDO::getCreateTime) ); /** @@ -376,6 +392,8 @@ public class CommentServiceImpl extends ServiceImpl im Wrappers.lambdaQuery(CommentDO.class) .eq(CommentDO::getParentCommentId, parentCommentId) .eq(CommentDO::getIsDelete, 0) + .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByAsc(CommentDO::getCreateTime) ); return commentDOs.stream() @@ -397,6 +415,7 @@ public class CommentServiceImpl extends ServiceImpl im List commentDOs = commentMapper.selectList( Wrappers.lambdaQuery(CommentDO.class) .eq(CommentDO::getIsDelete, 0) + .eq(CommentDO::getModerationStatus, "APPROVED") .eq(productId != null && productId > 0, CommentDO::getProductId, productId) .eq(userId != null && userId > 0, CommentDO::getUserId, userId) .eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId) @@ -540,8 +559,8 @@ public class CommentServiceImpl extends ServiceImpl im if (id > 0) { result.add(id); } - } catch (NumberFormatException ignored) { - // Ignore malformed legacy tokens. + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("评论图片必须引用已上传文件", exception); } } return new ArrayList<>(new LinkedHashSet<>(result)); @@ -569,7 +588,41 @@ public class CommentServiceImpl extends ServiceImpl im * @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper result consumed by the caller or returned to the frontend */ private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { - return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0); + return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0) + .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()); + } + + private String publicVisibilitySql() { + return "(t_comment.shop_id IS NULL OR t_comment.shop_id = 0 OR EXISTS " + + "(SELECT 1 FROM t_shop visible_shop WHERE visible_shop.id = t_comment.shop_id " + + "AND visible_shop.is_delete = 0 AND visible_shop.status = 1 " + + "AND visible_shop.moderation_status = 'APPROVED')) " + + "AND (t_comment.product_id IS NULL OR t_comment.product_id = 0 OR EXISTS " + + "(SELECT 1 FROM t_product visible_product " + + "JOIN t_shop product_shop ON product_shop.id = visible_product.shop_id " + + "AND product_shop.is_delete = 0 AND product_shop.status = 1 " + + "AND product_shop.moderation_status = 'APPROVED' " + + "WHERE visible_product.id = t_comment.product_id " + + "AND visible_product.is_delete = 0 AND visible_product.front_visible = 1 " + + "AND visible_product.moderation_status = 'APPROVED'))"; + } + + private void moderateComment(CommentDO comment, Long userId) { + moderateComment(comment, userId, comment.getCommentContent(), comment.getImageFileIds()); + } + + private void moderateComment(CommentDO comment, Long userId, String content, String imageFileIds) { + try { + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("commentContent", content); + payload.put("imageFileIds", imageFileIds); + List imageIds = parseImageFileIds(imageFileIds); + contentModerationService.assessVersion("COMMENT", comment.getId(), userId, content, + objectMapper.writeValueAsString(payload), imageIds); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("评论审核内容序列化失败", exception); + } } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java index d9779869..fba44294 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java @@ -22,6 +22,18 @@ public class MinioStorageConfig { private String endpoint; + /** + * Optional public endpoint used only when MinIO signs URLs for clients. + * Internal uploads, downloads and deletes continue to use endpoint. + */ + private String publicEndpoint; + + /** + * Optional MinIO region used when signing URLs. When blank, the region is resolved once + * through the internal endpoint so that signing never depends on public DNS. + */ + private String region; + private String bucketName; private String accessKey; @@ -34,14 +46,36 @@ public class MinioStorageConfig { @Bean @ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true") public MinioClient minioClient() { - if (!StringUtils.hasText(endpoint) + return buildClient(endpoint); + } + + /** + * Builds the client used to sign URLs. The region must be passed explicitly, otherwise the + * MinIO SDK queries the endpoint for the bucket region before signing. + */ + public MinioClient createSigningClient(String signingRegion) { + if (!Boolean.TRUE.equals(enabled) || !StringUtils.hasText(publicEndpoint)) { + return null; + } + return buildClient(publicEndpoint, signingRegion); + } + + private MinioClient buildClient(String clientEndpoint) { + return buildClient(clientEndpoint, null); + } + + private MinioClient buildClient(String clientEndpoint, String clientRegion) { + if (!StringUtils.hasText(clientEndpoint) || !StringUtils.hasText(accessKey) || !StringUtils.hasText(secretKey)) { throw new IllegalStateException("MinIO is enabled but endpoint/accessKey/secretKey is incomplete"); } - return MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .build(); + MinioClient.Builder builder = MinioClient.builder() + .endpoint(clientEndpoint) + .credentials(accessKey, secretKey); + if (StringUtils.hasText(clientRegion)) { + builder.region(clientRegion.trim()); + } + return builder.build(); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java index 7d9bbfc5..621a0622 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java @@ -4,6 +4,11 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.AnnouncementMapper; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; @@ -28,6 +33,11 @@ public class FrontendFileController { private final ProductMapper productMapper; private final ShopMapper shopMapper; private final EffectDiagramMapper effectDiagramMapper; + private final CommentMapper commentMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; + private final AnnouncementMapper announcementMapper; + private final SystemMessageMapper systemMessageMapper; + private final UserMapper userMapper; /** * Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public. @@ -71,7 +81,12 @@ public class FrontendFileController { } return positive(productMapper.countPublicImageReference(fileId)) || positive(shopMapper.countPublicImageReference(fileId)) - || positive(effectDiagramMapper.countPublicImageReference(fileId)); + || positive(effectDiagramMapper.countPublicImageReference(fileId)) + || positive(commentMapper.countPublicImageReference(fileId)) + || positive(orderArtistReviewMapper.countPublicImageReference(fileId)) + || positive(announcementMapper.countPublicImageReference(fileId)) + || positive(systemMessageMapper.countPublicImageReference(fileId)) + || positive(userMapper.countPublicImageReference(fileId)); } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadController.java new file mode 100644 index 00000000..535fcdde --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadController.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.controller.front; + +import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/object-storage-file") +@RequiredArgsConstructor +public class MiniProgramObjectStorageUploadController { + + private final ObjectStorageDirectUploadService objectStorageDirectUploadService; + + @PostMapping("/upload") + @OperationGuard(action = "mini-program-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result uploadFile(HttpServletRequest request, + @RequestParam("file") MultipartFile file) { + Object userTypeValue = request.getAttribute("userType"); + if (!(userTypeValue instanceof Integer) + || (!Integer.valueOf(2).equals(userTypeValue) && !Integer.valueOf(3).equals(userTypeValue))) { + return Result.error(403, "当前账号无权上传门店业务文件"); + } + try { + return Result.success(objectStorageDirectUploadService.upload(file)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("文件上传失败: " + e.getMessage()); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java index ed328e55..51d03a2f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java @@ -10,6 +10,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.dto.ObjectStorageUploadOut import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; @@ -46,6 +47,7 @@ public class ObjectStorageFileController { * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageDirectUploadService objectStorageDirectUploadService; /** * Variable `objectStorageOrchestrationService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -156,35 +158,7 @@ public class ObjectStorageFileController { @OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result uploadFile(@RequestParam("file") MultipartFile file) { try { - uploadSecurityValidator.validate(file); - String originalFilename = file.getOriginalFilename(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - - ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( - file.getInputStream(), - file.getSize(), - file.getContentType(), - objectName - ); - - ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); - dto.setFileName(originalFilename); - dto.setFileUrl(uploadOutcome.getPrimaryUrl()); - dto.setObjectName(objectName); - dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); - dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); - dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); - dto.setContentType(file.getContentType()); - dto.setFileSize(file.getSize()); - dto.setPrimaryUploadStatus(1); - dto.setBackupUploadStatus(0); - dto.setBackupRetryCount(0); - dto.setUploadAttempts(uploadOutcome.getAttempts()); - dto.setStatus(1); - - Long fileId = objectStorageFileService.createObjectStorageFile(dto); - return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); + return Result.success(objectStorageDirectUploadService.upload(file)); } catch (Exception e) { e.printStackTrace(); return Result.error("文件上传失败: " + e.getMessage()); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java new file mode 100644 index 00000000..6facdae0 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java @@ -0,0 +1,73 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.service; + +import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.jayucloud.salon.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.security.UploadSecurityValidator; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; + +@Service +@RequiredArgsConstructor +public class ObjectStorageDirectUploadService { + + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final UploadSecurityValidator uploadSecurityValidator; + private final ObjectStorageProperties objectStorageProperties; + + public ObjectStorageFileVO upload(MultipartFile file) throws Exception { + uploadSecurityValidator.validate(file); + return upload(file.getOriginalFilename(), file.getInputStream(), file.getSize(), file.getContentType(), ""); + } + + public ObjectStorageFileVO uploadUserProfileImage(MultipartFile file, Long userId) throws Exception { + uploadSecurityValidator.validate(file); + return upload(file.getOriginalFilename(), file.getInputStream(), file.getSize(), file.getContentType(), "profile/" + userId + "/"); + } + + public ObjectStorageFileVO uploadUserProfileImage(String fileName, InputStream inputStream, long fileSize, + String contentType, Long userId) throws Exception { + uploadSecurityValidator.validateMetadata(fileName, contentType, fileSize); + return upload(fileName, inputStream, fileSize, contentType, "profile/" + userId + "/"); + } + + private ObjectStorageFileVO upload(String fileName, InputStream inputStream, long fileSize, + String contentType, String objectNamePrefix) throws Exception { + String extension = ""; + if (fileName != null && fileName.lastIndexOf('.') >= 0) { + extension = fileName.substring(fileName.lastIndexOf('.')); + } + String objectName = objectNamePrefix + snowflakeIdGenerator.nextIdString() + extension; + ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( + inputStream, + fileSize, + contentType, + objectName + ); + + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(fileName); + dto.setFileUrl(uploadOutcome.getPrimaryUrl()); + dto.setObjectName(objectName); + dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); + dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); + dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); + dto.setContentType(contentType); + dto.setFileSize(fileSize); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setUploadAttempts(uploadOutcome.getAttempts()); + dto.setStatus(1); + + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + return objectStorageFileService.getObjectStorageFileById(fileId); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java index 3112446a..da393bc2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java @@ -75,4 +75,8 @@ public interface ObjectStorageFileService extends IService List listObjectStorageFilesByStatus(Integer status); void evictObjectStorageFileCache(Long id); + + Long findFileIdByReference(String reference); + + String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java index 9e1e2168..9ccdafa7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java @@ -9,25 +9,58 @@ import io.minio.MinioClient; import io.minio.PutObjectArgs; import io.minio.RemoveObjectArgs; import io.minio.http.Method; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.io.InputStream; import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @Slf4j @Service -@RequiredArgsConstructor public class MinioObjectStorageProvider implements ObjectStorageProvider { private static final long UNKNOWN_SIZE_PART_SIZE = 10 * 1024 * 1024L; + /** + * Region probe key: only used to compute a signature locally, no object is written or read. + */ + private static final String REGION_PROBE_OBJECT = "integration-probe/region-probe.txt"; + + private static final Pattern CREDENTIAL_SCOPE = Pattern.compile( + "X-Amz-Credential=[^&]*?%2F\\d{8}%2F([^%&]+)%2Fs3%2Faws4_request", Pattern.CASE_INSENSITIVE); + private final ObjectProvider minioClientProvider; + private final MinioClient signingClient; private final MinioStorageConfig minioStorageConfig; private final ObjectStorageProperties objectStorageProperties; + private volatile MinioClient resolvedSigningClient; + private volatile String resolvedSigningRegion; + + @Autowired + public MinioObjectStorageProvider( + ObjectProvider minioClientProvider, + MinioStorageConfig minioStorageConfig, + ObjectStorageProperties objectStorageProperties + ) { + this(minioClientProvider, minioStorageConfig, objectStorageProperties, null); + } + + MinioObjectStorageProvider( + ObjectProvider minioClientProvider, + MinioStorageConfig minioStorageConfig, + ObjectStorageProperties objectStorageProperties, + MinioClient signingClient + ) { + this.minioClientProvider = minioClientProvider; + this.minioStorageConfig = minioStorageConfig; + this.objectStorageProperties = objectStorageProperties; + this.signingClient = signingClient; + } @Override public String providerCode() { @@ -86,7 +119,7 @@ public class MinioObjectStorageProvider implements ObjectStorageProvider { if (!Boolean.TRUE.equals(minioStorageConfig.getPrivateBucket())) { return getFileUrl(objectName); } - return requireClient().getPresignedObjectUrl( + return signingClientForPresign().getPresignedObjectUrl( GetPresignedObjectUrlArgs.builder() .method(Method.GET) .bucket(minioStorageConfig.getBucketName()) @@ -96,6 +129,55 @@ public class MinioObjectStorageProvider implements ObjectStorageProvider { ); } + private MinioClient signingClientForPresign() throws Exception { + if (signingClient != null) { + return signingClient; + } + MinioClient cached = resolvedSigningClient; + if (cached != null) { + return cached; + } + synchronized (this) { + if (resolvedSigningClient == null) { + MinioClient client = StringUtils.hasText(minioStorageConfig.getPublicEndpoint()) + ? minioStorageConfig.createSigningClient(resolveSigningRegion()) + : null; + resolvedSigningClient = client == null ? requireClient() : client; + } + return resolvedSigningClient; + } + } + + /** + * Resolves the bucket region through the internal endpoint, so that signing does not depend on + * the public endpoint being resolvable from this host. + */ + private String resolveSigningRegion() throws Exception { + String configured = minioStorageConfig.getRegion(); + if (StringUtils.hasText(configured)) { + return configured.trim(); + } + if (resolvedSigningRegion != null) { + return resolvedSigningRegion; + } + String probeUrl = requireClient().getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder() + .method(Method.GET) + .bucket(minioStorageConfig.getBucketName()) + .object(REGION_PROBE_OBJECT) + .expiry(1, TimeUnit.MINUTES) + .build() + ); + Matcher matcher = CREDENTIAL_SCOPE.matcher(probeUrl == null ? "" : probeUrl); + if (!matcher.find()) { + throw new IllegalStateException( + "MinIO region cannot be resolved from internal endpoint, please configure minio.region"); + } + resolvedSigningRegion = matcher.group(1); + log.info("MinIO signing region resolved through internal endpoint, region={}", resolvedSigningRegion); + return resolvedSigningRegion; + } + private MinioClient requireClient() { MinioClient minioClient = minioClientProvider.getIfAvailable(); if (minioClient == null) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java index 33243a25..e1e845c3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -11,6 +11,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.mapper.ObjectStorageFileMa import com.xiaowang.jayucloud.salon.core.modules.file.mq.ObjectStorageBackupMessagePublisher; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; @@ -59,6 +60,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl query.eq(ObjectStorageFileDO::getFileUrl, reference) + .or().eq(ObjectStorageFileDO::getPrimaryUrl, reference) + .or().eq(StringUtils.hasText(objectName), ObjectStorageFileDO::getObjectName, objectName)) + .last("LIMIT 1")); + return file == null ? null : file.getId(); + } + + @Override + public String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes) { + ObjectStorageFileVO file = getObjectStorageFileById(fileId); + if (file == null || !Integer.valueOf(1).equals(file.getStatus())) { + throw new IllegalStateException("审核图片不存在或不可用"); + } + String url = objectStorageUrlSupport.getSignedUrlOrThrow(file, expiryMinutes); + if (!StringUtils.hasText(url) || !url.startsWith("https://")) { + throw new IllegalStateException("审核图片必须通过 HTTPS 访问"); + } + return url; + } + /** * 将 DO 转换为 VO * diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java index c02c7455..ad7f4f8b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java @@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageReplic import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -23,6 +24,9 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; import java.util.stream.Collectors; @Slf4j @@ -35,6 +39,12 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche private final List providers; private final ObjectStorageProperties objectStorageProperties; private final ObjectStorageReplicaService objectStorageReplicaService; + private final SystemParameterConfigService systemParameterConfigService; + private volatile ProviderOrderCache providerOrderCache; + private static final long PROVIDER_ORDER_CACHE_MILLIS = 30_000L; + private static final String PROVIDER_ORDER_GROUP = "FILE"; + private static final String PROVIDER_ORDER_KEY = "IMAGE_READ_PROVIDER_ORDER"; + private static final Set SUPPORTED_PROVIDERS = Set.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"); @Override public ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { @@ -110,7 +120,7 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche Map replicaMap = replicas.stream() .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); Exception lastFailure = null; - for (String providerCode : objectStorageProperties.getProviderOrder()) { + for (String providerCode : readProviderOrder()) { ObjectStorageReplicaDO replica = replicaMap.get(providerCode); if (replica == null || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { @@ -129,7 +139,7 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche @Override public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { Exception lastFailure = null; - for (String providerCode : objectStorageProperties.getProviderOrder()) { + for (String providerCode : readProviderOrder()) { try { ObjectStorageProvider provider = requireProvider(providerCode); ensureEnabled(provider); @@ -142,6 +152,52 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche throw new IllegalStateException("No available object storage signed URL for objectName=" + objectName, lastFailure); } + private List readProviderOrder() { + long now = System.currentTimeMillis(); + ProviderOrderCache cache = providerOrderCache; + if (cache != null && now < cache.expiresAt) return cache.providers; + synchronized (this) { + cache = providerOrderCache; + now = System.currentTimeMillis(); + if (cache != null && now < cache.expiresAt) return cache.providers; + List providers; + try { + providers = parseProviderOrder(systemParameterConfigService.getEnabledValue(PROVIDER_ORDER_GROUP, PROVIDER_ORDER_KEY)); + } catch (RuntimeException exception) { + log.warn("读取对象存储签名访问顺序失败,回退到当前环境默认配置", exception); + providers = Collections.emptyList(); + } + if (providers.isEmpty()) providers = validateFallbackOrder(objectStorageProperties.getProviderOrder()); + providerOrderCache = new ProviderOrderCache(providers, now + PROVIDER_ORDER_CACHE_MILLIS); + return providers; + } + } + + private List parseProviderOrder(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + return validateFallbackOrder(Arrays.asList(value.split(","))); + } + + private List validateFallbackOrder(List configured) { + if (configured == null) return Collections.emptyList(); + List providers = configured.stream().filter(StringUtils::hasText) + .map(value -> value.trim().toUpperCase(java.util.Locale.ROOT)).collect(Collectors.toList()); + if (providers.size() != SUPPORTED_PROVIDERS.size() || !SUPPORTED_PROVIDERS.equals(new java.util.HashSet<>(providers))) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(providers); + } + + private static final class ProviderOrderCache { + private final List providers; + private final long expiresAt; + + private ProviderOrderCache(List providers, long expiresAt) { + this.providers = providers; + this.expiresAt = expiresAt; + } + } + private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map replicaMap) { ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); replicaDTO.setProvider(providerCode); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java index 4ca6e791..3691eeb2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java @@ -1,6 +1,8 @@ package com.xiaowang.jayucloud.salon.core.modules.file.support; import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.config.AliyunOssConfig; +import com.xiaowang.jayucloud.salon.core.modules.file.config.MinioStorageConfig; import com.xiaowang.jayucloud.salon.core.modules.file.config.QiniuKodoConfig; import com.xiaowang.jayucloud.salon.core.modules.file.service.AliyunOssService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService; @@ -21,6 +23,8 @@ public class ObjectStorageUrlSupport { private static final int UPLOAD_STATUS_SUCCEEDED = 1; private final PrimaryObjectStorageService primaryObjectStorageService; + private final MinioStorageConfig minioStorageConfig; + private final AliyunOssConfig aliyunOssConfig; private final QiniuKodoConfig qiniuKodoConfig; private final AliyunOssService aliyunOssService; private final ObjectStorageProperties objectStorageProperties; @@ -32,7 +36,7 @@ public class ObjectStorageUrlSupport { } String objectName = extractObjectName(fileUrl); if (!StringUtils.hasText(objectName)) { - return fileUrl; + return isKnownStorageUrl(fileUrl) ? null : fileUrl; } try { return objectStorageOrchestrationService.getPresignedUrl( @@ -116,6 +120,9 @@ public class ObjectStorageUrlSupport { } String normalizedUrl = fileUrl.trim(); + if (normalizedUrl.startsWith("oss://")) { + return extractBucketObjectName(normalizedUrl.substring("oss://".length()), aliyunOssConfig.getBucketName()); + } if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) { return stripQuery(stripLeadingSlash(normalizedUrl)); } @@ -123,10 +130,17 @@ public class ObjectStorageUrlSupport { try { URI fileUri = URI.create(normalizedUrl); URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain())); - if (!sameAuthority(fileUri, domainUri)) { - return ""; + if (sameAuthority(fileUri, domainUri)) { + return stripQuery(stripLeadingSlash(fileUri.getPath())); } - return stripQuery(stripLeadingSlash(fileUri.getPath())); + if (sameConfiguredAuthority(fileUri, minioStorageConfig.getEndpoint()) + || sameConfiguredAuthority(fileUri, minioStorageConfig.getPublicEndpoint())) { + return extractBucketObjectName(fileUri.getPath(), minioStorageConfig.getBucketName()); + } + if (sameConfiguredAuthority(fileUri, aliyunOssConfig.getEndpoint())) { + return extractBucketObjectName(fileUri.getPath(), aliyunOssConfig.getBucketName()); + } + return ""; } catch (Exception e) { log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e); return ""; @@ -163,6 +177,9 @@ public class ObjectStorageUrlSupport { } private String normalizeDomain(String domain) { + if (!StringUtils.hasText(domain)) { + return ""; + } String normalized = domain.trim(); while (normalized.endsWith("/")) { normalized = normalized.substring(0, normalized.length() - 1); @@ -174,13 +191,55 @@ public class ObjectStorageUrlSupport { } private boolean sameAuthority(URI left, URI right) { - return left.getScheme() != null - && left.getScheme().equalsIgnoreCase(right.getScheme()) + return right != null && left.getHost() != null + && right.getHost() != null && left.getHost().equalsIgnoreCase(right.getHost()) && normalizedPort(left) == normalizedPort(right); } + private boolean sameConfiguredAuthority(URI fileUri, String endpoint) { + if (!StringUtils.hasText(endpoint)) { + return false; + } + try { + return sameAuthority(fileUri, URI.create(normalizeDomain(endpoint))); + } catch (Exception ignored) { + return false; + } + } + + private String extractBucketObjectName(String rawPath, String bucketName) { + String path = stripQuery(stripLeadingSlash(rawPath)); + if (!StringUtils.hasText(path) || !StringUtils.hasText(bucketName)) { + return ""; + } + String bucketPrefix = bucketName.trim() + "/"; + return path.startsWith(bucketPrefix) ? path.substring(bucketPrefix.length()) : path; + } + + private boolean isKnownStorageUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return false; + } + String normalized = fileUrl.trim(); + if (normalized.startsWith("oss://")) { + return true; + } + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + return false; + } + try { + URI uri = URI.create(normalized); + return sameConfiguredAuthority(uri, qiniuKodoConfig.getDomain()) + || sameConfiguredAuthority(uri, minioStorageConfig.getEndpoint()) + || sameConfiguredAuthority(uri, minioStorageConfig.getPublicEndpoint()) + || sameConfiguredAuthority(uri, aliyunOssConfig.getEndpoint()); + } catch (Exception ignored) { + return false; + } + } + private int normalizedPort(URI uri) { if (uri.getPort() >= 0) { return uri.getPort(); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java index 13c12e77..1d85f25c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java @@ -1,14 +1,17 @@ package com.xiaowang.jayucloud.salon.core.modules.integration.dto; +import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest; + import lombok.Data; import javax.validation.constraints.NotBlank; +import java.util.Map; /** * 微信小程序自动登录请求。 */ @Data -public class WechatMiniAutoLoginRequestDTO { +public class WechatMiniAutoLoginRequestDTO implements AgreementAwareRequest { @NotBlank(message = "微信登录凭证不能为空") /** @@ -20,4 +23,8 @@ public class WechatMiniAutoLoginRequestDTO { * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private Long preferredShopId; + + private Boolean agreementAccepted; + private Map agreementVersions; + private String clientType; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/entity/WechatSubscribeMessageLogDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/entity/WechatSubscribeMessageLogDO.java new file mode 100644 index 00000000..89c569c2 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/entity/WechatSubscribeMessageLogDO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +/** 微信订阅消息发送记录。 */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_wechat_subscribe_message_log") +public class WechatSubscribeMessageLogDO extends BaseEntity { + private String eventKey; + private String templateCode; + private Long userId; + private Long orderId; + private Long orderItemId; + private String openIdHash; + private String status; + private Integer retryCount; + private Integer errCode; + private String errMsg; + private LocalDateTime nextRetryTime; + private LocalDateTime sentTime; + private Integer isDelete; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/mapper/WechatSubscribeMessageLogMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/mapper/WechatSubscribeMessageLogMapper.java new file mode 100644 index 00000000..81cca550 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/mapper/WechatSubscribeMessageLogMapper.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDateTime; +import java.util.List; + +@Mapper +public interface WechatSubscribeMessageLogMapper extends BaseMapper { + @Select("SELECT * FROM t_wechat_subscribe_message_log WHERE is_delete = 0 AND ((status IN ('PENDING','RETRY') AND (next_retry_time IS NULL OR next_retry_time <= #{now})) OR (status = 'PROCESSING' AND update_time < DATE_SUB(#{now}, INTERVAL 10 MINUTE))) ORDER BY id ASC LIMIT #{limit}") + List selectDue(@Param("now") LocalDateTime now, @Param("limit") int limit); + + @Update("UPDATE t_wechat_subscribe_message_log SET status = 'PROCESSING', update_time = NOW() WHERE id = #{id} AND is_delete = 0 AND (status IN ('PENDING','RETRY') OR (status = 'PROCESSING' AND update_time < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))") + int claimForProcessing(@Param("id") Long id); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java index 9044cc7a..9bbf4fe8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java @@ -21,6 +21,14 @@ public interface WechatMiniAuthService { WechatMiniRegistrationTicket consumeRegistrationTicket(String ticket); + WechatMiniRegistrationTicket validateRegistrationTicket(String ticket); + + void transferRegistrationBinding(Long sourceUserId, Long targetUserId); + + void rememberRegistrationAvatarUpload(String ticket, Long fileId); + + void validateRegistrationAvatarUpload(String ticket, Long fileId); + /** * Run business method `autoLogin`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java index ba9e7435..b9ce7b89 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java @@ -1,5 +1,6 @@ package com.xiaowang.jayucloud.salon.core.modules.integration.service; +import java.util.Map; /** * 微信小程序开放接口客户端。 @@ -29,6 +30,15 @@ public interface WechatMiniClientService { */ String getConfiguredAppId(); + String getAccessTokenForContentModeration(); + + /** 发送微信小程序订阅消息。 */ + SubscribeMessageResult sendSubscribeMessage(String openId, String templateId, Map data, + String page, String miniprogramState); + + record SubscribeMessageResult(boolean success, int errCode, String errMsg) { + } + /** * Run business method `SessionInfo`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatSubscribeMessageService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatSubscribeMessageService.java new file mode 100644 index 00000000..29e777fe --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatSubscribeMessageService.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.integration.service; + +import java.time.LocalDateTime; + +/** Salon 微信订阅消息业务服务。 */ +public interface WechatSubscribeMessageService { + String TEMPLATE_SERVICE_START = "jURyVPL52qyUhm_c_OyvED5zivUZr_3LfAXjfV-KOJc"; + String TEMPLATE_CANCELLED = "0v80O2xaOS8D_aSrurqTo4fds8FmyMlEOsy66LXsjNQ"; + String TEMPLATE_APPOINTMENT = "Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo"; + + void enqueueAppointmentReminder(Long orderId, Long orderItemId); + + void enqueueCancellationNotice(Long orderId, Long orderItemId); + + void enqueueServiceStartReminder(Long orderId, Long orderItemId, LocalDateTime appointmentTime); + + void processDueMessages(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 03c42c24..d490a8dc 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.xiaowang.jayucloud.salon.core.config.BrandProperties; import com.xiaowang.jayucloud.salon.core.modules.integration.entity.MessageHubPushConfigDO; import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -138,7 +139,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { message.getMessageProperties().setHeader("X-MessageHub-Access-Token", requireAccessToken()); rabbitTemplate.send(ingressExchange, ingressRoutingKey, message); log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, exchange: {}, sourceSystem: {}, templateCode: {}", - sceneCode, phone, ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode")); + sceneCode, PhoneCrypto.current().mask(phone), ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode")); } catch (Exception exception) { log.error("发送短信验证码失败", exception); throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java index 7bf5ee0a..bd04c5be 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRe import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; @@ -61,6 +62,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { */ private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:"; private static final String REGISTRATION_TICKET_KEY_PREFIX = "user:wechat-mini:registration-ticket:"; + private static final String REGISTRATION_AVATAR_KEY_PREFIX = "user:wechat-mini:registration-avatar:"; private static final Duration TICKET_TTL = Duration.ofMinutes(5); /** * Variable `wechatMiniClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. @@ -112,9 +114,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } WorkbenchRegistrationApplicationDO application = findLatestApplication(user.getId()); if (application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus())) { - return applicationState(WechatMiniLoginResultVO.STATUS_REJECTED, "申请已被驳回,可修改后重新提交", application); + WechatMiniLoginResultVO result = registrationResult(user.getId(), sessionInfo.openId(), application); + result.setStatus(WechatMiniLoginResultVO.STATUS_REJECTED); + return result; } if (application != null && (WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()) + || WorkbenchRegistrationStatus.PENDING_CONTENT.equals(application.getStatus()) || WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) { return applicationState(WechatMiniLoginResultVO.STATUS_PENDING_REVIEW, "申请审核中", application); } @@ -154,9 +159,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } WorkbenchRegistrationApplicationDO application = findLatestApplication(user.getId()); if (application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus())) { - return registrationResult(user.getId(), sessionInfo.openId(), application); + WechatMiniLoginResultVO result = registrationResult(user.getId(), sessionInfo.openId(), application); + result.setStatus(WechatMiniLoginResultVO.STATUS_REJECTED); + return result; } if (application != null && (WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()) + || WorkbenchRegistrationStatus.PENDING_CONTENT.equals(application.getStatus()) || WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) { return applicationState(WechatMiniLoginResultVO.STATUS_PENDING_REVIEW, "申请审核中", application); } @@ -192,14 +200,18 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { @Override public WechatMiniRegistrationTicket consumeRegistrationTicket(String ticket) { - if (!StringUtils.hasText(ticket)) { - throw new BusinessException("注册票据不能为空"); - } - String key = REGISTRATION_TICKET_KEY_PREFIX + ticket; - String payload = redisTemplate.opsForValue().get(key); - if (!StringUtils.hasText(payload) || !Boolean.TRUE.equals(redisTemplate.delete(key))) { + WechatMiniRegistrationTicket value = validateRegistrationTicket(ticket); + if (!Boolean.TRUE.equals(redisTemplate.delete(REGISTRATION_TICKET_KEY_PREFIX + ticket))) { throw new BusinessException("注册票据已失效,请重新发起快捷登录"); } + return value; + } + + @Override + public WechatMiniRegistrationTicket validateRegistrationTicket(String ticket) { + if (!StringUtils.hasText(ticket)) throw new BusinessException("注册票据不能为空"); + String payload = redisTemplate.opsForValue().get(REGISTRATION_TICKET_KEY_PREFIX + ticket); + if (!StringUtils.hasText(payload)) throw new BusinessException("注册票据已失效,请重新发起快捷登录"); try { WechatMiniRegistrationTicket value = objectMapper.readValue(payload, WechatMiniRegistrationTicket.class); WechatMiniBindingDO binding = findBindingByOpenId(value.getOpenId()); @@ -213,6 +225,47 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } } + @Override + @Transactional(rollbackFor = Exception.class) + public void transferRegistrationBinding(Long sourceUserId, Long targetUserId) { + if (sourceUserId == null || targetUserId == null || Objects.equals(sourceUserId, targetUserId)) { + throw new BusinessException("微信身份关联目标不合法"); + } + String appId = wechatMiniClientService.getConfiguredAppId(); + WechatMiniBindingDO source = wechatMiniBindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId).eq(WechatMiniBindingDO::getUserId, sourceUserId) + .eq(WechatMiniBindingDO::getStatus, 1).last("FOR UPDATE")); + if (source == null) throw new BusinessException("注册申请的微信身份已失效"); + WechatMiniBindingDO occupied = wechatMiniBindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId).eq(WechatMiniBindingDO::getUserId, targetUserId) + .eq(WechatMiniBindingDO::getStatus, 1).last("FOR UPDATE")); + if (occupied != null) throw new BusinessException("该美甲师已关联微信账号"); + WechatMiniBindingDO historical = wechatMiniBindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId).eq(WechatMiniBindingDO::getUserId, targetUserId) + .last("FOR UPDATE")); + if (historical != null) wechatMiniBindingMapper.deleteById(historical.getId()); + source.setUserId(targetUserId); + source.setUpdateTime(LocalDateTime.now()); + wechatMiniBindingMapper.updateById(source); + } + + @Override + public void rememberRegistrationAvatarUpload(String ticket, Long fileId) { + if (fileId == null || fileId <= 0) throw new BusinessException("头像文件无效"); + validateRegistrationTicket(ticket); + Long ttl = redisTemplate.getExpire(REGISTRATION_TICKET_KEY_PREFIX + ticket); + if (ttl == null || ttl <= 0) throw new BusinessException("注册票据已失效,请重新发起快捷登录"); + redisTemplate.opsForValue().set(REGISTRATION_AVATAR_KEY_PREFIX + ticket, String.valueOf(fileId), Duration.ofSeconds(ttl)); + } + + @Override + public void validateRegistrationAvatarUpload(String ticket, Long fileId) { + if (fileId == null) return; + validateRegistrationTicket(ticket); + String uploadedFileId = redisTemplate.opsForValue().get(REGISTRATION_AVATAR_KEY_PREFIX + ticket); + if (!String.valueOf(fileId).equals(uploadedFileId)) throw new BusinessException("请重新选择并上传头像"); + } + @Override /** * Run business method `autoLogin`. @@ -280,6 +333,9 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { UserDO phoneUser = findActiveUserByPhone(phone); if (phoneUser != null) { + if (requiresWechatIdentityForStaff(phoneUser)) { + return WechatMiniLoginResultVO.needManualLogin("美甲师档案不能通过手机号关联,请使用关联微信身份或联系店长完成关联。"); + } if (userShopBindingSupport.listActiveShopIdsByUserId(phoneUser.getId()).isEmpty()) { return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone)); } @@ -288,6 +344,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone)); } + private boolean requiresWechatIdentityForStaff(UserDO user) { + return user != null && Integer.valueOf(3).equals(user.getType()) + && !StringUtils.hasText(user.getAccount()); + } + @Override @Transactional(rollbackFor = Exception.class) /** @@ -310,6 +371,10 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket()); LoginResponseVO loginResponse; if (ticketPayload.getUserId() != null) { + UserDO ticketUser = userMapper.selectById(ticketPayload.getUserId()); + if (requiresWechatIdentityForStaff(ticketUser)) { + throw new BusinessException("美甲师档案尚未关联微信身份,请联系店长完成关联"); + } loginResponse = userService.loginByUserId(ticketPayload.getUserId(), shopId); } else if (StringUtils.hasText(ticketPayload.getPhone())) { loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId); @@ -356,6 +421,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { .eq(WorkbenchRegistrationApplicationDO::getUserId, userId) .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) .orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime) + .orderByDesc(WorkbenchRegistrationApplicationDO::getId) .last("limit 1") ); } @@ -366,6 +432,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { result.setRegistrationStatus(application.getStatus()); result.setRegistrationRejectReason(application.getRejectReason()); result.setRegistrationApplicationId(application.getId()); + result.setRegistrationRole(application.getRoleType()); return result; } @@ -384,7 +451,8 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ticket, application == null ? null : application.getStatus(), application == null ? null : application.getRejectReason(), - application == null ? null : application.getId() + application == null ? null : application.getId(), + application == null ? null : application.getRoleType() ); result.setConsentUserId(userId); return result; @@ -500,12 +568,15 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { if (!StringUtils.hasText(phone)) { return null; } - return userMapper.selectOne( - new LambdaQueryWrapper() - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO user = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getPhoneHash, PhoneCrypto.current().index(phone.trim())) + .eq(UserDO::getIsDelete, 0) + .last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByPhone(phone.trim()); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java index 0733d6ac..3bb5fb73 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java @@ -20,6 +20,7 @@ import org.springframework.web.util.UriComponentsBuilder; import java.time.Duration; import java.util.Map; import java.util.Objects; +import java.util.HashMap; /** * WeChat mini program API client. @@ -201,6 +202,52 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { return properties.getAppId(); } + @Override + public String getAccessTokenForContentModeration() { + return getAccessToken(); + } + + @Override + public SubscribeMessageResult sendSubscribeMessage(String openId, String templateId, Map data, + String page, String miniprogramState) { + if (!StringUtils.hasText(openId) || !StringUtils.hasText(templateId)) { + return new SubscribeMessageResult(false, 40001, "缺少订阅消息接收人或模板"); + } + if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled())) { + return new SubscribeMessageResult(false, 40002, "订阅消息已关闭"); + } + if ("mock".equalsIgnoreCase(properties.getSubscribeMessageProvider())) { + return new SubscribeMessageResult(true, 0, "MOCK_OK"); + } + try { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + Map request = new HashMap<>(); + request.put("touser", openId); + request.put("template_id", templateId); + request.put("page", StringUtils.hasText(page) ? page : "/pages/planning/index"); + request.put("miniprogram_state", StringUtils.hasText(miniprogramState) ? miniprogramState : "developer"); + request.put("lang", "zh_CN"); + Map> templateData = new HashMap<>(); + if (data != null) { + data.forEach((key, value) -> templateData.put(key, Map.of("value", value == null ? "-" : value))); + } + request.put("data", templateData); + Map response = readJsonResponse( + doPostForString( + UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/message/subscribe/send") + .queryParam("access_token", getAccessToken()).build(true).toUriString(), + new HttpEntity<>(request, headers), "发送微信订阅消息失败"), + "发送微信订阅消息失败"); + int errCode = (int) parseLong(response.get("errcode"), 0L); + String errMsg = asText(response.get("errmsg")); + return new SubscribeMessageResult(errCode == 0, errCode, errMsg); + } catch (RuntimeException exception) { + // 订阅消息属于异步通知,微信暂时不可用时交给 Outbox 重试,不影响预约主流程。 + return new SubscribeMessageResult(false, -1, "微信订阅消息服务暂时不可用"); + } + } + /** * 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImpl.java new file mode 100644 index 00000000..aba1f4f8 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImpl.java @@ -0,0 +1,185 @@ +package com.xiaowang.jayucloud.salon.core.modules.integration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatSubscribeMessageLogMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Service +@RequiredArgsConstructor +public class WechatSubscribeMessageServiceImpl implements WechatSubscribeMessageService { + /** 微信 date 类型使用中文日期格式;time 类型单独使用 HH:mm。 */ + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); + private static final DateTimeFormatter CLOCK_TIME = DateTimeFormatter.ofPattern("HH:mm"); + private static final String PENDING = "PENDING"; + private static final String RETRY = "RETRY"; + private static final String SENT = "SENT"; + private static final String FAILED = "FAILED"; + + private final WechatSubscribeMessageLogMapper logMapper; + private final WechatMiniBindingMapper bindingMapper; + private final WechatMiniClientService wechatMiniClientService; + private final WechatMiniProperties properties; + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final ProductMapper productMapper; + private final UserMapper userMapper; + private final PhoneCrypto phoneCrypto; + + @Override + public void enqueueAppointmentReminder(Long orderId, Long orderItemId) { + enqueue("APPOINTMENT", TEMPLATE_APPOINTMENT, orderId, orderItemId, null); + } + + @Override + public void enqueueCancellationNotice(Long orderId, Long orderItemId) { + enqueue("CANCELLED", TEMPLATE_CANCELLED, orderId, orderItemId, null); + } + + @Override + public void enqueueServiceStartReminder(Long orderId, Long orderItemId, LocalDateTime appointmentTime) { + enqueue("SERVICE_START", TEMPLATE_SERVICE_START, orderId, orderItemId, appointmentTime); + } + + private void enqueue(String eventType, String templateCode, Long orderId, Long orderItemId, LocalDateTime dueTime) { + if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled()) || orderItemId == null) return; + OrderItemDO item = orderItemMapper.selectById(orderItemId); + if (item == null || item.getArtistId() == null) return; + String eventKey = eventType + ":" + orderItemId + ":" + item.getArtistId() + + (dueTime == null ? "" : ":" + dueTime); + WechatSubscribeMessageLogDO log = new WechatSubscribeMessageLogDO(); + log.setEventKey(eventKey); + log.setTemplateCode(templateCode); + log.setOrderId(orderId); + log.setOrderItemId(orderItemId); + log.setUserId(item.getArtistId()); + log.setStatus(PENDING); + log.setRetryCount(0); + log.setNextRetryTime(dueTime == null ? LocalDateTime.now() : dueTime.minusMinutes(Math.max(1, properties.getServiceStartReminderLeadMinutes() == null ? 30 : properties.getServiceStartReminderLeadMinutes()))); + log.setIsDelete(0); + try { logMapper.insert(log); } catch (DuplicateKeyException ignored) { } + } + + @Override + @Scheduled(fixedDelayString = "${jayucloud-salon.wechat.mini.subscribe-message-scan-delay-millis:60000}") + public void processDueMessages() { + if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled())) return; + List logs = logMapper.selectDue(LocalDateTime.now(), 50); + for (WechatSubscribeMessageLogDO log : logs) { + if (logMapper.claimForProcessing(log.getId()) != 1) continue; + try { + processOne(log); + } catch (RuntimeException exception) { + retry(log, -1, "订阅消息处理暂时失败"); + } + } + } + + private void processOne(WechatSubscribeMessageLogDO log) { + OrderItemDO item = orderItemMapper.selectById(log.getOrderItemId()); + OrderDO order = item == null ? null : orderMapper.selectById(item.getOrderId()); + if (item == null || order == null || Integer.valueOf(1).equals(item.getIsDelete()) || Integer.valueOf(1).equals(order.getIsDelete())) { + mark(log, FAILED, 40004, "预约不存在", null); return; + } + if (log.getUserId() != null && !log.getUserId().equals(item.getArtistId())) { + mark(log, FAILED, 40008, "预约承接美甲师已变化", null); return; + } + if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) && (item.getAppointmentTime() == null || !Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()))) { + mark(log, FAILED, 40005, "预约已取消或状态已变化", null); return; + } + if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) && !item.getAppointmentTime().isAfter(LocalDateTime.now())) { + mark(log, FAILED, 40011, "预约已开始,跳过开始提醒", null); return; + } + if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) + && !log.getEventKey().endsWith(String.valueOf(item.getAppointmentTime()))) { + mark(log, FAILED, 40008, "预约时间已变化", null); return; + } + if (TEMPLATE_APPOINTMENT.equals(log.getTemplateCode()) && !Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + mark(log, FAILED, 40009, "预约已不在待服务状态", null); return; + } + if (TEMPLATE_CANCELLED.equals(log.getTemplateCode()) && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { + mark(log, FAILED, 40010, "预约取消状态已变化", null); return; + } + Long artistId = item.getArtistId(); + if (artistId == null) { mark(log, FAILED, 40006, "预约尚未分配美甲师", null); return; } + UserDO artist = userMapper.selectById(artistId); + if (artist == null) { mark(log, FAILED, 40007, "美甲师不存在", null); return; } + LambdaQueryWrapper bindingQuery = new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getUserId, artistId) + .eq(WechatMiniBindingDO::getStatus, 1); + if (StringUtils.hasText(properties.getAppId())) { + bindingQuery.eq(WechatMiniBindingDO::getAppId, properties.getAppId()); + } + WechatMiniBindingDO binding = bindingMapper.selectOne(bindingQuery.last("LIMIT 1")); + if (binding == null || !StringUtils.hasText(binding.getOpenId())) { mark(log, FAILED, 43101, "美甲师未授权订阅消息", null); return; } + log.setUserId(artistId); + log.setOpenIdHash(phoneCrypto.index(binding.getOpenId())); + logMapper.updateById(log); + ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId()); + String productTitle = clip(product == null ? "预约服务" : product.getTitle(), 20); + String customerName = clip(StringUtils.hasText(order.getCustomerNameSnapshot()) ? order.getCustomerNameSnapshot() : "到店客户", 20); + String dateTime = item.getAppointmentTime() == null ? "待确认" : DATE_TIME.format(item.getAppointmentTime()); + String clockTime = item.getAppointmentTime() == null ? "待确认" : CLOCK_TIME.format(item.getAppointmentTime()); + Map data = new LinkedHashMap<>(); + if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode())) { + data.put("thing1", "预约即将开始,请提前准备"); data.put("date3", clip(dateTime, 20)); data.put("thing6", productTitle); data.put("thing7", customerName); + } else if (TEMPLATE_CANCELLED.equals(log.getTemplateCode())) { + data.put("name1", clip(customerName, 10)); data.put("thing2", productTitle); data.put("time4", clip(clockTime, 20)); data.put("thing6", clip(StringUtils.hasText(order.getCancelReason()) ? order.getCancelReason() : "门店取消预约", 20)); + } else { + data.put("thing1", productTitle); data.put("time2", clip(clockTime, 20)); data.put("thing3", "请提前确认服务安排"); data.put("name5", clip(StringUtils.hasText(artist.getNickname()) ? artist.getNickname() : artist.getAccount(), 10)); data.put("name6", clip(customerName, 10)); + } + WechatMiniClientService.SubscribeMessageResult result = wechatMiniClientService.sendSubscribeMessage(binding.getOpenId(), log.getTemplateCode(), data, properties.getSubscribeMessagePage(), properties.getSubscribeMessageMiniprogramState()); + if (result.success()) mark(log, SENT, 0, result.errMsg(), LocalDateTime.now()); + else if (isPermanentWechatError(result.errCode())) mark(log, FAILED, result.errCode(), result.errMsg(), null); + else retry(log, result.errCode(), result.errMsg()); + } + + private boolean isPermanentWechatError(int code) { + return code == 40001 || code == 40003 || code == 40004 || code == 40037 + || code == 41028 || code == 41030 || code == 43101 || code == 47003; + } + + private void retry(WechatSubscribeMessageLogDO log, int code, String message) { + int count = log.getRetryCount() == null ? 0 : log.getRetryCount(); + int max = properties.getSubscribeMessageMaxRetries() == null ? 3 : properties.getSubscribeMessageMaxRetries(); + if (count >= max) { mark(log, FAILED, code, message, null); return; } + mark(log, RETRY, code, message, LocalDateTime.now().plusSeconds(10L * (count + 1))); + } + + private void mark(WechatSubscribeMessageLogDO log, String status, int code, String message, LocalDateTime time) { + log.setStatus(status); log.setErrCode(code); log.setErrMsg(clip(message, 500)); log.setNextRetryTime(time); + if (SENT.equals(status)) log.setSentTime(LocalDateTime.now()); + log.setRetryCount(log.getRetryCount() == null ? 0 : log.getRetryCount() + (RETRY.equals(status) ? 1 : 0)); + logMapper.updateById(log); + } + + private static String clip(String value, int max) { + if (!StringUtils.hasText(value)) return "-"; + String text = value.trim(); return text.length() <= max ? text : text.substring(0, max); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java index 22b5f3e3..e185a585 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java @@ -79,6 +79,7 @@ public class WechatMiniLoginResultVO { private String registrationStatus; private String registrationRejectReason; private Long registrationApplicationId; + private String registrationRole; @JsonIgnore private Long consentUserId; @@ -90,7 +91,7 @@ public class WechatMiniLoginResultVO { } public static WechatMiniLoginResultVO registration(String ticket, String registrationStatus, - String rejectReason, Long applicationId) { + String rejectReason, Long applicationId, String roleType) { WechatMiniLoginResultVO result = state(STATUS_NEED_REGISTRATION, "请完善身份和门店资料并提交审核"); result.setNewUser(true); result.setRegistrationRequired(true); @@ -98,6 +99,7 @@ public class WechatMiniLoginResultVO { result.setRegistrationStatus(registrationStatus); result.setRegistrationRejectReason(rejectReason); result.setRegistrationApplicationId(applicationId); + result.setRegistrationRole(roleType); return result; } @@ -123,7 +125,7 @@ public class WechatMiniLoginResultVO { resultVO.setMessage("手机号尚未绑定店铺,请先完成身份注册"); resultVO.setRegistrationRequired(true); resultVO.setRegistrationTicket(loginResponse.getRegistrationTicket()); - resultVO.setPhone(loginResponse.getPhone()); + resultVO.setPhone(maskPhone(loginResponse.getPhone())); resultVO.setRegistrationReason(loginResponse.getRegistrationReason()); resultVO.setRegistrationStatus(loginResponse.getRegistrationStatus()); resultVO.setRegistrationRejectReason(loginResponse.getRegistrationRejectReason()); @@ -131,6 +133,13 @@ public class WechatMiniLoginResultVO { return resultVO; } + private static String maskPhone(String phone) { + if (phone == null || phone.length() != 11 || !phone.matches("1[3-9]\\d{9}")) { + return phone; + } + return phone.substring(0, 3) + "****" + phone.substring(7); + } + public static WechatMiniLoginResultVO selectShop( String message, String ticket, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java index 2474ec4e..e1d0afb0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java @@ -2,8 +2,10 @@ package com.xiaowang.jayucloud.salon.core.modules.manager.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.salon.core.common.BusinessException; import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistColorUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistScheduleDTO; import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistScheduleExceptionDTO; import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistScheduleRuleDTO; @@ -15,6 +17,9 @@ import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistScheduleRuleSet import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistScheduleRuleVO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistScheduleVO; import com.xiaowang.jayucloud.salon.core.modules.manager.dto.ManagerCustomerCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderVO; import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO; import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentMoveDTO; import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentStatusDTO; @@ -27,11 +32,18 @@ import com.xiaowang.jayucloud.salon.core.modules.product.service.ProductService; import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.UnlinkedWechatUserVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import lombok.RequiredArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; @@ -45,12 +57,13 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.time.LocalDate; import java.util.List; @RestController -@RequestMapping("/admin/manager") +@RequestMapping({"/admin/manager", "/manager"}) @RequiredArgsConstructor public class AdminManagerController { @@ -61,6 +74,8 @@ public class AdminManagerController { private final ProductService productService; private final ShopService shopService; private final AdminScopeHelper adminScopeHelper; + private final CustomerDialService customerDialService; + private final OrderService orderService; @GetMapping("/planning/calendar") @RequirePermission("schedule:view") @@ -107,6 +122,30 @@ public class AdminManagerController { return Result.success(planningService.getAppointment(currentUser, orderItemId)); } + @PutMapping("/planning/appointments/{orderItemId}") + @RequirePermission("order:process") + @OperationGuard(action = "manager-planning-update-appointment", ttlSeconds = 10, message = "预约保存处理中,请勿重复提交") + public Result updateAppointment(HttpServletRequest request, + @PathVariable Long orderItemId, + @RequestBody PlanningAppointmentCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.updateAppointment(currentUser, orderItemId, dto)); + } + + @PostMapping("/orders/{orderId}/offline-payment") + @RequirePermission("order:process") + @OperationGuard(action = "manager-order-offline-payment", ttlSeconds = 10, message = "收款登记处理中,请勿重复提交") + public Result registerOfflinePayment(HttpServletRequest request, + @PathVariable Long orderId, + @RequestBody OrderOfflinePaymentDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (Integer.valueOf(3).equals(currentUser.getType())) { + throw new BusinessException(403, "美甲师账号不能登记收款"); + } + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(orderService.registerOfflinePayment(orderId, currentUser.getId(), scopedShopId, dto)); + } + @PutMapping("/planning/appointments/{orderItemId}/time-artist") @RequirePermission("order:process") @OperationGuard(action = "manager-planning-move-appointment", ttlSeconds = 10, message = "预约调整处理中,请勿重复提交") @@ -141,6 +180,64 @@ public class AdminManagerController { return Result.success(result); } + @GetMapping("/customers/matches") + @RequirePermission("user:view") + public Result> customerMatches(HttpServletRequest request, + @RequestParam String nickname, + @RequestParam(required = false) String phone) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(userService.findCustomerMatches(nickname, phone, shopId)); + } + + @GetMapping("/customers/identity-matches") + @RequirePermission("user:view") + public Result> customerIdentityMatches(HttpServletRequest request, + @RequestParam String nickname, + @RequestParam(required = false) String wechatId, + @RequestParam(required = false) String phone) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(userService.findCustomerIdentityMatches(nickname, wechatId, phone, shopId)); + } + + @GetMapping("/customers/appointment-options") + @RequirePermission("user:view") + public Result> appointmentCustomerOptions(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "30") Integer size, + @RequestParam(required = false) String keyword) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + adminScopeHelper.requireShopContext(currentUser); + return Result.success(userService.listCustomersForAppointment(page, size, keyword, shopId)); + } + + @PostMapping("/customers/{customerId}/dial") + @RequirePermission("user:view") + public Result dialCustomer(HttpServletRequest request, + HttpServletResponse response, + @PathVariable Long customerId, + @RequestParam(required = false) Long appointmentId, + @RequestParam(required = false) Long orderId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + response.setHeader("Cache-Control", "no-store"); + return Result.success(customerDialService.dial(currentUser, customerId, appointmentId, orderId, request)); + } + + @PostMapping("/customers/dial") + @RequirePermission("user:view") + public Result dialCustomerForGuest(HttpServletRequest request, + HttpServletResponse response, + @RequestParam(required = false) Long customerId, + @RequestParam(required = false) Long appointmentId, + @RequestParam(required = false) Long orderId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + response.setHeader("Cache-Control", "no-store"); + return Result.success(customerDialService.dial(currentUser, customerId, appointmentId, orderId, request)); + } + @GetMapping("/customers/{id}") @RequirePermission("user:view") public Result customer(HttpServletRequest request, @PathVariable Long id) { @@ -157,18 +254,7 @@ public class AdminManagerController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再新增客户"); Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); - String phone = dto.getPhone().trim(); - UserDTO userDTO = new UserDTO(); - userDTO.setNickname(dto.getNickname().trim()); - userDTO.setPhone(phone); - userDTO.setContactPhone(phone); - userDTO.setAccount(phone); - userDTO.setType(0); - userDTO.setShopId(shopId); - userDTO.setShopIds(List.of(shopId)); - userDTO.setLevel("普通"); - userDTO.setVipId(0L); - return Result.success(userService.createUser(userDTO)); + return Result.success(userService.createManagerCustomer(dto.getNickname(), dto.getWechatId(), dto.getPhone(), shopId)); } @GetMapping("/employees") @@ -201,7 +287,20 @@ public class AdminManagerController { if (!adminScopeHelper.isPlatformAdmin(currentUser)) { adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getUserId(), "无权编辑其他店铺员工"); } - return Result.success(nailArtistInfoService.saveOrUpdateNailArtistInfo(dto)); + return Result.success(nailArtistInfoService.submitNailArtistInfo(dto, currentUser.getId())); + } + + @PutMapping("/employees/{userId}/color") + @RequirePermission("nail_artist:edit") + @OperationGuard(action = "manager-nail-artist-color", ttlSeconds = 10, message = "美甲师颜色保存处理中,请勿重复提交") + public Result updateEmployeeColor(HttpServletRequest request, + @PathVariable Long userId, + @RequestBody(required = false) ArtistColorUpdateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权编辑其他店铺员工"); + } + return Result.success(nailArtistInfoService.updateArtistColor(userId, dto == null ? null : dto.getColor())); } @PostMapping("/employees/users") @@ -220,6 +319,22 @@ public class AdminManagerController { return Result.success(userService.createUser(dto)); } + @PostMapping("/employees/users/unlinked") + @RequirePermission("user:create") + @OperationGuard(action = "manager-user-create-unlinked", ttlSeconds = 10, message = "美甲师档案创建处理中,请勿重复提交") + public Result createUnlinkedEmployee(HttpServletRequest request, + @RequestBody UserDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setType(3); + adminScopeHelper.ensureAssignableUserType(currentUser, dto.getType()); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + dto.setShopId(managedShopId); + dto.setShopIds(List.of(managedShopId)); + } + return Result.success(userService.createUnlinkedEmployee(dto, dto.getShopId())); + } + @GetMapping("/employees/schedules") @RequirePermission("schedule:view") public Result> schedules(HttpServletRequest request, @@ -270,6 +385,75 @@ public class AdminManagerController { return Result.success(artistScheduleService.saveException(dto)); } + @GetMapping("/employees/schedule-exceptions") + @RequirePermission("schedule:view") + public Result> listScheduleExceptions(HttpServletRequest request, + @RequestParam(required = false) Long artistId, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(artistScheduleService.listExceptions(shopId, artistId, startDate, endDate)); + } + + @GetMapping("/orders/preview") + @RequirePermission("order:view") + public Result> orderPreview(HttpServletRequest request, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, null); + List orders = Integer.valueOf(3).equals(currentUser.getType()) + ? orderService.getOrdersByArtistId(currentUser.getId()) + : orderService.getAllOrders(); + if (scopedShopId != null && !Integer.valueOf(3).equals(currentUser.getType())) { + orders = orders.stream().filter(order -> scopedShopId.equals(order.getShopId())).toList(); + } + if (startDate != null) { + orders = orders.stream() + .filter(order -> order.getCreateTime() != null && !order.getCreateTime().toLocalDate().isBefore(startDate)) + .toList(); + } + if (endDate != null) { + orders = orders.stream() + .filter(order -> order.getCreateTime() != null && !order.getCreateTime().toLocalDate().isAfter(endDate)) + .toList(); + } + List preview = orders.stream() + .sorted((left, right) -> { + if (left.getCreateTime() == null) return 1; + if (right.getCreateTime() == null) return -1; + return right.getCreateTime().compareTo(left.getCreateTime()); + }) + .limit(10) + .toList(); + return Result.success(preview); + } + + @GetMapping("/employees/users/unlinked-candidates") + @RequirePermission("user:create") + public Result> unlinkedWechatCandidates(HttpServletRequest request, + @RequestParam(required = false) String keyword) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + java.util.Set linkedUserIds = nailArtistInfoService.getByShopId(shopId).stream() + .map(NailArtistInfoDTO::getUserId) + .filter(java.util.Objects::nonNull) + .collect(java.util.stream.Collectors.toSet()); + String normalizedKeyword = keyword == null ? "" : keyword.trim().toLowerCase(); + List candidates = userService.listUsersByShopId(shopId).stream() + .filter(user -> Integer.valueOf(1).equals(user.getType())) + .filter(user -> user.getId() != null && !linkedUserIds.contains(user.getId())) + .filter(user -> normalizedKeyword.isEmpty() + || String.valueOf(user.getNickname() == null ? "" : user.getNickname()).toLowerCase().contains(normalizedKeyword) + || String.valueOf(user.getMaskedPhone() == null ? "" : user.getMaskedPhone()).contains(normalizedKeyword)) + .limit(50) + .map(user -> new UnlinkedWechatUserVO(user.getId(), user.getNickname(), user.getMaskedPhone(), + user.getAvatar(), user.getWechatId(), user.getCreateTime())) + .toList(); + return Result.success(candidates); + } + @GetMapping("/products") @RequirePermission("product:view") public Result> products(HttpServletRequest request, @@ -312,4 +496,33 @@ public class AdminManagerController { } return Result.success(shopService.updateShop(shopId, dto)); } + + @GetMapping("/shop/appointment-settings") + @RequirePermission("shop:view") + public Result appointmentSettings(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(shopService.getAppointmentSettings(shopId)); + } + + @PutMapping("/shop/appointment-settings") + @RequirePermission("shop:edit") + @OperationGuard(action = "manager-shop-appointment-settings-update", ttlSeconds = 10, message = "预约设置正在保存,请勿重复提交") + public Result updateAppointmentSettings(HttpServletRequest request, @RequestBody ShopAppointmentSettingsDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(shopService.updateAppointmentSettings(shopId, dto)); + } + + @PutMapping("/shop/name") + @RequirePermission("shop:edit") + @OperationGuard(action = "manager-shop-name-review", ttlSeconds = 10, message = "门店名称正在提交审核,请勿重复操作") + public Result updateShopName(HttpServletRequest request, @RequestBody ShopNameUpdateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(shopService.updateShopName(shopId, dto)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java index 396e8700..f129a4c2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java @@ -3,7 +3,6 @@ package com.xiaowang.jayucloud.salon.core.modules.manager.dto; import lombok.Data; import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; @Data public class ManagerCustomerCreateDTO { @@ -11,7 +10,7 @@ public class ManagerCustomerCreateDTO { @NotBlank(message = "客户姓名不能为空") private String nickname; - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + private String wechatId; + private String phone; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java new file mode 100644 index 00000000..2bf1f36b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.manager.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AppointmentCustomerOptionVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + private String name; + /** 脱敏后的手机号,永不返回完整号码 */ + private String phone; + /** 是否存在可拨打的手机号,呼叫按钮据此展示 */ + private Boolean phoneAvailable; + private String avatar; + private LocalDateTime createdAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/UnlinkedWechatUserVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/UnlinkedWechatUserVO.java new file mode 100644 index 00000000..7eef18f3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/UnlinkedWechatUserVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.modules.manager.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@AllArgsConstructor +public class UnlinkedWechatUserVO { + private Long id; + private String nickname; + private String maskedPhone; + private String avatar; + private String wechatId; + private LocalDateTime createTime; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java deleted file mode 100644 index 4373969b..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CampaignDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CampaignService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CampaignVO; -import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/admin/campaign") -@RequiredArgsConstructor -public class AdminCampaignController { - - private final CampaignService campaignService; - private final AdminScopeHelper adminScopeHelper; - private final SecurityAuditSupport securityAuditSupport; - - @GetMapping("/list") - @RequirePermission("campaign:view") - public Result> list(HttpServletRequest request, - @RequestParam(required = false) Integer status, - @RequestParam(defaultValue = "1") Integer page, - @RequestParam(defaultValue = "10") Integer size) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); - return Result.success(campaignService.listCampaigns(shopId, status, page, size)); - } - - @PostMapping("/save") - @RequirePermission("campaign:manage") - public Result save(HttpServletRequest request, @RequestBody CampaignDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); - try { - CampaignVO result = campaignService.saveCampaign(dto); - securityAuditSupport.success(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "campaignId=" + result.getId()); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java deleted file mode 100644 index 882fa9c3..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - -/** - * 后台优惠券管理控制器 - */ -@RestController -@RequestMapping("/admin/coupon") -@RequiredArgsConstructor -public class AdminCouponController { - /** - * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponService couponService; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建优惠券 - */ - @PostMapping("/create") - @RequirePermission("coupon:create") - @OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - @OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - @OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 获取所有优惠券 - */ - @GetMapping("/list/all") - @RequirePermission("coupon:view") - public Result> listAllCoupons(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - List coupons = couponService.listAllCoupons(); - Long resolvedShopId = shopId; - if (resolvedShopId != null) { - coupons = coupons.stream() - .filter(coupon -> resolvedShopId.equals(coupon.getShopId())) - .collect(Collectors.toList()); - } - return Result.success(coupons); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - @OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - @OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java deleted file mode 100644 index e437ed39..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.UserCouponVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * 优惠券控制器 - */ -@RestController -@RequestMapping("/coupon") -@RequiredArgsConstructor -public class CouponController { - /** - * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponService couponService; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建优惠券 - */ - @PostMapping("/create") - @RequirePermission("coupon:create") - public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 获取用户优惠券列表 - */ - @GetMapping("/user/list") - public Result> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) { - List userCoupons = couponService.listUserCoupons(userId, status); - return Result.success(userCoupons); - } - - /** - * 使用优惠券 - */ - @PostMapping("/use") - public Result useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) { - boolean success = couponService.useCoupon(userCouponId, userId); - return Result.success(success); - } - - /** - * 获取商品可用的优惠券 - */ - @GetMapping("/available") - public Result> getAvailableCoupons( - @RequestParam(required = false, defaultValue = "") String productTags, - @RequestParam Double productPrice, - @RequestParam(required = false) Long shopId, - @RequestAttribute("userId") Long userId - ) { - List availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId); - return Result.success(availableCoupons); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java deleted file mode 100644 index 125fde8a..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.GrowthService; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.GrowthSummaryVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/growth") -@RequiredArgsConstructor -public class GrowthController { - - private final GrowthService growthService; - - @GetMapping("/summary") - public Result summary(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(growthService.getSummary(userId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java deleted file mode 100644 index dd000704..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.ProductLikeService; -import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -/** - * 商品点赞控制器 - * - * @author xiaowang - * @date 2026-03-05 - */ -@RestController -@RequestMapping("/product-like") -@RequiredArgsConstructor -public class ProductLikeController { - /** - * Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductLikeService productLikeService; - - /** - * 点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/like/{productId}") - @OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.addLike(userId, productId); - return Result.success(true); - } - - /** - * 取消点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/unlike/{productId}") - @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.removeLike(userId, productId); - return Result.success(true); - } - - /** - * 检查用户是否已点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否已点赞 - */ - @GetMapping("/check/{productId}") - public Result checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - boolean isLiked = productLikeService.isProductLiked(userId, productId); - return Result.success(isLiked); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java deleted file mode 100644 index 0fc71ff0..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipBenefitDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipBenefitVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipBenefitService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * VIP权益信息表 Controller - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/vip-benefit", "/api/vip-benefit"}) -@RequiredArgsConstructor -public class VipBenefitController { - /** - * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipBenefitService vipBenefitService; - - /** - * 创建VIP权益 - * - * @param vipBenefitDTO VIP权益DTO - * @return VIP权益ID - */ - @PostMapping("/create") - public Result createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { - Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); - return Result.success(id); - } - - /** - * 更新VIP权益 - * - * @param id VIP权益ID - * @param vipBenefitDTO VIP权益DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { - boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); - return Result.success(success); - } - - /** - * 删除VIP权益 - * - * @param id VIP权益ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipBenefit(@PathVariable Long id) { - boolean success = vipBenefitService.deleteVipBenefit(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP权益 - * - * @param id VIP权益ID - * @return VIP权益VO - */ - @GetMapping("/get/{id}") - public Result getVipBenefitById(@PathVariable Long id) { - VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); - return Result.success(vipBenefitVO); - } - - /** - * 查询所有VIP权益 - * - * @return VIP权益VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipBenefits() { - List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); - return Result.success(vipBenefitVOs); - } - - /** - * 根据所需VIP等级查询VIP权益 - * - * @param requiredVipLevel 所需VIP等级 - * @return VIP权益VO列表 - */ - @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") - public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { - List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); - return Result.success(vipBenefitVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java deleted file mode 100644 index c98795da..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipInfoDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipInfoVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipInfoService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户VIP信息表 Controller - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/vip-info", "/api/vip-info"}) -@RequiredArgsConstructor -public class VipInfoController { - /** - * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipInfoService vipInfoService; - - /** - * 创建VIP信息 - * - * @param vipInfoDTO VIP信息DTO - * @return VIP信息ID - */ - @PostMapping("/create") - public Result createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { - Long id = vipInfoService.createVipInfo(vipInfoDTO); - return Result.success(id); - } - - /** - * 更新VIP信息 - * - * @param id VIP信息ID - * @param vipInfoDTO VIP信息DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { - boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); - return Result.success(success); - } - - /** - * 删除VIP信息 - * - * @param id VIP信息ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipInfo(@PathVariable Long id) { - boolean success = vipInfoService.deleteVipInfo(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP信息 - * - * @param id VIP信息ID - * @return VIP信息VO - */ - @GetMapping("/get/{id}") - public Result getVipInfoById(@PathVariable Long id) { - VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); - return Result.success(vipInfoVO); - } - - /** - * 查询所有VIP信息 - * - * @return VIP信息VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipInfos() { - List vipInfoVOs = vipInfoService.listAllVipInfos(); - return Result.success(vipInfoVOs); - } - - /** - * 根据VIP等级查询VIP信息 - * - * @param vipLevel VIP等级 - * @return VIP信息VO列表 - */ - @GetMapping("/list/vipLevel/{vipLevel}") - public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { - List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); - return Result.success(vipInfoVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java deleted file mode 100644 index a8a5a343..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipRechargePlanDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipRechargePlanService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipRechargePlanVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"}) -/** - * VipRechargePlanController 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 VipRechargePlanController { - /** - * Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipRechargePlanService vipRechargePlanService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @GetMapping("/admin/list") - @RequirePermission("user:vip:manage") - /** - * Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); - } - - @PostMapping("/admin/create") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Create a new record. - * 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 - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); - } - - @PutMapping("/admin/{id}") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Update an existing record. - * 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 - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); - } - - @PutMapping("/admin/{id}/status") - @RequirePermission("user:vip:manage") - /** - * Change the enabled/status flag of one record. - * 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 - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); - } - - @GetMapping("/my/list") - /** - * List records for the current query or current user scope. - * 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> result consumed by the caller or returned to the frontend - */ - public Result> listMy(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(vipRechargePlanService.listMyPlans(userId)); - } - - @GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"}) - /** - * Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java deleted file mode 100644 index f1b850fb..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistAddWithGroupDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistGroupDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistMoveDTO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.service.WishlistService; -import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistGroupVO; -import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistInspirationVO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestAttribute; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/wishlist") -public class WishlistController { - - @Autowired - private WishlistService wishlistService; - - @PostMapping("/add") - @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @PostMapping("/add-with-group") - @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request); - return Result.success("ok"); - } - - @PostMapping("/remove") - @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.removeFromWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @GetMapping("/check") - public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.isInWishlist(userId, productId)); - } - - @GetMapping("/list") - public Result> getWishlist(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getWishlistByUserId(userId)); - } - - @GetMapping("/groups") - public Result> listGroups(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.listGroups(userId)); - } - - @PostMapping("/groups") - public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.createGroup(userId, request)); - } - - @PutMapping("/groups/{id}") - public Result updateGroup( - @PathVariable Long id, - @RequestBody WishlistGroupDTO request, - @RequestAttribute("userId") Long userId - ) { - return Result.success(wishlistService.updateGroup(userId, id, request)); - } - - @DeleteMapping("/groups/{id}") - public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.deleteGroup(userId, id)); - } - - @PostMapping("/move") - @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.moveWishlist(userId, request)); - } - - @GetMapping("/inspiration") - public Result getInspiration(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getInspiration(userId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java index dbe4fe58..f73e22e3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java @@ -27,6 +27,9 @@ public class AnnouncementCreateDTO { */ private String content; + /** 公告图片文件ID集合,多个ID以逗号分隔。 */ + private String imageFileIds; + @NotBlank(message = "公告范围不能为空") /** * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java index 833bca6b..3075823e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java @@ -30,6 +30,9 @@ public class AnnouncementDO extends BaseEntity { */ private String content; + @TableField("image_file_ids") + private String imageFileIds; + @TableField("publisher_id") /** * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. @@ -66,6 +69,9 @@ public class AnnouncementDO extends BaseEntity { */ private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("sort_order") /** * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java index d0667a59..76ec67cd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java @@ -106,6 +106,9 @@ public class SystemMessageDO extends BaseEntity { */ private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("publish_time") /** * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java index 8e71d620..ca978c9f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java @@ -2,10 +2,14 @@ package com.xiaowang.jayucloud.salon.core.modules.message.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.message.entity.AnnouncementDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; /** * AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. */ public interface AnnouncementMapper extends BaseMapper { + @Select("SELECT COUNT(1) FROM t_announcement WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java index 43a7b814..6c5caebf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java @@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.message.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.message.entity.SystemMessageDO; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; @Mapper /** @@ -10,4 +12,6 @@ import org.apache.ibatis.annotations.Mapper; * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. */ public interface SystemMessageMapper extends BaseMapper { + @Select("SELECT COUNT(1) FROM t_system_message WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND image_file_id = #{fileId}") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java index 3a7143df..360e2998 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -13,8 +13,11 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.message.service.AnnouncementService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.message.vo.AnnouncementVO; import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -83,6 +86,9 @@ public class AnnouncementServiceImpl extends ServiceImpl payload = new java.util.LinkedHashMap<>(); + payload.put("title", announcement.getTitle()); payload.put("content", announcement.getContent()); + payload.put("imageFileIds", announcement.getImageFileIds()); payload.put("status", 1); + contentModerationService.assessVersion("ANNOUNCEMENT", announcement.getId(), currentUser.getId(), + announcement.getTitle() + "\n" + announcement.getContent(), objectMapper.writeValueAsString(payload), + parseImageFileIds(announcement.getImageFileIds())); + } catch (Exception exception) { + throw new IllegalStateException("公告审核任务创建失败", exception); + } return announcement.getId(); } @@ -212,7 +230,7 @@ public class AnnouncementServiceImpl extends ServiceImpl() .eq(AnnouncementDO::getIsDelete, 0) .eq(AnnouncementDO::getStatus, 1) + .eq(AnnouncementDO::getModerationStatus, "APPROVED") .orderByDesc(AnnouncementDO::getSortOrder) .orderByDesc(AnnouncementDO::getPublishTime)) .stream() @@ -373,6 +392,7 @@ public class AnnouncementServiceImpl extends ServiceImpl parseImageFileIdsStrict(String value) { + if (!StringUtils.hasText(value)) return List.of(); + return java.util.Arrays.stream(value.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .map(token -> { + try { + long id = Long.parseLong(token); + if (id <= 0) throw new NumberFormatException("file id must be positive"); + return id; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("公告图片必须引用已上传文件", exception); + } + }) + .distinct() + .collect(Collectors.toList()); + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return List.of(); + return java.util.Arrays.stream(value.split(",")) + .map(String::trim).filter(StringUtils::hasText) + .map(token -> { try { return Long.valueOf(token); } catch (NumberFormatException ignored) { return null; } }) + .filter(id -> id != null && id > 0).distinct().collect(Collectors.toList()); + } + /** * Run business method `targetTypeName`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java index dd69afcf..2e966913 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java @@ -16,10 +16,13 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapp import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.message.service.SystemMessageService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.modules.message.vo.SystemMessageVO; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -97,10 +100,13 @@ public class SystemMessageServiceImpl extends ServiceImpl payload = new java.util.LinkedHashMap<>(); + payload.put("title", title); payload.put("content", content); payload.put("imageFileId", dto.getImageFileId()); payload.put("status", 1); + List imageIds = dto.getImageFileId() == null ? List.of() : List.of(dto.getImageFileId()); + contentModerationService.assessVersion("SYSTEM_MESSAGE", message.getId(), currentUser.getId(), + title + "\n" + content, objectMapper.writeValueAsString(payload), imageIds); + } catch (Exception exception) { + throw new IllegalStateException("站内消息审核任务创建失败", exception); + } return message.getId(); } @@ -267,7 +285,7 @@ public class SystemMessageServiceImpl extends ServiceImpl() .eq(SystemMessageDO::getIsDelete, 0) .eq(SystemMessageDO::getStatus, 1) + .eq(SystemMessageDO::getModerationStatus, "APPROVED") .orderByDesc(SystemMessageDO::getPublishTime)) .stream() .filter(message -> isMessageVisibleToUser(message, user)) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java index d068d8a7..11ec1597 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java @@ -23,6 +23,7 @@ public class AnnouncementVO { * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private String content; + private List imageFileIds; /** * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/admin/AdminOrderController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/admin/AdminOrderController.java index c809518a..d3372f7d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/admin/AdminOrderController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/admin/AdminOrderController.java @@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.order.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteSubmitDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; @@ -160,4 +162,21 @@ public class AdminOrderController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); return Result.success(orderService.confirmShopQuote(id, currentUser.getId(), currentUser.getType())); } + + /** + * 店长登记线下收款。当前仅支持 payMethod=OFFLINE,实收金额必须等于订单应付金额。 + */ + @PostMapping("/{orderId}/offline-payment") + @RequirePermission("order:process") + @OperationGuard(action = "admin-order-offline-payment", ttlSeconds = 10, message = "收款登记处理中,请勿重复提交") + public Result registerOfflinePayment(HttpServletRequest request, + @PathVariable Long orderId, + @RequestBody OrderOfflinePaymentDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (Integer.valueOf(3).equals(currentUser.getType())) { + throw new BusinessException(403, "美甲师账号不能登记线下收款"); + } + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(orderService.registerOfflinePayment(orderId, currentUser.getId(), scopedShopId, dto)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java deleted file mode 100644 index 029b3630..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.order.controller.front; - -import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.order.dto.CartDTO; -import com.xiaowang.jayucloud.salon.core.modules.order.service.CartService; -import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jayucloud.salon.core.modules.order.vo.CartVO; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@RestController -@RequestMapping("/cart") -/** - * CartController 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 CartController { - - @Resource - /** - * Purpose: cartService supports CartController.java by holding or executing the cart service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CartService cartService; - - @PostMapping("/add") - @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.addToCart(userId, cartDTO); - return Result.success(); - } - - @DeleteMapping("/remove/{productId}") - @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.removeFromCart(userId, productId); - return Result.success(); - } - - @PostMapping("/batch-remove") - @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `batchRemoveFromCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartItemIds parameter `cartItemIds` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.batchRemoveFromCart(userId, cartItemIds); - return Result.success(); - } - - @PutMapping("/update") - @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.updateCartQuantity(userId, cartDTO); - return Result.success(); - } - - @GetMapping("/list") - /** - * 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> result consumed by the caller or returned to the frontend - */ - public Result> getCartList(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - List cartList = cartService.getCartList(userId); - return Result.success(cartList); - } - - @DeleteMapping("/clear") - @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `clearCart`. - * 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 result consumed by the caller or returned to the frontend - */ - public Result clearCart(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.clearCart(userId); - return Result.success(); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java index 6f4b3663..137822d0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java @@ -3,7 +3,6 @@ package com.xiaowang.jayucloud.salon.core.modules.order.controller.front; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRejectDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRequestDTO; @@ -14,7 +13,6 @@ import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeOptionsVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeRequestVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistReviewVO; @@ -73,12 +71,6 @@ public class OrderController { return Result.success(orderVO); } - @PostMapping("/checkout-preview") - public Result checkoutPreview(@RequestBody CheckoutPreviewDTO checkoutPreviewDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.checkoutPreview(userId, checkoutPreviewDTO)); - } - @GetMapping("/list") /** * Load data by the supplied parameter. @@ -115,9 +107,11 @@ public class OrderController { * @param request parameter `request` supplied by the caller * @return Result result consumed by the caller or returned to the frontend */ - public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { + public Result cancelOrder(@PathVariable Long orderId, + @RequestParam(required = false) String cancelReason, + HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); - orderService.cancelOrder(orderId, userId); + orderService.cancelOrder(orderId, userId, cancelReason); return Result.success(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java new file mode 100644 index 00000000..dd3ff993 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 线下收款登记入参。 + * payMethod 可选 OFFLINE、CASH、WECHAT、ALIPAY;paidAmount 为实收金额,允许与订单应付金额不一致。 + */ +@Data +public class OrderOfflinePaymentDTO { + private String payMethod; + private BigDecimal paidAmount; + private LocalDateTime paidAt; + private String paidRemark; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java index a64c727d..f48299e7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java @@ -67,6 +67,9 @@ public class OrderArtistReviewDO extends BaseEntity { */ private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("rating_score") /** * Purpose: ratingScore supports OrderArtistReviewDO.java by holding or executing the rating score business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java index f32076e7..7f355301 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java @@ -1,6 +1,9 @@ package com.xiaowang.jayucloud.salon.core.modules.order.entity; import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler; import lombok.Data; import java.math.BigDecimal; @@ -8,7 +11,7 @@ import java.time.LocalDateTime; import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; @Data -@TableName("t_order") +@TableName(value = "t_order", autoResultMap = true) /** * OrderDO maps to a database table row. Mapper classes persist and query this object. * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. @@ -53,9 +56,16 @@ public class OrderDO extends BaseEntity { private String paymentMethod; private String paymentOrderNo; private String refundStatus; + private Long paidBy; + private String paidByType; + private String paidRemark; private String customerRemark; + private String cancelReason; private String customerNameSnapshot; + @TableField(typeHandler = PhoneEncryptionTypeHandler.class) private String customerPhoneSnapshot; + @TableField(value = "customer_phone_snapshot_hash", fill = FieldFill.INSERT_UPDATE) + private String customerPhoneSnapshotHash; private String quoteStatus; private String orderSource; private Integer quoteUserConfirmed; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java index 63e2fef3..249408bd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java @@ -25,6 +25,24 @@ public interface OrderArtistReviewMapper extends BaseMapper @Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1") OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId); - @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0") + @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0 AND moderation_status = 'APPROVED'") BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT COUNT(1) FROM t_order_artist_review r " + + "LEFT JOIN t_product p ON p.id = r.product_id " + + "LEFT JOIN t_shop s ON s.id = COALESCE(r.shop_id, p.shop_id) " + + "WHERE r.id = #{reviewId} AND r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' " + + "AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' " + + "AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' " + + "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReferenceByReviewId(@Param("reviewId") Long reviewId, @Param("fileId") Long fileId); + + @Select("SELECT COUNT(1) FROM t_order_artist_review r " + + "LEFT JOIN t_product p ON p.id = r.product_id " + + "LEFT JOIN t_shop s ON s.id = COALESCE(r.shop_id, p.shop_id) " + + "WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' " + + "AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' " + + "AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' " + + "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderMapper.java index d45cc85e..3aaf1ffe 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderMapper.java @@ -21,6 +21,9 @@ public interface OrderMapper extends BaseMapper { @Select("SELECT * FROM t_order WHERE order_no = #{orderNo}") OrderDO selectByOrderNo(@Param("orderNo") String orderNo); + @Select("SELECT * FROM t_order WHERE id = #{orderId} FOR UPDATE") + OrderDO selectByIdForUpdate(@Param("orderId") Long orderId); + @Select("SELECT DISTINCT o.* FROM t_order o " + "INNER JOIN t_order_item oi ON o.id = oi.order_id " + "WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " + diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java index 228bf9fe..f8c81f1a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java @@ -1,14 +1,13 @@ package com.xiaowang.jayucloud.salon.core.modules.order.service; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderDTO; -import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRejectDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRequestDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteReplyDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteSubmitDTO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistCalendarAppointmentVO; -import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeOptionsVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeRequestVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistReviewVO; @@ -31,11 +30,6 @@ public interface OrderService { */ OrderVO createOrder(Long userId, OrderDTO orderDTO); - /** - * Preview checkout pricing and coupon explanations without creating an order. - */ - CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO); - /** * 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. @@ -57,7 +51,11 @@ public interface OrderService { * @param orderId parameter `orderId` supplied by the caller * @param userId parameter `userId` supplied by the caller */ - void cancelOrder(Long orderId, Long userId); + default void cancelOrder(Long orderId, Long userId) { + cancelOrder(orderId, userId, null); + } + + void cancelOrder(Long orderId, Long userId, String cancelReason); /** * Run business method `processOrder`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -133,6 +131,11 @@ public interface OrderService { OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType); + /** + * 登记线下收款。operatorShopId 为当前操作人的门店作用域,为空表示平台管理员。 + */ + OrderVO registerOfflinePayment(Long orderId, Long operatorId, Long operatorShopId, OrderOfflinePaymentDTO dto); + OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto); OrderVO confirmUserQuote(Long orderId, Long userId); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java index d5f6f88e..175759af 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java @@ -145,6 +145,7 @@ public class AfterSaleServiceImpl implements AfterSaleService { message.setActionPath("/after-sales?afterSaleId=" + afterSale.getId()); message.setPopupEnabled(1); message.setStatus(1); + message.setModerationStatus("APPROVED"); message.setPublishTime(LocalDateTime.now()); message.setIsDelete(0); systemMessageMapper.insert(message); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java index 64c6f469..60893ee9 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java @@ -3,12 +3,13 @@ package com.xiaowang.jayucloud.salon.core.modules.order.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xiaowang.jayucloud.salon.core.common.BusinessException; -import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRejectDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRequestDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistReviewSubmitDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderItemDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteItemDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteReplyDTO; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteSubmitDTO; @@ -41,20 +42,25 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper; import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; import com.xiaowang.jayucloud.salon.core.modules.integration.service.BusinessEventOutboxService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService; import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; import com.xiaowang.jayucloud.salon.core.modules.product.service.TagService; import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStateMachine; import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistCalendarAppointmentVO; -import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutCouponPreviewVO; -import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO.CheckoutIssueVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutCouponPreviewVO; +import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeRequestVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistReviewVO; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderItemVO; @@ -128,6 +134,10 @@ public class OrderServiceImpl implements OrderService { */ private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; private static final int BOOKING_UNAVAILABLE_CODE = 409; + private static final String PAYMENT_STATUS_UNPAID = "UNPAID"; + private static final String PAYMENT_STATUS_PAID = "PAID"; + private static final String PAYMENT_METHOD_OFFLINE = "OFFLINE"; + private static final String PAID_BY_TYPE_SHOP_MANAGER = "SHOP_MANAGER"; private static final String ISSUE_ORDER_ITEM = "ORDER_ITEM"; private static final String ISSUE_PRODUCT_UNAVAILABLE = "PRODUCT_UNAVAILABLE"; private static final String ISSUE_SHOP_MISMATCH = "SHOP_MISMATCH"; @@ -284,6 +294,15 @@ public class OrderServiceImpl implements OrderService { */ private OrderArtistReviewMapper orderArtistReviewMapper; + @Resource + private ContentModerationService contentModerationService; + + @Resource + private ObjectStorageFileService objectStorageFileService; + + @Resource + private ObjectMapper objectMapper; + @Resource /** * Purpose: orderArtistChangeRequestMapper supports OrderServiceImpl.java by holding or executing the order artist change request mapper business role. @@ -419,6 +438,9 @@ public class OrderServiceImpl implements OrderService { @Resource private AppointmentReservationMapper appointmentReservationMapper; + @Resource + private WechatSubscribeMessageService wechatSubscribeMessageService; + @PreDestroy /** * Run business method `shutdownOrderLockRenewExecutor`. @@ -530,53 +552,6 @@ public class OrderServiceImpl implements OrderService { } } - @Override - public CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO) { - OrderDTO orderDTO = toOrderDTO(checkoutPreviewDTO); - CheckoutPricingContext pricingContext = buildCheckoutPricingContext(userId, orderDTO); - List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); - List availableCouponOptions = couponService.getAvailableCoupons( - userId, - pricingContext.getProductTagNames(), - pricingContext.getTotalAmount().doubleValue(), - pricingContext.getShopId() - ); - if (availableCouponOptions == null) { - availableCouponOptions = List.of(); - } - - List availableCoupons = availableCouponOptions.stream() - .map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount())) - .sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed() - .thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))) - .toList(); - - CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons); - if (bestCoupon != null) { - bestCoupon.setBest(true); - } - - CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon); - BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount()); - BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount); - if (payableAmount.compareTo(BigDecimal.ZERO) < 0) { - payableAmount = BigDecimal.ZERO; - } - - CheckoutPreviewVO preview = new CheckoutPreviewVO(); - preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount())); - preview.setSavedAmount(scaleMoney(savedAmount)); - preview.setPayableAmount(scaleMoney(payableAmount)); - preview.setBestCoupon(bestCoupon); - preview.setAvailableCoupons(availableCoupons); - preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext)); - preview.setBookingAvailable(bookingIssues.isEmpty()); - preview.setBookingIssues(bookingIssues); - preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons)); - preview.setSummaryText(buildCheckoutSummaryText(preview)); - return preview; - } - /** * Create a new record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -836,63 +811,6 @@ public class OrderServiceImpl implements OrderService { return buildOrderVO(order); } - private OrderDTO toOrderDTO(CheckoutPreviewDTO checkoutPreviewDTO) { - OrderDTO orderDTO = new OrderDTO(); - if (checkoutPreviewDTO == null) { - return orderDTO; - } - orderDTO.setCouponId(checkoutPreviewDTO.getCouponId()); - orderDTO.setCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); - orderDTO.setRemark(checkoutPreviewDTO.getRemark()); - orderDTO.setItems(checkoutPreviewDTO.getItems()); - return orderDTO; - } - - private CheckoutPricingContext buildCheckoutPricingContext(Long userId, OrderDTO orderDTO) { - if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { - throw new RuntimeException("订单项不能为空"); - } - - List orderItemDTOs = orderDTO.getItems(); - Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); - BigDecimal totalAmount = BigDecimal.ZERO; - Set selectedTagNames = new LinkedHashSet<>(); - Long shopId = null; - - for (OrderItemDTO orderItemDTO : orderItemDTOs) { - validateOrderQuantity(orderItemDTO.getQuantity()); - ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - throw new RuntimeException("商品不存在或已下架"); - } - - CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId()); - Integer requestedQuantity = requestedQuantityByProductId.get(product.getId()); - if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) { - throw new RuntimeException("请先将商品加入购物车后再结算"); - } - if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { - throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); - } - - if (shopId == null) { - shopId = product.getShopId(); - validateUserCanCreateOrderInShop(userId, shopId); - } else if (!shopId.equals(product.getShopId())) { - throw new RuntimeException("跨店铺商品请分开下单"); - } - - collectPreviewTagNames(selectedTagNames, product.getTags()); - BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()))); - } - - if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { - throw new RuntimeException("订单金额无效"); - } - return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames)); - } - private List collectCheckoutBookingIssues(Long userId, OrderDTO orderDTO) { List issues = new ArrayList<>(); if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { @@ -1454,6 +1372,12 @@ public class OrderServiceImpl implements OrderService { * @param userId parameter `userId` supplied by the caller */ public void cancelOrder(Long orderId, Long userId) { + cancelOrder(orderId, userId, null); + } + + @Override + @Transactional + public void cancelOrder(Long orderId, Long userId, String cancelReason) { OrderDO order = orderMapper.selectById(orderId); if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { /** @@ -1483,6 +1407,8 @@ public class OrderServiceImpl implements OrderService { OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.CANCELLED.getCode()); order.setStatus(3); + String normalizedReason = StringUtils.hasText(cancelReason) ? cancelReason.trim() : "客户取消预约"; + order.setCancelReason(normalizedReason.length() > 255 ? normalizedReason.substring(0, 255) : normalizedReason); if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { order.setQuoteStatus(QUOTE_STATUS_EXPIRED); order.setQuoteUserConfirmed(0); @@ -1491,6 +1417,7 @@ public class OrderServiceImpl implements OrderService { } orderMapper.updateById(order); appointmentCapacityService.releaseByOrder(orderId); + enqueueCancellationMessages(orderId); /** * Run business method `restoreUserCoupon`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -1532,6 +1459,9 @@ public class OrderServiceImpl implements OrderService { && !"HISTORICAL_BACKFILL".equals(order.getOrderSource())) { throw new RuntimeException("普通预约不能进入服务中状态"); } + if (targetStatus == OrderStatus.COMPLETED) { + ensurePaidBeforeCompletion(order); + } if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) && !(Integer.valueOf(OrderStatus.IN_SERVICE.getCode()).equals(order.getStatus()) && (status == OrderStatus.COMPLETED.getCode() || status == OrderStatus.CANCELLED.getCode())) @@ -1550,12 +1480,17 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("订单状态已变化,请刷新后重试"); } order.setStatus(status); + if (targetStatus == OrderStatus.CANCELLED && !StringUtils.hasText(order.getCancelReason())) { + order.setCancelReason("门店取消预约"); + } + orderMapper.updateById(order); if (targetStatus == OrderStatus.COMPLETED) { businessEventOutboxService.enqueueOrderCompleted(order.getId()); } if (targetStatus == OrderStatus.CANCELLED) { appointmentCapacityService.releaseByOrder(order.getId()); restoreUserCoupon(order, order.getUserId()); + enqueueCancellationMessages(order.getId()); if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { order.setQuoteStatus(QUOTE_STATUS_EXPIRED); order.setQuoteUserConfirmed(0); @@ -1566,6 +1501,21 @@ public class OrderServiceImpl implements OrderService { } } + private void enqueueCancellationMessages(Long orderId) { + if (orderId == null) { + return; + } + List items = orderItemMapper.selectByOrderId(orderId); + if (items == null) { + return; + } + for (OrderItemDO item : items) { + if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) { + wechatSubscribeMessageService.enqueueCancellationNotice(orderId, item.getId()); + } + } + } + @Override @Transactional /** @@ -1592,6 +1542,7 @@ public class OrderServiceImpl implements OrderService { */ throw new RuntimeException("当前订单状态不允许完成"); } + ensurePaidBeforeCompletion(order); List activeItems = orderItemMapper.selectByOrderId(orderId).stream() .filter(item -> !Integer.valueOf(1).equals(item.getIsDelete())) @@ -1791,9 +1742,25 @@ public class OrderServiceImpl implements OrderService { review.setRatingScore(rating); review.setContent(trimToNull(dto == null ? null : dto.getContent())); review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds())); + review.setModerationStatus("PENDING"); review.setStatus(REVIEW_STATUS_SUBMITTED); review.setSubmittedAt(LocalDateTime.now()); orderArtistReviewMapper.updateById(review); + try { + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("content", review.getContent()); + payload.put("imageFileIds", review.getImageFileIds()); + List imageIds = parseIdSet(review.getImageFileIds()).stream().toList(); + ContentModerationResultVO moderation = contentModerationService.assessVersion( + "ORDER_ARTIST_REVIEW", review.getId(), userId, review.getContent(), + objectMapper.writeValueAsString(payload), imageIds); + if (moderation != null && "APPROVED".equals(moderation.getStatus())) { + review.setModerationStatus("APPROVED"); + orderArtistReviewMapper.updateById(review); + } + } catch (Exception exception) { + throw new IllegalStateException("评价审核任务创建失败", exception); + } refreshArtistRating(review.getArtistId()); return buildArtistReviewVO(review); } @@ -1850,6 +1817,69 @@ public class OrderServiceImpl implements OrderService { return buildOrderVO(orderMapper.selectById(order.getId())); } + @Override + @Transactional + public OrderVO registerOfflinePayment(Long orderId, Long operatorId, Long operatorShopId, OrderOfflinePaymentDTO dto) { + if (orderId == null) { + throw new RuntimeException("订单ID不能为空"); + } + if (dto == null) { + throw new RuntimeException("收款登记信息不能为空"); + } + String payMethod = dto.getPayMethod() == null ? "" : dto.getPayMethod().trim().toUpperCase(); + if (!PAYMENT_METHOD_OFFLINE.equals(payMethod) + && !"CASH".equals(payMethod) + && !"WECHAT".equals(payMethod) + && !"ALIPAY".equals(payMethod)) { + throw new RuntimeException("payMethod 只能为 OFFLINE、CASH、WECHAT 或 ALIPAY"); + } + if (dto.getPaidAmount() == null) { + throw new RuntimeException("实收金额不能为空"); + } + if (dto.getPaidAmount().compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("实收金额不能小于0"); + } + String paidRemark = trimToNull(dto.getPaidRemark()); + if (paidRemark != null && paidRemark.length() > 500) { + throw new RuntimeException("收款备注不能超过500个字符"); + } + + OrderDO order = orderMapper.selectByIdForUpdate(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + if (operatorShopId != null && !operatorShopId.equals(order.getShopId())) { + throw new BusinessException(403, "无权处理其他店铺订单"); + } + if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { + throw new RuntimeException("订单已取消,不能登记收款"); + } + + LocalDateTime paidAt = (dto.getPaidAt() == null ? LocalDateTime.now() : dto.getPaidAt()).withNano(0); + if (PAYMENT_STATUS_PAID.equals(order.getPaymentStatus())) { + boolean sameMethod = payMethod.equals(order.getPaymentMethod()); + boolean sameAmount = order.getPaidAmount() != null && order.getPaidAmount().compareTo(dto.getPaidAmount()) == 0; + boolean sameTime = order.getPayTime() != null && order.getPayTime().withNano(0).equals(paidAt); + if (sameMethod && sameAmount && sameTime) { + return buildOrderVO(order); + } + throw new RuntimeException("该订单已登记收款,金额或收款方式与首次登记不一致,不能重复登记"); + } + if (order.getPaymentStatus() != null && !PAYMENT_STATUS_UNPAID.equals(order.getPaymentStatus())) { + throw new RuntimeException("订单当前支付状态为 " + order.getPaymentStatus() + ",不能登记线下收款"); + } + + order.setPaymentStatus(PAYMENT_STATUS_PAID); + order.setPaymentMethod(payMethod); + order.setPaidAmount(dto.getPaidAmount()); + order.setPayTime(paidAt); + order.setPaidBy(operatorId); + order.setPaidByType(PAID_BY_TYPE_SHOP_MANAGER); + order.setPaidRemark(paidRemark); + orderMapper.updateById(order); + return buildOrderVO(order); + } + @Override @Transactional public OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto) { @@ -2144,6 +2174,7 @@ public class OrderServiceImpl implements OrderService { review.setArtistId(item.getArtistId()); review.setCustomerId(order.getUserId()); review.setStatus(REVIEW_STATUS_PENDING); + review.setModerationStatus("APPROVED"); review.setIsDelete(0); review = insertPendingArtistReview(review); if (review == null || review.getId() == null) { @@ -2220,8 +2251,11 @@ public class OrderServiceImpl implements OrderService { vo.setCustomerId(review.getCustomerId()); vo.setRating(review.getRatingScore()); vo.setRatingScore(review.getRatingScore()); - vo.setContent(review.getContent()); - vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds()))); + boolean moderationApproved = "APPROVED".equals(review.getModerationStatus()); + vo.setContent(moderationApproved ? review.getContent() : null); + vo.setImageFileIds(moderationApproved + ? new ArrayList<>(parseIdSet(review.getImageFileIds())) + : new ArrayList<>()); vo.setStatus(review.getStatus()); vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价"); vo.setReminderMessageId(review.getReminderMessageId()); @@ -2296,9 +2330,18 @@ public class OrderServiceImpl implements OrderService { } /** - * Purpose: trimToNull supports OrderServiceImpl.java by holding or executing the trim to null business role. + * 完成订单前强制校验收款状态:未收款不得完成,不设任何豁免。 * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ + /** + * 完成订单前强制校验收款状态:未收款不得完成,不设任何豁免。 + */ + private void ensurePaidBeforeCompletion(OrderDO order) { + if (!PAYMENT_STATUS_PAID.equals(order.getPaymentStatus())) { + throw new RuntimeException("订单未收款,不能完成;请先登记线下收款"); + } + } + private String trimToNull(String value) { if (!StringUtils.hasText(value)) { return null; @@ -3063,6 +3106,7 @@ public class OrderServiceImpl implements OrderService { message.setActionPath(actionPath); message.setPopupEnabled(1); message.setStatus(1); + message.setModerationStatus("APPROVED"); message.setPublishTime(LocalDateTime.now()); message.setIsDelete(0); systemMessageMapper.insert(message); @@ -3102,6 +3146,7 @@ public class OrderServiceImpl implements OrderService { message.setIdempotencyKey(idempotencyKey); message.setPopupEnabled(1); message.setStatus(1); + message.setModerationStatus("APPROVED"); message.setPublishTime(LocalDateTime.now()); message.setIsDelete(0); try { @@ -3320,6 +3365,13 @@ public class OrderServiceImpl implements OrderService { orderVO.setPaymentMethod(order.getPaymentMethod()); orderVO.setPaymentOrderNo(order.getPaymentOrderNo()); orderVO.setRefundStatus(order.getRefundStatus()); + orderVO.setPaidBy(order.getPaidBy()); + orderVO.setPaidByType(order.getPaidByType()); + orderVO.setPaidRemark(order.getPaidRemark()); + if (order.getPaidBy() != null) { + UserDO payer = getUserFromCache(order.getPaidBy(), userCache); + orderVO.setPaidByName(payer == null ? null : payer.getNickname()); + } orderVO.setCustomerRemark(order.getCustomerRemark()); orderVO.setQuoteStatus(order.getQuoteStatus()); orderVO.setQuoteStatusText(resolveQuoteStatusText(order.getQuoteStatus(), order.getStatus())); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/vo/OrderVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/vo/OrderVO.java index e25bed5f..dffd286b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/vo/OrderVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/vo/OrderVO.java @@ -64,6 +64,10 @@ public class OrderVO { private String paymentMethod; private String paymentOrderNo; private String refundStatus; + private Long paidBy; + private String paidByName; + private String paidByType; + private String paidRemark; private String customerRemark; private String quoteStatus; private String orderSource; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java deleted file mode 100644 index 45e4fc77..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.admin; - -import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService; -import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; -import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.RefundOrderVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/admin/payment") -@RequiredArgsConstructor -public class AdminPaymentController { - - private final PaymentService paymentService; - private final AdminScopeHelper adminScopeHelper; - private final SecurityAuditSupport securityAuditSupport; - - @PostMapping("/order/{orderId}/manual-confirm") - @RequirePermission("payment:manage") - public Result manualConfirm(HttpServletRequest request, - @PathVariable Long orderId, - @RequestParam(required = false) String remark) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - try { - PaymentOrderVO result = paymentService.manualConfirmOrderPaid(currentUser.getId(), orderId, remark); - securityAuditSupport.success(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/order/{orderId}/manual-refund") - @RequirePermission("refund:manage") - public Result manualRefund(HttpServletRequest request, - @PathVariable Long orderId, - @RequestParam(required = false) Long afterSaleId, - @RequestParam(required = false) String remark) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - try { - RefundOrderVO result = paymentService.manualRefundOrder(currentUser.getId(), orderId, afterSaleId, remark); - securityAuditSupport.success(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java deleted file mode 100644 index 87f1c49b..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceChangeDetailDTO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceChangeDetailService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户余额变动明细表 Controller - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"}) -@RequiredArgsConstructor -public class BalanceChangeDetailController { - /** - * Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceChangeDetailService balanceChangeDetailService; - - /** - * 创建余额变动明细 - * - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 余额变动明细ID - */ - @PostMapping("/create") - public Result createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO); - return Result.success(id); - } - - /** - * 更新余额变动明细 - * - * @param id 余额变动明细ID - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO); - return Result.success(success); - } - - /** - * 删除余额变动明细 - * - * @param id 余额变动明细ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalanceChangeDetail(@PathVariable Long id) { - boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id); - return Result.success(success); - } - - /** - * 根据ID查询余额变动明细 - * - * @param id 余额变动明细ID - * @return 余额变动明细VO - */ - @GetMapping("/get/{id}") - public Result getBalanceChangeDetailById(@PathVariable Long id) { - BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id); - return Result.success(balanceChangeDetailVO); - } - - /** - * 查询所有余额变动明细 - * - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalanceChangeDetails() { - List balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails(); - return Result.success(balanceChangeDetailVOs); - } - - /** - * 根据用户ID查询余额变动明细 - * - * @param userId 用户ID - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/user/{userId}") - public Result> listBalanceChangeDetailsByUserId(@PathVariable Long userId) { - List balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId); - return Result.success(balanceChangeDetailVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java deleted file mode 100644 index c625c430..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceDTO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户余额信息表 Controller - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/balance", "/api/balance"}) -@RequiredArgsConstructor -public class BalanceController { - /** - * Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceService balanceService; - - /** - * 创建余额 - * - * @param balanceDTO 余额DTO - * @return 余额ID - */ - @PostMapping("/create") - public Result createBalance(@RequestBody BalanceDTO balanceDTO) { - Long id = balanceService.createBalance(balanceDTO); - return Result.success(id); - } - - /** - * 更新余额 - * - * @param id 余额ID - * @param balanceDTO 余额DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) { - boolean success = balanceService.updateBalance(id, balanceDTO); - return Result.success(success); - } - - /** - * 删除余额 - * - * @param id 余额ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalance(@PathVariable Long id) { - boolean success = balanceService.deleteBalance(id); - return Result.success(success); - } - - /** - * 根据ID查询余额 - * - * @param id 余额ID - * @return 余额VO - */ - @GetMapping("/get/{id}") - public Result getBalanceById(@PathVariable Long id) { - BalanceVO balanceVO = balanceService.getBalanceById(id); - return Result.success(balanceVO); - } - - /** - * 查询所有余额 - * - * @return 余额VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalances() { - List balanceVOs = balanceService.listAllBalances(); - return Result.success(balanceVOs); - } - - /** - * 根据用户ID查询余额 - * - * @param userId 用户ID - * @return 余额VO - */ - @GetMapping("/get/user/{userId}") - public Result getBalanceByUserId(@PathVariable Long userId) { - BalanceVO balanceVO = balanceService.getBalanceByUserId(userId); - return Result.success(balanceVO); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/PaymentController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/PaymentController.java deleted file mode 100644 index 09e832e5..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/PaymentController.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front; - -import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/payment") -@RequiredArgsConstructor -public class PaymentController { - - private final PaymentService paymentService; - - @PostMapping("/order/{orderId}/prepare") - public Result prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.prepareOrderPayment(userId, orderId)); - } - - @PostMapping("/order/{orderId}/mock-success") - public Result mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java index b11e4eea..0c7c28fd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java @@ -8,6 +8,7 @@ import java.math.BigDecimal; public class PlanningAppointmentCreateDTO { private Long customerUserId; private String customerName; + private String wechatId; private String phone; private Long productId; private Integer quantity; @@ -16,6 +17,8 @@ public class PlanningAppointmentCreateDTO { private String appointmentTime; private String appointmentStartTime; private Integer durationMinutes; + private BigDecimal amount; + private Boolean createCustomerRecord; private String manualProductTitle; private BigDecimal manualProductPrice; private String manualProductDescription; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java index 62f84b9d..6bfa9163 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java @@ -5,4 +5,5 @@ import lombok.Data; @Data public class PlanningAppointmentStatusDTO { private Integer status; + private String cancelReason; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java index cf6247a7..e4596e53 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java @@ -9,8 +9,15 @@ public class PlanningBackfillOrderCreateDTO { private Long productId; private String manualProductTitle; private BigDecimal manualProductPrice; + private Integer durationMinutes; + private String manualProductDescription; + private String manualProductTags; + private String manualProductTargetAudience; + private String manualProductPrecautions; + private String manualProductImageFileIds; private Long customerUserId; private String customerName; + private String wechatId; private String phone; private String serviceDate; private String serviceTime; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java index 3de9d6d6..35861e04 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java @@ -22,6 +22,8 @@ public interface PlanningService { PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId); + PlanningAppointmentVO updateAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentCreateDTO dto); + PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto); Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index 21a076f2..de438205 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -22,15 +22,24 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService; import com.xiaowang.jayucloud.salon.core.modules.planning.service.PlanningService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningCalendarSupport; import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningTodayOverviewSupport; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistCountVO; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistVO; @@ -39,10 +48,12 @@ import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningDaySummaryV import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningScheduleVO; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningTodayOverviewVO; import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; @@ -71,7 +82,6 @@ public class PlanningServiceImpl implements PlanningService { private static final String RESERVATION_UNASSIGNED = "UNASSIGNED"; private static final String ASSIGNMENT_ASSIGNED = "ASSIGNED"; 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 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 ARTIST_COLORS = List.of( @@ -80,6 +90,7 @@ public class PlanningServiceImpl implements PlanningService { private final AdminScopeHelper adminScopeHelper; private final UserMapper userMapper; + private final UserService userService; private final NailArtistInfoMapper nailArtistInfoMapper; private final ArtistScheduleMapper artistScheduleMapper; private final ArtistScheduleExceptionMapper artistScheduleExceptionMapper; @@ -88,9 +99,15 @@ public class PlanningServiceImpl implements PlanningService { private final OrderItemMapper orderItemMapper; private final ProductMapper productMapper; private final ShopMapper shopMapper; + private final ShopBusinessExpiryService shopBusinessExpiryService; + private final ShopBusinessScheduleService shopBusinessScheduleService; private final AppointmentCapacityService appointmentCapacityService; private final OrderService orderService; + private final WechatSubscribeMessageService wechatSubscribeMessageService; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ObjectStorageFileService objectStorageFileService; + private final PhoneCrypto phoneCrypto; @Override public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) { @@ -105,11 +122,20 @@ public class PlanningServiceImpl implements PlanningService { Long shopId = requirePlanningShopId(currentUser); ShopDO shop = shopMapper.selectById(shopId); - PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours( - shop == null ? null : shop.getBusinessHours() - ); + Map weeklyHours = shopBusinessScheduleService.mapByDay( + shopId, shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours())); + PlanningCalendarSupport.BusinessHours businessHours = null; + for (int dayOfWeek = 1; dayOfWeek <= 7 && businessHours == null; dayOfWeek++) { + ShopBusinessHoursDayVO day = weeklyHours.get(dayOfWeek); + if (day != null && Boolean.TRUE.equals(day.getOpen())) { + businessHours = parseConfiguredBusinessHours(day.getStartTime() + "-" + day.getEndTime()); + } + } + boolean artistFiltered = artistId != null && artistId > 0; List artists = listArtists(shopId, artistId); + List artistOptions = artistFiltered ? listArtists(shopId, null) : artists; List schedules = listSchedules(shopId, start, end, artistId); Map artistNames = artists.stream() .collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a)); @@ -127,15 +153,26 @@ public class PlanningServiceImpl implements PlanningService { .filter(appointment -> appointment.getArtistId() != null) .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue())); + if (artistFiltered) { + List rangeAppointments = listAppointments(shopId, rangeStart, rangeEnd, null, artistOptions); + Map optionCountByArtist = rangeAppointments.stream() + .filter(appointment -> appointment.getArtistId() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); + artistOptions.forEach(artist -> artist.setRangeCount( + optionCountByArtist.getOrDefault(artist.getId(), 0L).intValue())); + } PlanningCalendarVO vo = new PlanningCalendarVO(); - vo.setBusinessStartTime(businessHours.start().toString()); - vo.setBusinessEndTime(businessHours.end().toString()); + vo.setBusinessStartTime(businessHours == null ? null : businessHours.start().toString()); + vo.setBusinessEndTime(businessHours == null ? null : businessHours.end().toString()); + vo.setDefaultAppointmentDurationMinutes(shop == null || shop.getDefaultAppointmentDurationMinutes() == null + || shop.getDefaultAppointmentDurationMinutes() <= 0 ? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes()); vo.setSlotMinutes(DEFAULT_SLOT_MINUTES); vo.setArtists(artists); + vo.setArtistOptions(artistOptions); vo.setSchedules(scheduleVos); vo.setAppointments(appointments); - vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments)); + vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments, weeklyHours)); return vo; } @@ -170,23 +207,38 @@ public class PlanningServiceImpl implements PlanningService { throw new RuntimeException("美甲师账号只能查看预约,不能新建预约"); } Long shopId = requirePlanningShopId(currentUser); - requireAppointmentDuration(dto.getDurationMinutes()); - ProductDO product = resolveAppointmentProduct(dto, shopId); - UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); - UserDO customer = resolveCustomer(shopId, dto); - + shopBusinessExpiryService.assertShopActive(shopId); + ShopDO shop = shopMapper.selectById(shopId); + int shopDefaultDuration = resolveShopDefaultDuration(shop); int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity(); - int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity; + ProductDO product = dto.getProductId() == null ? null : requireActiveProduct(dto.getProductId(), shopId); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity; LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureFutureAppointmentTime(startTime); ensureWithinBusinessHours(shopId, startTime, endTime); + if (product == null) { + product = createManualAppointmentProduct(dto, shopId, shopDefaultDuration); + durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity; + endTime = startTime.plusMinutes(durationMinutes); + ensureWithinBusinessHours(shopId, startTime, endTime); + } + UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); + UserDO customer = resolveCustomer(currentUser, shopId, dto); BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity)); + BigDecimal amount = dto.getAmount() == null + ? unitPrice.multiply(BigDecimal.valueOf(quantity)) + : dto.getAmount(); + if (amount.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } OrderDO order = new OrderDO(); order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); - order.setUserId(customer.getId()); + order.setUserId(customer == null ? null : customer.getId()); + order.setCustomerNameSnapshot(customer == null ? trimToNull(dto.getCustomerName()) : null); + order.setCustomerPhoneSnapshot(customer == null ? trimToNull(dto.getPhone()) : null); order.setShopId(shopId); order.setTotalAmount(amount); order.setActualAmount(amount); @@ -207,7 +259,7 @@ public class PlanningServiceImpl implements PlanningService { item.setOrderId(order.getId()); item.setProductId(product.getId()); item.setQuantity(quantity); - item.setPrice(unitPrice); + item.setPrice(amount.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP)); item.setArtistId(artist == null ? null : artist.getId()); item.setAppointmentTime(startTime); item.setIsDelete(0); @@ -224,6 +276,8 @@ public class PlanningServiceImpl implements PlanningService { endTime, trimToNull(dto.getClientRequestId()) ); + wechatSubscribeMessageService.enqueueAppointmentReminder(order.getId(), item.getId()); + wechatSubscribeMessageService.enqueueServiceStartReminder(order.getId(), item.getId(), startTime); } return getAppointment(currentUser, item.getId()); @@ -248,6 +302,14 @@ public class PlanningServiceImpl implements PlanningService { BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); if (price == null || price.compareTo(BigDecimal.ZERO) < 0) throw new RuntimeException("项目金额不能小于0"); product = new ProductDO(); product.setShopId(shopId); product.setTitle(title); product.setPrice(price); + 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())); + int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0 ? DEFAULT_DURATION_MINUTES : dto.getDurationMinutes(); + product.setApproximateDuration(durationMinutes + "分钟"); + product.setBookableArtists(String.valueOf(dto.getArtistId())); product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT); product.setFrontVisible(0); product.setLikeCount(0); product.setCollectCount(0); product.setIsDelete(0); productMapper.insert(product); } @@ -294,7 +356,148 @@ public class PlanningServiceImpl implements PlanningService { Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); Map customerMap = order.getUserId() == null ? Map.of() : loadUsers(Set.of(order.getUserId())); - return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); + return toAppointmentVO(reservation, item, order, product, customer, artistMap); + } + + @Override + @Transactional + public PlanningAppointmentVO updateAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentCreateDTO dto) { + if (dto == null) { + throw new RuntimeException("预约信息不能为空"); + } + if (orderItemId == null) { + throw new RuntimeException("预约ID不能为空"); + } + if (Integer.valueOf(3).equals(currentUser.getType())) { + 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()); + if ("HISTORICAL_BACKFILL".equals(order.getOrderSource())) { + throw new RuntimeException("历史补单不支持编辑预约"); + } + int currentStatus = order.getStatus() == null ? -1 : order.getStatus(); + if (currentStatus == OrderStatus.COMPLETED.getCode()) { + throw new RuntimeException("预约已完成,不能编辑"); + } + if (currentStatus == OrderStatus.CANCELLED.getCode()) { + throw new RuntimeException("预约已取消,不能编辑"); + } + if (currentStatus == OrderStatus.IN_SERVICE.getCode()) { + throw new RuntimeException("服务中的预约不能编辑"); + } + if (currentStatus != OrderStatus.PRICE_CONFIRMING.getCode() + && currentStatus != OrderStatus.PENDING_SERVICE.getCode()) { + throw new RuntimeException("当前状态不可编辑预约"); + } + + Long shopId = order.getShopId(); + ShopDO shop = shopMapper.selectById(shopId); + int shopDefaultDuration = resolveShopDefaultDuration(shop); + int quantity = item.getQuantity() == null || item.getQuantity() <= 0 ? 1 : item.getQuantity(); + ProductDO product = resolveUpdateProduct(dto, item, shopId, shopDefaultDuration); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity; + LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + + boolean timeChanged = item.getAppointmentTime() == null || !item.getAppointmentTime().equals(startTime); + if (timeChanged) { + ensureFutureAppointmentTime(startTime); + } + ensureWithinBusinessHours(shopId, startTime, endTime); + + UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); + boolean artistChanged = !Objects.equals(item.getArtistId(), artist == null ? null : artist.getId()); + + BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + BigDecimal amount = dto.getAmount() == null + ? unitPrice.multiply(BigDecimal.valueOf(quantity)) + : dto.getAmount(); + if (amount.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } + boolean paid = "PAID".equals(order.getPaymentStatus()); + BigDecimal currentAmount = order.getActualAmount(); + if (paid && (currentAmount == null || currentAmount.compareTo(amount) != 0)) { + throw new RuntimeException("订单已收款,不能修改成交金额"); + } + + UserDO customer = resolveCustomer(currentUser, shopId, dto); + order.setUserId(customer == null ? null : customer.getId()); + order.setCustomerNameSnapshot(customer == null ? trimToNull(dto.getCustomerName()) : null); + order.setCustomerPhoneSnapshot(customer == null ? trimToNull(dto.getPhone()) : null); + order.setCustomerRemark(trimToNull(dto.getRemark())); + if (!paid) { + order.setTotalAmount(amount); + order.setActualAmount(amount); + order.setPayAmount(amount); + } + orderMapper.updateById(order); + + item.setProductId(product.getId()); + item.setPrice(amount.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP)); + item.setArtistId(artist == null ? null : artist.getId()); + item.setAppointmentTime(startTime); + item.setIsDelete(0); + orderItemMapper.updateById(item); + + if (artist != null && (artistChanged || timeChanged)) { + appointmentCapacityService.moveReservationForArtistChange( + order.getId(), + item.getId(), + shopId, + artist.getId(), + artist.getId(), + product.getTitle(), + startTime, + endTime + ); + } else if (artist == null && artistChanged) { + appointmentReservationMapper.releaseByOrderItem(item.getId(), "RELEASED"); + } + return getAppointment(currentUser, item.getId()); + } + + private ProductDO resolveUpdateProduct(PlanningAppointmentCreateDTO dto, OrderItemDO item, Long shopId, int shopDefaultDuration) { + if (dto.getProductId() != null) { + return requireActiveProduct(dto.getProductId(), shopId); + } + String title = trimToNull(dto.getManualProductTitle()); + if (!hasText(title)) { + throw new RuntimeException("请填写美甲款式名称"); + } + ProductDO existing = item.getProductId() == null ? null : productMapper.selectById(item.getProductId()); + boolean editableManualProduct = existing != null + && PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT.equals(existing.getSourceType()) + && !Integer.valueOf(1).equals(existing.getIsDelete()) + && shopId.equals(existing.getShopId()); + if (!editableManualProduct) { + return createManualAppointmentProduct(dto, shopId, shopDefaultDuration); + } + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null) { + price = BigDecimal.ZERO; + } + if (price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } + int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0 + ? shopDefaultDuration : dto.getDurationMinutes(); + existing.setTitle(title); + existing.setDescription(trimToNull(dto.getManualProductDescription())); + existing.setTags(trimToNull(dto.getManualProductTags())); + existing.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); + existing.setPrecautions(trimToNull(dto.getManualProductPrecautions())); + existing.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + existing.setPrice(price); + existing.setApproximateDuration(durationMinutes + "分钟"); + existing.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId())); + productMapper.updateById(existing); + return existing; } @Override @@ -311,7 +514,8 @@ public class PlanningServiceImpl implements PlanningService { 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()) * + ShopDO shop = shopMapper.selectById(order.getShopId()); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), resolveShopDefaultDuration(shop)) * 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()) @@ -320,6 +524,7 @@ public class PlanningServiceImpl implements PlanningService { throw new RuntimeException("预约时间不能为空"); } LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureFutureAppointmentTime(startTime); ensureWithinBusinessHours(order.getShopId(), startTime, endTime); appointmentCapacityService.moveReservationForArtistChange( @@ -336,6 +541,8 @@ public class PlanningServiceImpl implements PlanningService { item.setArtistId(artist.getId()); item.setAppointmentTime(startTime); orderItemMapper.updateById(item); + wechatSubscribeMessageService.enqueueAppointmentReminder(order.getId(), item.getId()); + wechatSubscribeMessageService.enqueueServiceStartReminder(order.getId(), item.getId(), startTime); return getAppointment(currentUser, item.getId()); } @@ -356,6 +563,13 @@ public class PlanningServiceImpl implements PlanningService { } return true; } + if (targetStatus == OrderStatus.CANCELLED.getCode()) { + order.setCancelReason(StringUtils.hasText(dto.getCancelReason()) ? dto.getCancelReason().trim() : "门店取消预约"); + if (order.getCancelReason().length() > 255) { + order.setCancelReason(order.getCancelReason().substring(0, 255)); + } + orderMapper.updateById(order); + } orderService.processOrder(orderId, targetStatus); return true; } @@ -392,8 +606,9 @@ public class PlanningServiceImpl implements PlanningService { 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.setAvatar(objectStorageUrlSupport.toAccessibleUrl(user.getAvatar())); + vo.setColor(info != null && StringUtils.hasText(info.getColor()) + ? info.getColor() : 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()); @@ -515,7 +730,7 @@ public class PlanningServiceImpl implements PlanningService { continue; } ProductDO product = item == null ? null : productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap)); if (reservation.getOrderItemId() != null) { reservationItemIds.add(reservation.getOrderItemId()); @@ -530,7 +745,7 @@ public class PlanningServiceImpl implements PlanningService { continue; } ProductDO product = productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); result.add(toAppointmentVO(null, item, order, product, customer, artistMap)); } result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo)) @@ -544,7 +759,8 @@ public class PlanningServiceImpl implements PlanningService { if (start == null && item != null) { start = item.getAppointmentTime(); } - int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity()); + ShopDO shop = order == null || order.getShopId() == null ? null : shopMapper.selectById(order.getShopId()); + int durationMinutes = resolveDurationMinutes(product, null, resolveShopDefaultDuration(shop)) * 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); @@ -561,11 +777,16 @@ public class PlanningServiceImpl implements PlanningService { 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(order == null ? null : order.getCustomerNameSnapshot(), "散客") : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); - vo.setCustomerPhone(customer == null ? order == null ? null : order.getCustomerPhoneSnapshot() : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); + String plainPhone = customer == null + ? (order == null ? null : order.getCustomerPhoneSnapshot()) + : firstNonBlank(customer.getContactPhone(), customer.getPhone(), ""); + vo.setCustomerPhone(phoneCrypto.mask(plainPhone)); + vo.setCustomerPhoneAvailable(StringUtils.hasText(plainPhone) && !plainPhone.contains("*")); 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.setCoverImages(resolveProductCoverImages(product)); vo.setArtistId(artistId); boolean unassigned = artistId == null; vo.setArtistName(unassigned ? "待分配" : artist == null ? "美甲师" : artist.getName()); @@ -587,11 +808,24 @@ public class PlanningServiceImpl implements PlanningService { vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus)); vo.setAmount(order == null ? null : order.getActualAmount()); vo.setRemark(order == null ? null : order.getCustomerRemark()); + vo.setCancelReason(order == null ? null : order.getCancelReason()); + vo.setProductSourceType(product == null ? null : product.getSourceType()); + vo.setProductDescription(product == null ? null : product.getDescription()); + vo.setProductTags(product == null ? null : product.getTags()); + vo.setProductTargetAudience(product == null ? null : product.getTargetAudience()); + vo.setProductPrecautions(product == null ? null : product.getPrecautions()); + vo.setProductImageFileIds(product == null ? null : product.getImageFileIds()); + vo.setPaymentStatus(order == null ? null : order.getPaymentStatus()); + vo.setPaymentMethod(order == null ? null : order.getPaymentMethod()); + vo.setPayAmount(order == null ? null : order.getPayAmount()); + vo.setPaidAmount(order == null ? null : order.getPaidAmount()); + vo.setPayTime(order == null || order.getPayTime() == null ? null : DATE_TIME_FORMATTER.format(order.getPayTime())); return vo; } private List buildDaySummaries(LocalDate start, LocalDate end, List artists, - List schedules, List appointments) { + List schedules, List appointments, + Map weeklyHours) { Map> appointmentsByDate = appointments.stream() .filter(appointment -> appointment.getDate() != null) .collect(Collectors.groupingBy(PlanningAppointmentVO::getDate)); @@ -649,7 +883,12 @@ public class PlanningServiceImpl implements PlanningService { summary.setTotalCount(total); summary.setUnassignedCount(unassignedCount); summary.setArtistCounts(artistCounts); - summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull)); + ShopBusinessHoursDayVO shopDay = weeklyHours == null ? null : weeklyHours.get(cursor.getDayOfWeek().getValue()); + boolean shopOpen = shopDay == null || Boolean.TRUE.equals(shopDay.getOpen()); + summary.setShopOpen(shopOpen); + summary.setShopStartTime(shopDay == null ? null : shopDay.getStartTime()); + summary.setShopEndTime(shopDay == null ? null : shopDay.getEndTime()); + summary.setDayStatus(!shopOpen ? "rest" : PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull)); summaries.add(summary); cursor = cursor.plusDays(1); } @@ -721,23 +960,28 @@ public class PlanningServiceImpl implements PlanningService { return product; } - private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId, int defaultDurationMinutes) { if (dto.getProductId() != null) { return requireActiveProduct(dto.getProductId(), shopId); } - return createManualAppointmentProduct(dto, shopId); + return createManualAppointmentProduct(dto, shopId, defaultDurationMinutes); } - private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId, int defaultDurationMinutes) { String title = trimToNull(dto.getManualProductTitle()); + String imageFileIds = trimToNull(dto.getManualProductImageFileIds()); if (!hasText(title)) { - throw new RuntimeException("请选择预约作品或填写手动作品名称"); + throw new RuntimeException("请填写美甲款式名称"); } - BigDecimal price = dto.getManualProductPrice(); - if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { - throw new RuntimeException("手动作品价格不能小于0"); + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null) { + price = BigDecimal.ZERO; } - int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); + if (price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } + int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0 + ? defaultDurationMinutes : dto.getDurationMinutes(); ProductDO product = new ProductDO(); product.setShopId(shopId); product.setTitle(title); @@ -745,7 +989,7 @@ public class PlanningServiceImpl implements PlanningService { product.setTags(trimToNull(dto.getManualProductTags())); product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); product.setPrecautions(trimToNull(dto.getManualProductPrecautions())); - product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + product.setImageFileIds(imageFileIds); product.setPrice(price); product.setLikeCount(0); product.setCollectCount(0); @@ -758,13 +1002,6 @@ public class PlanningServiceImpl implements PlanningService { 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("请选择美甲师"); @@ -777,37 +1014,37 @@ public class PlanningServiceImpl implements PlanningService { return artist; } - private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) { + private UserDO resolveCustomer(UserDO currentUser, Long shopId, PlanningAppointmentCreateDTO dto) { if (dto.getCustomerUserId() != null) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getCustomerUserId(), "客户不属于当前店铺"); UserDO customer = userMapper.selectById(dto.getCustomerUserId()); - if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) { + if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete()) || !Integer.valueOf(0).equals(customer.getType())) { throw new RuntimeException("客户不存在"); } return customer; } - if (!hasText(dto.getPhone())) { - throw new RuntimeException("客户手机号不能为空"); + String customerName = trimToNull(dto.getCustomerName()); + String wechatId = trimToNull(dto.getWechatId()); + String phone = trimToNull(dto.getPhone()); + if (!hasText(customerName) && hasText(phone)) { + throw new RuntimeException("填写手机号时请同时填写客户姓名"); } - QueryWrapper 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; + if (Boolean.FALSE.equals(dto.getCreateCustomerRecord())) { + return null; } - 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; + if (!hasText(customerName)) { + return null; + } + List matches = + userService.findCustomerIdentityMatches(customerName, dto.getWechatId(), phone, shopId); + if (matches.size() > 1) { + throw new RuntimeException("存在多个匹配客户,请先选择已有客户"); + } + if (!matches.isEmpty()) { + return userMapper.selectById(matches.get(0).getId()); + } + Long customerId = userService.createManagerCustomer(customerName, wechatId, phone, shopId); + return userMapper.selectById(customerId); } private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) { @@ -831,7 +1068,13 @@ public class PlanningServiceImpl implements PlanningService { private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) { ShopDO shop = shopMapper.selectById(shopId); - PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours()); + String configuredHours = shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()); + ShopBusinessHoursDayVO shopDay = shopBusinessScheduleService.forDate(shopId, startTime.toLocalDate(), configuredHours); + if (shopDay == null || !Boolean.TRUE.equals(shopDay.getOpen())) throw new RuntimeException("预约日期门店休息,暂不可新建普通预约"); + PlanningCalendarSupport.BusinessHours hours = parseConfiguredBusinessHours( + shopDay.getStartTime() + "-" + shopDay.getEndTime()); + if (hours == null) throw new RuntimeException("门店营业时间未设置,请先完成设置"); LocalTime start = startTime.toLocalTime(); LocalTime end = endTime.toLocalTime(); if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { @@ -839,6 +1082,34 @@ public class PlanningServiceImpl implements PlanningService { } } + private PlanningCalendarSupport.BusinessHours parseConfiguredBusinessHours(String value) { + if (!StringUtils.hasText(value)) return null; + String[] parts = value.trim().split("-"); + if (parts.length != 2) return null; + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + return start.isBefore(end) ? new PlanningCalendarSupport.BusinessHours(start, end) : null; + } catch (RuntimeException ignored) { + return null; + } + } + + private void ensureFutureAppointmentTime(LocalDateTime startTime) { + LocalDate today = LocalDate.now(); + if (startTime.toLocalDate().isBefore(today)) { + throw new RuntimeException("历史日期请使用历史补单"); + } + if (!startTime.isAfter(LocalDateTime.now())) { + throw new RuntimeException("预约时间已过,请使用历史补单"); + } + } + + private int resolveShopDefaultDuration(ShopDO shop) { + return shop == null || shop.getDefaultAppointmentDurationMinutes() == null || shop.getDefaultAppointmentDurationMinutes() <= 0 + ? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes(); + } + private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) { if (hasText(appointmentStartTime)) { String normalized = appointmentStartTime.trim().replace('T', ' '); @@ -860,10 +1131,14 @@ public class PlanningServiceImpl implements PlanningService { } private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) { + return resolveDurationMinutes(product, overrideMinutes, DEFAULT_DURATION_MINUTES); + } + + private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes, int defaultMinutes) { if (overrideMinutes != null && overrideMinutes > 0) { return overrideMinutes; } - return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES); + return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), defaultMinutes); } private boolean isVisibleOrder(OrderDO order, Long shopId) { @@ -881,6 +1156,52 @@ public class PlanningServiceImpl implements PlanningService { .collect(Collectors.toMap(OrderItemDO::getId, Function.identity(), (a, b) -> a)); } + private List resolveProductCoverImages(ProductDO product) { + if (product == null || !hasText(product.getImageFileIds())) { + return List.of(); + } + Set fileIds = new HashSet<>(); + for (String rawId : product.getImageFileIds().split(",")) { + String normalized = rawId == null ? "" : rawId.trim(); + if (!normalized.isEmpty()) { + try { + fileIds.add(Long.parseLong(normalized)); + } catch (NumberFormatException ignored) { + } + } + } + if (fileIds.isEmpty()) { + return List.of(); + } + Map files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + return parseOrderedCoverUrls(product.getImageFileIds(), files); + } + + private List parseOrderedCoverUrls(String imageFileIds, Map files) { + List urls = new ArrayList<>(); + for (String rawId : imageFileIds.split(",")) { + String normalized = rawId == null ? "" : rawId.trim(); + if (normalized.isEmpty()) { + continue; + } + Long fileId; + try { + fileId = Long.parseLong(normalized); + } catch (NumberFormatException ignored) { + continue; + } + ObjectStorageFileVO file = files.get(fileId); + if (file == null) { + continue; + } + String url = objectStorageUrlSupport.toAccessibleUrl(file); + if (hasText(url)) { + urls.add(url); + } + } + return urls; + } + private Map loadOrders(Set orderIds) { if (orderIds == null || orderIds.isEmpty()) { return Map.of(); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java index daa086e3..d2f579a4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java @@ -66,9 +66,6 @@ public final class PlanningCalendarSupport { } public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) { - if (!hasWorkingSchedule) { - return "rest"; - } if (allWorkingArtistsBusy) { return "full"; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java index 1df34537..a4053c29 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.planning.vo; import lombok.Data; import java.math.BigDecimal; +import java.util.List; @Data public class PlanningAppointmentVO { @@ -11,9 +12,14 @@ public class PlanningAppointmentVO { private Long orderItemId; private Long customerId; private String customerName; + /** 脱敏后的客户手机号,完整号码仅通过拨号取号端点单次获取 */ private String customerPhone; + /** 是否存在可拨打的手机号,呼叫按钮据此展示 */ + private Boolean customerPhoneAvailable; private Long productId; private String productTitle; + /** 作品图片访问地址,用于预约详情项目图片轮播 */ + private List coverImages; private Long artistId; private String artistName; private String artistColor; @@ -32,4 +38,19 @@ public class PlanningAppointmentVO { private String conflictReason; private BigDecimal amount; private String remark; + private String cancelReason; + /** 风格库来源,MANAGER_APPOINTMENT 表示手动录入的款式 */ + private String productSourceType; + private String productDescription; + private String productTags; + private String productTargetAudience; + private String productPrecautions; + private String productImageFileIds; + /** 支付状态:UNPAID / PAID */ + private String paymentStatus; + /** 收款方式:OFFLINE / CASH / WECHAT / ALIPAY */ + private String paymentMethod; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private String payTime; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java index 26f412c1..28f1bb6c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java @@ -8,8 +8,11 @@ import java.util.List; public class PlanningCalendarVO { private String businessStartTime; private String businessEndTime; + private Integer defaultAppointmentDurationMinutes; private Integer slotMinutes; private List artists; + /** 全部美甲师选项(不受 artistId 筛选影响),供端侧筛选栏始终展示完整 chip 列表 */ + private List artistOptions; private List schedules; private List appointments; private List daySummaries; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java index 8b00cb88..e8c64a3d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java @@ -11,4 +11,7 @@ public class PlanningDaySummaryVO { private Integer unassignedCount; private List artistCounts; private String dayStatus; + private Boolean shopOpen; + private String shopStartTime; + private String shopEndTime; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java new file mode 100644 index 00000000..6cefdac5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "jayucloud-salon.privacy.content-moderation") +public class ContentModerationProperties { + private Boolean allowMock = false; + private Integer scene = 2; + private Integer imageUrlExpireMinutes = 5; + private Integer requestTimeoutMillis = 8000; + private Integer maxRetries = 3; + private String retryCron = "0 */2 * * * *"; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java new file mode 100644 index 00000000..04e21159 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 拨号取号配置。 + * provider 取值:direct(直拨真实号码)或 privacy-number(隐私号码,暂未对接)。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-salon.dial") +public class DialProperties { + + private String provider = "direct"; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java new file mode 100644 index 00000000..33eccf7c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class WechatContentModerationHttpConfig { + @Bean("wechatContentModerationRestTemplate") + public RestTemplate wechatContentModerationRestTemplate(ContentModerationProperties properties) { + int timeoutMillis = properties.getRequestTimeoutMillis() == null + ? 8000 : Math.max(1000, properties.getRequestTimeoutMillis()); + SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); + requestFactory.setConnectTimeout(timeoutMillis); + requestFactory.setReadTimeout(timeoutMillis); + return new RestTemplate(requestFactory); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminAccountClosureController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminAccountClosureController.java new file mode 100644 index 00000000..004748bf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminAccountClosureController.java @@ -0,0 +1,65 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin; + +import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ClosureSuccessorManagerVO; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin/privacy/account-closure") +public class AdminAccountClosureController { + private final AccountClosureService accountClosureService; + private final UserMapper userMapper; + + @GetMapping("/pending") + public Result> pending(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(accountClosureService.listPending()); + } + + @GetMapping("/successor-managers") + public Result> successorManagers(HttpServletRequest request) { + requirePlatformAdmin(request); + List managers = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getType, 2).eq(UserDO::getStatus, 1).eq(UserDO::getIsDelete, 0) + .select(UserDO::getId, UserDO::getNickname, UserDO::getShopId) + .orderByAsc(UserDO::getNickname)) + .stream().map(user -> new ClosureSuccessorManagerVO(user.getId(), user.getNickname(), user.getShopId())) + .collect(Collectors.toList()); + return Result.success(managers); + } + + @PostMapping("/{id}/process") + @OperationGuard(action = "admin-account-closure-process", ttlSeconds = 10, message = "申请处理中,请勿重复提交") + public Result process(HttpServletRequest request, @PathVariable Long id, + @RequestBody AccountClosureProcessDTO dto) { + Long reviewerId = requirePlatformAdmin(request); + return Result.success(accountClosureService.process(reviewerId, id, dto)); + } + + private Long requirePlatformAdmin(HttpServletRequest request) { + Object value = request.getAttribute("userId"); + if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效"); + Long userId = (Long) value; + UserDO actor = userMapper.selectById(userId); + if (actor == null || !Integer.valueOf(4).equals(actor.getType())) throw new IllegalArgumentException("无权处理注销申请"); + return userId; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java new file mode 100644 index 00000000..e8facf1a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin; + +import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.ContentModerationReviewDTO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@Validated +@RequestMapping("/admin/privacy/content-moderation") +public class AdminContentModerationController { + private final ContentModerationService contentModerationService; + private final UserMapper userMapper; + + @GetMapping("/pending") + public Result> pending(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(contentModerationService.listPending()); + } + + @PostMapping("/{id}/review") + @OperationGuard(action = "admin-content-moderation-review", ttlSeconds = 5, message = "复核处理中,请勿重复提交") + public Result review(HttpServletRequest request, @PathVariable Long id, + @Valid @RequestBody ContentModerationReviewDTO dto) { + Long reviewerId = requirePlatformAdmin(request); + if (dto.getApproved() == null) throw new IllegalArgumentException("请选择通过或拒绝"); + return Result.success(contentModerationService.review(reviewerId, id, dto.getApproved(), dto.getReason())); + } + + private Long requirePlatformAdmin(HttpServletRequest request) { + Object value = request.getAttribute("userId"); + if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效"); + Long userId = (Long) value; + UserDO actor = userMapper.selectById(userId); + if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) { + throw new IllegalArgumentException("无权处理内容复核"); + } + return userId; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminPhoneBackfillController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminPhoneBackfillController.java new file mode 100644 index 00000000..aa4b8cbd --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminPhoneBackfillController.java @@ -0,0 +1,43 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin; + +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneBackfillReport; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneDataBackfillService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin/privacy/phone-backfill") +public class AdminPhoneBackfillController { + private final PhoneDataBackfillService backfillService; + private final UserMapper userMapper; + + @GetMapping("/report") + public Result report(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(backfillService.backfill(true)); + } + + @PostMapping("/run") + public Result run(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(backfillService.backfill(false)); + } + + private void requirePlatformAdmin(HttpServletRequest request) { + Object value = request.getAttribute("userId"); + if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效"); + UserDO actor = userMapper.selectById((Long) value); + if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) { + throw new IllegalArgumentException("无权执行手机号数据处理"); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/AccountClosureController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/AccountClosureController.java new file mode 100644 index 00000000..19e74bff --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/AccountClosureController.java @@ -0,0 +1,44 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; + +import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/user/account-closure") +public class AccountClosureController { + private final AccountClosureService accountClosureService; + + @PostMapping + @OperationGuard(action = "account-closure-request", ttlSeconds = 10, message = "注销申请处理中,请勿重复提交") + public Result request(HttpServletRequest request) { + return Result.success(accountClosureService.request(userId(request))); + } + + @GetMapping("/me") + public Result getMine(HttpServletRequest request) { + return Result.success(accountClosureService.getMine(userId(request))); + } + + @DeleteMapping("/me") + @OperationGuard(action = "account-closure-withdraw", ttlSeconds = 10, message = "撤回处理中,请勿重复操作") + public Result withdraw(HttpServletRequest request) { + return Result.success(accountClosureService.withdraw(userId(request))); + } + + private Long userId(HttpServletRequest request) { + Object value = request.getAttribute("userId"); + if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效"); + return (Long) value; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java new file mode 100644 index 00000000..a9f87e8b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java @@ -0,0 +1,251 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.Locale; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/integration/wechat/content-moderation") +public class WechatContentModerationCallbackController { + private static final String CLAIMED = "CLAIMED"; + private static final String NOT_MINE = "NOT_MINE"; + + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final WechatMiniProperties wechatProperties; + private final WechatCallbackCrypto crypto; + private final ContentModerationService contentModerationService; + private final IntegrationProbeService integrationProbeService; + private final ContentModerationForwardService contentModerationForwardService; + private final SalonDeployProperties deployProperties; + private final ObjectMapper objectMapper; + + @GetMapping("/callback") + public String verifyEndpoint(@RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam(value = "msg_signature", required = false) String messageSignature, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam(value = "encrypt_type", required = false) String encryptType, + @RequestParam("echostr") String echoString) { + ModerationRuntimeConfig config = requireCallbackConfig(); + if ("aes".equalsIgnoreCase(encryptType)) { + if (!crypto.verify(config.getCallbackToken(), timestamp, nonce, echoString, messageSignature)) { + throw new IllegalArgumentException("微信审核回调 AES 握手校验失败"); + } + return crypto.decrypt(echoString, config.getEncodingAesKey(), wechatProperties.getAppId()); + } + if (!crypto.verifyPlain(config.getCallbackToken(), timestamp, nonce, signature)) { + throw new IllegalArgumentException("微信审核回调明文握手校验失败"); + } + return echoString; + } + + @PostMapping(value = "/callback", consumes = { + MediaType.APPLICATION_JSON_VALUE, + "application/*+json", + MediaType.APPLICATION_XML_VALUE, + MediaType.TEXT_XML_VALUE + }) + public String callback(@RequestParam(value = "timestamp", required = false) String timestamp, + @RequestParam(value = "nonce", required = false) String nonce, + @RequestParam(value = "msg_signature", required = false) String messageSignature, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam(value = "encrypt_type", required = false) String encryptType, + @RequestHeader(value = "X-Moderation-Forward-By", required = false) String forwardBy, + @RequestHeader(value = "X-Moderation-Forward-Hop", required = false) String forwardHop, + @RequestHeader(value = "X-Timestamp", required = false) String forwardTimestamp, + @RequestHeader(value = "X-Nonce", required = false) String forwardNonce, + @RequestHeader(value = "X-Signature", required = false) String forwardSignature, + @RequestBody String body, + javax.servlet.http.HttpServletResponse response) throws Exception { + if (StringUtils.hasText(forwardBy) || StringUtils.hasText(forwardHop)) { + return handleForwardedCallback(forwardBy, forwardHop, forwardTimestamp, forwardNonce, forwardSignature, body); + } + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce)) { + throw new IllegalArgumentException("微信审核回调缺少时间戳或随机串"); + } + ModerationRuntimeConfig config = requireWechatConfig(); + String encrypted = extractEncryptedPayload(body); + String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature; + if (!crypto.verify(config.getCallbackToken(), timestamp, nonce, + "aes".equalsIgnoreCase(encryptType) ? encrypted : "", expectedSignature)) { + throw new IllegalArgumentException("微信审核回调签名校验失败"); + } + if (!"aes".equalsIgnoreCase(encryptType) || !StringUtils.hasText(config.getEncodingAesKey())) { + throw new IllegalArgumentException("微信审核回调仅接受 AES 加密消息"); + } + String decoded = crypto.decrypt(encrypted, config.getEncodingAesKey(), wechatProperties.getAppId()); + Long taskId; + try { + taskId = contentModerationForwardService.persistCallback(decoded); + } catch (RuntimeException exception) { + response.setStatus(500); + log.error("微信审核回调落库失败,拒绝返回成功等待微信重试,errorType={}", + exception.getClass().getSimpleName()); + return "persist_failed"; + } + contentModerationForwardService.submit(taskId); + return "success"; + } + + /** + * 处理其它环境转发的回调:只允许一跳;验签通过后仅在本地认领,不再向外转发。 + * 应答三态:CLAIMED / NOT_MINE;验签失败、报文异常或跳数非法时抛异常(调用方归为 ERROR)。 + */ + private String handleForwardedCallback(String forwardBy, String forwardHop, String timestamp, + String nonce, String signature, String body) throws Exception { + if (!contentModerationForwardService.verifySignature(timestamp, nonce, signature, body)) { + throw new IllegalArgumentException("跨环境转发签名校验失败"); + } + String sourceEnv = normalizeEnv(forwardBy); + if (!StringUtils.hasText(sourceEnv)) { + throw new IllegalArgumentException("跨环境转发缺少来源环境"); + } + if (sourceEnv.equals(deployProperties.getEnv())) { + throw new IllegalArgumentException("跨环境转发来源为自身,已拒绝"); + } + int hop; + try { + hop = StringUtils.hasText(forwardHop) ? Integer.parseInt(forwardHop.trim()) : 1; + } catch (NumberFormatException exception) { + hop = 2; + } + if (hop != 1) { + throw new IllegalArgumentException("跨环境转发跳数非法,已拒绝"); + } + ParsedCallback parsed; + try { + parsed = parsePayload(body); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("跨环境转发报文无法解析"); + } + if (!StringUtils.hasText(parsed.traceId())) { + throw new IllegalArgumentException("跨环境转发报文缺少任务标识"); + } + if (!contentModerationForwardService.reserveTrace(parsed.traceId())) { + log.info("跨环境转发重复到达,按幂等返回已认领,traceId={}, sourceEnv={}", parsed.traceId(), sourceEnv); + return CLAIMED; + } + boolean claimed; + try { + claimed = claimLocally(parsed); + } catch (RuntimeException exception) { + contentModerationForwardService.releaseTrace(parsed.traceId()); + throw exception; + } + if (claimed) { + log.info("跨环境转发本地认领成功,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + parsed.traceId(), sourceEnv, deployProperties.getEnv(), hop); + return CLAIMED; + } + contentModerationForwardService.releaseTrace(parsed.traceId()); + log.info("跨环境转发本地未命中,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + parsed.traceId(), sourceEnv, deployProperties.getEnv(), hop); + return NOT_MINE; + } + + private boolean claimLocally(ParsedCallback parsed) { + if (integrationProbeService.handleImageCallback(parsed.traceId(), parsed.suggest(), null)) { + return true; + } + return contentModerationService.handleWechatImageResult( + parsed.traceId(), parsed.suggest(), parsed.reason()); + } + + private ParsedCallback parsePayload(String decoded) throws Exception { + if (!StringUtils.hasText(decoded)) { + throw new IllegalArgumentException("审核回调报文为空"); + } + if (decoded.trim().startsWith("<")) { + String traceId = firstNonBlank(crypto.value(decoded, "trace_id"), + crypto.value(decoded, "TraceId"), crypto.value(decoded, "task_id")); + String suggest = firstNonBlank(crypto.value(decoded, "suggest"), crypto.value(decoded, "Suggest"), "review"); + String reason = firstNonBlank(crypto.value(decoded, "errmsg"), crypto.value(decoded, "label"), + "微信异步图片审核回调"); + return new ParsedCallback(traceId, suggest, reason); + } + JsonNode root = objectMapper.readTree(decoded); + String traceId = firstText(root, "trace_id", "traceId", "task_id"); + String suggest = firstText(root.path("result"), "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = firstText(root, "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = "review"; + String reason = firstText(root, "errmsg", "reason"); + if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调"; + return new ParsedCallback(traceId, suggest, reason); + } + + private String normalizeEnv(String value) { + if (!StringUtils.hasText(value)) return null; + String normalized = value.trim().toLowerCase(Locale.ROOT); + return Arrays.asList("dev", "sit", "prod").contains(normalized) ? normalized : null; + } + + private String extractEncryptedPayload(String body) throws Exception { + if (!StringUtils.hasText(body)) { + throw new IllegalArgumentException("微信审核回调消息体为空"); + } + String trimmed = body.trim(); + if (trimmed.startsWith("{")) { + JsonNode root = objectMapper.readTree(trimmed); + String encrypted = firstText(root, "Encrypt", "encrypt"); + if (!StringUtils.hasText(encrypted)) { + throw new IllegalArgumentException("微信审核回调 JSON 缺少 Encrypt 字段"); + } + return encrypted; + } + return crypto.encryptedValue(body); + } + + private String firstText(JsonNode node, String... keys) { + for (String key : keys) if (node != null && node.hasNonNull(key)) return node.path(key).asText(); + return null; + } + + private String firstNonBlank(String... values) { + for (String value : values) if (StringUtils.hasText(value)) return value; + return null; + } + + private ModerationRuntimeConfig requireWechatConfig() { + ModerationRuntimeConfig config = requireCallbackConfig(); + if (!"WECHAT".equals(config.getProvider())) { + throw new IllegalStateException("微信内容审核回调尚未启用或配置不完整"); + } + return config; + } + + private ModerationRuntimeConfig requireCallbackConfig() { + ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationCallbackConfig(); + if (config == null || !config.isReady() + || !StringUtils.hasText(config.getCallbackToken()) + || !StringUtils.hasText(config.getEncodingAesKey())) { + throw new IllegalStateException("微信内容审核回调凭据尚未配置完整"); + } + return config; + } + + private record ParsedCallback(String traceId, String suggest, String reason) { + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java new file mode 100644 index 00000000..8d80a3e8 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +/** + * 拨号返回模式。 + */ +public final class DialMode { + + public static final String DIRECT = "DIRECT"; + + public static final String PRIVACY_NUMBER = "PRIVACY_NUMBER"; + + private DialMode() { + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java new file mode 100644 index 00000000..c85f9bd0 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +/** + * 单次取号结果,仅在本次响应中返回,不落库、不写日志、不缓存。 + */ +public class DialTarget { + + private final String mode; + private final String dialNumber; + private final int expiresInSeconds; + + public DialTarget(String mode, String dialNumber, int expiresInSeconds) { + this.mode = mode; + this.dialNumber = dialNumber; + this.expiresInSeconds = expiresInSeconds; + } + + public String getMode() { + return mode; + } + + public String getDialNumber() { + return dialNumber; + } + + public int getExpiresInSeconds() { + return expiresInSeconds; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java new file mode 100644 index 00000000..9732b4f3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +/** + * 拨号目标渠道。不同渠道返回不同的号码类型,调用方不得自行降级为真实号码。 + */ +public interface DialTargetProvider { + + /** + * 配置项中使用的渠道标识,例如 direct、privacy-number。 + */ + String providerKey(); + + /** + * 解析本次拨号目标。 + */ + DialTarget resolve(UserDO customer, OrderDO order); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java new file mode 100644 index 00000000..56e57e9b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java @@ -0,0 +1,65 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * 直拨渠道:实时读取客户档案中的号码,仅在本次响应返回。 + */ +@Component +@RequiredArgsConstructor +public class DirectDialTargetProvider implements DialTargetProvider { + + public static final int NUMBER_UNAVAILABLE_CODE = 422; + + public static final String NUMBER_UNAVAILABLE_BUSINESS_CODE = "DIAL_NUMBER_UNAVAILABLE"; + + private final PhoneCrypto phoneCrypto; + + @Override + public String providerKey() { + return "direct"; + } + + @Override + public DialTarget resolve(UserDO customer, OrderDO order) { + String plainPhone = resolvePlainPhone(customer, order); + if (!StringUtils.hasText(plainPhone) || plainPhone.contains("*")) { + throw new BusinessException(NUMBER_UNAVAILABLE_CODE, + "该预约/订单未登记可拨打的手机号(" + NUMBER_UNAVAILABLE_BUSINESS_CODE + ")"); + } + return new DialTarget(DialMode.DIRECT, plainPhone.trim(), 0); + } + + /** + * 号码来源优先级:订单/预约上的客户手机号快照优先,其次客户档案。 + */ + private String resolvePlainPhone(UserDO customer, OrderDO order) { + if (order != null && StringUtils.hasText(order.getCustomerPhoneSnapshot())) { + String snapshot = phoneCrypto.decrypt(order.getCustomerPhoneSnapshot()); + if (StringUtils.hasText(snapshot)) { + return snapshot; + } + } + if (customer != null) { + if (StringUtils.hasText(customer.getContactPhone())) { + String contactPhone = phoneCrypto.decrypt(customer.getContactPhone()); + if (StringUtils.hasText(contactPhone)) { + return contactPhone; + } + } + if (StringUtils.hasText(customer.getPhone())) { + String phone = phoneCrypto.decrypt(customer.getPhone()); + if (StringUtils.hasText(phone)) { + return phone; + } + } + } + return null; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java new file mode 100644 index 00000000..ff689af5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.springframework.stereotype.Component; + +/** + * 隐私号码占位渠道:未对接时明确报错,绝不静默回退为真实号码。 + */ +@Component +public class PlaceholderPrivacyNumberProvider implements DialTargetProvider { + + public static final int NOT_CONFIGURED_CODE = 4250; + + public static final String NOT_CONFIGURED_BUSINESS_CODE = "DIAL_PRIVACY_NUMBER_NOT_CONFIGURED"; + + @Override + public String providerKey() { + return "privacy-number"; + } + + @Override + public DialTarget resolve(UserDO customer, OrderDO order) { + throw new BusinessException(NOT_CONFIGURED_CODE, + "隐私号码服务未配置(" + NOT_CONFIGURED_BUSINESS_CODE + "),请联系平台开通"); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/AccountClosureProcessDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/AccountClosureProcessDTO.java new file mode 100644 index 00000000..25e9a019 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/AccountClosureProcessDTO.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class AccountClosureProcessDTO { + private String decision; + private Long successorManagerId; + private List archiveShopIds; + private String note; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/ContentModerationReviewDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/ContentModerationReviewDTO.java new file mode 100644 index 00000000..162ae123 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/ContentModerationReviewDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +public class ContentModerationReviewDTO { + private Boolean approved; + @NotBlank + private String reason; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/AccountClosureRequestDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/AccountClosureRequestDO.java new file mode 100644 index 00000000..64eb74d4 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/AccountClosureRequestDO.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_account_closure_request") +public class AccountClosureRequestDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private Long userId; + private String status; + private LocalDateTime requestedAt; + private LocalDateTime processedAt; + private Long reviewerId; + private String reviewerNote; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java new file mode 100644 index 00000000..0836c121 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_content_moderation_image_task") +public class ContentModerationImageTaskDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private Long recordId; + private Long fileId; + private String sourceEnvVersion; + private String providerTaskId; + private String status; + private String resultCode; + private String reason; + private Integer attemptCount; + private LocalDateTime nextRetryAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java new file mode 100644 index 00000000..0d6f093b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_content_moderation_record") +public class ContentModerationRecordDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private String contentType; + private Long businessId; + private Long userId; + private Integer versionNo; + private Integer imageCount; + private String textStatus; + private String textContent; + private String status; + private String provider; + private String resultCode; + private String reason; + private String payloadJson; + private Long reviewedBy; + private LocalDateTime reviewedAt; + private Integer attemptCount; + private LocalDateTime nextRetryAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/AccountClosureRequestMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/AccountClosureRequestMapper.java new file mode 100644 index 00000000..2f219aa3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/AccountClosureRequestMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO; + +public interface AccountClosureRequestMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java new file mode 100644 index 00000000..f4d8e8bc --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationImageTaskDO; + +public interface ContentModerationImageTaskMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationRecordMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationRecordMapper.java new file mode 100644 index 00000000..00d420c7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationRecordMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; + +public interface ContentModerationRecordMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java new file mode 100644 index 00000000..b6d3fe15 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +public interface ContentModerationProvider { + String providerName(); + + ModerationOutcome reviewText(String contentType, String content, String openId); + + ModerationOutcome submitImage(String contentType, String imageUrl, String openId); + + default ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) { + return submitImage(contentType, imageUrl, openId); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java new file mode 100644 index 00000000..5a5838f4 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java @@ -0,0 +1,36 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import org.springframework.stereotype.Component; + +@Component +public class LocalMockContentModerationProvider implements ContentModerationProvider { + @Override + public String providerName() { + return "LOCAL_MOCK"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return result(content); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return result(imageUrl); + } + + private ModerationOutcome result(String content) { + String value = content == null ? "" : content; + if (value.contains("[[MOCK:FAIL]]")) throw new IllegalStateException("本地模拟审核故障"); + if (value.contains("[[MOCK:REJECT]]")) { + return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "MOCK_REJECT", "本地模拟命中拒绝场景"); + } + if (value.contains("[[MOCK:PENDING]]")) { + return new ModerationOutcome(ModerationOutcome.Status.PENDING, "MOCK_PENDING", "本地模拟进入人工复核"); + } + if (value.contains("[[MOCK:APPROVE]]")) { + return new ModerationOutcome(ModerationOutcome.Status.APPROVED, "MOCK_APPROVE", "本地模拟通过场景"); + } + return new ModerationOutcome(ModerationOutcome.Status.APPROVED, "MOCK_UNMATCHED", "开发环境模拟审核默认通过"); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java new file mode 100644 index 00000000..b4ea0e4b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +public record ModerationOutcome(Status status, String code, String reason, String remoteTaskId) { + public ModerationOutcome(Status status, String code, String reason) { + this(status, code, reason, null); + } + + public enum Status { APPROVED, PENDING, REJECTED, RETRY } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java new file mode 100644 index 00000000..7a30daf8 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Slf4j +@Primary +@Component +@RequiredArgsConstructor +public class RoutingContentModerationProvider implements ContentModerationProvider { + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final LocalMockContentModerationProvider mockProvider; + private final UnconfiguredContentModerationProvider unconfiguredProvider; + private final WechatContentModerationProvider wechatProvider; + + @Override + public String providerName() { + return resolveProvider().providerName(); + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return resolveProvider().reviewText(contentType, content, openId); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return resolveProvider().submitImage(contentType, imageUrl, openId); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) { + return resolveProvider().submitImage(contentType, imageUrl, openId, sourceEnvVersion); + } + + private ContentModerationProvider resolveProvider() { + try { + ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationRuntimeConfig(); + if (config == null || !config.isReady()) return unconfiguredProvider; + if ("MOCK".equals(config.getProvider())) return mockProvider; + if ("WECHAT".equals(config.getProvider())) return wechatProvider; + } catch (RuntimeException exception) { + log.warn("无法读取内容审核安全配置,保持失败关闭", exception); + } + return unconfiguredProvider; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java new file mode 100644 index 00000000..8b561b02 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import org.springframework.stereotype.Component; + +@Component +public class UnconfiguredContentModerationProvider implements ContentModerationProvider { + @Override + public String providerName() { + return "UNCONFIGURED"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return new ModerationOutcome( + ModerationOutcome.Status.RETRY, + "PROVIDER_NOT_CONFIGURED", + "内容审核平台尚未接入,内容已隔离等待人工复核" + ); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return reviewText(contentType, imageUrl, openId); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java new file mode 100644 index 00000000..b5b3790e --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -0,0 +1,137 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Slf4j +@Component +public class WechatContentModerationProvider implements ContentModerationProvider { + private static final String TEXT_CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check"; + private static final String IMAGE_CHECK_URL = "https://api.weixin.qq.com/wxa/media_check_async"; + + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper; + private final WechatMiniClientService wechatMiniClientService; + private final ContentModerationProperties properties; + + public WechatContentModerationProvider( + @Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate, + ObjectMapper objectMapper, + WechatMiniClientService wechatMiniClientService, + ContentModerationProperties properties) { + this.restTemplate = restTemplate; + this.objectMapper = objectMapper; + this.wechatMiniClientService = wechatMiniClientService; + this.properties = properties; + } + + @Override + public String providerName() { + return "WECHAT"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); + if (!StringUtils.hasText(content)) return approved("EMPTY_TEXT"); + Map payload = new LinkedHashMap<>(); + payload.put("content", content); + payload.put("version", 2); + payload.put("scene", properties.getScene()); + payload.put("openid", openId); + return parseResult(post(TEXT_CHECK_URL, payload), false); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); + if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) { + return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址"); + } + // 微信 media_check_async 只接受 media_url、media_type、version、scene、openid; + // 额外字段(如 extra)会直接返回 47001 data format error,务必不要下发。 + Map payload = new LinkedHashMap<>(); + payload.put("media_url", imageUrl); + payload.put("media_type", 2); + payload.put("version", 1); + payload.put("scene", properties.getScene()); + payload.put("openid", openId); + return parseResult(post(IMAGE_CHECK_URL, payload), true); + } + + public ModerationOutcome submitTestImage(String imageUrl, String openId) { + return submitImage("INTEGRATION_PROBE", imageUrl, openId); + } + + private Map post(String endpoint, Map payload) { + String url = UriComponentsBuilder.fromHttpUrl(endpoint) + .queryParam("access_token", wechatMiniClientService.getAccessTokenForContentModeration()) + .toUriString(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + try { + String response = restTemplate.postForObject(url, new HttpEntity<>(payload, headers), String.class); + if (!StringUtils.hasText(response)) throw new IllegalStateException("微信审核服务返回空响应"); + Map body = objectMapper.readValue(response, new TypeReference>() {}); + int errorCode = number(body.get("errcode")); + if (errorCode != 0) { + log.warn("微信内容审核返回错误,endpoint={}, errcode={}, errmsg={}", endpoint, errorCode, text(body.get("errmsg"))); + } + return body; + } catch (RestClientException | java.io.IOException exception) { + throw new IllegalStateException("微信内容审核请求失败", exception); + } + } + + private ModerationOutcome parseResult(Map response, boolean asynchronous) { + int errorCode = number(response.get("errcode")); + if (errorCode != 0) { + if (errorCode == 87014) { + return new ModerationOutcome(ModerationOutcome.Status.REJECTED, String.valueOf(errorCode), "微信内容安全接口判定内容违规"); + } + if (errorCode == 47001) { + return retry(String.valueOf(errorCode), "微信审核请求参数格式无效,请核对接口字段"); + } + return retry(String.valueOf(errorCode), "微信内容安全接口暂不可用"); + } + if (asynchronous) { + String taskId = text(response.get("trace_id")); + return StringUtils.hasText(taskId) + ? new ModerationOutcome(ModerationOutcome.Status.PENDING, "WECHAT_ASYNC", "等待微信图片审核回调", taskId) + : retry("TRACE_ID_MISSING", "微信图片审核未返回任务标识"); + } + Object resultRaw = response.get("result"); + if (resultRaw instanceof Map) { + Object suggest = ((Map) resultRaw).get("suggest"); + if ("pass".equalsIgnoreCase(text(suggest))) return approved("WECHAT_PASS"); + if ("review".equalsIgnoreCase(text(suggest))) return pending("WECHAT_REVIEW", "微信要求人工复核"); + if ("risky".equalsIgnoreCase(text(suggest))) return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "WECHAT_RISKY", "微信内容安全接口判定内容违规"); + } + return retry("RESULT_MISSING", "微信内容安全接口未返回明确审核结论"); + } + + private int number(Object value) { + try { return value == null ? -1 : Integer.parseInt(String.valueOf(value)); } + catch (NumberFormatException ignored) { return -1; } + } + + private String text(Object value) { return value == null ? null : String.valueOf(value); } + private ModerationOutcome approved(String code) { return new ModerationOutcome(ModerationOutcome.Status.APPROVED, code, "审核通过"); } + private ModerationOutcome pending(String code, String reason) { return new ModerationOutcome(ModerationOutcome.Status.PENDING, code, reason); } + private ModerationOutcome retry(String code, String reason) { return new ModerationOutcome(ModerationOutcome.Status.RETRY, code, reason); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java new file mode 100644 index 00000000..fd0f650a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.scheduler; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ContentModerationRetryScheduler { + private final ContentModerationService contentModerationService; + + @Scheduled(cron = "${jayucloud-salon.privacy.content-moderation.retry-cron:0 */2 * * * *}") + public void retryFailedImageTasks() { + int count = contentModerationService.retryFailedImageTasks(); + if (count > 0) log.info("内容审核图片重试任务完成, count={}", count); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/AccountClosureService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/AccountClosureService.java new file mode 100644 index 00000000..77092474 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/AccountClosureService.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO; + +import java.util.List; + +public interface AccountClosureService { + AccountClosureRequestVO request(Long userId); + AccountClosureRequestVO getMine(Long userId); + boolean withdraw(Long userId); + List listPending(); + boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java new file mode 100644 index 00000000..abb269c3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java @@ -0,0 +1,57 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO; + +import java.util.List; + +/** + * 微信异步图片审核回调的持久化任务、跨环境串行探测与补偿。 + */ +public interface ContentModerationForwardService { + + ModerationForwardConfig runtimeConfig(); + + List listRecent(int limit); + + /** + * 回调到达后第一件事:按 trace_id 落库。重复回调直接返回已有任务 ID。 + * 落库失败抛出异常,由控制器返回非 200,让微信重试。 + */ + Long persistCallback(String rawPayload); + + /** + * 提交异步执行,不影响回调响应耗时。 + */ + void submit(Long taskId); + + /** + * 执行一次任务:抢锁、幂等判断、本地认领、串行探测、写回状态。 + */ + void executeTask(Long taskId); + + /** + * 补偿扫描:把到期或锁超时的任务重新提交执行。 + */ + int retryDueTasks(); + + /** + * 应用启动时扫描未完成任务,避免进程重启丢消息。 + */ + int recoverPendingTasks(); + + /** + * 处理前占位,保证同一个 trace_id 的业务处理只成功一次。 + */ + boolean reserveTrace(String traceId); + + /** + * 释放占位,允许后续重试继续处理。 + */ + void releaseTrace(String traceId); + + /** + * 校验转发请求的 HMAC 签名、时间窗与 nonce 防重放。 + */ + boolean verifySignature(String timestamp, String nonce, String signature, String body); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java new file mode 100644 index 00000000..7200052c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; + +import java.util.List; + +public interface ContentModerationService { + ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson); + ContentModerationResultVO assessVersion(String contentType, Long businessId, Long userId, String text, + String payloadJson, List imageFileIds); + List listPending(); + boolean review(Long reviewerId, Long recordId, boolean approved, String reason); + boolean handleWechatImageResult(String providerTaskId, String suggest, String reason); + + int retryFailedImageTasks(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java new file mode 100644 index 00000000..16a840cb --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +import javax.servlet.http.HttpServletRequest; + +/** + * 客户拨号取号服务:按门店范围与订单上下文单次授权,号码不落库、不写日志、不缓存。 + */ +public interface CustomerDialService { + + CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/AccountClosureServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/AccountClosureServiceImpl.java new file mode 100644 index 00000000..68282375 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/AccountClosureServiceImpl.java @@ -0,0 +1,297 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.AccountClosureRequestMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO; +import com.xiaowang.jayucloud.salon.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.jayucloud.salon.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserRelationDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserRelationMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; +import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper; +import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class AccountClosureServiceImpl implements AccountClosureService { + private static final String PENDING = "PENDING"; + private static final String WITHDRAWN = "WITHDRAWN"; + private static final String APPROVED = "APPROVED"; + private static final String REJECTED = "REJECTED"; + + private final AccountClosureRequestMapper requestMapper; + private final UserMapper userMapper; + private final ShopMapper shopMapper; + private final UserShopBindingMapper bindingMapper; + private final UserShopRoleMapper shopRoleMapper; + private final UserRelationMapper relationMapper; + private final WechatMiniBindingMapper wechatBindingMapper; + private final UserAgreementConsentMapper consentMapper; + private final SecurityAuditLogMapper securityAuditLogMapper; + private final OrderMapper orderMapper; + private final UserSessionService sessionService; + + @Override + @Transactional(rollbackFor = Exception.class) + public AccountClosureRequestVO request(Long userId) { + UserDO user = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getId, userId).eq(UserDO::getIsDelete, 0).last("FOR UPDATE")); + if (user == null) throw new IllegalStateException("账号不存在或已注销"); + if (Integer.valueOf(4).equals(user.getType())) throw new IllegalStateException("管理员账号不能申请注销"); + AccountClosureRequestDO pending = requestMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getUserId, userId) + .eq(AccountClosureRequestDO::getStatus, PENDING) + .orderByDesc(AccountClosureRequestDO::getRequestedAt) + .last("limit 1")); + if (pending != null) return toVO(pending, user); + + AccountClosureRequestDO request = new AccountClosureRequestDO(); + request.setUserId(userId); + request.setStatus(PENDING); + request.setRequestedAt(LocalDateTime.now()); + requestMapper.insert(request); + return toVO(request, user); + } + + @Override + public AccountClosureRequestVO getMine(Long userId) { + AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getUserId, userId) + .orderByDesc(AccountClosureRequestDO::getRequestedAt) + .last("limit 1")); + if (request == null) return null; + UserDO user = userMapper.selectById(userId); + return toVO(request, user); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean withdraw(Long userId) { + AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getUserId, userId) + .eq(AccountClosureRequestDO::getStatus, PENDING) + .orderByDesc(AccountClosureRequestDO::getRequestedAt) + .last("limit 1")); + if (request == null) return false; + request.setStatus(WITHDRAWN); + request.setProcessedAt(LocalDateTime.now()); + return requestMapper.updateById(request) > 0; + } + + @Override + public List listPending() { + return requestMapper.selectList(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getStatus, PENDING) + .orderByAsc(AccountClosureRequestDO::getRequestedAt)) + .stream() + .map(request -> toVO(request, userMapper.selectById(request.getUserId()))) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto) { + if (dto == null || (!"APPROVE".equals(dto.getDecision()) && !"REJECT".equals(dto.getDecision()))) { + throw new IllegalArgumentException("请选择批准或驳回"); + } + AccountClosureRequestDO request = requestMapper.selectById(requestId); + if (request == null || !PENDING.equals(request.getStatus())) throw new IllegalStateException("注销申请已处理或不存在"); + int claimed = requestMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountClosureRequestDO::getId, requestId) + .eq(AccountClosureRequestDO::getStatus, PENDING) + .set(AccountClosureRequestDO::getStatus, "PROCESSING")); + if (claimed != 1) throw new IllegalStateException("注销申请已处理或正在处理中"); + UserDO user = requireActiveUser(request.getUserId()); + if ("REJECT".equals(dto.getDecision())) { + if (!StringUtils.hasText(dto.getNote())) throw new IllegalArgumentException("驳回原因不能为空"); + request.setStatus(REJECTED); + request.setReviewerNote(dto.getNote().trim()); + } else { + transferOrArchiveShops(user, dto); + anonymizeUser(user); + request.setStatus(APPROVED); + request.setReviewerNote(StringUtils.hasText(dto.getNote()) ? dto.getNote().trim() : "已完成资料清理与会话撤销"); + } + request.setReviewerId(reviewerId); + request.setProcessedAt(LocalDateTime.now()); + return requestMapper.updateById(request) > 0; + } + + private void transferOrArchiveShops(UserDO user, AccountClosureProcessDTO dto) { + List bindings = bindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + if (bindings.isEmpty()) return; + if (!Integer.valueOf(2).equals(user.getType())) { + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0) + .set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + return; + } + if (dto.getSuccessorManagerId() != null) { + UserDO successor = requireActiveUser(dto.getSuccessorManagerId()); + if (!Integer.valueOf(2).equals(successor.getType()) || Objects.equals(successor.getId(), user.getId())) { + throw new IllegalArgumentException("接手账号必须是其他已启用店长"); + } + for (UserShopBindingDO binding : bindings) { + UserShopBindingDO successorBinding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, successor.getId()) + .eq(UserShopBindingDO::getShopId, binding.getShopId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .last("limit 1")); + if (successorBinding == null) { + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getId, binding.getId()) + .set(UserShopBindingDO::getUserId, successor.getId()) + .set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + } else { + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getId, binding.getId()) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + } + } + List roles = shopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0)); + for (UserShopRoleDO role : roles) { + UserShopRoleDO existing = shopRoleMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, successor.getId()) + .eq(UserShopRoleDO::getShopId, role.getShopId()) + .eq(UserShopRoleDO::getRoleId, role.getRoleId()) + .eq(UserShopRoleDO::getIsDelete, 0) + .last("limit 1")); + if (existing == null) { + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getId, role.getId()) + .set(UserShopRoleDO::getUserId, successor.getId()) + .set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + } else { + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getId, role.getId()) + .set(UserShopRoleDO::getIsDelete, 1) + .set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + } + } + return; + } + + Set shopIds = bindings.stream().map(UserShopBindingDO::getShopId).collect(Collectors.toSet()); + if (dto.getArchiveShopIds() == null || !dto.getArchiveShopIds().containsAll(shopIds)) { + throw new IllegalArgumentException("必须明确归档该账号关联的全部门店"); + } + shopMapper.update(null, new LambdaUpdateWrapper() + .in(ShopDO::getId, shopIds) + .set(ShopDO::getStatus, 0) + .set(ShopDO::getUpdateTime, LocalDateTime.now())); + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0) + .set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + } + + private void anonymizeUser(UserDO user) { + Long userId = user.getId(); + sessionService.revokeAllUserSessions(userId); + wechatBindingMapper.delete(new LambdaQueryWrapper().eq(WechatMiniBindingDO::getUserId, userId)); + relationMapper.update(null, new LambdaUpdateWrapper() + .eq(UserRelationDO::getUserId, userId).eq(UserRelationDO::getIsDelete, 0) + .set(UserRelationDO::getIsDelete, 1).set(UserRelationDO::getUpdateTime, LocalDateTime.now())); + relationMapper.update(null, new LambdaUpdateWrapper() + .eq(UserRelationDO::getParentUserId, userId).eq(UserRelationDO::getIsDelete, 0) + .set(UserRelationDO::getParentUserId, null).set(UserRelationDO::getUpdateTime, LocalDateTime.now())); + orderMapper.update(null, new LambdaUpdateWrapper() + .eq(OrderDO::getUserId, userId) + .set(OrderDO::getUserId, null) + .set(OrderDO::getCustomerNameSnapshot, "已注销用户") + .set(OrderDO::getCustomerPhoneSnapshot, null) + .set(OrderDO::getCustomerPhoneSnapshotHash, null) + .set(OrderDO::getUpdateTime, LocalDateTime.now())); + consentMapper.update(null, new LambdaUpdateWrapper() + .eq(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, userId) + .set(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, null)); + securityAuditLogMapper.update(null, new LambdaUpdateWrapper() + .eq(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, userId) + .set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, null) + .set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getAccount, "已注销用户")); + user.setNickname("已注销用户"); + user.setAccount(null); + user.setAccountHash(null); + user.setPassword(null); + user.setPhone(null); + user.setPhoneHash(null); + user.setContactPhone(null); + user.setContactPhoneHash(null); + user.setPhoneVerified(0); + user.setEmail(null); + user.setEmailVerified(0); + user.setBirthday(null); + user.setWechatId(null); + user.setWechatQrCode(null); + user.setAvatar(null); + user.setSignature(null); + user.setShopId(null); + user.setStatus(0); + user.setIsDelete(1); + user.setUpdateTime(LocalDateTime.now()); + userMapper.updateById(user); + } + + private UserDO requireActiveUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new IllegalStateException("账号不存在或已注销"); + return user; + } + + private AccountClosureRequestVO toVO(AccountClosureRequestDO request, UserDO user) { + AccountClosureRequestVO vo = new AccountClosureRequestVO(); + vo.setId(request.getId()); + vo.setUserId(request.getUserId()); + vo.setNickname(user == null ? "已注销用户" : user.getNickname()); + vo.setUserType(user == null ? null : user.getType()); + vo.setStatus(request.getStatus()); + vo.setRequestedAt(request.getRequestedAt()); + vo.setProcessingTargetText("目标:15个工作日内完成,具体时长视门店移交或归档流程而定。"); + if (user != null && Integer.valueOf(2).equals(user.getType())) { + List bindings = bindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + List shopIds = bindings.stream().map(UserShopBindingDO::getShopId).distinct().collect(Collectors.toList()); + vo.setShopIds(shopIds); + vo.setShopNames(shopIds.isEmpty() ? List.of() : shopMapper.selectBatchIds(shopIds).stream().map(ShopDO::getShopName).collect(Collectors.toList())); + } + vo.setProcessedAt(request.getProcessedAt()); + vo.setReviewerNote(request.getReviewerNote()); + return vo; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java new file mode 100644 index 00000000..1e472b4a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java @@ -0,0 +1,521 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationProbeResult; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.annotation.PreDestroy; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ContentModerationForwardServiceImpl implements ContentModerationForwardService { + private static final String STATUS_PENDING = "PENDING"; + private static final String STATUS_PROCESSING = "PROCESSING"; + private static final String STATUS_SUCCESS = "SUCCESS"; + private static final String STATUS_NO_ENV = "NO_ENV"; + private static final String STATUS_FAILED = "FAILED"; + private static final String STATUS_DEAD = "DEAD"; + + private static final long SIGNATURE_WINDOW_SECONDS = 300; + private static final long NONCE_TTL_SECONDS = 600; + private static final long LOCK_TIMEOUT_SECONDS = 600; + private static final Duration CLAIM_TTL = Duration.ofMinutes(30); + private static final String NONCE_KEY_PREFIX = "salon:content-moderation:forward:nonce:"; + private static final String CLAIM_KEY_PREFIX = "salon:content-moderation:claim:"; + private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By"; + private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop"; + private static final String TIMESTAMP_HEADER = "X-Timestamp"; + private static final String NONCE_HEADER = "X-Nonce"; + private static final String SIGNATURE_HEADER = "X-Signature"; + + private static final AtomicInteger THREAD_INDEX = new AtomicInteger(1); + private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(4, new ThreadFactory() { + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "moderation-callback-" + THREAD_INDEX.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + }); + + private final ModerationCallbackForwardMapper forwardMapper; + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final SalonDeployProperties deployProperties; + private final RedisTemplate redisTemplate; + private final ModerationForwardHttpClient forwardHttpClient; + private final IntegrationProbeService integrationProbeService; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; + private final WechatCallbackCrypto crypto; + + private final String instanceId = UUID.randomUUID().toString().replace("-", ""); + + @Override + public ModerationForwardConfig runtimeConfig() { + return secureIntegrationConfigService.getModerationForwardConfig(); + } + + @Override + public List listRecent(int limit) { + int size = limit <= 0 ? 10 : Math.min(limit, 50); + List rows = forwardMapper.selectList(new LambdaQueryWrapper() + .orderByDesc(ModerationCallbackForwardDO::getCreatedAt) + .last("LIMIT " + size)); + return rows.stream().map(this::toVO).toList(); + } + + @Override + public Long persistCallback(String rawPayload) { + String traceId; + String untracedNote = null; + try { + ParsedPayload parsed = parsePayload(rawPayload); + traceId = parsed.traceId(); + } catch (RuntimeException exception) { + traceId = null; + } + if (!StringUtils.hasText(traceId)) { + traceId = "untraced-" + sha256Hex(rawPayload == null ? "" : rawPayload).substring(0, 24); + untracedNote = "回调缺少 trace_id 或报文无法解析,已置为 DEAD 等待人工排查"; + } + ModerationCallbackForwardDO existing = findByTrace(traceId); + if (existing != null) { + log.info("微信审核回调已存在任务,按幂等返回,traceId={}, status={}", traceId, existing.getStatus()); + return existing.getId(); + } + LocalDateTime now = LocalDateTime.now(); + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setTraceId(traceId); + row.setSourceEnv(deployProperties.getEnv()); + row.setPayload(rawPayload); + if (untracedNote == null) { + row.setStatus(STATUS_PENDING); + row.setRetryCount(0); + row.setNextAttemptAt(now); + } else { + row.setStatus(STATUS_DEAD); + row.setRetryCount(0); + row.setLastError(untracedNote); + row.setFinishedAt(now); + } + row.setCreatedAt(now); + row.setUpdatedAt(now); + try { + forwardMapper.insert(row); + } catch (DuplicateKeyException exception) { + ModerationCallbackForwardDO duplicated = findByTrace(traceId); + if (duplicated == null) throw exception; + log.info("微信审核回调并发重复落库,按幂等返回,traceId={}", traceId); + return duplicated.getId(); + } + if (untracedNote != null) { + log.error("MODERATION_CALLBACK_UNTRACED traceId={}, sourceEnv={}, payloadLength={}, note={}", + traceId, deployProperties.getEnv(), rawPayload == null ? 0 : rawPayload.length(), untracedNote); + } + return row.getId(); + } + + @Override + public void submit(Long taskId) { + if (taskId == null) return; + EXECUTOR.execute(() -> executeTask(taskId)); + } + + @Override + public void executeTask(Long taskId) { + if (taskId == null) return; + ModerationCallbackForwardDO snapshot = forwardMapper.selectById(taskId); + if (snapshot == null || isTerminal(snapshot.getStatus())) return; + String owner = deployProperties.getEnv() + "-" + instanceId; + if (!claimTask(taskId, owner)) { + log.info("微信审核回调任务已被其它实例占用或未到执行时间,taskId={}", taskId); + return; + } + ModerationCallbackForwardDO row = forwardMapper.selectById(taskId); + if (row == null) return; + try { + process(row, owner); + } catch (RuntimeException exception) { + log.error("微信审核回调异步处理异常,taskId={}, traceId={}, errorType={}", + taskId, row.getTraceId(), exception.getClass().getSimpleName()); + releaseTrace(row.getTraceId()); + failOrRetry(row, owner, "异步处理异常:" + exception.getClass().getSimpleName(), true); + } + } + + @Override + @Scheduled(fixedDelayString = "${salon.moderation-forward.retry-scan-ms:30000}") + public int retryDueTasks() { + return dispatchDueTasks(50); + } + + @Override + public int recoverPendingTasks() { + return dispatchDueTasks(100); + } + + @EventListener(ApplicationReadyEvent.class) + public void recoverOnStartup() { + int recovered = recoverPendingTasks(); + if (recovered > 0) { + log.info("微信审核回调启动补偿扫描完成,提交任务数={}", recovered); + } + } + + @Override + public boolean reserveTrace(String traceId) { + if (!StringUtils.hasText(traceId)) return false; + try { + Boolean fresh = redisTemplate.opsForValue() + .setIfAbsent(CLAIM_KEY_PREFIX + traceId, "1", CLAIM_TTL); + return Boolean.TRUE.equals(fresh); + } catch (RuntimeException exception) { + log.warn("审核回调幂等占位写入失败,按未占用继续处理,traceId={}", traceId); + return true; + } + } + + @Override + public void releaseTrace(String traceId) { + if (!StringUtils.hasText(traceId)) return; + try { + redisTemplate.delete(CLAIM_KEY_PREFIX + traceId); + } catch (RuntimeException exception) { + log.warn("审核回调幂等占位释放失败,traceId={}", traceId); + } + } + + @Override + public boolean verifySignature(String timestamp, String nonce, String signature, String body) { + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false; + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready()) return false; + long epochSeconds; + try { + epochSeconds = Long.parseLong(timestamp.trim()); + } catch (NumberFormatException exception) { + return false; + } + if (Math.abs(System.currentTimeMillis() / 1000 - epochSeconds) > SIGNATURE_WINDOW_SECONDS) return false; + if (!reserveNonce(nonce.trim())) return false; + String expected = sign(config.getSecret(), timestamp.trim(), nonce.trim(), body == null ? "" : body); + return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), + signature.trim().toLowerCase(java.util.Locale.ROOT).getBytes(StandardCharsets.UTF_8)); + } + + @PreDestroy + public void shutdown() { + EXECUTOR.shutdown(); + } + + private void process(ModerationCallbackForwardDO row, String owner) { + ParsedPayload parsed = parsePayload(row.getPayload()); + String traceId = row.getTraceId(); + if (!reserveTrace(traceId)) { + finishSuccess(row, owner, row.getSourceEnv(), "幂等短路:本环境已处理"); + return; + } + boolean localHit; + try { + localHit = claimLocally(parsed); + } catch (RuntimeException exception) { + releaseTrace(traceId); + throw exception; + } + if (localHit) { + finishSuccess(row, owner, deployProperties.getEnv(), null); + return; + } + + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready()) { + releaseTrace(traceId); + failOrRetry(row, owner, "跨环境转发未启用或共享密钥缺失", false); + return; + } + List envs = config.orderedTargets(deployProperties.getEnv()); + if (envs.isEmpty()) { + releaseTrace(traceId); + failOrRetry(row, owner, "未配置可用的目标环境地址", false); + return; + } + + List results = new ArrayList<>(); + List erroredEnvs = new ArrayList<>(); + String claimedEnv = null; + for (String env : envs) { + ModerationProbeResult result; + try { + result = forwardHttpClient.probe(config.targetFor(env), row.getPayload(), + buildHeaders(config, deployProperties.getEnv(), row.getPayload())); + } catch (RuntimeException exception) { + result = ModerationProbeResult.ERROR; + } + results.add(env + "=" + result.name()); + if (result == ModerationProbeResult.CLAIMED) { + claimedEnv = env; + break; + } + if (result == ModerationProbeResult.ERROR) erroredEnvs.add(env); + } + + if (!erroredEnvs.isEmpty()) { + log.error("MODERATION_FORWARD_TARGET_ERROR traceId={}, sourceEnv={}, order={}, erroredEnvs={}, results={}", + traceId, deployProperties.getEnv(), envs, erroredEnvs, results); + } + if (claimedEnv != null) { + String note = erroredEnvs.isEmpty() ? null : "部分环境未正常应答:" + erroredEnvs; + finishSuccess(row, owner, claimedEnv, note); + return; + } + releaseTrace(traceId); + boolean anyError = !erroredEnvs.isEmpty(); + failOrRetry(row, owner, "无环境认领;尝试顺序=" + envs + ",结果=" + results, anyError); + } + + private void finishSuccess(ModerationCallbackForwardDO row, String owner, String targetEnv, String note) { + LocalDateTime now = LocalDateTime.now(); + applyOutcome(row.getId(), owner, STATUS_SUCCESS, targetEnv, + row.getRetryCount() == null ? 0 : row.getRetryCount(), note, null, now); + log.info("微信审核回调任务处理成功,traceId={}, sourceEnv={}, targetEnv={}, taskId={}", + row.getTraceId(), row.getSourceEnv(), targetEnv, row.getId()); + } + + private void failOrRetry(ModerationCallbackForwardDO row, String owner, String note, boolean error) { + ModerationForwardConfig config = runtimeConfig(); + int maxRetry = config.getMaxRetry() <= 0 ? ModerationForwardConfig.DEFAULT_MAX_RETRY : config.getMaxRetry(); + int retryCount = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1; + LocalDateTime now = LocalDateTime.now(); + if (retryCount > maxRetry) { + applyOutcome(row.getId(), owner, STATUS_DEAD, null, retryCount, note, null, now); + log.error("MODERATION_CALLBACK_DEAD traceId={}, sourceEnv={}, taskId={}, retryCount={}, lastError={}", + row.getTraceId(), row.getSourceEnv(), row.getId(), retryCount, note); + return; + } + long delaySeconds = config.backoffSecondsFor(retryCount); + LocalDateTime nextAttemptAt = now.plusSeconds(delaySeconds); + applyOutcome(row.getId(), owner, error ? STATUS_FAILED : STATUS_NO_ENV, null, + retryCount, note, nextAttemptAt, null); + log.warn("微信审核回调任务待补偿,traceId={}, sourceEnv={}, taskId={}, retryCount={}, nextAttemptAt={}, lastError={}", + row.getTraceId(), row.getSourceEnv(), row.getId(), retryCount, nextAttemptAt, note); + } + + private void applyOutcome(Long taskId, String owner, String status, String targetEnv, int retryCount, + String lastError, LocalDateTime nextAttemptAt, LocalDateTime finishedAt) { + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("id", taskId) + .eq("locked_by", owner) + .set("status", status) + .set("target_env", StringUtils.hasText(targetEnv) ? targetEnv : null) + .set("retry_count", retryCount) + .set("last_error", clip(lastError, 500)) + .set("next_attempt_at", nextAttemptAt) + .set("finished_at", finishedAt) + .set("locked_by", null) + .set("locked_at", null) + .set("updated_at", LocalDateTime.now()); + if (forwardMapper.update(null, wrapper) <= 0) { + log.warn("微信审核回调任务写回失败或锁已丢失,taskId={}, targetStatus={}", taskId, status); + } + } + + private boolean claimTask(Long taskId, String owner) { + LocalDateTime now = LocalDateTime.now(); + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("id", taskId) + .apply("(status IN ('PENDING','RETRY','NO_ENV','FAILED','TARGET_MISSING') " + + "OR (status = 'PROCESSING' AND locked_at < {0}))", now.minusSeconds(LOCK_TIMEOUT_SECONDS)) + .apply("(next_attempt_at IS NULL OR next_attempt_at <= {0})", now) + .set("status", STATUS_PROCESSING) + .set("locked_by", owner) + .set("locked_at", now) + .set("updated_at", now); + return forwardMapper.update(null, wrapper) > 0; + } + + private int dispatchDueTasks(int limit) { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime staleBefore = now.minusSeconds(LOCK_TIMEOUT_SECONDS); + List rows = forwardMapper.selectList( + new LambdaQueryWrapper() + .apply("(status IN ('PENDING','RETRY','NO_ENV','FAILED','TARGET_MISSING') " + + "OR (status = 'PROCESSING' AND locked_at < {0}))", staleBefore) + .apply("(next_attempt_at IS NULL OR next_attempt_at <= {0})", now) + .orderByAsc(ModerationCallbackForwardDO::getId) + .last("LIMIT " + limit)); + int dispatched = 0; + for (ModerationCallbackForwardDO row : rows) { + submit(row.getId()); + dispatched++; + } + return dispatched; + } + + private boolean claimLocally(ParsedPayload parsed) { + if (integrationProbeService.handleImageCallback(parsed.traceId(), parsed.suggest(), null)) { + return true; + } + return contentModerationService.handleWechatImageResult( + parsed.traceId(), parsed.suggest(), parsed.reason()); + } + + private ParsedPayload parsePayload(String decoded) { + if (!StringUtils.hasText(decoded)) { + throw new IllegalArgumentException("审核回调报文为空"); + } + try { + if (decoded.trim().startsWith("<")) { + String traceId = firstNonBlank(crypto.value(decoded, "trace_id"), + crypto.value(decoded, "TraceId"), crypto.value(decoded, "task_id")); + String suggest = firstNonBlank(crypto.value(decoded, "suggest"), + crypto.value(decoded, "Suggest"), "review"); + String reason = firstNonBlank(crypto.value(decoded, "errmsg"), + crypto.value(decoded, "label"), "微信异步图片审核回调"); + return new ParsedPayload(traceId, suggest, reason); + } + JsonNode root = objectMapper.readTree(decoded); + String traceId = firstText(root, "trace_id", "traceId", "task_id"); + String suggest = firstText(root.path("result"), "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = firstText(root, "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = "review"; + String reason = firstText(root, "errmsg", "reason"); + if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调"; + return new ParsedPayload(traceId, suggest, reason); + } catch (Exception exception) { + throw new IllegalArgumentException("审核回调报文无法解析", exception); + } + } + + private Map buildHeaders(ModerationForwardConfig config, String sourceEnv, String payload) { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String nonce = UUID.randomUUID().toString().replace("-", ""); + String signature = sign(config.getSecret(), timestamp, nonce, payload == null ? "" : payload); + Map headers = new HashMap<>(); + headers.put(FORWARD_BY_HEADER, sourceEnv); + headers.put(FORWARD_HOP_HEADER, "1"); + headers.put(TIMESTAMP_HEADER, timestamp); + headers.put(NONCE_HEADER, nonce); + headers.put(SIGNATURE_HEADER, signature); + return headers; + } + + private boolean reserveNonce(String nonce) { + try { + Boolean fresh = redisTemplate.opsForValue().setIfAbsent(NONCE_KEY_PREFIX + nonce, "1", + Duration.ofSeconds(NONCE_TTL_SECONDS)); + return Boolean.TRUE.equals(fresh); + } catch (RuntimeException exception) { + log.warn("转发 nonce 防重放写入失败,按拒绝处理"); + return false; + } + } + + private String sign(String secret, String timestamp, String nonce, String body) { + try { + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body); + return hex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.GeneralSecurityException exception) { + throw new IllegalStateException("转发签名计算失败", exception); + } + } + + private String sha256Hex(String value) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return hex(digest.digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("无法计算报文摘要", exception); + } + } + + private String hex(byte[] bytes) { + StringBuilder builder = new StringBuilder(bytes.length * 2); + for (byte item : bytes) builder.append(String.format("%02x", item)); + return builder.toString(); + } + + private ModerationCallbackForwardDO findByTrace(String traceId) { + if (!StringUtils.hasText(traceId)) return null; + return forwardMapper.selectOne(new LambdaQueryWrapper() + .eq(ModerationCallbackForwardDO::getTraceId, traceId) + .last("LIMIT 1")); + } + + private boolean isTerminal(String status) { + return STATUS_SUCCESS.equals(status) || STATUS_DEAD.equals(status); + } + + private ModerationForwardRecordVO toVO(ModerationCallbackForwardDO row) { + ModerationForwardRecordVO vo = new ModerationForwardRecordVO(); + vo.setId(row.getId()); + vo.setTraceId(row.getTraceId()); + vo.setSourceEnv(row.getSourceEnv()); + vo.setTargetEnv(row.getTargetEnv()); + vo.setStatus(row.getStatus()); + vo.setRetryCount(row.getRetryCount()); + vo.setLastError(row.getLastError()); + vo.setPayload(row.getPayload()); + vo.setNextAttemptAt(row.getNextAttemptAt()); + vo.setFinishedAt(row.getFinishedAt()); + vo.setCreatedAt(row.getCreatedAt()); + vo.setUpdatedAt(row.getUpdatedAt()); + return vo; + } + + private String firstText(JsonNode node, String... keys) { + for (String key : keys) if (node != null && node.hasNonNull(key)) return node.path(key).asText(); + return null; + } + + private String firstNonBlank(String... values) { + for (String value : values) if (StringUtils.hasText(value)) return value; + return null; + } + + private String clip(String value, int max) { + if (!StringUtils.hasText(value)) return null; + String trimmed = value.trim(); + return trimmed.length() <= max ? trimmed : trimmed.substring(0, max); + } + + private record ParsedPayload(String traceId, String suggest, String reason) { + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java new file mode 100644 index 00000000..cb5126c1 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java @@ -0,0 +1,564 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO; +import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.jayucloud.salon.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.AnnouncementMapper; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationImageTaskDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationImageTaskMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.EffectDiagramDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.Comparator; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ContentModerationServiceImpl implements ContentModerationService { + private final ContentModerationProvider provider; + private final ContentModerationRecordMapper recordMapper; + private final ContentModerationImageTaskMapper imageTaskMapper; + private final ProductMapper productMapper; + private final EffectDiagramMapper effectDiagramMapper; + private final NailArtistInfoMapper nailArtistInfoMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; + private final CommentMapper commentMapper; + private final ShopMapper shopMapper; + private final AnnouncementMapper announcementMapper; + private final SystemMessageMapper systemMessageMapper; + private final UserMapper userMapper; + private final WechatMiniBindingMapper bindingMapper; + private final WechatMiniClientService wechatMiniClientService; + private final ObjectStorageFileService objectStorageFileService; + private final ContentModerationProperties properties; + private final ObjectMapper objectMapper; + + @Override + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson) { + return assessVersion(contentType, businessId, userId, content, payloadJson, Collections.emptyList()); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public ContentModerationResultVO assessVersion(String contentType, Long businessId, Long userId, String text, + String payloadJson, List imageFileIds) { + List normalizedImageIds = imageFileIds == null ? Collections.emptyList() : imageFileIds.stream() + .filter(fileId -> fileId != null && fileId > 0) + .collect(java.util.stream.Collectors.collectingAndThen( + java.util.stream.Collectors.toCollection(LinkedHashSet::new), ArrayList::new)); + ContentModerationRecordDO record = new ContentModerationRecordDO(); + record.setContentType(contentType); + record.setBusinessId(businessId); + record.setUserId(userId); + record.setVersionNo(nextVersion(contentType, businessId, userId)); + record.setTextContent(text); + record.setImageCount(normalizedImageIds.size()); + record.setProvider(provider.providerName()); + record.setPayloadJson(payloadJson); + record.setAttemptCount(1); + int maxRetries = Math.max(0, properties.getMaxRetries() == null ? 3 : properties.getMaxRetries()); + + String openId = resolveOpenId(userId); + ModerationOutcome textOutcome = StringUtils.hasText(openId) + ? safeTextReview(contentType, text, openId) + : outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核"); + boolean textRetryExhausted = exhausted(textOutcome, 1, maxRetries); + record.setTextStatus(textRetryExhausted ? "PENDING" : textOutcome.status().name()); + record.setResultCode(textOutcome.code()); + record.setReason(textRetryExhausted ? "自动重试已关闭,转人工复核" : textOutcome.reason()); + record.setStatus(textRetryExhausted ? "PENDING" : textOutcome.status().name()); + record.setNextRetryAt(textOutcome.status() == ModerationOutcome.Status.RETRY && !textRetryExhausted ? LocalDateTime.now().plusMinutes(2) : null); + recordMapper.insert(record); + + if (!normalizedImageIds.isEmpty()) { + for (Long fileId : normalizedImageIds) { + ContentModerationImageTaskDO task = new ContentModerationImageTaskDO(); + task.setRecordId(record.getId()); + task.setFileId(fileId); + String sourceEnvVersion = currentMiniProgramEnvVersion(); + task.setSourceEnvVersion(sourceEnvVersion); + task.setAttemptCount(1); + ModerationOutcome imageOutcome = StringUtils.hasText(openId) + ? safeImageReview(contentType, fileId, openId, sourceEnvVersion) + : outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核"); + boolean imageRetryExhausted = exhausted(imageOutcome, 1, maxRetries); + task.setStatus(imageRetryExhausted ? "PENDING" : imageOutcome.status().name()); + task.setResultCode(imageOutcome.code()); + task.setReason(imageRetryExhausted ? "自动重试已关闭,转人工复核" : imageOutcome.reason()); + task.setProviderTaskId(imageOutcome.remoteTaskId()); + task.setNextRetryAt(imageOutcome.status() == ModerationOutcome.Status.RETRY && !imageRetryExhausted ? LocalDateTime.now().plusMinutes(2) : null); + imageTaskMapper.insert(task); + } + } + refreshAggregate(record); + return result(record); + } + + @Override + public List listPending() { + List records = recordMapper.selectList(new LambdaQueryWrapper() + .in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY") + .orderByAsc(ContentModerationRecordDO::getCreateTime)); + List result = new ArrayList<>(); + for (ContentModerationRecordDO record : records) { + ContentModerationRecordVO vo = new ContentModerationRecordVO(); + vo.setId(record.getId()); + vo.setContentType(record.getContentType()); + vo.setBusinessId(record.getBusinessId()); + vo.setStatus(record.getStatus()); + vo.setResultCode(record.getResultCode()); + vo.setReason(record.getReason()); + vo.setTextPreview(record.getTextContent()); + vo.setAttemptCount(record.getAttemptCount()); + vo.setCreateTime(record.getCreateTime()); + UserDO author = record.getUserId() == null ? null : userMapper.selectById(record.getUserId()); + vo.setAuthorName(author == null ? "后台/未知发布者" : author.getNickname()); + vo.setImages(loadImagePreviews(record)); + result.add(vo); + } + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean review(Long reviewerId, Long recordId, boolean approved, String reason) { + if (!StringUtils.hasText(reason)) throw new IllegalArgumentException("复核说明不能为空"); + ContentModerationRecordDO record = lockVersionRecord(recordId); + if (record == null || !isReviewable(record.getStatus())) throw new IllegalStateException("该内容已复核或不存在"); + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getRecordId, recordId) + .orderByAsc(ContentModerationImageTaskDO::getId) + .last("FOR UPDATE")); + if (approved && tasks.size() != (record.getImageCount() == null ? 0 : record.getImageCount())) { + throw new IllegalStateException("图片审核任务不完整,不能通过复核"); + } + if (approved) { + for (ContentModerationImageTaskDO task : tasks) { + try { + objectStorageFileService.createTemporaryModerationUrl(task.getFileId(), properties.getImageUrlExpireMinutes()); + } catch (RuntimeException exception) { + throw new IllegalStateException("存在无法安全预览的图片,不能通过复核"); + } + } + } + for (ContentModerationImageTaskDO task : tasks) { + task.setStatus(approved ? "APPROVED" : "REJECTED"); + task.setReason("由管理员人工复核"); + task.setProviderTaskId(null); + task.setNextRetryAt(null); + imageTaskMapper.updateById(task); + } + record.setTextStatus(approved ? "APPROVED" : "REJECTED"); + record.setStatus(approved ? "APPROVED" : "REJECTED"); + record.setReviewedBy(reviewerId); + record.setReviewedAt(LocalDateTime.now()); + record.setReason(reason.trim()); + record.setNextRetryAt(null); + if (approved && isCurrentVersionLocked(record)) applyApprovedPayload(record); + record.setPayloadJson(null); + return recordMapper.updateById(record) > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) { + if (!StringUtils.hasText(providerTaskId)) return false; + ContentModerationImageTaskDO candidate = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId).last("LIMIT 1")); + if (candidate == null) return false; + if (!isReviewable(candidate.getStatus())) return true; + + ContentModerationRecordDO record = lockVersionRecord(candidate.getRecordId()); + if (record == null || !isReviewable(record.getStatus())) return true; + + ContentModerationImageTaskDO task = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getId, candidate.getId()) + .eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId) + .last("FOR UPDATE")); + if (task == null || !isReviewable(task.getStatus())) return task != null; + if ("pass".equalsIgnoreCase(suggest)) task.setStatus("APPROVED"); + else if ("risky".equalsIgnoreCase(suggest)) task.setStatus("REJECTED"); + else task.setStatus("PENDING"); + task.setResultCode("WECHAT_CALLBACK_" + (suggest == null ? "UNKNOWN" : suggest.toUpperCase())); + task.setReason(reason); + task.setNextRetryAt(null); + imageTaskMapper.updateById(task); + refreshAggregate(record); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int retryFailedImageTasks() { + int maxRetries = properties.getMaxRetries() == null ? 3 : properties.getMaxRetries(); + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getStatus, "RETRY") + .le(ContentModerationImageTaskDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationImageTaskDO::getNextRetryAt) + .or().le(ContentModerationImageTaskDO::getNextRetryAt, LocalDateTime.now())) + .orderByAsc(ContentModerationImageTaskDO::getRecordId) + .orderByAsc(ContentModerationImageTaskDO::getId) + .last("LIMIT 100")); + int attempted = 0; + for (ContentModerationImageTaskDO candidate : tasks) { + ContentModerationRecordDO record = lockVersionRecord(candidate.getRecordId()); + String openId = record == null ? null : resolveOpenId(record.getUserId()); + if (record == null || !isReviewable(record.getStatus()) || !StringUtils.hasText(openId)) continue; + ContentModerationImageTaskDO task = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getId, candidate.getId()) + .eq(ContentModerationImageTaskDO::getStatus, "RETRY") + .le(ContentModerationImageTaskDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationImageTaskDO::getNextRetryAt) + .or().le(ContentModerationImageTaskDO::getNextRetryAt, LocalDateTime.now())) + .last("FOR UPDATE")); + if (task == null) continue; + attempted++; + task.setProviderTaskId(null); + String sourceEnvVersion = normalizeTaskEnvVersion(task.getSourceEnvVersion()); + if ("LEGACY".equals(sourceEnvVersion)) sourceEnvVersion = "UNKNOWN"; + task.setSourceEnvVersion(sourceEnvVersion); + ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId, sourceEnvVersion); + task.setAttemptCount((task.getAttemptCount() == null ? 0 : task.getAttemptCount()) + 1); + task.setStatus(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "PENDING" : outcome.status().name()); + task.setResultCode(outcome.code()); + task.setReason(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "自动重试次数已耗尽,转人工复核" : outcome.reason()); + task.setProviderTaskId(outcome.remoteTaskId()); + task.setNextRetryAt(outcome.status() == ModerationOutcome.Status.RETRY && !exhausted(outcome, task.getAttemptCount(), maxRetries) ? LocalDateTime.now().plusMinutes(2) : null); + imageTaskMapper.updateById(task); + refreshAggregate(record); + } + List records = recordMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationRecordDO::getTextStatus, "RETRY") + .le(ContentModerationRecordDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationRecordDO::getNextRetryAt) + .or().le(ContentModerationRecordDO::getNextRetryAt, LocalDateTime.now())) + .orderByAsc(ContentModerationRecordDO::getId) + .last("LIMIT 100")); + for (ContentModerationRecordDO candidate : records) { + ContentModerationRecordDO record = lockVersionRecord(candidate.getId()); + if (record == null || !"RETRY".equals(record.getTextStatus()) + || (record.getNextRetryAt() != null && record.getNextRetryAt().isAfter(LocalDateTime.now()))) continue; + String openId = resolveOpenId(record.getUserId()); + if (!isReviewable(record.getStatus()) || !StringUtils.hasText(openId)) continue; + attempted++; + ModerationOutcome outcome = safeTextReview(record.getContentType(), record.getTextContent(), openId); + record.setAttemptCount((record.getAttemptCount() == null ? 0 : record.getAttemptCount()) + 1); + boolean exhausted = exhausted(outcome, record.getAttemptCount(), maxRetries); + record.setTextStatus(exhausted ? "PENDING" : outcome.status().name()); + record.setStatus(exhausted ? "PENDING" : outcome.status().name()); + record.setResultCode(outcome.code()); + record.setReason(exhausted ? "自动重试次数已耗尽,转人工复核" : outcome.reason()); + record.setNextRetryAt(outcome.status() == ModerationOutcome.Status.RETRY && !exhausted ? LocalDateTime.now().plusMinutes(2) : null); + recordMapper.updateById(record); + refreshAggregate(record); + } + return attempted; + } + + private void refreshAggregate(ContentModerationRecordDO record) { + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getRecordId, record.getId())); + boolean rejected = "REJECTED".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "REJECTED".equals(task.getStatus())); + boolean retry = "RETRY".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "RETRY".equals(task.getStatus())); + boolean allImagesApproved = tasks.stream().allMatch(task -> "APPROVED".equals(task.getStatus())); + boolean pending = "PENDING".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "PENDING".equals(task.getStatus())); + int expectedImageCount = record.getImageCount() == null ? 0 : record.getImageCount(); + if (tasks.size() != expectedImageCount) pending = true; + if (rejected) record.setStatus("REJECTED"); + else if (retry) record.setStatus("RETRY"); + else if (pending) record.setStatus("PENDING"); + else if (allImagesApproved && "APPROVED".equals(record.getTextStatus())) { + if (isCurrentVersionLocked(record)) { + applyApprovedPayload(record); + } + record.setStatus("APPROVED"); + record.setPayloadJson(null); + record.setReason("文字及全部图片审核通过"); + record.setNextRetryAt(null); + } + recordMapper.updateById(record); + } + + private boolean isCurrentVersionLocked(ContentModerationRecordDO record) { + ContentModerationRecordDO latest = currentVersion(record, true); + return latest != null && record.getId().equals(latest.getId()); + } + + private ContentModerationRecordDO currentVersion(ContentModerationRecordDO record, boolean lock) { + return latestVersion(versionScope(record, lock)); + } + + private ContentModerationRecordDO lockVersionRecord(Long recordId) { + if (recordId == null) return null; + ContentModerationRecordDO snapshot = recordMapper.selectById(recordId); + if (snapshot == null) return null; + return versionScope(snapshot, true).stream() + .filter(record -> recordId.equals(record.getId())) + .findFirst() + .orElse(null); + } + + private List versionScope(ContentModerationRecordDO record, boolean lock) { + LambdaQueryWrapper query = new LambdaQueryWrapper() + .eq(ContentModerationRecordDO::getContentType, record.getContentType()); + if (record.getBusinessId() != null) { + query.eq(ContentModerationRecordDO::getBusinessId, record.getBusinessId()); + } else if (record.getUserId() != null) { + query.isNull(ContentModerationRecordDO::getBusinessId).eq(ContentModerationRecordDO::getUserId, record.getUserId()); + } else { + query.isNull(ContentModerationRecordDO::getBusinessId).isNull(ContentModerationRecordDO::getUserId); + } + query.orderByAsc(ContentModerationRecordDO::getId); + if (lock) query.last("FOR UPDATE"); + return recordMapper.selectList(query); + } + + private ContentModerationRecordDO latestVersion(List records) { + if (records == null || records.isEmpty()) return null; + return records.stream() + .max(Comparator.comparing(ContentModerationRecordDO::getVersionNo, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .orElse(null); + } + + private void applyApprovedPayload(ContentModerationRecordDO record) { + if (!StringUtils.hasText(record.getPayloadJson())) return; + try { + JsonNode payload = objectMapper.readTree(record.getPayloadJson()); + switch (record.getContentType()) { + case "PRODUCT": applyProduct(record.getBusinessId(), payload); break; + case "EFFECT_DIAGRAM": applyEffectDiagram(record.getBusinessId(), payload); break; + case "COMMENT": applyComment(record.getBusinessId(), payload); break; + case "ORDER_ARTIST_REVIEW": applyOrderArtistReview(record.getBusinessId(), payload); break; + case "USER_PROFILE": case "USER_AVATAR": applyUser(record.getBusinessId() == null ? record.getUserId() : record.getBusinessId(), payload); break; + case "NAIL_ARTIST_PROFILE": applyNailArtistProfile(record.getBusinessId(), payload); break; + case "SHOP": applyShop(record.getBusinessId(), payload); break; + case "ANNOUNCEMENT": applyAnnouncement(record.getBusinessId(), payload); break; + case "SYSTEM_MESSAGE": applySystemMessage(record.getBusinessId(), payload); break; + default: throw new IllegalStateException("不支持的审核内容类型: " + record.getContentType()); + } + } catch (Exception exception) { + throw new IllegalStateException("隔离内容快照无法应用", exception); + } + } + + private void applyProduct(Long id, JsonNode p) { + ProductDO row = productMapper.selectById(id); if (row == null) return; + if (p.has("shopId")) row.setShopId(p.path("shopId").asLong()); + if (p.has("title")) row.setTitle(p.path("title").asText()); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("targetAudience")) row.setTargetAudience(p.path("targetAudience").asText(null)); + if (p.has("precautions")) row.setPrecautions(p.path("precautions").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("price")) row.setPrice(p.path("price").decimalValue()); + if (p.has("tags")) row.setTags(p.path("tags").asText(null)); + if (p.has("approximateDuration")) row.setApproximateDuration(p.path("approximateDuration").asText(null)); + if (p.has("bookableArtists")) row.setBookableArtists(p.path("bookableArtists").asText(null)); + if (p.has("availableCoupons")) row.setAvailableCoupons(p.path("availableCoupons").asText(null)); + row.setFrontVisible(p.path("frontVisible").asInt(1)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); productMapper.updateById(row); + } + + private void applyEffectDiagram(Long id, JsonNode p) { + EffectDiagramDO row = effectDiagramMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("productId")) row.setProductId(p.path("productId").asLong()); + if (p.has("category")) row.setCategory(p.path("category").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("price")) row.setPrice(p.path("price").isNull() ? null : p.path("price").decimalValue()); + if (p.has("duration")) row.setDuration(p.path("duration").asText(null)); + if (p.has("tag")) row.setTag(p.path("tag").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + effectDiagramMapper.updateById(row); + } + + private void applyComment(Long id, JsonNode p) { + CommentDO row = commentMapper.selectById(id); if (row == null) return; + row.setCommentContent(p.path("commentContent").asText(row.getCommentContent())); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); commentMapper.updateById(row); + } + + private void applyOrderArtistReview(Long id, JsonNode p) { + OrderArtistReviewDO row = orderArtistReviewMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("content")) row.setContent(p.path("content").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + orderArtistReviewMapper.updateById(row); + } + + private void applyUser(Long id, JsonNode p) { + UserDO row = userMapper.selectById(id); if (row == null) return; + if (p.hasNonNull("nickname")) row.setNickname(p.path("nickname").asText()); + if (p.has("signature")) row.setSignature(p.path("signature").asText(null)); + if (p.has("avatar")) row.setAvatar(p.path("avatar").asText(null)); + if (p.has("wechatQrCode")) row.setWechatQrCode(p.path("wechatQrCode").asText(null)); + row.setProfileModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); userMapper.updateById(row); + } + + private void applyNailArtistProfile(Long id, JsonNode p) { + NailArtistInfoDO row = nailArtistInfoMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("identity")) row.setIdentity(p.path("identity").asText(null)); + if (p.has("experience")) row.setExperience(p.path("experience").isNull() ? null : p.path("experience").asInt()); + if (p.has("skills")) row.setSkills(p.path("skills").asText(null)); + if (p.has("portfolio")) row.setPortfolio(p.path("portfolio").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + nailArtistInfoMapper.updateById(row); + } + + private void applyShop(Long id, JsonNode p) { + ShopDO row = shopMapper.selectById(id); if (row == null) return; + if (p.has("shopName")) row.setShopName(p.path("shopName").asText()); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("address")) row.setAddress(p.path("address").asText()); + if (p.has("mapProvider")) row.setMapProvider(p.path("mapProvider").asText(null)); + if (p.has("longitude")) row.setLongitude(p.path("longitude").isNull() ? null : p.path("longitude").decimalValue()); + if (p.has("latitude")) row.setLatitude(p.path("latitude").isNull() ? null : p.path("latitude").decimalValue()); + if (p.has("businessHours")) row.setBusinessHours(p.path("businessHours").asText(null)); + if (p.has("coverImageFileId")) row.setCoverImageFileId(p.path("coverImageFileId").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("themeBackgroundImageFileId")) row.setThemeBackgroundImageFileId(p.path("themeBackgroundImageFileId").asText(null)); + if (p.has("themePrimaryColor")) row.setThemePrimaryColor(p.path("themePrimaryColor").asText(null)); + if (p.has("themeSecondaryColor")) row.setThemeSecondaryColor(p.path("themeSecondaryColor").asText(null)); + if (p.has("themeAccentColor")) row.setThemeAccentColor(p.path("themeAccentColor").asText(null)); + if (p.has("themePageBgColor")) row.setThemePageBgColor(p.path("themePageBgColor").asText(null)); + if (p.has("themeCardBgColor")) row.setThemeCardBgColor(p.path("themeCardBgColor").asText(null)); + row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); shopMapper.updateById(row); + } + + private void applyAnnouncement(Long id, JsonNode p) { + AnnouncementDO row = announcementMapper.selectById(id); if (row == null) return; + row.setTitle(p.path("title").asText(row.getTitle())); row.setContent(p.path("content").asText(row.getContent())); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setStatus(p.path("status").asInt(1)); row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); announcementMapper.updateById(row); + } + + private void applySystemMessage(Long id, JsonNode p) { + SystemMessageDO row = systemMessageMapper.selectById(id); if (row == null) return; + row.setTitle(p.path("title").asText(row.getTitle())); row.setContent(p.path("content").asText(row.getContent())); + if (p.has("imageFileId")) row.setImageFileId(p.path("imageFileId").isNull() ? null : p.path("imageFileId").asLong()); + row.setStatus(p.path("status").asInt(1)); row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); systemMessageMapper.updateById(row); + } + + private List loadImagePreviews(ContentModerationRecordDO record) { + List previews = new ArrayList<>(); + for (ContentModerationImageTaskDO task : imageTaskMapper.selectList(new LambdaQueryWrapper().eq(ContentModerationImageTaskDO::getRecordId, record.getId()))) { + ContentModerationRecordVO.ImagePreview image = new ContentModerationRecordVO.ImagePreview(); image.setFileId(task.getFileId()); image.setStatus(task.getStatus()); + try { image.setUrl(objectStorageFileService.createTemporaryModerationUrl(task.getFileId(), properties.getImageUrlExpireMinutes())); } + catch (RuntimeException exception) { log.warn("审核图片安全预览生成失败, taskId={}", task.getId()); } + previews.add(image); + } + return previews; + } + + private ModerationOutcome safeTextReview(String type, String text, String openId) { + try { return provider.reviewText(type, text, openId); } + catch (RuntimeException exception) { return outcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试"); } + } + + private ModerationOutcome safeImageReview(String type, Long fileId, String openId, String sourceEnvVersion) { + try { + String url = objectStorageFileService.createTemporaryModerationUrl(fileId, properties.getImageUrlExpireMinutes()); + return provider.submitImage(type, url, openId, normalizeEnvVersion(sourceEnvVersion)); + } catch (RuntimeException exception) { + return outcome(ModerationOutcome.Status.RETRY, "IMAGE_REVIEW_FAILURE", "图片审核暂不可用,内容已隔离等待重试"); + } + } + + private String currentMiniProgramEnvVersion() { + Object attributes = RequestContextHolder.getRequestAttributes(); + if (!(attributes instanceof ServletRequestAttributes)) return "UNKNOWN"; + String envVersion = ((ServletRequestAttributes) attributes).getRequest().getHeader("X-Mini-Program-Env-Version"); + return normalizeEnvVersion(envVersion); + } + + private String normalizeEnvVersion(String value) { + if ("develop".equals(value) || "trial".equals(value) || "release".equals(value)) return value; + if ("LEGACY".equals(value)) return "LEGACY"; + return "UNKNOWN"; + } + + private String normalizeTaskEnvVersion(String value) { + return StringUtils.hasText(value) ? normalizeEnvVersion(value) : "LEGACY"; + } + + private String resolveOpenId(Long userId) { + if (userId == null) return null; + try { + String appId = wechatMiniClientService.getConfiguredAppId(); + WechatMiniBindingDO binding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getUserId, userId).eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getStatus, 1).last("LIMIT 1")); + return binding == null ? null : binding.getOpenId(); + } catch (RuntimeException exception) { return null; } + } + + private int nextVersion(String type, Long businessId, Long userId) { + ContentModerationRecordDO scope = new ContentModerationRecordDO(); + scope.setContentType(type); + scope.setBusinessId(businessId); + scope.setUserId(userId); + ContentModerationRecordDO latest = latestVersion(versionScope(scope, true)); + return latest == null || latest.getVersionNo() == null ? 1 : latest.getVersionNo() + 1; + } + + private ContentModerationResultVO result(ContentModerationRecordDO record) { + ContentModerationResultVO vo = new ContentModerationResultVO(); vo.setRecordId(record.getId()); vo.setStatus(record.getStatus()); vo.setReason(record.getReason()); return vo; + } + private boolean isReviewable(String status) { return "PENDING".equals(status) || "RETRY".equals(status); } + private boolean exhausted(ModerationOutcome outcome, int attempts, int maxRetries) { + return outcome.status() == ModerationOutcome.Status.RETRY && attempts > Math.max(0, maxRetries); + } + private ModerationOutcome outcome(ModerationOutcome.Status status, String code, String reason) { return new ModerationOutcome(status, code, reason); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java new file mode 100644 index 00000000..f70423a6 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java @@ -0,0 +1,141 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.DialProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTarget; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Objects; + +/** + * 客户拨号取号实现:先校验门店范围与订单归属,再按配置渠道单次取号并记录审计。 + */ +@Service +@RequiredArgsConstructor +public class CustomerDialServiceImpl implements CustomerDialService { + + private static final String AUDIT_ACTION = SecurityAuditActions.CUSTOMER_DIAL; + + private final AdminScopeHelper adminScopeHelper; + private final UserService userService; + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final RequestThrottleService requestThrottleService; + private final SecurityAuditSupport securityAuditSupport; + private final DialProperties dialProperties; + private final List providers; + + @Override + public CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request) { + adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号"); + Long currentShopId = currentUser.getShopId(); + requestThrottleService.checkCustomerDial(request, currentUser.getId()); + + if (customerId == null && appointmentId == null && orderId == null) { + throw new BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)"); + } + + OrderDO order = null; + if (appointmentId != null) { + OrderItemDO item = orderItemMapper.selectById(appointmentId); + if (item == null || Objects.equals(1, item.getIsDelete())) { + throw new BusinessException(404, "预约不存在"); + } + order = orderMapper.selectById(item.getOrderId()); + if (order == null || Objects.equals(1, order.getIsDelete())) { + throw new BusinessException(404, "预约关联订单不存在"); + } + } + if (orderId != null) { + if (order != null && !Objects.equals(orderId, order.getId())) { + throw new BusinessException(403, "预约与订单不匹配,或无权拨打"); + } + if (order == null) { + order = orderMapper.selectById(orderId); + if (order == null || Objects.equals(1, order.getIsDelete())) { + throw new BusinessException(404, "订单不存在"); + } + } + } + if (order != null && !Objects.equals(currentShopId, order.getShopId())) { + throw new BusinessException(403, "无权拨打其他店铺预约/订单客户"); + } + + UserDO customer = resolveCustomer(currentUser, customerId, order); + Long auditCustomerId = customer == null ? null : customer.getId(); + + DialTargetProvider provider = resolveProvider(); + String reason = "customerId=" + auditCustomerId + + ";appointmentId=" + appointmentId + + ";orderId=" + (order == null ? null : order.getId()) + + ";provider=" + provider.providerKey(); + try { + DialTarget target = provider.resolve(customer, order); + securityAuditSupport.success(request, AUDIT_ACTION, reason + ";mode=" + target.getMode() + ";result=SUCCESS"); + CustomerDialVO vo = new CustomerDialVO(); + vo.setMode(target.getMode()); + vo.setDialNumber(target.getDialNumber()); + vo.setExpiresInSeconds(target.getExpiresInSeconds()); + return vo; + } catch (BusinessException exception) { + securityAuditSupport.fail(request, AUDIT_ACTION, + reason + ";result=FAIL;errorCode=" + exception.getCode()); + throw exception; + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, AUDIT_ACTION, + reason + ";result=FAIL;errorType=" + exception.getClass().getSimpleName()); + throw exception; + } + } + + /** + * 解析目标客户:优先使用显式 customerId,其次订单关联客户;散客预约返回 null,不要求客户有账号。 + */ + private UserDO resolveCustomer(UserDO currentUser, Long customerId, OrderDO order) { + Long targetCustomerId = customerId; + if (targetCustomerId == null && order != null) { + targetCustomerId = order.getUserId(); + } + if (targetCustomerId == null) { + return null; + } + if (order != null && !Objects.equals(targetCustomerId, order.getUserId())) { + throw new BusinessException(403, "该客户与预约/订单不匹配,或无权拨打"); + } + UserDO customer = userService.getById(targetCustomerId); + if (customer == null || Objects.equals(1, customer.getIsDelete()) || !Objects.equals(0, customer.getType())) { + throw new BusinessException(404, "客户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetCustomerId, "无权拨打其他店铺客户"); + return customer; + } + + private DialTargetProvider resolveProvider() { + String configured = StringUtils.hasText(dialProperties.getProvider()) + ? dialProperties.getProvider().trim() + : "direct"; + for (DialTargetProvider provider : providers) { + if (configured.equalsIgnoreCase(provider.providerKey())) { + return provider; + } + } + throw new BusinessException(500, "拨号渠道配置无效(jayucloud-salon.dial.provider=" + configured + ")"); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java new file mode 100644 index 00000000..95de9e3b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java @@ -0,0 +1,47 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.support; + +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.util.Locale; +import java.util.Map; + +/** + * 跨环境审核回调探测客户端。 + * 连接超时 1 秒、读取超时 2 秒,保证串行探测尽量在微信回调窗口内完成; + * 超时、非 2xx 与无法识别的应答统一归为 {@link ModerationProbeResult#ERROR}。 + */ +@Component +public class ModerationForwardHttpClient { + + private final RestTemplate restTemplate; + + public ModerationForwardHttpClient() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(1000); + factory.setReadTimeout(2000); + this.restTemplate = new RestTemplate(factory); + } + + public ModerationProbeResult probe(String url, String body, Map headers) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + headers.forEach(httpHeaders::set); + try { + ResponseEntity response = restTemplate.postForEntity( + url, new HttpEntity<>(body, httpHeaders), String.class); + if (!response.getStatusCode().is2xxSuccessful()) return ModerationProbeResult.ERROR; + String text = response.getBody() == null ? "" : response.getBody().trim().toUpperCase(Locale.ROOT); + if (ModerationProbeResult.CLAIMED.name().equals(text)) return ModerationProbeResult.CLAIMED; + if (ModerationProbeResult.NOT_MINE.name().equals(text)) return ModerationProbeResult.NOT_MINE; + return ModerationProbeResult.ERROR; + } catch (RuntimeException exception) { + return ModerationProbeResult.ERROR; + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationProbeResult.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationProbeResult.java new file mode 100644 index 00000000..85c22f03 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationProbeResult.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.support; + +/** + * 跨环境审核回调探测的三态应答。 + */ +public enum ModerationProbeResult { + /** 目标环境本地存在该 trace_id 的审核记录,已完成处理。 */ + CLAIMED, + /** 目标环境本地不存在该 trace_id 的审核记录。 */ + NOT_MINE, + /** 超时、5xx、验签失败或报文异常,不能当作“不是”。 */ + ERROR +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java new file mode 100644 index 00000000..0fa13211 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java @@ -0,0 +1,82 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.support; + +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class WechatCallbackCrypto { + public boolean verifyPlain(String token, String timestamp, String nonce, String signature) { + if (!StringUtils.hasText(token) || !StringUtils.hasText(timestamp) + || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false; + return sha1Equals(Arrays.asList(token, timestamp, nonce), signature); + } + + public boolean verify(String token, String timestamp, String nonce, String encrypted, String signature) { + if (!StringUtils.hasText(token) || !StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) + || !StringUtils.hasText(encrypted) || !StringUtils.hasText(signature)) return false; + return sha1Equals(Arrays.asList(token, timestamp, nonce, encrypted), signature); + } + + private boolean sha1Equals(List values, String signature) { + try { + String source = values.stream().sorted().collect(Collectors.joining()); + byte[] digest = MessageDigest.getInstance("SHA-1").digest(source.getBytes(StandardCharsets.UTF_8)); + return MessageDigest.isEqual(HexFormat.of().formatHex(digest).getBytes(StandardCharsets.US_ASCII), signature.getBytes(StandardCharsets.US_ASCII)); + } catch (Exception exception) { return false; } + } + + public String encryptedValue(String xml) { + return element(xml, "Encrypt"); + } + + public String decrypt(String encrypted, String encodingAesKey, String expectedAppId) { + try { + byte[] aesKey = Base64.getDecoder().decode(encodingAesKey + "="); + byte[] cipherText = Base64.getDecoder().decode(encrypted); + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(Arrays.copyOf(aesKey, 16))); + byte[] padded = cipher.doFinal(cipherText); + int messageLength = ByteBuffer.wrap(padded, 16, 4).getInt(); + if (messageLength < 0 || messageLength > padded.length - 20) throw new IllegalArgumentException("微信回调密文长度无效"); + String appId = new String(padded, 20 + messageLength, padded.length - 20 - messageLength, StandardCharsets.UTF_8).trim(); + if (!expectedAppId.equals(appId)) throw new IllegalArgumentException("微信回调 AppID 不匹配"); + return new String(padded, 20, messageLength, StandardCharsets.UTF_8); + } catch (Exception exception) { + throw new IllegalArgumentException("微信审核回调解密失败", exception); + } + } + + public String value(String xml, String key) { + return element(xml, key); + } + + public String element(String xml, String key) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setXIncludeAware(false); + factory.setExpandEntityReferences(false); + Document document = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))); + return document.getElementsByTagName(key).item(0) == null ? null : document.getElementsByTagName(key).item(0).getTextContent(); + } catch (Exception exception) { throw new IllegalArgumentException("微信审核回调 XML 无效", exception); } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/AccountClosureRequestVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/AccountClosureRequestVO.java new file mode 100644 index 00000000..c050fe07 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/AccountClosureRequestVO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class AccountClosureRequestVO { + private Long id; + private Long userId; + private String nickname; + private Integer userType; + private List shopIds; + private List shopNames; + private String status; + private LocalDateTime requestedAt; + private String processingTargetText; + private LocalDateTime processedAt; + private String reviewerNote; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ClosureSuccessorManagerVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ClosureSuccessorManagerVO.java new file mode 100644 index 00000000..2152752b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ClosureSuccessorManagerVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ClosureSuccessorManagerVO { + private Long id; + private String nickname; + private Long shopId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java new file mode 100644 index 00000000..edea2ff7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class ContentModerationRecordVO { + private Long id; + private String contentType; + private Long businessId; + private String authorName; + private String status; + private String resultCode; + private String reason; + private String textPreview; + private List images; + private Integer attemptCount; + private LocalDateTime createTime; + + @Data + public static class ImagePreview { + private Long fileId; + private String url; + private String status; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationResultVO.java new file mode 100644 index 00000000..f3301075 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationResultVO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +@Data +public class ContentModerationResultVO { + private Long recordId; + private String status; + private String reason; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java new file mode 100644 index 00000000..a62bc030 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +/** + * 单次拨号取号响应。 + */ +@Data +public class CustomerDialVO { + + /** DIRECT:真实号码;PRIVACY_NUMBER:隐私号码 */ + private String mode; + + /** 本次可拨打的号码,仅用于当前客户端一次性拨号 */ + private String dialNumber; + + /** 号码有效秒数,DIRECT 为 0 表示不设时效 */ + private Integer expiresInSeconds; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java index cf634963..3e764305 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java @@ -64,6 +64,7 @@ public class AdminProductController { */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); Long id = productService.createProduct(productDTO); return Result.success(id); @@ -82,6 +83,7 @@ public class AdminProductController { */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); ProductVO productVO = productService.getProductById(id); if (productVO == null) { return Result.success(false); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java index cc04a7f4..3bdea3e0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java @@ -72,6 +72,7 @@ public class ProductController { */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); Long id = productService.createProduct(productDTO); return Result.success(id); @@ -89,6 +90,7 @@ public class ProductController { */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); ProductVO productVO = productService.getProductById(id); if (productVO == null) { return Result.success(false); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java index bbd80343..38e66360 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java @@ -88,4 +88,7 @@ public class ProductDTO { * 来源类型 */ private String sourceType; + + /** Server-populated author id; never trust a client-supplied value. */ + private Long publisherUserId; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java index ccb2a9b1..7cb2b926 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java @@ -62,6 +62,9 @@ public class EffectDiagramDO extends BaseEntity { @TableField("tag") private String tag; + @TableField("moderation_status") + private String moderationStatus; + /** * 效果图点赞数 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java index 738d62dd..5739e23b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java @@ -105,6 +105,9 @@ public class ProductDO extends BaseEntity { @TableField("front_visible") private Integer frontVisible; + @TableField("moderation_status") + private String moderationStatus; + /** * 来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java index 4a238076..bfe5f63a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java @@ -14,6 +14,6 @@ import org.apache.ibatis.annotations.Select; */ public interface EffectDiagramMapper extends BaseMapper { - @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") + @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' WHERE e.is_delete = 0 AND e.moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java index 40115dab..bfe1e148 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java @@ -51,6 +51,6 @@ public interface ProductMapper extends BaseMapper { @Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}") int decrementLikeCount(@Param("productId") Long productId); - @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") + @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' WHERE p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java index 46ab151c..cd7dcbee 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java @@ -7,10 +7,26 @@ import com.xiaowang.jayucloud.salon.core.modules.product.entity.EffectDiagramDO; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; import com.xiaowang.jayucloud.salon.core.modules.product.service.EffectDiagramService; import com.xiaowang.jayucloud.salon.core.modules.product.vo.EffectDiagramVO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.util.StringUtils; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Collections; +import java.util.Arrays; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; import java.util.stream.Collectors; /** @@ -27,6 +43,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl 0; + EffectDiagramDO candidate = copy(source); + candidate.setProductId(effectDiagramDTO.getProductId()); + candidate.setCategory(effectDiagramDTO.getCategory()); + candidate.setImageFileIds(effectDiagramDTO.getImageFileIds()); + candidate.setDescription(effectDiagramDTO.getDescription()); + candidate.setPrice(effectDiagramDTO.getPrice()); + candidate.setDuration(effectDiagramDTO.getDuration()); + candidate.setTag(effectDiagramDTO.getTag()); + candidate.setModerationStatus("PENDING"); + ContentModerationResultVO moderation = assess(candidate); + return "APPROVED".equals(moderation.getStatus()) && effectDiagramMapper.updateById(candidate) > 0; } @Override @@ -81,7 +110,7 @@ public class EffectDiagramServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend */ public List listAllEffectDiagrams() { - List effectDiagramDOs = effectDiagramMapper.selectList(null); + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class).eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED")); return effectDiagramDOs.stream() + .filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -133,8 +166,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) .eq(EffectDiagramDO::getProductId, productId) + .eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED") ); - return effectDiagramDOs.stream() + return effectDiagramDOs.stream().filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -150,8 +185,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) .eq(EffectDiagramDO::getCategory, category) + .eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED") ); - return effectDiagramDOs.stream() + return effectDiagramDOs.stream().filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -177,4 +214,66 @@ public class EffectDiagramServiceImpl extends ServiceImpl payload = new LinkedHashMap<>(); + payload.put("productId", effect.getProductId()); payload.put("category", effect.getCategory()); + payload.put("imageFileIds", effect.getImageFileIds()); payload.put("description", effect.getDescription()); + payload.put("price", effect.getPrice()); payload.put("duration", effect.getDuration()); payload.put("tag", effect.getTag()); + String text = String.join("\n", safe(effect.getCategory()), safe(effect.getDescription()), safe(effect.getTag())); + return contentModerationService.assessVersion("EFFECT_DIAGRAM", effect.getId(), currentUserId(), text, + objectMapper.writeValueAsString(payload), parseImageFileIds(effect.getImageFileIds())); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("效果图审核内容序列化失败", exception); + } + } + + private EffectDiagramDO copy(EffectDiagramDO source) { + EffectDiagramDO target = new EffectDiagramDO(); + target.setId(source.getId()); target.setProductId(source.getProductId()); target.setCategory(source.getCategory()); + target.setImageFileIds(source.getImageFileIds()); target.setDescription(source.getDescription()); target.setPrice(source.getPrice()); + target.setDuration(source.getDuration()); target.setTag(source.getTag()); target.setLikeCount(source.getLikeCount()); + target.setModerationStatus(source.getModerationStatus()); target.setIsDelete(source.getIsDelete()); + target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private boolean isPublic(EffectDiagramDO effect) { + ProductDO product = effect.getProductId() == null ? null : productMapper.selectById(effect.getProductId()); + ShopDO shop = product == null || product.getShopId() == null ? null : shopMapper.selectById(product.getShopId()); + return product != null && shop != null + && Integer.valueOf(0).equals(product.getIsDelete()) + && Integer.valueOf(1).equals(product.getFrontVisible()) + && "APPROVED".equals(product.getModerationStatus()) + && Integer.valueOf(0).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(shop.getStatus()) + && "APPROVED".equals(shop.getModerationStatus()); + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + List imageIds = new ArrayList<>(); + for (String valuePart : value.split(",")) { + String token = valuePart.trim(); + if (!StringUtils.hasText(token)) continue; + try { + long fileId = Long.parseLong(token); + if (fileId <= 0) throw new NumberFormatException("file id must be positive"); + imageIds.add(fileId); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("效果图必须引用已上传文件", exception); + } + } + return imageIds.stream().distinct().collect(java.util.stream.Collectors.toList()); + } + + private String safe(String value) { return value == null ? "" : value; } + + private Long currentUserId() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) return null; + Object value = attributes.getRequest().getAttribute("userId"); + return value instanceof Long ? (Long) value : null; + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java index 84d3dd52..6f990bc3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java @@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; import com.xiaowang.jayucloud.salon.core.modules.product.dto.ProductDTO; import com.xiaowang.jayucloud.salon.core.modules.marketing.entity.CouponDO; @@ -24,8 +26,11 @@ import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO; import com.xiaowang.jayucloud.salon.core.modules.product.vo.TagInfo; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.Duration; @@ -113,6 +118,8 @@ public class ProductServiceImpl extends ServiceImpl im * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final AppCacheProperties appCacheProperties; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; @Override /** @@ -121,6 +128,7 @@ public class ProductServiceImpl extends ServiceImpl im * @param productDTO parameter `productDTO` supplied by the caller * @return Long result consumed by the caller or returned to the frontend */ + @Transactional(rollbackFor = Exception.class) public Long createProduct(ProductDTO productDTO) { validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); @@ -138,10 +146,18 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setApproximateDuration(productDTO.getApproximateDuration()); productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible())); + Integer requestedFrontVisible = resolveFrontVisible(productDTO.getFrontVisible()); + productDO.setFrontVisible(0); productDO.setSourceType(resolveSourceType(productDTO.getSourceType())); productDO.setIsDelete(0); + productDO.setModerationStatus("PENDING"); productMapper.insert(productDO); + ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible, productDTO.getPublisherUserId()); + if ("APPROVED".equals(moderation.getStatus())) { + productDO.setFrontVisible(requestedFrontVisible); + productDO.setModerationStatus("APPROVED"); + productMapper.updateById(productDO); + } evictPublicProductCaches(productDO.getId()); return productDO.getId(); } @@ -154,6 +170,7 @@ public class ProductServiceImpl extends ServiceImpl im * @param productDTO parameter `productDTO` supplied by the caller * @return boolean result consumed by the caller or returned to the frontend */ + @Transactional(rollbackFor = Exception.class) public boolean updateProduct(Long id, ProductDTO productDTO) { ProductDO productDO = productMapper.selectById(id); if (productDO == null) { @@ -161,26 +178,35 @@ public class ProductServiceImpl extends ServiceImpl im } validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); - productDO.setShopId(productDTO.getShopId()); - productDO.setTitle(productDTO.getTitle()); - productDO.setDescription(productDTO.getDescription()); - productDO.setTargetAudience(productDTO.getTargetAudience()); - productDO.setPrecautions(productDTO.getPrecautions()); - productDO.setImageFileIds(productDTO.getImageFileIds()); - productDO.setPrice(productDTO.getPrice()); - productDO.setTags(productDTO.getTags()); + ProductDO candidate = copyProduct(productDO); + candidate.setShopId(productDTO.getShopId()); + candidate.setTitle(productDTO.getTitle()); + candidate.setDescription(productDTO.getDescription()); + candidate.setTargetAudience(productDTO.getTargetAudience()); + candidate.setPrecautions(productDTO.getPrecautions()); + candidate.setImageFileIds(productDTO.getImageFileIds()); + candidate.setPrice(productDTO.getPrice()); + candidate.setTags(productDTO.getTags()); if (productDTO.getLikeCount() != null) { - productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + candidate.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); } if (productDTO.getCollectCount() != null) { - productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + candidate.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + } + candidate.setApproximateDuration(productDTO.getApproximateDuration()); + candidate.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + candidate.setAvailableCoupons(productDTO.getAvailableCoupons()); + Integer requestedFrontVisible = resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible()); + candidate.setFrontVisible(productDO.getFrontVisible()); + candidate.setModerationStatus("PENDING"); + candidate.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); + ContentModerationResultVO moderation = assessProduct(candidate, requestedFrontVisible, productDTO.getPublisherUserId()); + boolean updated = true; + if ("APPROVED".equals(moderation.getStatus())) { + candidate.setFrontVisible(requestedFrontVisible); + candidate.setModerationStatus("APPROVED"); + updated = productMapper.updateById(candidate) > 0; } - productDO.setApproximateDuration(productDTO.getApproximateDuration()); - productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); - productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible())); - productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); - boolean updated = productMapper.updateById(productDO) > 0; if (updated) { /** * Run business method `evictPublicProductCaches`. @@ -193,6 +219,59 @@ public class ProductServiceImpl extends ServiceImpl im return updated; } + private ContentModerationResultVO assessProduct(ProductDO product, Integer requestedFrontVisible, Long publisherUserId) { + try { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("shopId", product.getShopId()); snapshot.put("title", product.getTitle()); + snapshot.put("description", product.getDescription()); snapshot.put("targetAudience", product.getTargetAudience()); + snapshot.put("precautions", product.getPrecautions()); snapshot.put("imageFileIds", product.getImageFileIds()); + snapshot.put("price", product.getPrice()); snapshot.put("tags", product.getTags()); + snapshot.put("approximateDuration", product.getApproximateDuration()); snapshot.put("bookableArtists", product.getBookableArtists()); + snapshot.put("availableCoupons", product.getAvailableCoupons()); snapshot.put("frontVisible", requestedFrontVisible == null ? 1 : requestedFrontVisible); + String content = String.join("\n", List.of(safe(product.getTitle()), safe(product.getDescription()), + safe(product.getTargetAudience()), safe(product.getPrecautions()), safe(product.getTags()))); + return contentModerationService.assessVersion("PRODUCT", product.getId(), publisherUserId, + content, objectMapper.writeValueAsString(snapshot), parseImageFileIds(product.getImageFileIds())); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("作品审核内容序列化失败", exception); + } + } + + private ProductDO copyProduct(ProductDO source) { + ProductDO target = new ProductDO(); + target.setId(source.getId()); target.setShopId(source.getShopId()); target.setTitle(source.getTitle()); + target.setDescription(source.getDescription()); target.setTargetAudience(source.getTargetAudience()); + target.setPrecautions(source.getPrecautions()); target.setImageFileIds(source.getImageFileIds()); + target.setPrice(source.getPrice()); target.setTags(source.getTags()); target.setLikeCount(source.getLikeCount()); + target.setCollectCount(source.getCollectCount()); target.setApproximateDuration(source.getApproximateDuration()); + target.setBookableArtists(source.getBookableArtists()); target.setAvailableCoupons(source.getAvailableCoupons()); + target.setFrontVisible(source.getFrontVisible()); target.setSourceType(source.getSourceType()); + target.setModerationStatus(source.getModerationStatus()); target.setIsDelete(source.getIsDelete()); + target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + List imageIds = new ArrayList<>(); + for (String valuePart : value.split(",")) { + String token = valuePart.trim(); + if (!StringUtils.hasText(token)) continue; + try { + long fileId = Long.parseLong(token); + if (fileId <= 0) throw new NumberFormatException("file id must be positive"); + imageIds.add(fileId); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("作品图片必须引用已上传文件", exception); + } + } + return imageIds.stream().distinct().collect(Collectors.toList()); + } + + private String safe(String value) { + return value == null ? "" : value; + } + @Override /** * Delete, revoke, or logically remove a record. @@ -305,7 +384,9 @@ public class ProductServiceImpl extends ServiceImpl im ProductDO productDO = productMapper.selectById(id); if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete()) - || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible())) { + || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible()) + || !"APPROVED".equals(productDO.getModerationStatus()) + || !isPublicShop(productDO.getShopId())) { return null; } return convertToVO(productDO); @@ -887,6 +968,7 @@ public class ProductServiceImpl extends ServiceImpl im LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .eq(ProductDO::getModerationStatus, "APPROVED") .orderByDesc(ProductDO::getCreateTime); if (shopId != null) { wrapper.eq(ProductDO::getShopId, shopId); @@ -984,7 +1066,11 @@ public class ProductServiceImpl extends ServiceImpl im private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getFrontVisible, FRONT_VISIBLE); + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .eq(ProductDO::getModerationStatus, "APPROVED"); + wrapper.apply("EXISTS (SELECT 1 FROM t_shop public_product_shop WHERE public_product_shop.id = t_product.shop_id " + + "AND public_product_shop.is_delete = 0 AND public_product_shop.status = 1 " + + "AND public_product_shop.moderation_status = 'APPROVED')"); if (shopId != null) { wrapper.eq(ProductDO::getShopId, shopId); } @@ -1006,12 +1092,22 @@ public class ProductServiceImpl extends ServiceImpl im return wrapper; } + private boolean isPublicShop(Long shopId) { + if (shopId == null || shopId <= 0) return false; + ShopDO shop = shopMapper.selectById(shopId); + return shop != null && !Integer.valueOf(1).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(shop.getStatus()) + && "APPROVED".equals(shop.getModerationStatus()); + } + private Integer resolveFrontVisible(Integer frontVisible) { return Integer.valueOf(0).equals(frontVisible) ? 0 : FRONT_VISIBLE; } private String resolveSourceType(String sourceType) { - return StringUtils.hasText(sourceType) ? sourceType.trim() : SOURCE_TYPE_BACKEND; + // MANAGER_APPOINTMENT products are created only by the planning domain. A public + // product endpoint must never trust a client-provided source to bypass moderation. + return SOURCE_TYPE_BACKEND; } private Integer resolveUpdateFrontVisible(Integer currentFrontVisible, Integer nextFrontVisible) { @@ -1022,10 +1118,8 @@ public class ProductServiceImpl extends ServiceImpl im } private String resolveUpdateSourceType(String currentSourceType, String nextSourceType) { - if (StringUtils.hasText(nextSourceType)) { - return resolveSourceType(nextSourceType); - } - return StringUtils.hasText(currentSourceType) ? currentSourceType : SOURCE_TYPE_BACKEND; + return "MANAGER_APPOINTMENT".equals(currentSourceType) + ? currentSourceType : SOURCE_TYPE_BACKEND; } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java index f058ca6f..97bb3b87 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java @@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.controller; import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRejectDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationAssociateDTO; import com.xiaowang.jayucloud.salon.core.modules.registration.service.WorkbenchRegistrationService; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; @@ -18,7 +20,7 @@ import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController -@RequestMapping("/admin/user/workbench/registration") +@RequestMapping({"/admin/user/workbench/registration", "/user/workbench/registration"}) public class AdminWorkbenchRegistrationController { private final WorkbenchRegistrationService registrationService; private final UserMapper userMapper; @@ -40,11 +42,29 @@ public class AdminWorkbenchRegistrationController { return Result.success(registrationService.getReviewSummary(requireUserId(request))); } + @GetMapping("/unassociated") + public Result> unassociatedApplications(HttpServletRequest request) { + return Result.success(registrationService.listUnassociatedApplications(requireUserId(request))); + } + @PostMapping("/{id}/approve") - public Result approve(HttpServletRequest request, @PathVariable Long id) { + public Result approve(HttpServletRequest request, @PathVariable Long id, + @RequestBody(required = false) WorkbenchRegistrationApproveDTO requestDTO) { Long userId = requireUserId(request); UserDO user = userMapper.selectById(userId); - return Result.success(registrationService.approve(userId, isPlatformAdmin(user), id)); + return Result.success(registrationService.approve(userId, isPlatformAdmin(user), id, requestDTO)); + } + + @GetMapping("/{id}/unbound-artists") + public Result unboundArtists(HttpServletRequest request, @PathVariable Long id) { + return Result.success(registrationService.listUnboundArtists(requireUserId(request), id)); + } + + @PostMapping("/{id}/pre-associate") + public Result preAssociate(HttpServletRequest request, @PathVariable Long id, + @RequestBody WorkbenchRegistrationAssociateDTO requestDTO) { + return Result.success(registrationService.preAssociate(requireUserId(request), id, + requestDTO == null ? null : requestDTO.getTargetArtistUserId())); } @PostMapping("/{id}/reject") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationAvatarController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationAvatarController.java new file mode 100644 index 00000000..257f023d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationAvatarController.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.controller; + +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationAvatarVO; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Locale; + +@RestController +@RequestMapping("/user/workbench/register") +public class WorkbenchRegistrationAvatarController { + + private static final long MAX_AVATAR_SIZE = 5L * 1024 * 1024; + + private final WechatMiniAuthService wechatMiniAuthService; + private final ObjectStorageDirectUploadService objectStorageDirectUploadService; + + public WorkbenchRegistrationAvatarController(WechatMiniAuthService wechatMiniAuthService, + ObjectStorageDirectUploadService objectStorageDirectUploadService) { + this.wechatMiniAuthService = wechatMiniAuthService; + this.objectStorageDirectUploadService = objectStorageDirectUploadService; + } + + @PostMapping("/avatar") + public Result uploadAvatar( + @RequestParam("registrationTicket") String registrationTicket, + @RequestParam("file") MultipartFile file) { + if (!StringUtils.hasText(registrationTicket)) return Result.error("注册票据不能为空"); + if (file == null || file.isEmpty() || file.getSize() > MAX_AVATAR_SIZE) { + return Result.error("头像不能为空且不能超过5MB"); + } + String contentType = file.getContentType() == null ? "" : file.getContentType().toLowerCase(Locale.ROOT); + String filename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().toLowerCase(Locale.ROOT); + boolean supportedImage = ("image/jpeg".equals(contentType) && (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))) + || ("image/png".equals(contentType) && filename.endsWith(".png")) + || ("image/webp".equals(contentType) && filename.endsWith(".webp")); + if (!supportedImage) return Result.error("头像仅支持 JPG、PNG 或 WebP 图片"); + + try { + wechatMiniAuthService.validateRegistrationTicket(registrationTicket); + ObjectStorageFileVO fileVO = objectStorageDirectUploadService.upload(file); + wechatMiniAuthService.rememberRegistrationAvatarUpload(registrationTicket, fileVO.getId()); + return Result.success(new WorkbenchRegistrationAvatarVO(fileVO.getId())); + } catch (Exception error) { + return Result.error(error.getMessage() == null ? "头像上传失败" : error.getMessage()); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java index 848c0128..d1b9dba1 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java @@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -38,7 +39,14 @@ public class WorkbenchRegistrationController { @GetMapping("/register/status") public Result status(@RequestParam String phone) { - UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone, phone).eq(UserDO::getIsDelete, 0).last("limit 1")); + String normalizedPhone = phone == null ? "" : phone.trim(); + UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone)) + .eq(UserDO::getIsDelete, 0).last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } if (user == null) { throw new IllegalArgumentException("未找到注册申请"); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationApproveDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationApproveDTO.java new file mode 100644 index 00000000..af856e55 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationApproveDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class WorkbenchRegistrationApproveDTO { + private Long targetArtistUserId; + private Boolean useApplicantNickname; + private Boolean useApplicantAvatar; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationAssociateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationAssociateDTO.java new file mode 100644 index 00000000..3f996b87 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationAssociateDTO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class WorkbenchRegistrationAssociateDTO { + private Long targetArtistUserId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java index f2714893..2afe55be 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java @@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.dto; import lombok.Getter; import lombok.Setter; +import java.math.BigDecimal; + @Getter @Setter public class WorkbenchRegistrationRequestDTO { @@ -12,5 +14,9 @@ public class WorkbenchRegistrationRequestDTO { private Long shopId; private String shopName; private String shopAddress; + private BigDecimal shopLongitude; + private BigDecimal shopLatitude; private Boolean agreementAccepted; + private String applicantNickname; + private Long applicantAvatarFileId; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java index 522b8b3f..3a1d7abf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java @@ -43,6 +43,18 @@ public class WorkbenchRegistrationApplicationDO extends BaseEntity { @TableField("reject_reason") private String rejectReason; + @TableField("content_moderation_record_id") + private Long contentModerationRecordId; + + @TableField("target_artist_user_id") + private Long targetArtistUserId; + + @TableField("applicant_nickname") + private String applicantNickname; + + @TableField("applicant_avatar_file_id") + private Long applicantAvatarFileId; + @TableField("is_delete") private Integer isDelete; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationStatus.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationStatus.java index fdf1c1ed..4416b58b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationStatus.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationStatus.java @@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.entity; public final class WorkbenchRegistrationStatus { public static final String PENDING_ADMIN = "PENDING_ADMIN"; + public static final String PENDING_CONTENT = "PENDING_CONTENT"; public static final String PENDING_MANAGER = "PENDING_MANAGER"; public static final String APPROVED = "APPROVED"; public static final String REJECTED = "REJECTED"; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java index d3b68a5e..244fda3c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java @@ -5,8 +5,38 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRe import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; +import java.util.List; + public interface WorkbenchRegistrationApplicationMapper extends BaseMapper { @Select("SELECT * FROM t_workbench_registration_application WHERE id = #{id} AND is_delete = 0 FOR UPDATE") WorkbenchRegistrationApplicationDO selectByIdForUpdate(@Param("id") Long id); + + @Select("SELECT a.* FROM t_workbench_registration_application a " + + "INNER JOIN t_content_moderation_record m ON m.id = a.content_moderation_record_id " + + "AND m.content_type = 'STAFF_REGISTRATION' AND m.business_id = a.id AND m.user_id = a.user_id " + + "AND m.status = 'APPROVED' " + + "WHERE a.role_type = 'STAFF' AND a.status = 'PENDING_MANAGER' AND a.shop_id = #{shopId} " + + "AND a.is_delete = 0 ORDER BY a.create_time ASC, a.id ASC") + List selectPendingStaffApplicationsForReview(@Param("shopId") Long shopId); + + @Select("SELECT COUNT(*) FROM t_workbench_registration_application a " + + "INNER JOIN t_content_moderation_record m ON m.id = a.content_moderation_record_id " + + "AND m.content_type = 'STAFF_REGISTRATION' AND m.business_id = a.id AND m.user_id = a.user_id " + + "AND m.status = 'APPROVED' " + + "WHERE a.role_type = 'STAFF' AND a.status = 'PENDING_MANAGER' AND a.shop_id = #{shopId} " + + "AND a.is_delete = 0") + Long countPendingStaffApplicationsForReview(@Param("shopId") Long shopId); + + @Select("SELECT a.* FROM t_workbench_registration_application a " + + "LEFT JOIN t_content_moderation_record m ON m.id = a.content_moderation_record_id " + + "WHERE a.role_type = 'STAFF' AND a.is_delete = 0 AND (" + + "(a.status = 'PENDING_CONTENT' AND (m.id IS NULL OR m.content_type IS NULL OR m.content_type <> 'STAFF_REGISTRATION' " + + "OR m.business_id IS NULL OR m.business_id <> a.id OR m.user_id IS NULL OR m.user_id <> a.user_id " + + "OR m.status IS NULL OR m.status IN ('APPROVED', 'REJECTED'))) " + + "OR (a.status = 'PENDING_MANAGER' AND (m.id IS NULL OR m.content_type IS NULL OR m.content_type <> 'STAFF_REGISTRATION' " + + "OR m.business_id IS NULL OR m.business_id <> a.id OR m.user_id IS NULL OR m.user_id <> a.user_id " + + "OR m.status IS NULL OR m.status <> 'APPROVED'))) " + + "ORDER BY a.create_time ASC, a.id ASC LIMIT 100") + List selectStaffApplicationsAwaitingContentReview(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/scheduler/ManagerRegistrationModerationScheduler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/scheduler/ManagerRegistrationModerationScheduler.java new file mode 100644 index 00000000..c6b0bb11 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/scheduler/ManagerRegistrationModerationScheduler.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.scheduler; + +import com.xiaowang.jayucloud.salon.core.modules.registration.service.WorkbenchRegistrationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ManagerRegistrationModerationScheduler { + private final WorkbenchRegistrationService registrationService; + + @Scheduled(fixedDelay = 30000L) + public void processPendingApplications() { + try { + registrationService.processPendingManagerModeration(); + registrationService.processPendingStaffModeration(); + } catch (RuntimeException exception) { + log.warn("注册申请内容审核补偿处理失败", exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java index fe41e0a0..d0b1e2f8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java @@ -1,9 +1,11 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.service; import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationArtistVO; import java.util.List; @@ -14,5 +16,11 @@ public interface WorkbenchRegistrationService { List listForReviewer(Long reviewerId, boolean platformAdmin); WorkbenchRegistrationReviewSummaryVO getReviewSummary(Long reviewerId); boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId); + boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId, WorkbenchRegistrationApproveDTO request); boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason); + List listUnboundArtists(Long reviewerId, Long applicationId); + List listUnassociatedApplications(Long reviewerId); + boolean preAssociate(Long reviewerId, Long applicationId, Long targetArtistUserId); + void processPendingManagerModeration(); + void processPendingStaffModeration(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java index fdab6898..52ec2150 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java @@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationRole; import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus; @@ -10,6 +11,9 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.service.WorkbenchR import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationArtistVO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniRegistrationTicket; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; @@ -17,16 +21,28 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.LocalDateTime; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; @@ -44,6 +60,14 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe private final UserShopBindingMapper userShopBindingMapper; private final WechatMiniAuthService wechatMiniAuthService; private final SystemParameterConfigService systemParameterConfigService; + private final ContentModerationService contentModerationService; + private final ContentModerationRecordMapper contentModerationRecordMapper; + private final ShopBusinessExpiryService shopBusinessExpiryService; + private final ShopBusinessScheduleService shopBusinessScheduleService; + private final TransactionTemplate transactionTemplate; + private final WechatMiniBindingMapper wechatMiniBindingMapper; + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; public WorkbenchRegistrationServiceImpl( WorkbenchRegistrationApplicationMapper applicationMapper, @@ -53,7 +77,15 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe UserShopBindingSupport userShopBindingSupport, UserShopBindingMapper userShopBindingMapper, WechatMiniAuthService wechatMiniAuthService, - SystemParameterConfigService systemParameterConfigService + SystemParameterConfigService systemParameterConfigService, + ContentModerationService contentModerationService, + ContentModerationRecordMapper contentModerationRecordMapper, + ShopBusinessExpiryService shopBusinessExpiryService, + ShopBusinessScheduleService shopBusinessScheduleService, + PlatformTransactionManager transactionManager, + WechatMiniBindingMapper wechatMiniBindingMapper, + ObjectStorageFileService objectStorageFileService, + ObjectStorageUrlSupport objectStorageUrlSupport ) { this.applicationMapper = applicationMapper; this.userMapper = userMapper; @@ -63,6 +95,14 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe this.userShopBindingMapper = userShopBindingMapper; this.wechatMiniAuthService = wechatMiniAuthService; this.systemParameterConfigService = systemParameterConfigService; + this.contentModerationService = contentModerationService; + this.contentModerationRecordMapper = contentModerationRecordMapper; + this.shopBusinessExpiryService = shopBusinessExpiryService; + this.shopBusinessScheduleService = shopBusinessScheduleService; + this.transactionTemplate = new TransactionTemplate(transactionManager); + this.wechatMiniBindingMapper = wechatMiniBindingMapper; + this.objectStorageFileService = objectStorageFileService; + this.objectStorageUrlSupport = objectStorageUrlSupport; } @Override @@ -75,6 +115,13 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe String managerShopName = WorkbenchRegistrationRole.MANAGER.equals(roleType) ? requireText(request.getShopName(), "店铺名称不能为空") : null; + if ((request.getShopLongitude() == null) != (request.getShopLatitude() == null)) { + throw new IllegalArgumentException("地图坐标信息不完整,请重新选点"); + } + if (request.getShopLongitude() != null && (request.getShopLongitude().abs().compareTo(java.math.BigDecimal.valueOf(180)) > 0 + || request.getShopLatitude().abs().compareTo(java.math.BigDecimal.valueOf(90)) > 0)) { + throw new IllegalArgumentException("地图坐标超出有效范围"); + } ShopDO selectedStaffShop = null; if (WorkbenchRegistrationRole.STAFF.equals(roleType)) { require(request.getShopId() != null, "请选择要加入的店铺"); @@ -82,38 +129,55 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe require(selectedStaffShop != null, "店铺不存在或暂未营业"); } - WechatMiniRegistrationTicket ticket = wechatMiniAuthService.consumeRegistrationTicket( - requireText(request.getRegistrationTicket(), "注册票据不能为空")); + if (WorkbenchRegistrationRole.STAFF.equals(roleType)) { + String applicantNickname = requireText(request.getApplicantNickname(), "昵称不能为空"); + require(applicantNickname.length() <= 20, "昵称不能超过20个字"); + require(request.getApplicantAvatarFileId() != null, "请选择头像"); + } + + String registrationTicket = requireText(request.getRegistrationTicket(), "注册票据不能为空"); + WechatMiniRegistrationTicket ticket = wechatMiniAuthService.validateRegistrationTicket(registrationTicket); UserDO user = userMapper.selectById(ticket.getUserId()); require(user != null && !Integer.valueOf(1).equals(user.getIsDelete()), "注册用户不存在"); - WorkbenchRegistrationApplicationDO application = request.getApplicationId() == null + WorkbenchRegistrationApplicationDO previousApplication = request.getApplicationId() == null ? findLatest(user.getId()) : applicationMapper.selectById(request.getApplicationId()); - if (application != null) { - require(user.getId().equals(application.getUserId()), "注册申请与账号不匹配"); - require(WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus()), "该注册申请当前不可重新提交"); - } else { - application = new WorkbenchRegistrationApplicationDO(); + if (request.getApplicationId() != null) { + require(previousApplication != null && Integer.valueOf(0).equals(previousApplication.getIsDelete()), "注册申请不存在"); } + if (previousApplication != null) { + require(user.getId().equals(previousApplication.getUserId()), "注册申请与账号不匹配"); + require(WorkbenchRegistrationStatus.REJECTED.equals(previousApplication.getStatus()), "该注册申请当前不可重新提交"); + require(roleType.equals(previousApplication.getRoleType()), "不能修改注册身份,请重新选择身份"); + } + + if (WorkbenchRegistrationRole.STAFF.equals(roleType)) { + wechatMiniAuthService.validateRegistrationAvatarUpload(registrationTicket, request.getApplicantAvatarFileId()); + } + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); ShopDO shop = null; if (WorkbenchRegistrationRole.MANAGER.equals(roleType)) { - shop = WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType()) && application.getShopId() != null - ? shopMapper.selectById(application.getShopId()) : null; + shop = previousApplication != null && WorkbenchRegistrationRole.MANAGER.equals(previousApplication.getRoleType()) + && previousApplication.getShopId() != null ? shopMapper.selectById(previousApplication.getShopId()) : null; if (shop == null) { shop = new ShopDO(); } shop.setShopName(managerShopName); shop.setAddress(request.getShopAddress()); + shop.setLongitude(request.getShopLongitude()); + shop.setLatitude(request.getShopLatitude()); shop.setDescription("Salon店务工作台注册申请"); shop.setBusinessHours("10:00-22:00"); shop.setStatus(0); shop.setIsDelete(0); + shop.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDateTime.now().toLocalDate())); if (shop.getId() == null) { shopMapper.insert(shop); } else { shopMapper.updateById(shop); } + shopBusinessScheduleService.initializeDefault(shop.getId(), "10:00-22:00"); } else { shop = selectedStaffShop; } @@ -133,24 +197,48 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe userShopBindingSupport.updateBindingStatus(user.getId(), shop.getId(), 0); } - if (!StringUtils.hasText(application.getApplicationNo())) { - application.setApplicationNo("SALON-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20).toUpperCase()); - } + application.setApplicationNo("SALON-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20).toUpperCase()); application.setUserId(user.getId()); application.setRoleType(roleType); application.setShopId(shop.getId()); application.setShopName(shop.getShopName()); application.setShopAddress(shop.getAddress()); - application.setStatus(WorkbenchRegistrationRole.MANAGER.equals(roleType) ? WorkbenchRegistrationStatus.PENDING_ADMIN : WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setStatus(WorkbenchRegistrationRole.MANAGER.equals(roleType) ? WorkbenchRegistrationStatus.PENDING_ADMIN : WorkbenchRegistrationStatus.PENDING_CONTENT); + application.setTargetArtistUserId(null); + application.setApplicantNickname(WorkbenchRegistrationRole.STAFF.equals(roleType) && StringUtils.hasText(request.getApplicantNickname()) + ? request.getApplicantNickname().trim() : null); + application.setApplicantAvatarFileId(WorkbenchRegistrationRole.STAFF.equals(roleType) ? request.getApplicantAvatarFileId() : null); + application.setContentModerationRecordId(null); application.setRejectReason(null); application.setReviewerId(null); application.setReviewedAt(null); application.setIsDelete(0); - if (application.getId() == null) { - applicationMapper.insert(application); - } else { + applicationMapper.insert(application); + if (WorkbenchRegistrationRole.MANAGER.equals(roleType)) { + String reviewText = "门店名称:" + shop.getShopName() + "\n门店地址:" + (shop.getAddress() == null ? "未填写" : shop.getAddress()); + ContentModerationResultVO moderation = contentModerationService.assessVersion( + "SHOP", null, user.getId(), reviewText, null, Collections.emptyList()); + application.setContentModerationRecordId(moderation.getRecordId()); + applicationMapper.updateById(application); + processManagerModeration(application.getId()); + application = applicationMapper.selectById(application.getId()); + } else if (application.getApplicantNickname() != null || application.getApplicantAvatarFileId() != null) { + ContentModerationResultVO moderation = contentModerationService.assessVersion( + "STAFF_REGISTRATION", application.getId(), user.getId(), application.getApplicantNickname(), null, + application.getApplicantAvatarFileId() == null ? Collections.emptyList() : List.of(application.getApplicantAvatarFileId())); + require(moderation != null && moderation.getRecordId() != null, "申请资料审核记录创建失败,请重试"); + application.setContentModerationRecordId(moderation.getRecordId()); + if ("REJECTED".equals(moderation.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setRejectReason(StringUtils.hasText(moderation.getReason()) ? moderation.getReason() : "申请资料内容未通过审核"); + application.setReviewedAt(LocalDateTime.now()); + } else if ("APPROVED".equals(moderation.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + } applicationMapper.updateById(application); } + // 在数据库写入全部成功后消费票据,避免校验或持久化失败消耗用户凭证。 + wechatMiniAuthService.consumeRegistrationTicket(registrationTicket); return toStatus(application); } @@ -172,10 +260,13 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe public List listForReviewer(Long reviewerId, boolean platformAdmin) { List applications; if (platformAdmin) { - applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getRoleType, WorkbenchRegistrationRole.MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime)); } else { UserDO reviewer = requireManager(reviewerId); - applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER).eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + applications = applicationMapper.selectPendingStaffApplicationsForReview(reviewer.getShopId()); } List applicantIds = applications.stream() .map(WorkbenchRegistrationApplicationDO::getUserId) @@ -186,18 +277,27 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe ? Map.of() : userMapper.selectBatchIds(applicantIds).stream() .collect(Collectors.toMap(UserDO::getId, Function.identity())); + List moderationIds = applications.stream() + .map(WorkbenchRegistrationApplicationDO::getContentModerationRecordId) + .filter(Objects::nonNull).distinct().collect(Collectors.toList()); + Map moderationById = moderationIds.isEmpty() + ? Map.of() + : contentModerationRecordMapper.selectBatchIds(moderationIds).stream() + .collect(Collectors.toMap(ContentModerationRecordDO::getId, Function.identity())); return applications.stream() - .map(application -> toReviewVO(application, applicants.get(application.getUserId()))) + .filter(application -> platformAdmin || staffContentApproved(application, + application.getContentModerationRecordId() == null + ? null : moderationById.get(application.getContentModerationRecordId()))) + .map(application -> toReviewVO(application, applicants.get(application.getUserId()), + application.getContentModerationRecordId() == null + ? null : moderationById.get(application.getContentModerationRecordId()))) .collect(Collectors.toList()); } @Override public WorkbenchRegistrationReviewSummaryVO getReviewSummary(Long reviewerId) { UserDO reviewer = requireManager(reviewerId); - Long pendingCount = applicationMapper.selectCount(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) - .eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER) - .eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()) - .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0)); + Long pendingCount = applicationMapper.countPendingStaffApplicationsForReview(reviewer.getShopId()); boolean noticeEnabled = "true".equalsIgnoreCase(systemParameterConfigService.getEnabledValue( "WORKBENCH", "MANAGER_REGISTRATION_REVIEW_NOTICE")); return new WorkbenchRegistrationReviewSummaryVO(pendingCount == null ? 0L : pendingCount, noticeEnabled); @@ -206,20 +306,72 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe @Override @Transactional(rollbackFor = Exception.class) public boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId) { + return approve(reviewerId, platformAdmin, applicationId, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId, WorkbenchRegistrationApproveDTO request) { WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, platformAdmin, applicationId); + if (WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType())) { + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + require(moderation != null && "APPROVED".equals(moderation.getStatus()), "门店资料内容审核通过后才能审核注册申请"); + } + if (WorkbenchRegistrationRole.STAFF.equals(application.getRoleType())) { + Long targetArtistUserId = request != null && request.getTargetArtistUserId() != null + ? request.getTargetArtistUserId() : application.getTargetArtistUserId(); + require(targetArtistUserId != null, "请选择要关联的美甲师"); + require(targetArtistUserId > 0, "目标美甲师不合法"); + UserDO target = loadActiveArtistForUpdate(targetArtistUserId, application.getShopId()); + require(!hasActiveWechatBinding(target.getId()), "目标美甲师已关联微信账号"); + require(!hasPendingAssociation(target.getId(), applicationId), "该美甲师已被其他申请预关联"); + application.setTargetArtistUserId(target.getId()); + return approveApplication(application, reviewerId, request); + } + return approveApplication(application, reviewerId, request); + } + + private boolean approveApplication(WorkbenchRegistrationApplicationDO application, Long reviewerId) { + return approveApplication(application, reviewerId, null); + } + + private boolean approveApplication(WorkbenchRegistrationApplicationDO application, Long reviewerId, WorkbenchRegistrationApproveDTO request) { UserDO user = userMapper.selectById(application.getUserId()); require(user != null, "申请用户不存在"); if (WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType())) { - require(platformAdmin && WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()), "无权审核该申请"); ShopDO shop = shopMapper.selectById(application.getShopId()); require(shop != null, "申请店铺不存在"); shop.setStatus(1); shopMapper.updateById(shop); + shopBusinessExpiryService.startDefaultValidity(shop.getId(), LocalDateTime.now().toLocalDate()); + } + if (WorkbenchRegistrationRole.STAFF.equals(application.getRoleType())) { + Long targetId = application.getTargetArtistUserId(); + UserDO target = loadActiveArtistForUpdate(targetId, application.getShopId()); + if (request != null && Boolean.TRUE.equals(request.getUseApplicantNickname()) && StringUtils.hasText(application.getApplicantNickname())) { + requireApplicantProfileApproved(application); + target.setNickname(application.getApplicantNickname()); + } + if (request != null && Boolean.TRUE.equals(request.getUseApplicantAvatar()) && application.getApplicantAvatarFileId() != null) { + requireApplicantProfileApproved(application); + ObjectStorageFileVO file = contentModerationFile(application.getApplicantAvatarFileId()); + target.setAvatar(objectStorageUrlSupport.toStoredUrl(StringUtils.hasText(file.getObjectName()) + ? file.getObjectName() : file.getFileUrl())); + } + target.setStatus(1); + userMapper.updateById(target); + wechatMiniAuthService.transferRegistrationBinding(application.getUserId(), target.getId()); + userShopBindingSupport.updateBindingStatus(target.getId(), application.getShopId(), 1); + userService.syncManagedPermissions(target.getId()); + user.setStatus(0); + userMapper.updateById(user); + } else { + user.setStatus(1); + userMapper.updateById(user); + userShopBindingSupport.updateBindingStatus(user.getId(), application.getShopId(), 1); + userService.syncManagedPermissions(user.getId()); } - user.setStatus(1); - userMapper.updateById(user); - userShopBindingSupport.updateBindingStatus(user.getId(), application.getShopId(), 1); - userService.syncManagedPermissions(user.getId()); application.setStatus(WorkbenchRegistrationStatus.APPROVED); application.setReviewerId(reviewerId); application.setReviewedAt(LocalDateTime.now()); @@ -227,6 +379,161 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe return true; } + private ObjectStorageFileVO contentModerationFile(Long fileId) { + ObjectStorageFileVO file = objectStorageFileService.getObjectStorageFileById(fileId); + require(file != null && Integer.valueOf(1).equals(file.getStatus()), "申请头像文件不可用"); + return file; + } + + private void requireApplicantProfileApproved(WorkbenchRegistrationApplicationDO application) { + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + require(moderation != null && "STAFF_REGISTRATION".equals(moderation.getContentType()) + && Objects.equals(application.getId(), moderation.getBusinessId()) + && "APPROVED".equals(moderation.getStatus()), "申请昵称或头像尚未通过内容审核"); + } + + @Override + public List listUnboundArtists(Long reviewerId, Long applicationId) { + WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, false, applicationId); + List users = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getType, 3).eq(UserDO::getShopId, application.getShopId()).eq(UserDO::getStatus, 1).eq(UserDO::getIsDelete, 0).orderByAsc(UserDO::getNickname)); + return users.stream() + .filter(user -> !hasActiveWechatBinding(user.getId())) + .filter(user -> !hasPendingAssociation(user.getId(), applicationId)) + .map(user -> new WorkbenchRegistrationArtistVO(user.getId(), user.getNickname(), + objectStorageUrlSupport.toAccessibleUrl(user.getAvatar()))) + .collect(Collectors.toList()); + } + + @Override + public List listUnassociatedApplications(Long reviewerId) { + return listForReviewer(reviewerId, false).stream().filter(item -> item.getTargetArtistUserId() == null).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean preAssociate(Long reviewerId, Long applicationId, Long targetArtistUserId) { + WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, false, applicationId); + require(targetArtistUserId != null, "请选择美甲师"); + UserDO target = loadActiveArtistForUpdate(targetArtistUserId, application.getShopId()); + require(!hasActiveWechatBinding(target.getId()), "目标美甲师已关联微信账号"); + require(!hasPendingAssociation(targetArtistUserId, applicationId), "该美甲师已被其他申请预关联"); + application.setTargetArtistUserId(targetArtistUserId); + return applicationMapper.updateById(application) > 0; + } + + private UserDO loadActiveArtistForUpdate(Long userId, Long shopId) { + UserDO artist = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getId, userId) + .eq(UserDO::getType, 3) + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .last("FOR UPDATE")); + require(artist != null, "目标美甲师不属于当前门店或已停用"); + return artist; + } + + private boolean hasPendingAssociation(Long artistUserId, Long currentApplicationId) { + WorkbenchRegistrationApplicationDO occupied = applicationMapper.selectOne(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getTargetArtistUserId, artistUserId) + .eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .last("LIMIT 1 FOR UPDATE")); + return occupied != null && !Objects.equals(occupied.getId(), currentApplicationId); + } + + private boolean hasActiveWechatBinding(Long userId) { + return wechatMiniBindingMapper.selectCount(Wrappers.lambdaQuery(WechatMiniBindingDO.class).eq(WechatMiniBindingDO::getUserId, userId).eq(WechatMiniBindingDO::getStatus, 1)) > 0; + } + + public void processPendingManagerModeration() { + List pending = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getRoleType, WorkbenchRegistrationRole.MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .isNotNull(WorkbenchRegistrationApplicationDO::getContentModerationRecordId) + .orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime) + .last("LIMIT 100")); + for (WorkbenchRegistrationApplicationDO application : pending) { + try { + transactionTemplate.executeWithoutResult(status -> processManagerModeration(application.getId())); + } catch (RuntimeException ignored) { + // Roll back only this application; the next pass retries it independently. + } + } + } + + @Override + public void processPendingStaffModeration() { + for (WorkbenchRegistrationApplicationDO application : applicationMapper.selectStaffApplicationsAwaitingContentReview()) { + try { + transactionTemplate.executeWithoutResult(status -> processStaffModeration(application.getId())); + } catch (RuntimeException ignored) { + // 每个申请独立处理,失败后由下一轮补偿重试。 + } + } + } + + @Transactional(rollbackFor = Exception.class) + public void processStaffModeration(Long applicationId) { + WorkbenchRegistrationApplicationDO application = applicationMapper.selectByIdForUpdate(applicationId); + if (application == null || !WorkbenchRegistrationRole.STAFF.equals(application.getRoleType()) + || !(WorkbenchRegistrationStatus.PENDING_CONTENT.equals(application.getStatus()) + || WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) return; + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + boolean moderationMatches = moderation != null + && "STAFF_REGISTRATION".equals(moderation.getContentType()) + && Objects.equals(application.getId(), moderation.getBusinessId()) + && Objects.equals(application.getUserId(), moderation.getUserId()); + if (!moderationMatches) { + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setRejectReason("申请资料审核记录缺失或关联异常,请重新提交"); + application.setTargetArtistUserId(null); + application.setReviewedAt(LocalDateTime.now()); + } else if ("REJECTED".equals(moderation.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setRejectReason(StringUtils.hasText(moderation.getReason()) ? moderation.getReason() : "申请资料内容未通过审核"); + application.setTargetArtistUserId(null); + application.setReviewedAt(LocalDateTime.now()); + } else if ("APPROVED".equals(moderation.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setRejectReason(null); + application.setReviewedAt(null); + } else { + if (WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.PENDING_CONTENT); + applicationMapper.updateById(application); + } + return; + } + applicationMapper.updateById(application); + } + + @Transactional(rollbackFor = Exception.class) + public void processManagerModeration(Long applicationId) { + WorkbenchRegistrationApplicationDO application = applicationMapper.selectByIdForUpdate(applicationId); + if (application == null || !WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType()) + || !WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()) + || application.getContentModerationRecordId() == null) return; + ContentModerationRecordDO moderation = contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + if (moderation == null || !"SHOP".equals(moderation.getContentType()) || moderation.getBusinessId() != null + || !Objects.equals(moderation.getUserId(), application.getUserId())) return; + if ("REJECTED".equals(moderation.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setRejectReason(StringUtils.hasText(moderation.getReason()) ? moderation.getReason() : "门店资料内容未通过审核"); + application.setReviewedAt(LocalDateTime.now()); + applicationMapper.updateById(application); + return; + } + boolean autoApproveEnabled = "true".equalsIgnoreCase(systemParameterConfigService.getEnabledValue( + "WORKBENCH", "MANAGER_REGISTRATION_AUTO_APPROVE")); + if (autoApproveEnabled && "APPROVED".equals(moderation.getStatus())) { + approveApplication(application, null); + } + } + @Override @Transactional(rollbackFor = Exception.class) public boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason) { @@ -235,6 +542,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe application.setReviewerId(reviewerId); application.setReviewedAt(LocalDateTime.now()); application.setRejectReason(requireText(reason, "驳回原因不能为空")); + application.setTargetArtistUserId(null); applicationMapper.updateById(application); return true; } @@ -250,29 +558,50 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe require(Objects.equals(reviewer.getShopId(), application.getShopId()), "无权审核该店铺申请"); require(WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()), "店长只能审核店员申请"); require(WorkbenchRegistrationRole.STAFF.equals(application.getRoleType()), "店长只能审核店员申请"); + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + require(staffContentApproved(application, moderation), "申请资料内容审核通过后才能进入店长审核"); } return application; } private WorkbenchRegistrationApplicationDO findLatest(Long userId) { - return applicationMapper.selectOne(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getUserId, userId).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime).last("limit 1")); + return applicationMapper.selectOne(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getUserId, userId).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime).orderByDesc(WorkbenchRegistrationApplicationDO::getId).last("limit 1")); } private WorkbenchRegistrationStatusVO toStatus(WorkbenchRegistrationApplicationDO application) { - return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName()); + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), + application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName(), + moderation == null ? null : moderation.getStatus(), moderation == null ? null : moderation.getReason(), + application.getCreateTime()); } - private WorkbenchRegistrationReviewVO toReviewVO(WorkbenchRegistrationApplicationDO application, UserDO applicant) { + private WorkbenchRegistrationReviewVO toReviewVO(WorkbenchRegistrationApplicationDO application, UserDO applicant, + ContentModerationRecordDO moderation) { WorkbenchRegistrationReviewVO review = new WorkbenchRegistrationReviewVO(); BeanUtils.copyProperties(application, review); if (applicant != null) { - review.setApplicantNickname(applicant.getNickname()); - review.setApplicantAvatar(applicant.getAvatar()); + review.setApplicantNickname(application.getApplicantNickname()); + review.setApplicantAvatar(application.getApplicantAvatarFileId() != null + ? objectStorageFileService.createTemporaryModerationUrl(application.getApplicantAvatarFileId(), 30) : null); review.setApplicantMaskedPhone(maskPhone(applicant.getPhone())); } + review.setContentModerationStatus(moderation == null ? "MISSING" : moderation.getStatus()); + review.setContentModerationReason(moderation == null ? "未关联内容审核记录" : moderation.getReason()); + review.setTargetArtistUserId(application.getTargetArtistUserId()); return review; } + private boolean staffContentApproved(WorkbenchRegistrationApplicationDO application, ContentModerationRecordDO moderation) { + return moderation != null + && "STAFF_REGISTRATION".equals(moderation.getContentType()) + && Objects.equals(application.getId(), moderation.getBusinessId()) + && Objects.equals(application.getUserId(), moderation.getUserId()) + && "APPROVED".equals(moderation.getStatus()); + } + private UserDO requireManager(Long reviewerId) { UserDO reviewer = userMapper.selectById(reviewerId); require(reviewer != null && Integer.valueOf(2).equals(reviewer.getType()) && reviewer.getShopId() != null, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationArtistVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationArtistVO.java new file mode 100644 index 00000000..7ed59b99 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationArtistVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.vo; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class WorkbenchRegistrationArtistVO { + private Long userId; + private String nickname; + private String avatar; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationAvatarVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationAvatarVO.java new file mode 100644 index 00000000..41729448 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationAvatarVO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.vo; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class WorkbenchRegistrationAvatarVO { + private Long fileId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java index 16ab3fb0..714b6477 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java @@ -24,4 +24,7 @@ public class WorkbenchRegistrationReviewVO { private String applicantNickname; private String applicantAvatar; private String applicantMaskedPhone; + private Long targetArtistUserId; + private String contentModerationStatus; + private String contentModerationReason; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java index d23342fa..011bee69 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java @@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.vo; import lombok.AllArgsConstructor; import lombok.Getter; +import java.time.LocalDateTime; + @Getter @AllArgsConstructor public class WorkbenchRegistrationStatusVO { @@ -13,4 +15,7 @@ public class WorkbenchRegistrationStatusVO { private String rejectReason; private Long shopId; private String shopName; + private String contentModerationStatus; + private String contentModerationReason; + private LocalDateTime createTime; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java index 9e371877..ca1aaada 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java @@ -60,13 +60,6 @@ public class SecurityAuditLogDO extends BaseEntity { */ private String ipAddress; - @TableField("device_id") - /** - * Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - @TableField("operate_time") /** * Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java index 29e580c0..b4b32fc5 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java @@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO; import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper; import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; -import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.security.vo.SecurityAuditLogVO; import lombok.RequiredArgsConstructor; @@ -38,12 +37,11 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { try { SecurityAuditLogDO log = new SecurityAuditLogDO(); log.setUserId(userId); - log.setAccount(limit(account, 80)); + log.setAccount(maskPhoneAccount(account)); log.setAction(limit(action, 80)); log.setResult(limit(result, 20)); log.setReason(limit(reason, 500)); log.setIpAddress(limit(resolveClientIp(request), 80)); - log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120)); log.setOperateTime(LocalDateTime.now()); auditLogMapper.insert(log); } catch (Exception ignored) { @@ -101,7 +99,6 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { vo.setResult(log.getResult()); vo.setReason(log.getReason()); vo.setIpAddress(log.getIpAddress()); - vo.setDeviceId(log.getDeviceId()); vo.setOperateTime(log.getOperateTime()); return vo; } @@ -132,4 +129,12 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { } return value.substring(0, max); } + + private String maskPhoneAccount(String value) { + if (value == null) return null; + String normalized = value.trim(); + return normalized.matches("1[3-9]\\d{9}") + ? normalized.substring(0, 3) + "****" + normalized.substring(7) + : limit(normalized, 80); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java index ef1b430f..83ed716f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java @@ -107,6 +107,8 @@ public final class SecurityAuditActions { public static final String CAMPAIGN_PUBLISH = "CAMPAIGN_PUBLISH"; public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW"; public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW"; + public static final String SECURE_CONFIG_UPDATE = "SECURE_CONFIG_UPDATE"; + public static final String CUSTOMER_DIAL = "CUSTOMER_DIAL"; private SecurityAuditActions() { } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java index c8352bb1..ed48ae7c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java @@ -46,11 +46,6 @@ public class SecurityAuditLogVO { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private String ipAddress; - /** - * Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; /** * Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java index 32b20c54..7c0c9aa7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java @@ -6,6 +6,8 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; @@ -17,6 +19,7 @@ import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.time.LocalDate; @RestController @RequestMapping("/admin/shops") @@ -39,6 +42,7 @@ public class AdminShopController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final SecurityAuditSupport securityAuditSupport; + private final ShopBusinessExpiryService shopBusinessExpiryService; @GetMapping("/list") @RequirePermission("shop:view") @@ -180,6 +184,33 @@ public class AdminShopController { return Result.success(shop); } + @GetMapping("/business-expiries") + @RequirePermission("shop:view") + public Result> listBusinessExpiries( + HttpServletRequest request, @RequestParam String shopIds) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅平台管理员可以管理门店经营有效期"); + List ids = java.util.Arrays.stream(shopIds.split(",")) + .map(String::trim) + .filter(value -> !value.isEmpty()) + .map(Long::valueOf) + .distinct() + .limit(100) + .collect(java.util.stream.Collectors.toList()); + return Result.success(shopBusinessExpiryService.listExpiries(ids)); + } + + @PutMapping("/{id}/business-expiry") + @RequirePermission("shop:edit") + @OperationGuard(action = "admin-shop-business-expiry", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateBusinessExpiry( + HttpServletRequest request, @PathVariable Long id, @RequestBody BusinessExpiryRequest body) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅平台管理员可以管理门店经营有效期"); + return Result.success(shopBusinessExpiryService.updateExpiry(id, + body == null || body.getExpireDate() == null ? null : LocalDate.parse(body.getExpireDate()))); + } + @Data /** * Purpose: StatusRequest supports AdminShopController.java by holding or executing the status request business role. @@ -192,4 +223,9 @@ public class AdminShopController { */ private Integer status; } + + @Data + public static class BusinessExpiryRequest { + private String expireDate; + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java index 5753348e..ab8cd7fe 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java @@ -115,7 +115,7 @@ public class ShopController { * @return Result result consumed by the caller or returned to the frontend */ public Result getShopById(@PathVariable Long id) { - ShopVO shopVO = shopService.getShopById(id); + ShopVO shopVO = shopService.getPublicShopById(id); return Result.success(shopVO); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java new file mode 100644 index 00000000..07e951df --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; +import java.util.List; + +@Data +public class ShopAppointmentSettingsDTO { + private String businessHours; + private Integer defaultAppointmentDurationMinutes; + private List weeklyHours; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopBusinessHoursDayDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopBusinessHoursDayDTO.java new file mode 100644 index 00000000..bdedcbe3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopBusinessHoursDayDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; + +@Data +public class ShopBusinessHoursDayDTO { + private Integer dayOfWeek; + private Boolean open; + private String startTime; + private String endTime; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java new file mode 100644 index 00000000..1c43a3f5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; + +@Data +public class ShopNameUpdateDTO { + private String shopName; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java index 67535d1e..1540d7d2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java @@ -76,6 +76,12 @@ public class ShopDO extends BaseEntity { @TableField("business_hours") private String businessHours; + @TableField("appointment_business_hours") + private String appointmentBusinessHours; + + @TableField("default_appointment_duration_minutes") + private Integer defaultAppointmentDurationMinutes; + /** * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 */ @@ -136,6 +142,9 @@ public class ShopDO extends BaseEntity { @TableField("status") private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("authorization_start_date") /** * Purpose: authorizationStartDate supports ShopDO.java by holding or executing the authorization start date business role. @@ -156,6 +165,9 @@ public class ShopDO extends BaseEntity { @TableField("authorization_expire_time") private LocalDateTime authorizationExpireTime; + @TableField("business_expire_time") + private LocalDateTime businessExpireTime; + /** * 逻辑删除:0-未删,1-已删 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java index 1b5792dc..5cec65eb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java @@ -14,6 +14,6 @@ import org.apache.ibatis.annotations.Select; */ public interface ShopMapper extends BaseMapper { - @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") + @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessExpiryService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessExpiryService.java new file mode 100644 index 00000000..58aa45c2 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessExpiryService.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service; + +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO; + +import java.time.LocalDate; +import java.util.List; + +public interface ShopBusinessExpiryService { + int getDefaultValidDays(); + java.time.LocalDateTime defaultExpireTime(LocalDate startDate); + void startDefaultValidity(Long shopId, LocalDate startDate); + void assertShopActive(Long shopId); + ShopBusinessExpiryVO getExpiry(Long shopId); + List listExpiries(List shopIds); + ShopBusinessExpiryVO updateExpiry(Long shopId, LocalDate expireDate); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessScheduleService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessScheduleService.java new file mode 100644 index 00000000..634eaee2 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessScheduleService.java @@ -0,0 +1,158 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service; + +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.sql.Time; +import java.time.LocalDate; +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.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class ShopBusinessScheduleService { + private static final LocalTime DEFAULT_START = LocalTime.of(10, 0); + private static final LocalTime DEFAULT_END = LocalTime.of(22, 0); + private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm"); + + private final JdbcTemplate jdbcTemplate; + + public ShopBusinessScheduleService(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public List list(Long shopId, String legacyHours) { + ensureDefaultSchedule(shopId, legacyHours); + return jdbcTemplate.query( + "SELECT day_of_week, is_open, start_time, end_time FROM t_shop_weekly_schedule WHERE shop_id = ? ORDER BY day_of_week", + (rs, rowNum) -> { + ShopBusinessHoursDayVO day = new ShopBusinessHoursDayVO(); + day.setDayOfWeek(rs.getInt("day_of_week")); + day.setOpen(rs.getInt("is_open") == 1); + Time start = rs.getTime("start_time"); + Time end = rs.getTime("end_time"); + day.setStartTime(start == null ? null : start.toLocalTime().format(TIME_FORMAT)); + day.setEndTime(end == null ? null : end.toLocalTime().format(TIME_FORMAT)); + return day; + }, shopId + ); + } + + public Map mapByDay(Long shopId, String legacyHours) { + Map result = new HashMap<>(); + list(shopId, legacyHours).forEach(day -> result.put(day.getDayOfWeek(), day)); + return result; + } + + public ShopBusinessHoursDayVO forDate(Long shopId, LocalDate date, String legacyHours) { + if (date == null) return null; + return mapByDay(shopId, legacyHours).get(date.getDayOfWeek().getValue()); + } + + @Transactional + public void initializeDefault(Long shopId, String legacyHours) { + ensureDefaultSchedule(shopId, legacyHours); + } + + @Transactional + public void save(Long shopId, List requested, String legacyHours) { + List days = requested; + if (days == null || days.isEmpty()) { + days = legacySchedule(legacyHours); + } + if (days.size() != 7) throw new IllegalArgumentException("请设置周一至周日的营业状态"); + Map byDay = new HashMap<>(); + for (ShopBusinessHoursDayDTO day : days) { + if (day == null || day.getDayOfWeek() == null || day.getDayOfWeek() < 1 || day.getDayOfWeek() > 7 + || byDay.putIfAbsent(day.getDayOfWeek(), day) != null) { + throw new IllegalArgumentException("每周营业设置必须包含周一至周日且不能重复"); + } + if (!Boolean.TRUE.equals(day.getOpen())) { + day.setOpen(false); + day.setStartTime(null); + day.setEndTime(null); + continue; + } + LocalTime start = parseTime(day.getStartTime(), "营业开始时间"); + LocalTime end = parseTime(day.getEndTime(), "营业结束时间"); + if (!start.isBefore(end)) throw new IllegalArgumentException("营业开始时间必须早于结束时间"); + day.setStartTime(start.format(TIME_FORMAT)); + day.setEndTime(end.format(TIME_FORMAT)); + } + if (byDay.size() != 7) throw new IllegalArgumentException("请完整设置周一至周日"); + + ensureDefaultSchedule(shopId, legacyHours); + for (int dayOfWeek = 1; dayOfWeek <= 7; dayOfWeek++) { + ShopBusinessHoursDayDTO day = byDay.get(dayOfWeek); + jdbcTemplate.update( + "UPDATE t_shop_weekly_schedule SET is_open = ?, start_time = ?, end_time = ?, update_time = CURRENT_TIMESTAMP WHERE shop_id = ? AND day_of_week = ?", + Boolean.TRUE.equals(day.getOpen()) ? 1 : 0, + day.getStartTime() == null ? null : Time.valueOf(day.getStartTime() + ":00"), + day.getEndTime() == null ? null : Time.valueOf(day.getEndTime() + ":00"), + shopId, + dayOfWeek + ); + } + } + + private void ensureDefaultSchedule(Long shopId, String legacyHours) { + if (shopId == null) throw new IllegalArgumentException("门店不能为空"); + LocalTime[] parsed = parseLegacyHours(legacyHours); + LocalTime start = parsed == null ? DEFAULT_START : parsed[0]; + LocalTime end = parsed == null ? DEFAULT_END : parsed[1]; + for (int day = 1; day <= 7; day++) { + jdbcTemplate.update( + "INSERT IGNORE INTO t_shop_weekly_schedule (shop_id, day_of_week, is_open, start_time, end_time, create_time, update_time) VALUES (?, ?, 1, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)", + shopId, day, Time.valueOf(start), Time.valueOf(end) + ); + } + } + + private List legacySchedule(String legacyHours) { + LocalTime[] times = parseLegacyHours(legacyHours); + LocalTime start = times == null ? DEFAULT_START : times[0]; + LocalTime end = times == null ? DEFAULT_END : times[1]; + List result = new ArrayList<>(); + for (int day = 1; day <= 7; day++) { + ShopBusinessHoursDayDTO item = new ShopBusinessHoursDayDTO(); + item.setDayOfWeek(day); + item.setOpen(true); + item.setStartTime(start.format(TIME_FORMAT)); + item.setEndTime(end.format(TIME_FORMAT)); + result.add(item); + } + return result; + } + + private LocalTime[] parseLegacyHours(String value) { + if (!StringUtils.hasText(value)) return null; + String[] parts = value.trim().split("-"); + if (parts.length != 2) return null; + try { + LocalTime start = parseTime(parts[0], "营业开始时间"); + LocalTime end = parseTime(parts[1], "营业结束时间"); + return start.isBefore(end) ? new LocalTime[]{start, end} : null; + } catch (IllegalArgumentException ignored) { + return null; + } + } + + private LocalTime parseTime(String value, String label) { + if (!StringUtils.hasText(value)) throw new IllegalArgumentException(label + "不能为空"); + try { + String normalized = value.trim(); + return LocalTime.parse(normalized.length() == 5 ? normalized : normalized.substring(0, 5), TIME_FORMAT); + } catch (DateTimeParseException | IndexOutOfBoundsException e) { + throw new IllegalArgumentException(label + "格式不正确"); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java index 1006a133..43fb26fb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java @@ -6,6 +6,9 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopTrustProfileVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; import java.util.List; @@ -51,6 +54,15 @@ public interface ShopService extends IService { */ ShopVO getShopById(Long id); + ShopAppointmentSettingsVO getAppointmentSettings(Long id); + + boolean updateAppointmentSettings(Long id, ShopAppointmentSettingsDTO settings); + + boolean updateShopName(Long id, ShopNameUpdateDTO request); + + /** Public shop detail with the approved-content visibility gate applied. */ + ShopVO getPublicShopById(Long id); + /** * Purpose: getShopTrustProfile aggregates public shop confidence signals. * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopBusinessExpiryServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopBusinessExpiryServiceImpl.java new file mode 100644 index 00000000..d22c1560 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopBusinessExpiryServiceImpl.java @@ -0,0 +1,113 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +@Service +@RequiredArgsConstructor +public class ShopBusinessExpiryServiceImpl implements ShopBusinessExpiryService { + private static final int DEFAULT_VALID_DAYS = 30; + private static final String EXPIRED_MESSAGE = "门店经营有效期已到期,暂不能新增预约,请联系平台管理员办理续期"; + + private final ShopMapper shopMapper; + private final SystemParameterConfigService systemParameterConfigService; + + @Override + public int getDefaultValidDays() { + String value = systemParameterConfigService.getEnabledValue("SHOP", "SHOP_DEFAULT_VALID_DAYS"); + if (!StringUtils.hasText(value)) return DEFAULT_VALID_DAYS; + try { + int days = Integer.parseInt(value.trim()); + return days > 0 && days <= 3650 ? days : DEFAULT_VALID_DAYS; + } catch (NumberFormatException ignored) { + return DEFAULT_VALID_DAYS; + } + } + + @Override + public LocalDateTime defaultExpireTime(LocalDate startDate) { + LocalDate start = startDate == null ? LocalDate.now() : startDate; + return start.plusDays(getDefaultValidDays() - 1L).atTime(23, 59, 59); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void startDefaultValidity(Long shopId, LocalDate startDate) { + ShopDO shop = requireShop(shopId); + shop.setBusinessExpireTime(defaultExpireTime(startDate)); + shopMapper.updateById(shop); + } + + @Override + public void assertShopActive(Long shopId) { + ShopDO shop = requireShop(shopId); + if (shop.getBusinessExpireTime() == null) { + throw new IllegalStateException("门店经营有效期未设置,暂不能新增预约,请联系平台管理员设置有效期"); + } + if (LocalDateTime.now().isAfter(shop.getBusinessExpireTime())) { + throw new IllegalStateException(EXPIRED_MESSAGE); + } + } + + @Override + public ShopBusinessExpiryVO getExpiry(Long shopId) { + return toVO(requireShop(shopId)); + } + + @Override + public List listExpiries(List shopIds) { + if (shopIds == null || shopIds.isEmpty()) return Collections.emptyList(); + List ids = shopIds.stream().filter(Objects::nonNull).distinct().limit(100).toList(); + if (ids.isEmpty()) return Collections.emptyList(); + return shopMapper.selectList(Wrappers.lambdaQuery(ShopDO.class) + .in(ShopDO::getId, ids) + .eq(ShopDO::getIsDelete, 0)) + .stream().map(this::toVO).toList(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public ShopBusinessExpiryVO updateExpiry(Long shopId, LocalDate expireDate) { + if (expireDate == null) throw new IllegalArgumentException("请选择门店到期日期"); + if (expireDate.isBefore(LocalDate.now())) throw new IllegalArgumentException("到期日期不能早于今天"); + ShopDO shop = requireShop(shopId); + shop.setBusinessExpireTime(expireDate.atTime(23, 59, 59)); + shopMapper.updateById(shop); + return toVO(shop); + } + + private ShopDO requireShop(Long shopId) { + ShopDO shop = shopId == null ? null : shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在或已删除"); + } + return shop; + } + + private ShopBusinessExpiryVO toVO(ShopDO shop) { + ShopBusinessExpiryVO vo = new ShopBusinessExpiryVO(); + vo.setShopId(shop.getId()); + vo.setBusinessExpireTime(shop.getBusinessExpireTime()); + LocalDateTime now = LocalDateTime.now(); + boolean expired = shop.getBusinessExpireTime() != null && now.isAfter(shop.getBusinessExpireTime()); + vo.setBusinessExpired(expired); + vo.setBusinessRemainingDays(shop.getBusinessExpireTime() == null ? null + : expired ? 0 : (int) Math.max(1, ChronoUnit.DAYS.between(now.toLocalDate(), shop.getBusinessExpireTime().toLocalDate()) + 1)); + return vo; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java index 2778fc8f..48cc1278 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java @@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.core.type.TypeReference; import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewDO; import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; @@ -23,14 +25,21 @@ import com.xiaowang.jayucloud.salon.core.modules.integration.service.MapService; import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.modules.shop.support.ShopThemeSupport; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopTrustProfileVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -41,6 +50,8 @@ import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -85,6 +96,9 @@ public class ShopServiceImpl extends ServiceImpl implements * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ShopMapper shopMapper; + private final ContentModerationRecordMapper contentModerationRecordMapper; + private final ShopBusinessExpiryService shopBusinessExpiryService; + private final ShopBusinessScheduleService shopBusinessScheduleService; /** * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -139,6 +153,8 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final MapService mapService; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; @Override @Transactional(rollbackFor = Exception.class) @@ -150,20 +166,24 @@ public class ShopServiceImpl extends ServiceImpl implements */ public Long createShop(ShopDTO shopDTO) { ShopDO shopDO = new ShopDO(); - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); + shopDO.setShopName(""); + shopDO.setDescription(null); + shopDO.setAddress(""); shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); shopDO.setLongitude(shopDTO.getLongitude()); shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); + shopDO.setBusinessHours(null); + shopDO.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDate.now())); + shopDO.setCoverImageFileId(null); + shopDO.setImageFileIds(null); + shopDO.setModerationStatus("PENDING"); applyTheme(shopDO, shopDTO); applyAuthorization(shopDO, shopDTO); shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); shopDO.setIsDelete(0); shopMapper.insert(shopDO); + shopBusinessScheduleService.initializeDefault(shopDO.getId(), "10:00-22:00"); + submitShopSnapshot(shopDO, shopDTO); couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); evictShopCaches(shopDO.getId()); return shopDO.getId(); @@ -185,21 +205,8 @@ public class ShopServiceImpl extends ServiceImpl implements if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); } - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); - shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); - shopDO.setLongitude(shopDTO.getLongitude()); - shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); - applyTheme(shopDO, shopDTO); - applyAuthorization(shopDO, shopDTO); - if (shopDTO.getStatus() != null) { - shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); - } - boolean updated = shopMapper.updateById(shopDO) > 0; + boolean updated = updateShopOperationalFields(shopDO, shopDTO); + submitShopSnapshot(shopDO, shopDTO); if (updated) { /** * Run business method `evictShopCaches`. @@ -212,6 +219,172 @@ public class ShopServiceImpl extends ServiceImpl implements return updated; } + @Override + public ShopAppointmentSettingsVO getAppointmentSettings(Long id) { + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + ShopAppointmentSettingsVO result = new ShopAppointmentSettingsVO(); + result.setShopName(shop.getShopName()); + ContentModerationRecordDO latestReview = contentModerationRecordMapper.selectOne(Wrappers.lambdaQuery(ContentModerationRecordDO.class) + .eq(ContentModerationRecordDO::getContentType, "SHOP") + .eq(ContentModerationRecordDO::getBusinessId, id) + .orderByDesc(ContentModerationRecordDO::getVersionNo) + .last("limit 1")); + result.setShopNameModerationStatus(latestReview == null ? shop.getModerationStatus() : latestReview.getStatus()); + if (latestReview != null && StringUtils.hasText(latestReview.getPayloadJson())) { + try { + result.setPendingShopName(objectMapper.readTree(latestReview.getPayloadJson()).path("shopName").asText(null)); + } catch (Exception ignored) { + result.setPendingShopName(null); + } + } + result.setBusinessHours(StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()); + result.setWeeklyHours(shopBusinessScheduleService.list(id, result.getBusinessHours())); + result.setDefaultAppointmentDurationMinutes(shop.getDefaultAppointmentDurationMinutes() == null + || shop.getDefaultAppointmentDurationMinutes() <= 0 ? 60 : shop.getDefaultAppointmentDurationMinutes()); + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateAppointmentSettings(Long id, ShopAppointmentSettingsDTO settings) { + if (settings == null) throw new IllegalArgumentException("预约设置不能为空"); + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + Integer duration = settings.getDefaultAppointmentDurationMinutes(); + if (duration == null || duration < 15 || duration > 720) { + throw new IllegalArgumentException("默认预约时长需在15至720分钟之间"); + } + shopBusinessScheduleService.save(id, settings.getWeeklyHours(), settings.getBusinessHours()); + List weeklyHours = shopBusinessScheduleService.list( + id, StringUtils.hasText(settings.getBusinessHours()) ? settings.getBusinessHours() : shop.getBusinessHours()); + String firstOpenHours = weeklyHours.stream().filter(day -> Boolean.TRUE.equals(day.getOpen())) + .sorted(java.util.Comparator.comparing(com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO::getDayOfWeek)) + .map(day -> day.getStartTime() + "-" + day.getEndTime()).findFirst().orElse(null); + shop.setAppointmentBusinessHours(firstOpenHours); + shop.setDefaultAppointmentDurationMinutes(duration); + return shopMapper.updateById(shop) > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateShopName(Long id, ShopNameUpdateDTO request) { + if (request == null || !StringUtils.hasText(request.getShopName())) { + throw new IllegalArgumentException("门店名称不能为空"); + } + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + ShopDTO profile = new ShopDTO(); + profile.setShopName(request.getShopName().trim()); + profile.setDescription(shop.getDescription()); + profile.setAddress(shop.getAddress()); + profile.setMapProvider(shop.getMapProvider()); + profile.setLongitude(shop.getLongitude()); + profile.setLatitude(shop.getLatitude()); + profile.setBusinessHours(shop.getBusinessHours()); + profile.setCoverImageFileId(shop.getCoverImageFileId()); + profile.setImageFileIds(shop.getImageFileIds()); + profile.setThemePrimaryColor(shop.getThemePrimaryColor()); + profile.setThemeSecondaryColor(shop.getThemeSecondaryColor()); + profile.setThemeAccentColor(shop.getThemeAccentColor()); + profile.setThemePageBgColor(shop.getThemePageBgColor()); + profile.setThemeCardBgColor(shop.getThemeCardBgColor()); + profile.setThemeBackgroundImageFileId(shop.getThemeBackgroundImageFileId()); + submitShopSnapshot(shop, profile); + return true; + } + + private String normalizeAppointmentBusinessHours(String value) { + if (!StringUtils.hasText(value)) throw new IllegalArgumentException("请设置门店营业时间"); + String[] parts = value.trim().split("-"); + if (parts.length != 2) throw new IllegalArgumentException("营业时间格式不正确"); + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + if (!start.isBefore(end)) throw new IllegalArgumentException("营业结束时间必须晚于开始时间"); + return start + "-" + end; + } catch (DateTimeParseException exception) { + throw new IllegalArgumentException("营业时间格式不正确,请使用小时和分钟"); + } + } + + private boolean updateShopOperationalFields(ShopDO current, ShopDTO dto) { + boolean changed = false; + if (dto.getStatus() != null) { + current.setStatus(normalizeStatus(dto.getStatus())); + changed = true; + } + if (dto.getAuthorizationStartDate() != null || dto.getAuthorizationDays() != null || dto.getAuthorizationExpireTime() != null) { + applyAuthorization(current, dto); + changed = true; + } + return !changed || shopMapper.updateById(current) > 0; + } + + private ShopDO copyShop(ShopDO source) { + ShopDO target = new ShopDO(); + target.setId(source.getId()); target.setShopName(source.getShopName()); target.setDescription(source.getDescription()); + target.setAddress(source.getAddress()); target.setMapProvider(source.getMapProvider()); target.setLongitude(source.getLongitude()); + target.setLatitude(source.getLatitude()); target.setBusinessHours(source.getBusinessHours()); target.setCoverImageFileId(source.getCoverImageFileId()); + target.setAppointmentBusinessHours(source.getAppointmentBusinessHours()); target.setDefaultAppointmentDurationMinutes(source.getDefaultAppointmentDurationMinutes()); + target.setImageFileIds(source.getImageFileIds()); target.setThemePrimaryColor(source.getThemePrimaryColor()); + target.setThemeSecondaryColor(source.getThemeSecondaryColor()); target.setThemeAccentColor(source.getThemeAccentColor()); + target.setThemePageBgColor(source.getThemePageBgColor()); target.setThemeCardBgColor(source.getThemeCardBgColor()); + target.setThemeBackgroundImageFileId(source.getThemeBackgroundImageFileId()); target.setStatus(source.getStatus()); + target.setAuthorizationStartDate(source.getAuthorizationStartDate()); target.setAuthorizationDays(source.getAuthorizationDays()); + target.setAuthorizationExpireTime(source.getAuthorizationExpireTime()); target.setIsDelete(source.getIsDelete()); + target.setModerationStatus(source.getModerationStatus()); target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private void submitShopSnapshot(ShopDO current, ShopDTO dto) { + try { + ShopDO candidate = copyShop(current); + candidate.setShopName(dto.getShopName()); candidate.setDescription(dto.getDescription()); candidate.setAddress(dto.getAddress()); + candidate.setMapProvider(mapService.normalizeProvider(dto.getMapProvider())); + candidate.setLongitude(dto.getLongitude()); candidate.setLatitude(dto.getLatitude()); + candidate.setBusinessHours(dto.getBusinessHours()); candidate.setCoverImageFileId(dto.getCoverImageFileId()); + candidate.setImageFileIds(dto.getImageFileIds()); applyTheme(candidate, dto); + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("shopName", candidate.getShopName()); payload.put("description", candidate.getDescription()); + payload.put("address", candidate.getAddress()); payload.put("businessHours", candidate.getBusinessHours()); + payload.put("mapProvider", candidate.getMapProvider()); payload.put("longitude", candidate.getLongitude()); + payload.put("latitude", candidate.getLatitude()); + payload.put("coverImageFileId", candidate.getCoverImageFileId()); payload.put("imageFileIds", candidate.getImageFileIds()); + payload.put("themePrimaryColor", candidate.getThemePrimaryColor()); + payload.put("themeSecondaryColor", candidate.getThemeSecondaryColor()); + payload.put("themeAccentColor", candidate.getThemeAccentColor()); + payload.put("themePageBgColor", candidate.getThemePageBgColor()); + payload.put("themeCardBgColor", candidate.getThemeCardBgColor()); + payload.put("themeBackgroundImageFileId", candidate.getThemeBackgroundImageFileId()); + String text = String.join("\n", java.util.Arrays.asList(candidate.getShopName(), candidate.getDescription(), candidate.getAddress(), candidate.getBusinessHours())); + java.util.List images = new java.util.ArrayList<>(); + addImageIds(images, candidate.getCoverImageFileId()); addImageIds(images, candidate.getImageFileIds()); addImageIds(images, candidate.getThemeBackgroundImageFileId()); + contentModerationService.assessVersion("SHOP", current.getId(), null, text, objectMapper.writeValueAsString(payload), images); + } catch (Exception exception) { + throw new IllegalStateException("门店展示资料审核任务创建失败", exception); + } + } + + private void addImageIds(java.util.List ids, String value) { + if (!StringUtils.hasText(value)) return; + for (String token : value.split(",")) { + if (!StringUtils.hasText(token)) continue; + Long fileId = objectStorageFileService.findFileIdByReference(token.trim()); + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("门店图片必须引用已上传文件"); + } + if (!ids.contains(fileId)) ids.add(fileId); + } + } + @Override @Transactional(rollbackFor = Exception.class) /** @@ -282,6 +455,18 @@ public class ShopServiceImpl extends ServiceImpl implements ); } + @Override + public ShopVO getPublicShopById(Long id) { + ShopDO shop = id == null ? null : shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete()) + || !Integer.valueOf(1).equals(normalizeStatus(shop.getStatus())) + || !"APPROVED".equals(shop.getModerationStatus()) + || !isAuthorizationValid(shop)) { + return null; + } + return convertToVO(shop); + } + @Override /** * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. @@ -292,7 +477,8 @@ public class ShopServiceImpl extends ServiceImpl implements return null; } ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) + || !"APPROVED".equals(shopDO.getModerationStatus()) || !isAuthorizationValid(shopDO)) { return null; } @@ -358,6 +544,7 @@ public class ShopServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(ShopDO.class) .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) + .eq(ShopDO::getModerationStatus, "APPROVED") .orderByDesc(ShopDO::getCreateTime) ).stream() .filter(this::isAuthorizationValid) @@ -404,6 +591,7 @@ public class ShopServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(ShopDO.class) .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) + .eq(ShopDO::getModerationStatus, "APPROVED") .like(ShopDO::getShopName, normalizedShopName) ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); return shopDOs.stream() @@ -456,7 +644,8 @@ public class ShopServiceImpl extends ServiceImpl implements private long countActiveProducts(Long shopId) { Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0)); + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getModerationStatus, "APPROVED")); return count == null ? 0L : count; } @@ -476,6 +665,7 @@ public class ShopServiceImpl extends ServiceImpl implements return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getShopId, shopId) .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getModerationStatus, "APPROVED") .and(wrapper -> applyProductTagTokenConditions(wrapper, featuredTagTokens)) .orderByDesc(ProductDO::getCollectCount) .orderByDesc(ProductDO::getLikeCount) @@ -530,14 +720,24 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: only status=1 reviews should feed public trust display. */ private List listSubmittedReviews(Long shopId, int limit) { - return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + if (!isPublicShop(shopId)) { + return Collections.emptyList(); + } + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .orderByDesc(OrderArtistReviewDO::getSubmittedAt) - .orderByDesc(OrderArtistReviewDO::getCreateTime) - .last("LIMIT " + Math.max(1, limit))) - .stream() + .orderByDesc(OrderArtistReviewDO::getCreateTime)); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + return reviews.stream() + .filter(review -> approvedProductIds.contains(review.getProductId())) + .limit(Math.max(1, limit)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @@ -547,11 +747,20 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: render it beside average rating so customers can judge sample size. */ private long countSubmittedReviews(Long shopId) { - Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + if (!isPublicShop(shopId)) { + return 0L; + } + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) - .eq(OrderArtistReviewDO::getIsDelete, 0)); - return count == null ? 0L : count; + .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED")); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + return reviews.stream().filter(review -> approvedProductIds.contains(review.getProductId())).count(); } /** @@ -559,11 +768,23 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: use submitted reviews only and return zero when no rating exists. */ private BigDecimal calculateAverageRating(Long shopId) { + if (!isPublicShop(shopId)) { + return BigDecimal.ZERO; + } List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .isNotNull(OrderArtistReviewDO::getRatingScore)); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + reviews = reviews.stream() + .filter(review -> approvedProductIds.contains(review.getProductId())) + .collect(Collectors.toList()); if (reviews == null || reviews.isEmpty()) { return BigDecimal.ZERO; } @@ -578,6 +799,32 @@ public class ShopServiceImpl extends ServiceImpl implements return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); } + private boolean isPublicShop(Long shopId) { + if (shopId == null) { + return false; + } + ShopDO shop = shopMapper.selectById(shopId); + return shop != null + && !Integer.valueOf(1).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(normalizeStatus(shop.getStatus())) + && "APPROVED".equals(shop.getModerationStatus()) + && isAuthorizationValid(shop); + } + + private Set listApprovedProductIds(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return Collections.emptySet(); + } + return productMapper.selectBatchIds(productIds).stream() + .filter(Objects::nonNull) + .filter(product -> !Integer.valueOf(1).equals(product.getIsDelete())) + .filter(product -> Integer.valueOf(1).equals(product.getFrontVisible())) + .filter(product -> "APPROVED".equals(product.getModerationStatus())) + .map(ProductDO::getId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + /** * Purpose: buildFeaturedProduct converts a product row into a compact trust card. * Usage: keep this card small and do not include unpublished product internals. @@ -764,6 +1011,7 @@ public class ShopServiceImpl extends ServiceImpl implements shopVO.setLatitude(shopDO.getLatitude()); shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); shopVO.setBusinessHours(shopDO.getBusinessHours()); + shopVO.setModerationStatus(shopDO.getModerationStatus()); shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); shopVO.setCoverImageUrls(new java.util.ArrayList<>()); shopVO.setImageFileIds(shopDO.getImageFileIds()); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java new file mode 100644 index 00000000..0511175c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.vo; + +import lombok.Data; +import java.util.List; + +@Data +public class ShopAppointmentSettingsVO { + private String shopName; + private String shopNameModerationStatus; + private String pendingShopName; + private String businessHours; + private Integer defaultAppointmentDurationMinutes; + private List weeklyHours; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessExpiryVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessExpiryVO.java new file mode 100644 index 00000000..99d0bfba --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessExpiryVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class ShopBusinessExpiryVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + private LocalDateTime businessExpireTime; + private Boolean businessExpired; + private Integer businessRemainingDays; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessHoursDayVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessHoursDayVO.java new file mode 100644 index 00000000..05e73436 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessHoursDayVO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.vo; + +import lombok.Data; + +@Data +public class ShopBusinessHoursDayVO { + private Integer dayOfWeek; + private Boolean open; + private String startTime; + private String endTime; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java index 34bcb7c4..d3ebbd5b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java @@ -70,6 +70,8 @@ public class ShopVO { */ private String businessHours; + private String moderationStatus; + /** * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java new file mode 100644 index 00000000..18fda741 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java @@ -0,0 +1,135 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.controller.admin; + +import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.Map; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin/system-settings/secure-integration") +public class AdminSecureIntegrationConfigController { + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final IntegrationProbeService integrationProbeService; + private final ContentModerationForwardService contentModerationForwardService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping + @RequirePermission("messagehub:config:manage") + public Result getConfig(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + config.setProbeResults(integrationProbeService.listLatest(currentUser)); + config.setModerationForwardRecent(contentModerationForwardService.listRecent(10)); + return Result.success(config); + } + + @GetMapping("/map-runtime") + @RequirePermission("messagehub:config:manage") + public Result> getMapRuntimeConfig(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(secureIntegrationConfigService.getMapRuntimeConfig(currentUser)); + } + + @PostMapping("/map") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-map-config-save", ttlSeconds = 5, message = "地图设置正在保存,请勿重复提交") + public Result saveMapConfig(HttpServletRequest request, + @Valid @RequestBody SecureIntegrationConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + secureIntegrationConfigService.saveMapConfig(currentUser, dto); + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=MAP"); + return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=MAP"); + throw exception; + } + } + + @PostMapping("/content-moderation") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-moderation-config-save", ttlSeconds = 5, message = "内容审核设置正在保存,请勿重复提交") + public Result saveModerationConfig(HttpServletRequest request, + @Valid @RequestBody SecureIntegrationConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + secureIntegrationConfigService.saveModerationConfig(currentUser, dto); + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION"); + return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION"); + throw exception; + } + } + + @PostMapping("/content-moderation-forward") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-moderation-forward-config-save", ttlSeconds = 5, message = "跨环境转发设置正在保存,请勿重复提交") + public Result saveModerationForwardConfig(HttpServletRequest request, + @Valid @RequestBody SecureIntegrationConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + secureIntegrationConfigService.saveModerationForwardConfig(currentUser, dto); + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "section=CONTENT_MODERATION_FORWARD"); + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + config.setModerationForwardRecent(contentModerationForwardService.listRecent(10)); + return Result.success(config); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION_FORWARD"); + throw exception; + } + } + + @GetMapping("/probe-results") + @RequirePermission("messagehub:config:manage") + public Result> listProbeResults(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(integrationProbeService.listLatest(currentUser)); + } + + @PostMapping("/probe") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-integration-probe", ttlSeconds = 8, message = "接入测试处理中,请勿重复提交") + public Result probe(HttpServletRequest request, + @Valid @RequestBody IntegrationProbeRequestDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + IntegrationProbeResultVO result = integrationProbeService.probe(currentUser, dto); + String auditDetail = "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus(); + if ("FAIL".equals(result.getStatus())) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail); + } else { + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail); + } + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "probe=" + dto.getService() + "/" + dto.getOperation()); + throw exception; + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java index 1c189feb..0597bfd7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java @@ -6,9 +6,11 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService; import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; import lombok.RequiredArgsConstructor; @@ -47,6 +49,10 @@ public class LegalAgreementController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final RequestThrottleService requestThrottleService; + /** + * Purpose: agreementVersionCacheService 在同意成功后清除该用户的协议缓存。 + */ + private final AgreementVersionCacheService agreementVersionCacheService; @GetMapping("/current") /** @@ -68,6 +74,28 @@ public class LegalAgreementController { return Result.success(legalAgreementService.getCurrentAgreement(type)); } + @GetMapping("/pending") + /** + * Purpose: pending 返回当前协议版本;登录用户额外返回是否已同意新版本。免登录只返回当前版本。 + */ + public Result pending(HttpServletRequest request) { + requestThrottleService.checkAgreementRead(request, "PENDING"); + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getPendingAgreements(userId)); + } + + @PostMapping("/accept") + /** + * Purpose: accept 记录登录用户对当前发布协议版本的同意。 + */ + public Result accept(HttpServletRequest request, + @RequestParam(required = false) String clientType) { + Long userId = (Long) request.getAttribute("userId"); + legalAgreementService.acceptCurrentAgreements(userId, clientType, request); + agreementVersionCacheService.evictUser(userId); + return Result.success(legalAgreementService.getPendingAgreements(userId)); + } + @GetMapping("/admin/list") @RequirePermission("legal_agreement:manage") /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java index 0b1d02cf..b7da2b76 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java @@ -58,34 +58,6 @@ public class SystemParameterConfigController { return Result.success(configService.saveConfig(currentUser, dto)); } - @GetMapping("/admin/tencent-map") - /** - * Purpose: getTencentMapKey supports SystemParameterConfigController.java by holding or executing the get tencent map key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> getTencentMapKey(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); - return Result.success(result); - } - - @GetMapping("/admin/map-config") - /** - * Purpose: getMapConfig supports SystemParameterConfigController.java by holding or executing the get map config business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> getMapConfig(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - String provider = configService.getEnabledValue("MAP", "MAP_PROVIDER"); - result.put("provider", "AMAP".equalsIgnoreCase(provider) ? "AMAP" : "TENCENT"); - result.put("tencentWebKey", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); - result.put("amapWebKey", configService.getEnabledValue("MAP", "AMAP_WEB_KEY")); - result.put("amapMiniKey", configService.getEnabledValue("MAP", "AMAP_MINI_KEY")); - return Result.success(result); - } - @GetMapping("/admin/user-default-password") @RequirePermission("user:create") public Result> getUserDefaultPassword(HttpServletRequest request) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java new file mode 100644 index 00000000..d93fab43 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +public class IntegrationProbeRequestDTO { + @NotBlank(message = "测试服务不能为空") + private String service; + + @NotBlank(message = "测试操作不能为空") + private String operation; + + private String mode = "DIAGNOSTIC"; + private String targetPhone; + private Boolean confirmed; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java new file mode 100644 index 00000000..f8414ac7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.dto; + +import lombok.Data; + +import java.util.List; +import java.util.Map; + +@Data +public class SecureIntegrationConfigDTO { + private String mapProvider; + private Boolean mapEnabled; + private String tencentWebKey; + private String amapWebKey; + private String amapMiniKey; + private Boolean clearTencentWebKey; + private Boolean clearAmapWebKey; + private Boolean clearAmapMiniKey; + + private String moderationProvider; + private String moderationCallbackUrl; + private String moderationCallbackToken; + private String moderationEncodingAesKey; + private Boolean clearModerationCallbackToken; + private Boolean clearModerationEncodingAesKey; + + private Boolean moderationForwardEnabled; + private Map moderationForwardTargets; + private List moderationForwardOrder; + private String moderationForwardSecret; + private Boolean clearModerationForwardSecret; + /** 补偿最大重试次数(1-10),未填写使用默认值。 */ + private Integer moderationForwardMaxRetry; + /** 补偿指数退避秒数梯度,未填写使用默认 30/120/600/3600。 */ + private List moderationForwardBackoffSeconds; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java new file mode 100644 index 00000000..8c4510d3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_integration_probe_result") +public class IntegrationProbeResultDO extends BaseEntity { + @TableField("service_code") + private String serviceCode; + + @TableField("operation_code") + private String operationCode; + + @TableField("mode") + private String mode; + + @TableField("provider") + private String provider; + + @TableField("status") + private String status; + + @TableField("summary") + private String summary; + + @TableField("error_code") + private String errorCode; + + @TableField("checks_json") + private String checksJson; + + @TableField("remote_task_id") + private String remoteTaskId; + + @TableField("correlation_key") + private String correlationKey; + + @TableField("temporary_object_provider") + private String temporaryObjectProvider; + + @TableField("temporary_object_name") + private String temporaryObjectName; + + @TableField("expires_at") + private java.time.LocalDateTime expiresAt; + + @TableField("checked_at") + private java.time.LocalDateTime checkedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java new file mode 100644 index 00000000..17a602a7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java @@ -0,0 +1,58 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("t_moderation_callback_forward") +public class ModerationCallbackForwardDO { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + @TableField("trace_id") + private String traceId; + + @TableField("source_env") + private String sourceEnv; + + @TableField("target_env") + private String targetEnv; + + @TableField("extra_json") + private String extraJson; + + @TableField("payload") + private String payload; + + @TableField("status") + private String status; + + @TableField("retry_count") + private Integer retryCount; + + @TableField("last_error") + private String lastError; + + @TableField("created_at") + private LocalDateTime createdAt; + + @TableField("updated_at") + private LocalDateTime updatedAt; + + @TableField("next_attempt_at") + private LocalDateTime nextAttemptAt; + + @TableField("locked_by") + private String lockedBy; + + @TableField("locked_at") + private LocalDateTime lockedAt; + + @TableField("finished_at") + private LocalDateTime finishedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/SecureIntegrationConfigDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/SecureIntegrationConfigDO.java new file mode 100644 index 00000000..01affe03 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/SecureIntegrationConfigDO.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_secure_integration_config") +public class SecureIntegrationConfigDO extends BaseEntity { + @TableField("config_group") + private String configGroup; + + @TableField("config_key") + private String configKey; + + @TableField("config_value") + private String configValue; + + @TableField("is_secret") + private Integer secret; + + @TableField("enabled") + private Integer enabled; + + @TableField("updated_by") + private Long updatedBy; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java new file mode 100644 index 00000000..46b6bcab --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface IntegrationProbeResultMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java new file mode 100644 index 00000000..04d42c24 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ModerationCallbackForwardMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/SecureIntegrationConfigMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/SecureIntegrationConfigMapper.java new file mode 100644 index 00000000..0724b3ab --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/SecureIntegrationConfigMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegrationConfigDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SecureIntegrationConfigMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java new file mode 100644 index 00000000..c6661883 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java @@ -0,0 +1,69 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@Data +@AllArgsConstructor +public class ModerationForwardConfig { + public static final int DEFAULT_MAX_RETRY = 4; + public static final List DEFAULT_BACKOFF_SECONDS = + Collections.unmodifiableList(Arrays.asList(30L, 120L, 600L, 3600L)); + + private boolean enabled; + private Map targets; + private String secret; + private List order; + private int maxRetry; + private List backoffSeconds; + + public static ModerationForwardConfig disabled() { + return new ModerationForwardConfig(false, Collections.emptyMap(), "", Collections.emptyList(), + DEFAULT_MAX_RETRY, DEFAULT_BACKOFF_SECONDS); + } + + public String targetFor(String env) { + if (!enabled || env == null || targets == null) return null; + String target = targets.get(env); + return StringUtils.hasText(target) ? target.trim() : null; + } + + public boolean ready() { + return enabled && StringUtils.hasText(secret); + } + + /** + * 按配置顺序返回可探测的目标环境,自动排除本环境与未配置地址的环境。 + */ + public List orderedTargets(String localEnv) { + List result = new ArrayList<>(); + if (order != null) { + for (String env : order) { + if (targetFor(env) != null && !env.equals(localEnv) && !result.contains(env)) result.add(env); + } + } + if (targets != null) { + for (String env : targets.keySet()) { + if (targetFor(env) != null && !env.equals(localEnv) && !result.contains(env)) result.add(env); + } + } + return result; + } + + /** + * 第 retryCount 次失败后的等待秒数(retryCount 从 1 开始)。 + */ + public long backoffSecondsFor(int retryCount) { + List values = backoffSeconds == null || backoffSeconds.isEmpty() + ? DEFAULT_BACKOFF_SECONDS : backoffSeconds; + int index = Math.max(0, Math.min(retryCount - 1, values.size() - 1)); + return values.get(index); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationRuntimeConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationRuntimeConfig.java new file mode 100644 index 00000000..ea04a176 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationRuntimeConfig.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ModerationRuntimeConfig { + private String provider; + private String callbackUrl; + private String callbackToken; + private String encodingAesKey; + private boolean ready; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureConfigEncryptionService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureConfigEncryptionService.java new file mode 100644 index 00000000..65f6b4bc --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureConfigEncryptionService.java @@ -0,0 +1,92 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; + +@Component +public class SecureConfigEncryptionService { + private static final String PREFIX = "v1:"; + private static final int NONCE_LENGTH = 12; + private static final int TAG_LENGTH_BITS = 128; + private static final SecureRandom RANDOM = new SecureRandom(); + + private final String encodedMasterKey; + + @Autowired + public SecureConfigEncryptionService() { + this(System.getenv("SALON_SECURE_CONFIG_MASTER_KEY")); + } + + SecureConfigEncryptionService(String encodedMasterKey) { + this.encodedMasterKey = encodedMasterKey; + } + + public boolean isConfigured() { + try { + decodeKey(); + return true; + } catch (IllegalStateException exception) { + return false; + } + } + + public String encrypt(String value) { + if (!StringUtils.hasText(value)) return null; + byte[] nonce = new byte[NONCE_LENGTH]; + RANDOM.nextBytes(nonce); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, decodeKey(), new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + byte[] encrypted = cipher.doFinal(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + byte[] payload = new byte[nonce.length + encrypted.length]; + System.arraycopy(nonce, 0, payload, 0, nonce.length); + System.arraycopy(encrypted, 0, payload, nonce.length, encrypted.length); + return PREFIX + Base64.getEncoder().encodeToString(payload); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("安全配置加密失败", exception); + } + } + + public String decrypt(String value) { + if (!StringUtils.hasText(value)) return ""; + if (!value.startsWith(PREFIX)) throw new IllegalStateException("安全配置密文版本不受支持"); + byte[] payload; + try { + payload = Base64.getDecoder().decode(value.substring(PREFIX.length())); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("安全配置密文格式错误", exception); + } + if (payload.length <= NONCE_LENGTH) throw new IllegalStateException("安全配置密文长度错误"); + byte[] nonce = Arrays.copyOfRange(payload, 0, NONCE_LENGTH); + byte[] ciphertext = Arrays.copyOfRange(payload, NONCE_LENGTH, payload.length); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, decodeKey(), new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + return new String(cipher.doFinal(ciphertext), java.nio.charset.StandardCharsets.UTF_8); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("安全配置无法解密,请检查环境主密钥是否与写入时一致", exception); + } + } + + private SecretKeySpec decodeKey() { + if (!StringUtils.hasText(encodedMasterKey)) { + throw new IllegalStateException("尚未配置安全接入加密主密钥"); + } + try { + byte[] key = Base64.getDecoder().decode(encodedMasterKey.trim()); + if (key.length != 32) throw new IllegalStateException("安全接入加密主密钥必须是 Base64 编码的 32 字节密钥"); + return new SecretKeySpec(key, "AES"); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("安全接入加密主密钥必须是有效的 Base64 字符串", exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java new file mode 100644 index 00000000..9507bd9a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java @@ -0,0 +1,15 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service; + +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +import java.util.List; + +public interface IntegrationProbeService { + IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request); + + List listLatest(UserDO currentUser); + + boolean handleImageCallback(String taskId, String suggest, String probeId); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java index 30a53df3..a2a4f857 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.service; import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest; import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; @@ -31,6 +32,10 @@ public interface LegalAgreementService { UserAgreementConsentVO getMyConsent(Long userId); + AgreementPendingVO getPendingAgreements(Long userId); + + void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest httpRequest); + void requireAccepted(AgreementAwareRequest request); void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java new file mode 100644 index 00000000..d574f5eb --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service; + +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +import java.util.Map; + +public interface SecureIntegrationConfigService { + SecureIntegrationConfigVO getAdminConfig(UserDO currentUser); + + void saveMapConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + ModerationForwardConfig getModerationForwardConfig(); + + Map getMapRuntimeConfig(UserDO currentUser); + + ModerationRuntimeConfig getModerationRuntimeConfig(); + + ModerationRuntimeConfig getModerationCallbackConfig(); + + void migrateLegacyMapConfig(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java new file mode 100644 index 00000000..183b717e --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java @@ -0,0 +1,628 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.WechatContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.IntegrationProbeResultMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeCheckVO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.core.env.Environment; + +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Slf4j +@Service +public class IntegrationProbeServiceImpl implements IntegrationProbeService { + private static final String[] SERVICES = {"CONTENT_MODERATION", "MAP", "OBJECT_STORAGE", "SMS", "SUBSCRIBE_MESSAGE"}; + private static final String TEXT = "CONTENT_MODERATION"; + private static final String MAP = "MAP"; + private static final String STORAGE = "OBJECT_STORAGE"; + private static final String SMS = "SMS"; + private static final String SUBSCRIBE = "SUBSCRIBE_MESSAGE"; + private static final Pattern URL_IN_MESSAGE = Pattern.compile("https?://[^\\s\"'<>]+"); + private static final Pattern URL_HOST = Pattern.compile("^(https?://[^/?#]+)"); + private static final Pattern SENSITIVE_PARAM = Pattern.compile( + "(?i)(signature|token|access[-_]?key(?:[-_]?id|[-_]?secret)?|secret[-_]?key)=([^&\\s\"']+)"); + private static final int FAILURE_REASON_MAX_LENGTH = 120; + + private final IntegrationProbeResultMapper resultMapper; + private final ObjectMapper objectMapper; + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final WechatMiniProperties wechatMiniProperties; + private final WechatMiniClientService wechatMiniClientService; + private final WechatMiniBindingMapper bindingMapper; + private final WechatContentModerationProvider wechatContentModerationProvider; + private final List storageProviders; + private final MessageHubPushConfigService messageHubPushConfigService; + private final MessageHubClientService messageHubClientService; + private final RestTemplate restTemplate; + private final Environment environment; + + public IntegrationProbeServiceImpl(IntegrationProbeResultMapper resultMapper, + ObjectMapper objectMapper, + SecureIntegrationConfigService secureIntegrationConfigService, + WechatMiniProperties wechatMiniProperties, + WechatMiniClientService wechatMiniClientService, + WechatMiniBindingMapper bindingMapper, + WechatContentModerationProvider wechatContentModerationProvider, + List storageProviders, + MessageHubPushConfigService messageHubPushConfigService, + MessageHubClientService messageHubClientService, + @Qualifier("restTemplate") RestTemplate restTemplate, + Environment environment) { + this.resultMapper = resultMapper; + this.objectMapper = objectMapper; + this.secureIntegrationConfigService = secureIntegrationConfigService; + this.wechatMiniProperties = wechatMiniProperties; + this.wechatMiniClientService = wechatMiniClientService; + this.bindingMapper = bindingMapper; + this.wechatContentModerationProvider = wechatContentModerationProvider; + this.storageProviders = storageProviders; + this.messageHubPushConfigService = messageHubPushConfigService; + this.messageHubClientService = messageHubClientService; + this.restTemplate = restTemplate; + this.environment = environment; + } + + @Override + public IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request) { + requirePlatformAdmin(currentUser); + String service = normalize(request.getService()); + String operation = normalize(request.getOperation()); + String mode = normalize(request.getMode()); + if (!Arrays.asList(SERVICES).contains(service)) throw new IllegalArgumentException("不支持的测试服务"); + if (!"DIAGNOSTIC".equals(mode) && !"REAL".equals(mode)) throw new IllegalArgumentException("不支持的测试模式"); + validateOperation(service, operation, mode); + if ("REAL".equals(mode) && (SMS.equals(service) || SUBSCRIBE.equals(service)) && !Boolean.TRUE.equals(request.getConfirmed())) { + throw new IllegalArgumentException("真实发送测试必须先确认可能产生的外部副作用"); + } + IntegrationProbeResultVO result; + try { + result = switch (service) { + case TEXT -> probeModeration(currentUser, operation, mode); + case MAP -> probeMap(currentUser, operation); + case STORAGE -> probeStorage(operation); + case SMS -> probeSms(currentUser, operation, mode, request.getTargetPhone()); + case SUBSCRIBE -> probeSubscribe(operation, mode); + default -> failure(service, operation, mode, "不支持的测试服务", "UNSUPPORTED"); + }; + } catch (RuntimeException exception) { + log.warn("系统接入探测失败,service={}, operation={}, mode={}, type={}", service, operation, mode, exception.getClass().getSimpleName()); + result = failure(service, operation, mode, safeMessage(exception), "PROBE_FAILURE"); + } + save(result); + return result; + } + + @Override + public List listLatest(UserDO currentUser) { + requirePlatformAdmin(currentUser); + return resultMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(IntegrationProbeResultDO::getServiceCode) + .orderByAsc(IntegrationProbeResultDO::getOperationCode)) + .stream().map(this::toVO).toList(); + } + + @Override + public boolean handleImageCallback(String taskId, String suggest, String probeId) { + IntegrationProbeResultDO row = null; + if (StringUtils.hasText(taskId)) { + row = resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getRemoteTaskId, taskId).last("LIMIT 1")); + } + if (row == null && StringUtils.hasText(probeId)) { + row = resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1")); + } + if (row == null) return false; + if (!TEXT.equals(row.getServiceCode()) || !"IMAGE_CALLBACK".equals(row.getOperationCode())) return false; + if (!"PENDING".equals(row.getStatus())) return true; + if (row.getExpiresAt() != null && row.getExpiresAt().isBefore(LocalDateTime.now())) { + row.setStatus("FAIL"); + row.setSummary("图片审核回调已超过等待期限"); + row.setErrorCode("CALLBACK_TIMEOUT"); + row.setCheckedAt(LocalDateTime.now()); + deleteTemporaryObject(row); + resultMapper.updateById(row); + return true; + } + String candidateSuggest = StringUtils.hasText(suggest) ? suggest.trim().toLowerCase(Locale.ROOT) : "review"; + String normalizedSuggest = List.of("pass", "review", "risky").contains(candidateSuggest) ? candidateSuggest : "unknown"; + row.setStatus("pass".equals(normalizedSuggest) ? "PASS" : "review".equals(normalizedSuggest) ? "WARN" : "FAIL"); + row.setSummary("微信图片审核回调:" + normalizedSuggest); + row.setCheckedAt(LocalDateTime.now()); + try { row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片审核回调", row.getStatus(), row.getSummary())))); } + catch (Exception ignored) { } + deleteTemporaryObject(row); + resultMapper.updateById(row); + return true; + } + + @Scheduled(fixedDelay = 300000) + public void expirePendingImageProbes() { + List expired = resultMapper.selectList(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getServiceCode, TEXT) + .eq(IntegrationProbeResultDO::getOperationCode, "IMAGE_CALLBACK") + .eq(IntegrationProbeResultDO::getStatus, "PENDING") + .lt(IntegrationProbeResultDO::getExpiresAt, LocalDateTime.now())); + for (IntegrationProbeResultDO row : expired) { + row.setStatus("FAIL"); + row.setSummary("图片审核回调超时,请检查微信回调地址和公网可达性"); + row.setErrorCode("CALLBACK_TIMEOUT"); + row.setCheckedAt(LocalDateTime.now()); + deleteTemporaryObject(row); + resultMapper.updateById(row); + } + List cleanup = resultMapper.selectList(new LambdaQueryWrapper() + .isNotNull(IntegrationProbeResultDO::getTemporaryObjectName) + .lt(IntegrationProbeResultDO::getExpiresAt, LocalDateTime.now())); + for (IntegrationProbeResultDO row : cleanup) { + deleteTemporaryObject(row); + resultMapper.updateById(row); + } + } + + private IntegrationProbeResultVO probeModeration(UserDO currentUser, String operation, String mode) { + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + List checks = new ArrayList<>(); + String provider = config.getModerationProvider(); + if ("WECHAT".equals(provider)) { + checks.add(check("审核 Provider", true, "微信内容安全审核", "未启用")); + checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取")); + checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置")); + String callbackUrl = config.getModerationCallbackUrl(); + boolean callbackUrlValid = false; + try { + java.net.URI callback = java.net.URI.create(callbackUrl == null ? "" : callbackUrl); + callbackUrlValid = "https".equalsIgnoreCase(callback.getScheme()) + && StringUtils.hasText(callback.getHost()) + && (callback.getPort() == -1 || callback.getPort() == 443) + && callback.getUserInfo() == null && callback.getQuery() == null && callback.getFragment() == null + && "/api/integration/wechat/content-moderation/callback".equals(callback.getPath()); + } catch (IllegalArgumentException ignored) { } + checks.add(check("回调 HTTPS 地址", callbackUrlValid, "公网 HTTPS 回调地址有效", "回调地址缺失或格式不正确")); + checks.add(check("回调 Token", Boolean.TRUE.equals(config.getModerationCallbackTokenConfigured()), "已配置", "未配置")); + checks.add(check("EncodingAESKey", Boolean.TRUE.equals(config.getModerationEncodingAesKeyConfigured()), "已配置", "未配置")); + checks.add(check("回调配置汇总", Boolean.TRUE.equals(config.getModerationCallbackReady()), "回调资料完整", "回调 URL、Token、AESKey、加密主密钥或 App 凭据不完整")); + } else if ("MOCK".equals(provider)) { + boolean mockAllowed = Boolean.TRUE.equals(config.getMockProviderAllowed()); + checks.add(new IntegrationProbeCheckVO("审核 Provider", mockAllowed ? "PASS" : "FAIL", mockAllowed ? "本地模拟审核已启用" : "当前环境不允许模拟审核")); + checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "模拟渠道不会调用微信接口")); + } else { + checks.add(new IntegrationProbeCheckVO("审核 Provider", "WARN", "内容审核未启用,内容保持隔离")); + } + if ("CONFIG".equals(operation)) return result(TEXT, operation, mode, config.getModerationProvider(), statusForChecks(checks), "内容审核配置诊断完成", null, checks); + if ("MOCK".equals(config.getModerationProvider()) && Boolean.TRUE.equals(config.getMockProviderAllowed())) { + checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "当前使用本地模拟审核,不会调用微信接口")); + return result(TEXT, operation, mode, "MOCK", "WARN", "当前为本地模拟流程", null, checks); + } + if ("MOCK".equals(config.getModerationProvider())) return result(TEXT, operation, mode, "MOCK", "FAIL", "当前环境不允许使用模拟审核", "MOCK_NOT_ALLOWED", checks); + if (!"WECHAT".equals(config.getModerationProvider())) return result(TEXT, operation, mode, config.getModerationProvider(), "FAIL", "微信内容审核未启用", "PROVIDER_DISABLED", checks); + if (!Boolean.TRUE.equals(config.getModerationReady())) return result(TEXT, operation, mode, "WECHAT", "FAIL", "微信审核配置未就绪,未发起接口请求", "MODERATION_NOT_READY", checks); + String openId = findProbeOpenId(); + if (!StringUtils.hasText(openId)) { + checks.add(new IntegrationProbeCheckVO("测试账号", "WARN", "当前环境没有可用微信绑定,请先使用体验版登录")); + return result(TEXT, operation, mode, "WECHAT", "WARN", "缺少可用于探测的微信绑定账号", "OPENID_REQUIRED", checks); + } + if ("IMAGE_CALLBACK".equals(operation)) return probeImageCallback(mode, openId, checks); + ModerationOutcome outcome = wechatContentModerationProvider.reviewText("INTEGRATION_PROBE", "Salon 接入测试", openId); + String status = outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : outcome.status() == ModerationOutcome.Status.PENDING ? "WARN" : "FAIL"; + checks.add(new IntegrationProbeCheckVO("微信文本接口", status, outcome.reason())); + return result(TEXT, "TEXT", mode, "WECHAT", status, status.equals("PASS") ? "微信文本审核接口调用成功" : outcome.reason(), outcome.code(), checks); + } + + private IntegrationProbeResultVO probeImageCallback(String mode, String openId, List checks) { + IntegrationProbeResultDO current = findResult(TEXT, "IMAGE_CALLBACK"); + if (current != null && "PENDING".equals(current.getStatus()) && current.getExpiresAt() != null && current.getExpiresAt().isAfter(LocalDateTime.now())) { + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "PENDING", "已有图片测试正在等待微信回调", null, + List.of(new IntegrationProbeCheckVO("微信图片异步接口", "PENDING", "等待上一条测试的微信回调或超时清理"))); + } + if (current != null && StringUtils.hasText(current.getTemporaryObjectName())) { + deleteTemporaryObject(current); + resultMapper.updateById(current); + if (StringUtils.hasText(current.getTemporaryObjectName())) { + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "上一张临时测试图片仍未清理,请稍后重试", "TEMP_CLEANUP_FAILED", + List.of(new IntegrationProbeCheckVO("临时图片清理", "FAIL", "无法确认旧测试文件已删除"))); + } + } + String objectName = "integration-probe/" + UUID.randomUUID() + ".png"; + String probeId = UUID.randomUUID().toString(); + ObjectStorageProvider uploaded = null; + boolean awaitingCallback = false; + boolean pendingSaved = false; + try { + byte[] image = createProbePng(); + for (ObjectStorageProvider provider : storageProviders) { + if (provider.isEnabled()) { + uploaded = provider; + provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName); + break; + } + } + if (uploaded == null) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "没有可用对象存储,无法生成图片审核地址", "STORAGE_UNAVAILABLE", checks); + String url = uploaded.getPresignedUrl(objectName, 5); + if (!StringUtils.hasText(url) || !url.startsWith("https://")) { + checks.add(new IntegrationProbeCheckVO("临时图片地址", "FAIL", "对象存储未提供公网 HTTPS 签名地址")); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks); + } + savePendingImageProbe(mode, probeId, uploaded.providerCode(), objectName); + pendingSaved = true; + ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId); + String status = outcome.status() == ModerationOutcome.Status.PENDING ? "PENDING" : outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : "FAIL"; + checks.add(new IntegrationProbeCheckVO("微信图片异步接口", status, outcome.reason())); + awaitingCallback = "PENDING".equals(status); + updatePendingImageTask(probeId, outcome.remoteTaskId()); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", status, outcome.reason(), outcome.code(), checks); + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO("微信图片异步接口", "FAIL", "临时图片上传或审核请求失败")); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "微信图片审核探测失败", "IMAGE_PROBE_FAILED", checks); + } finally { + if (uploaded != null && !awaitingCallback && !pendingSaved) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); } + } + } + + private byte[] createProbePng() throws java.io.IOException { + java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(64, 64, java.awt.image.BufferedImage.TYPE_INT_RGB); + java.awt.Graphics2D graphics = image.createGraphics(); + try { graphics.setColor(java.awt.Color.WHITE); graphics.fillRect(0, 0, 64, 64); } + finally { graphics.dispose(); } + java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); + javax.imageio.ImageIO.write(image, "png", output); + return output.toByteArray(); + } + + private void savePendingImageProbe(String mode, String probeId, String provider, String objectName) throws Exception { + IntegrationProbeResultDO row = findResult(TEXT, "IMAGE_CALLBACK"); + if (row == null) { row = new IntegrationProbeResultDO(); row.setServiceCode(TEXT); row.setOperationCode("IMAGE_CALLBACK"); } + row.setMode(mode); row.setProvider("WECHAT"); row.setStatus("PENDING"); row.setSummary("已提交微信图片审核,等待回调"); row.setErrorCode(null); + row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片异步接口", "PENDING", "等待微信回调")))); + row.setRemoteTaskId(null); row.setCorrelationKey(probeId); row.setTemporaryObjectProvider(provider); row.setTemporaryObjectName(objectName); + row.setExpiresAt(LocalDateTime.now().plusMinutes(5)); row.setCheckedAt(LocalDateTime.now()); + if (row.getId() == null) resultMapper.insert(row); else resultMapper.updateById(row); + } + + private void updatePendingImageTask(String probeId, String taskId) { + if (!StringUtils.hasText(taskId)) return; + IntegrationProbeResultDO row = resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1")); + if (row != null) { row.setRemoteTaskId(clip(taskId, 128)); resultMapper.updateById(row); } + } + + private IntegrationProbeResultDO findResult(String service, String operation) { + return resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getServiceCode, service) + .eq(IntegrationProbeResultDO::getOperationCode, operation).last("LIMIT 1")); + } + + private void deleteTemporaryObject(IntegrationProbeResultDO row) { + if (!StringUtils.hasText(row.getTemporaryObjectProvider()) || !StringUtils.hasText(row.getTemporaryObjectName())) return; + ObjectStorageProvider provider = storageProviders.stream() + .filter(item -> item.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().orElse(null); + if (provider == null) return; + try { + provider.deleteFile(row.getTemporaryObjectName()); + row.setTemporaryObjectProvider(null); + row.setTemporaryObjectName(null); + } catch (Exception ignored) { + log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); + } + } + + private IntegrationProbeResultVO probeMap(UserDO currentUser, String operation) { + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + List checks = new ArrayList<>(); + boolean amapKey = Boolean.TRUE.equals(config.getAmapWebKeyConfigured()); + boolean tencentKey = Boolean.TRUE.equals(config.getTencentWebKeyConfigured()); + boolean miniKey = Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()); + boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? amapKey : tencentKey; + checks.add(check("当前渠道 Web Key", selectedKey, "已配置", "未配置")); + checks.add(new IntegrationProbeCheckVO("高德 Web Key", amapKey ? "PASS" : "WARN", amapKey ? "已配置" : "未配置")); + checks.add(new IntegrationProbeCheckVO("腾讯 Web Key", tencentKey ? "PASS" : "WARN", tencentKey ? "已配置" : "未配置")); + checks.add(new IntegrationProbeCheckVO("高德小程序 Key", miniKey ? "PASS" : "WARN", miniKey ? "已配置" : "未配置,仅影响小程序选点")); + if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), statusForChecks(checks), "地图接入配置诊断完成", null, checks); + if (!selectedKey) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "当前地图渠道缺少 Web Key", "MAP_KEY_MISSING", checks); + if (!Boolean.TRUE.equals(config.getMapEnabled())) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "WARN", "地图服务当前已停用,保存并启用后才能测试真实请求", "MAP_DISABLED", checks); + if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "PASS", "地图 Key 配置诊断完成", null, checks); + Map runtime = secureIntegrationConfigService.getMapRuntimeConfig(currentUser); + String key = runtime.get("key"); + String url = "AMAP".equals(config.getMapProvider()) + ? "https://restapi.amap.com/v3/geocode/geo?address=" + java.net.URLEncoder.encode("天安门", StandardCharsets.UTF_8) + "&key=" + key + : "https://apis.map.qq.com/ws/geocoder/v1/?address=" + java.net.URLEncoder.encode("天安门", StandardCharsets.UTF_8) + "&key=" + key; + try { + JsonNode body = objectMapper.readTree(restTemplate.getForObject(url, String.class)); + boolean success = "AMAP".equals(config.getMapProvider()) ? body.path("status").asInt(0) == 1 : body.path("status").asInt(-1) == 0; + checks.add(new IntegrationProbeCheckVO("地图 API 请求", success ? "PASS" : "FAIL", success ? "固定地址解析成功" : "地图服务返回失败")); + return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), success ? "PASS" : "FAIL", success ? "地图服务调用成功" : "地图服务调用失败", null, checks); + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO("地图 API 请求", "FAIL", "地图接口不可达或返回格式异常")); + return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "地图服务调用失败", "MAP_REQUEST_FAILED", checks); + } + } + + private IntegrationProbeResultVO probeStorage(String operation) { + List checks = new ArrayList<>(); + if ("CONFIG".equals(operation)) { + for (ObjectStorageProvider provider : storageProviders) { + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), provider.isEnabled() ? "PASS" : "WARN", provider.isEnabled() ? "已启用并具备基本配置" : "未启用或配置不完整")); + } + String status = checks.isEmpty() ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; + return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储配置完整" : "存在未启用的对象存储渠道", null, checks); + } + byte[] bytes = "salon-integration-probe".getBytes(StandardCharsets.UTF_8); + String objectName = "integration-probe/" + UUID.randomUUID() + ".txt"; + int enabled = 0; + try { + for (ObjectStorageProvider provider : storageProviders) { + if (!provider.isEnabled()) { + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "WARN", "未启用或配置不完整")); + continue; + } + enabled++; + boolean cleanupFailed = false; + String stage = "上传"; + try { + provider.uploadStream(new java.io.ByteArrayInputStream(bytes), bytes.length, "text/plain", objectName); + stage = "服务端读取"; + try (InputStream input = provider.downloadFile(objectName)) { + boolean same = java.util.Arrays.equals(bytes, input.readAllBytes()); + stage = "生成签名地址"; + String signed = provider.getPresignedUrl(objectName, 5); + stage = "签名访问"; + // 传 URI 而不是字符串:字符串重载会经 DefaultUriBuilderFactory 的 URI_COMPONENT 展开, + // 把签名参数里的 %2B/%2F/%3D 二次编码成 %252B/%252F/%253D,导致对象存储验签失败。 + byte[] signedBytes = StringUtils.hasText(signed) + ? restTemplate.exchange(URI.create(signed), HttpMethod.GET, null, byte[].class).getBody() + : null; + stage = "内容比对"; + boolean signedRead = java.util.Arrays.equals(bytes, signedBytes); + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), same && signedRead ? "PASS" : "FAIL", same && signedRead ? "上传、读取和签名访问成功" : "对象内容或签名读取不一致")); + } + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "FAIL", storageFailureDetail(stage, exception))); + } finally { + try { provider.deleteFile(objectName); } + catch (Exception ignored) { cleanupFailed = true; log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); } + } + if (cleanupFailed) checks.add(new IntegrationProbeCheckVO(provider.providerCode() + " 清理", "FAIL", "临时测试对象未能删除,请检查存储状态")); + } + String status = enabled == 0 ? "FAIL" : checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; + return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储三副本往返测试成功" : "对象存储存在未就绪渠道", null, checks); + } catch (RuntimeException exception) { + return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", "FAIL", "对象存储测试失败", "STORAGE_PROBE_FAILED", checks); + } + } + + private String storageFailureDetail(String stage, Exception exception) { + return stage + "失败(" + exception.getClass().getSimpleName() + ":" + describeStorageFailure(exception) + ")"; + } + + private String describeStorageFailure(Exception exception) { + String message = exception.getMessage(); + if (!StringUtils.hasText(message)) { + return "无错误消息"; + } + Matcher urlMatcher = URL_IN_MESSAGE.matcher(message); + StringBuffer masked = new StringBuffer(); + while (urlMatcher.find()) { + urlMatcher.appendReplacement(masked, Matcher.quoteReplacement(maskUrl(urlMatcher.group()))); + } + urlMatcher.appendTail(masked); + String sanitized = SENSITIVE_PARAM.matcher(masked.toString()).replaceAll("$1=***"); + sanitized = sanitized.replaceAll("\\s+", " ").trim(); + return sanitized.length() > FAILURE_REASON_MAX_LENGTH + ? sanitized.substring(0, FAILURE_REASON_MAX_LENGTH) + "…" + : sanitized; + } + + private String maskUrl(String url) { + Matcher hostMatcher = URL_HOST.matcher(url); + if (hostMatcher.find()) { + return hostMatcher.group(1) + "/…"; + } + return "(地址已隐藏)"; + } + + private IntegrationProbeResultVO probeSms(UserDO currentUser, String operation, String mode, String phone) { + List checks = new ArrayList<>(); + List configs = messageHubPushConfigService.listConfigs(currentUser); + List expectedScenes = List.of("USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE", "USER_RESET_PASSWORD_SMS_CODE", "USER_BIND_PHONE_SMS_CODE", "USER_CHANGE_PHONE_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE"); + long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) + && "SMS".equalsIgnoreCase(item.getPlatform()) && Integer.valueOf(1).equals(item.getEnabled()) + && StringUtils.hasText(item.getSendMethod()) && StringUtils.hasText(item.getQueueName()) + && StringUtils.hasText(item.getTemplateCode()))).count(); + checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景配置完整并启用")); + String baseUrl = environment.getProperty("messagehub.client.base-url", "http://192.168.10.107:8080"); + String accessToken = environment.getProperty("messagehub.client.access-token"); + String exchange = environment.getProperty("messagehub.client.ingress-exchange", "messagehub.ingress.exchange"); + String routingKey = environment.getProperty("messagehub.client.ingress-routing-key", "message.send"); + String smsQueue = environment.getProperty("messagehub.client.sms-queue", "smsQueue"); + String sourceSystem = environment.getProperty("messagehub.client.source-system", "jayucloud-salon"); + String templateCode = environment.getProperty("messagehub.client.verify-template-code", "SPUG_SMS_VERIFY_1"); + String sendMethod = environment.getProperty("messagehub.client.send-method", "SPUG"); + boolean endpointConfigured = safeHttpUrl(baseUrl); + checks.add(check("MessageHub 地址", endpointConfigured, "已配置 HTTP(S) 地址", "地址未配置或格式无效")); + checks.add(check("MessageHub 访问凭据", StringUtils.hasText(accessToken), "已配置", "未配置")); + boolean deliveryConfigured = StringUtils.hasText(exchange) && StringUtils.hasText(routingKey) + && StringUtils.hasText(smsQueue) && StringUtils.hasText(sourceSystem) + && StringUtils.hasText(templateCode) && StringUtils.hasText(sendMethod); + checks.add(check("短信投递参数", deliveryConfigured, "交换机、路由、队列、来源和模板已配置", "部分投递参数缺失")); + boolean complete = enabled == expectedScenes.size() && endpointConfigured && StringUtils.hasText(accessToken) && deliveryConfigured; + if ("CONFIG".equals(operation) || !"REAL".equals(mode)) return result(SMS, operation, mode, "MESSAGEHUB", complete ? "PASS" : "FAIL", complete ? "短信场景配置完整;未发送真实短信" : "部分短信场景未启用", null, checks); + if (!complete) return result(SMS, operation, mode, "MESSAGEHUB", "FAIL", "短信场景配置不完整,未发送测试短信", "SMS_CONFIG_INCOMPLETE", checks); + if (!StringUtils.hasText(phone) || !phone.matches("^1[3-9]\\d{9}$")) throw new IllegalArgumentException("真实短信测试需要填写有效手机号"); + int testCode = java.util.concurrent.ThreadLocalRandom.current().nextInt(100000, 1000000); + messageHubClientService.sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, String.valueOf(testCode)); + checks.add(new IntegrationProbeCheckVO("真实短信投递", "PASS", "测试短信已提交,手机号 " + maskPhone(phone))); + return result(SMS, "SEND", mode, "MESSAGEHUB", "PASS", "测试短信已提交", null, checks); + } + + private IntegrationProbeResultVO probeSubscribe(String operation, String mode) { + List checks = new ArrayList<>(); + String provider = StringUtils.hasText(wechatMiniProperties.getSubscribeMessageProvider()) ? wechatMiniProperties.getSubscribeMessageProvider().trim().toLowerCase(Locale.ROOT) : "mock"; + boolean enabled = Boolean.TRUE.equals(wechatMiniProperties.getSubscribeMessageEnabled()); + boolean liveProvider = "wechat".equals(provider) && enabled; + checks.add(new IntegrationProbeCheckVO("发送渠道", liveProvider ? "PASS" : "WARN", liveProvider ? "微信真实发送已启用" : "当前为 Mock 或已停用")); + if (!liveProvider) { + checks.add(new IntegrationProbeCheckVO("小程序凭据", "WARN", "当前未调用微信接口,因此不校验真实凭据")); + checks.add(new IntegrationProbeCheckVO("固定模板", "PASS", "3 个固定模板 ID 已加载")); + return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", + "当前为 Mock 或已停用,未调用微信接口", null, checks); + } + boolean credentials = StringUtils.hasText(wechatMiniProperties.getAppId()) && StringUtils.hasText(wechatMiniProperties.getAppSecret()); + checks.add(check("小程序凭据", credentials, "已配置", "AppID 或 AppSecret 未配置")); + if (!credentials) return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息凭据不完整", "WECHAT_CREDENTIALS_MISSING", checks); + checks.add(check("固定模板", WechatSubscribeMessageService.TEMPLATE_APPOINTMENT.length() > 10 + && WechatSubscribeMessageService.TEMPLATE_CANCELLED.length() > 10 + && WechatSubscribeMessageService.TEMPLATE_SERVICE_START.length() > 10, + "3 个固定模板 ID 已加载", "固定模板 ID 不完整")); + try { + wechatMiniClientService.getAccessTokenForContentModeration(); + checks.add(new IntegrationProbeCheckVO("access_token", "PASS", "获取成功")); + if ("SEND".equals(operation) && "REAL".equals(mode)) { + String openId = findProbeOpenId(); + checks.add(check("测试账号", StringUtils.hasText(openId), "已找到当前环境绑定账号", "请先使用体验版登录")); + if (!StringUtils.hasText(openId)) return result(SUBSCRIBE, operation, mode, "WECHAT", "WARN", "缺少可用于探测的微信绑定账号", "OPENID_REQUIRED", checks); + WechatMiniClientService.SubscribeMessageResult send = wechatMiniClientService.sendSubscribeMessage(openId, WechatSubscribeMessageService.TEMPLATE_APPOINTMENT, + Map.of("thing1", "接入测试", "time2", "12:00", "thing3", "请忽略此测试消息", "name5", "测试技师", "name6", "测试客户"), wechatMiniProperties.getSubscribeMessagePage(), wechatMiniProperties.getSubscribeMessageMiniprogramState()); + String status = send.success() ? "PASS" : "FAIL"; + String sendDetail = send.success() ? "测试消息已提交" : subscribeSendError(send.errCode()); + checks.add(new IntegrationProbeCheckVO("订阅消息发送", status, sendDetail)); + return result(SUBSCRIBE, "SEND", mode, "WECHAT", status, sendDetail, send.success() ? null : String.valueOf(send.errCode()), checks); + } + return checkSubscribeTemplates(operation, mode, checks); + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO("access_token", "FAIL", "微信接口不可用")); + return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息接口探测失败", "WECHAT_REQUEST_FAILED", checks); + } + } + + private IntegrationProbeResultVO checkSubscribeTemplates(String operation, String mode, List checks) throws Exception { + String accessToken = wechatMiniClientService.getAccessTokenForContentModeration(); + String url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8); + JsonNode response = objectMapper.readTree(restTemplate.getForObject(url, String.class)); + int errorCode = response.path("errcode").asInt(0); + if (errorCode != 0) { + checks.add(new IntegrationProbeCheckVO("微信模板列表", "WARN", "微信未允许读取模板清单,请使用真实发送确认模板状态")); + return result(SUBSCRIBE, operation, mode, "WECHAT", "WARN", "凭据可用,模板状态需真实发送验证", String.valueOf(errorCode), checks); + } + java.util.Set configured = new java.util.HashSet<>(); + for (JsonNode item : response.path("data")) { + String templateId = item.path("priTmplId").asText(); + if (StringUtils.hasText(templateId)) configured.add(templateId); + } + List required = List.of(WechatSubscribeMessageService.TEMPLATE_APPOINTMENT, WechatSubscribeMessageService.TEMPLATE_CANCELLED, WechatSubscribeMessageService.TEMPLATE_SERVICE_START); + long matched = required.stream().filter(configured::contains).count(); + checks.add(new IntegrationProbeCheckVO("固定订阅模板", matched == required.size() ? "PASS" : "FAIL", matched + "/" + required.size() + " 个模板已添加到当前小程序")); + return result(SUBSCRIBE, operation, mode, "WECHAT", matched == required.size() ? "PASS" : "FAIL", matched == required.size() ? "订阅消息凭据与固定模板可用" : "微信后台缺少订阅模板", matched == required.size() ? null : "TEMPLATE_MISSING", checks); + } + + private IntegrationProbeResultVO result(String service, String operation, String mode, String provider, String status, String summary, String errorCode, List checks) { + IntegrationProbeResultVO result = new IntegrationProbeResultVO(); + result.setService(service); result.setOperation(operation); result.setMode(mode); result.setProvider(provider); result.setStatus(status); result.setSummary(summary); result.setErrorCode(errorCode); result.setCheckedAt(LocalDateTime.now()); result.setChecks(checks); + return result; + } + + private IntegrationProbeResultVO failure(String service, String operation, String mode, String summary, String errorCode) { + return result(service, operation, mode, "UNKNOWN", "FAIL", summary, errorCode, new ArrayList<>()); + } + + private void validateOperation(String service, String operation, String mode) { + boolean valid = switch (service) { + case TEXT -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation); + case MAP -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "REQUEST").contains(operation); + case STORAGE -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "ROUND_TRIP").contains(operation); + case SMS -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); + case SUBSCRIBE -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); + default -> false; + }; + if (!valid) throw new IllegalArgumentException("服务测试操作与测试模式不匹配"); + } + + private IntegrationProbeCheckVO check(String name, boolean ok, String pass, String fail) { return new IntegrationProbeCheckVO(name, ok ? "PASS" : "FAIL", ok ? pass : fail); } + + private String statusForChecks(List checks) { return checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; } + + private String findProbeOpenId() { + if (!StringUtils.hasText(wechatMiniProperties.getAppId())) return null; + WechatMiniBindingDO binding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, wechatMiniProperties.getAppId()) + .eq(WechatMiniBindingDO::getStatus, 1) + .isNotNull(WechatMiniBindingDO::getOpenId) + .last("LIMIT 1")); + return binding == null ? null : binding.getOpenId(); + } + + private void save(IntegrationProbeResultVO result) { + try { + IntegrationProbeResultDO row = findResult(result.getService(), result.getOperation()); + if (row == null) { row = new IntegrationProbeResultDO(); row.setServiceCode(result.getService()); row.setOperationCode(result.getOperation()); } + if ("PENDING".equals(result.getStatus()) && row.getId() != null && !"PENDING".equals(row.getStatus())) return; + row.setMode(result.getMode()); row.setProvider(result.getProvider()); row.setStatus(result.getStatus()); row.setSummary(clip(result.getSummary(), 500)); row.setErrorCode(clip(result.getErrorCode(), 64)); row.setCheckedAt(result.getCheckedAt()); + if (!"PENDING".equals(result.getStatus())) deleteTemporaryObject(row); + row.setChecksJson(objectMapper.writeValueAsString(result.getChecks())); + if (row.getId() == null) resultMapper.insert(row); else resultMapper.updateById(row); + } catch (Exception exception) { log.warn("保存接入探测结果失败,service={}, operation={}", result.getService(), result.getOperation()); } + } + + private IntegrationProbeResultVO toVO(IntegrationProbeResultDO row) { + IntegrationProbeResultVO result = result(row.getServiceCode(), row.getOperationCode(), row.getMode(), row.getProvider(), row.getStatus(), row.getSummary(), row.getErrorCode(), new ArrayList<>()); + result.setCheckedAt(row.getCheckedAt()); + try { result.setChecks(objectMapper.readValue(row.getChecksJson(), new TypeReference>() {})); } catch (Exception ignored) { } + return result; + } + + private String normalize(String value) { return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; } + private boolean safeHttpUrl(String value) { + if (!StringUtils.hasText(value)) return false; + try { + java.net.URI uri = java.net.URI.create(value.trim()); + return ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())) && StringUtils.hasText(uri.getHost()); + } catch (IllegalArgumentException ignored) { return false; } + } + private String safeMessage(RuntimeException exception) { return "探测请求未完成,请查看脱敏检查项"; } + private String subscribeSendError(int code) { + if (code == 43101) return "当前绑定账号尚未授权此订阅模板"; + if (code == 40037 || code == 47003) return "订阅模板无效或模板字段不匹配"; + if (code == 40001 || code == 40014) return "微信 access_token 无效或已过期"; + return "微信未接受测试消息,请核对模板状态和订阅授权"; + } + private String clip(String value, int max) { if (!StringUtils.hasText(value)) return null; String text = value.trim(); return text.length() <= max ? text : text.substring(0, max); } + private String maskPhone(String phone) { return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); } + private void requirePlatformAdmin(UserDO user) { if (user == null || !Integer.valueOf(4).equals(user.getType())) throw new RuntimeException("仅平台管理员可以测试系统接入"); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java index 694d7861..ba15b6cf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java @@ -11,6 +11,7 @@ import com.xiaowang.jayucloud.salon.core.modules.system.mapper.LegalAgreementMap import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; import lombok.RequiredArgsConstructor; @@ -20,6 +21,8 @@ import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -170,6 +173,57 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { return new UserAgreementConsentVO(versions); } + @Override + /** + * Purpose: getPendingAgreements 返回当前协议版本与该用户的同意状态;未登录时只返回当前版本。 + */ + public AgreementPendingVO getPendingAgreements(Long userId) { + Map currentVersions = new LinkedHashMap<>(); + Map acceptedVersions = new LinkedHashMap<>(); + List pendingTypes = new ArrayList<>(); + Map accepted = userId == null + ? Collections.emptyMap() + : getMyConsent(userId).getConsentVersions(); + for (String type : List.of(USER_TERMS, PRIVACY_POLICY)) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + continue; + } + currentVersions.put(type, current.getVersion()); + String acceptedVersion = accepted == null ? null : accepted.get(type); + if (StringUtils.hasText(acceptedVersion)) { + acceptedVersions.put(type, acceptedVersion); + } + if (!StringUtils.hasText(acceptedVersion) || !current.getVersion().equals(acceptedVersion)) { + pendingTypes.add(type); + } + } + Boolean pending = userId == null ? null : !pendingTypes.isEmpty(); + return new AgreementPendingVO(pending, currentVersions, acceptedVersions, pendingTypes); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: acceptCurrentAgreements 记录用户对当前发布版本的同意,不依赖客户端上报版本。 + */ + public void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest httpRequest) { + if (userId == null) { + throw new RuntimeException("请先登录后再同意协议"); + } + String normalizedClientType = StringUtils.hasText(clientType) + ? clientType.trim().toUpperCase() + : "WEB"; + String ip = resolveClientIp(httpRequest); + for (String type : List.of(USER_TERMS, PRIVACY_POLICY)) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + upsertConsent(userId, type, current.getVersion(), "agreement-gate", normalizedClientType, ip); + } + } + @Override /** * Purpose: requireAccepted supports LegalAgreementServiceImpl.java by holding or executing the require accepted business role. @@ -201,8 +255,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { version, entry, clientType, - resolveClientIp(httpRequest), - httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER) + resolveClientIp(httpRequest) )); } @@ -225,7 +278,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { * Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ - private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) { + private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip) { if (!StringUtils.hasText(version)) { return; } @@ -240,7 +293,6 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { consent.setEntry(entry); consent.setClientType(clientType); consent.setIpAddress(ip); - consent.setDeviceId(deviceId); consent.setConsentTime(LocalDateTime.now()); if (existing == null) { consentMapper.insert(consent); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java new file mode 100644 index 00000000..0d1eb622 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java @@ -0,0 +1,592 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegrationConfigDO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.SecureConfigEncryptionService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +@Slf4j +@Service +@RequiredArgsConstructor +public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConfigService { + private static final String MAP = "MAP"; + private static final String MODERATION = "CONTENT_MODERATION"; + private static final String MODERATION_FORWARD = "CONTENT_MODERATION_FORWARD"; + private static final String SYSTEM = "SYSTEM"; + private static final String LEGACY_MAP_MIGRATED = "LEGACY_MAP_MIGRATED"; + private static final String WECHAT_CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; + + private final SecureIntegrationConfigMapper secureConfigMapper; + private final SystemParameterConfigMapper systemParameterConfigMapper; + private final SecureConfigEncryptionService encryptionService; + private final ContentModerationProperties moderationProperties; + private final WechatMiniProperties wechatMiniProperties; + private final ObjectMapper objectMapper; + + @Override + @Transactional + public SecureIntegrationConfigVO getAdminConfig(UserDO currentUser) { + requirePlatformAdmin(currentUser); + migrateLegacyMapConfig(); + SecureIntegrationConfigVO result = new SecureIntegrationConfigVO(); + result.setEncryptionKeyConfigured(encryptionService.isConfigured()); + result.setMapLegacyMigrationPending(hasLegacyMapValues() && !isLegacyMapMigrationComplete()); + result.setMapProvider(readValue(MAP, "PROVIDER", "TENCENT")); + result.setMapEnabled(Boolean.parseBoolean(readValue(MAP, "ENABLED", "false"))); + result.setTencentWebKeyConfigured(hasStoredValue(MAP, "TENCENT_WEB_KEY")); + result.setAmapWebKeyConfigured(hasStoredValue(MAP, "AMAP_WEB_KEY")); + result.setAmapMiniKeyConfigured(hasStoredValue(MAP, "AMAP_MINI_KEY")); + + boolean moderationProviderReadable = encryptionService.isConfigured() + || !hasStoredValue(MODERATION, "PROVIDER"); + String moderationProvider = moderationProviderReadable + ? normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider())) + : "DISABLED"; + boolean tokenConfigured = hasStoredValue(MODERATION, "CALLBACK_TOKEN"); + boolean aesConfigured = hasStoredValue(MODERATION, "ENCODING_AES_KEY"); + boolean callbackConfigured = isValidCallbackUrl(readValue(MODERATION, "CALLBACK_URL", "")); + boolean appConfigured = isWechatMiniConfigured(); + boolean callbackReady = encryptionService.isConfigured() + && tokenConfigured && aesConfigured && callbackConfigured && appConfigured; + boolean moderationReady = "MOCK".equals(moderationProvider) + ? isMockAllowed() + : "WECHAT".equals(moderationProvider) && callbackReady; + + result.setModerationProvider(moderationProvider); + result.setModerationCallbackUrl(readValue(MODERATION, "CALLBACK_URL", "")); + result.setModerationCallbackTokenConfigured(tokenConfigured); + result.setModerationEncodingAesKeyConfigured(aesConfigured); + result.setModerationCallbackReady(callbackReady); + result.setModerationReady(moderationReady); + result.setWechatMiniAppConfigured(appConfigured); + result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId()) + ? wechatMiniProperties.getAppId() : ""); + result.setMockProviderAllowed(isMockAllowed()); + + ModerationForwardConfig forwardConfig = getModerationForwardConfig(); + result.setModerationForwardEnabled(forwardConfig.isEnabled()); + result.setModerationForwardTargets(forwardConfig.getTargets()); + result.setModerationForwardOrder(forwardConfig.getOrder()); + result.setModerationForwardSecretConfigured(StringUtils.hasText(forwardConfig.getSecret())); + result.setModerationForwardMaxRetry(forwardConfig.getMaxRetry()); + result.setModerationForwardBackoffSeconds(forwardConfig.getBackoffSeconds() == null + ? ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS + : forwardConfig.getBackoffSeconds()); + + result.setUpdatedAt(latestUpdateTime()); + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveMapConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) { + requirePlatformAdmin(currentUser); + requireEncryptionKey(); + migrateLegacyMapConfig(); + + String provider = upper(dto.getMapProvider(), "TENCENT"); + if (!"TENCENT".equals(provider) && !"AMAP".equals(provider)) { + throw new IllegalArgumentException("地图渠道仅支持腾讯地图或高德地图"); + } + updateSecret(MAP, "TENCENT_WEB_KEY", dto.getTencentWebKey(), dto.getClearTencentWebKey(), currentUser.getId()); + updateSecret(MAP, "AMAP_WEB_KEY", dto.getAmapWebKey(), dto.getClearAmapWebKey(), currentUser.getId()); + updateSecret(MAP, "AMAP_MINI_KEY", dto.getAmapMiniKey(), dto.getClearAmapMiniKey(), currentUser.getId()); + + boolean enabled = Boolean.TRUE.equals(dto.getMapEnabled()); + if (enabled) { + String selectedKey = "AMAP".equals(provider) + ? resolveUpdatedSecret(MAP, "AMAP_WEB_KEY", dto.getAmapWebKey(), dto.getClearAmapWebKey()) + : resolveUpdatedSecret(MAP, "TENCENT_WEB_KEY", dto.getTencentWebKey(), dto.getClearTencentWebKey()); + if (!StringUtils.hasText(selectedKey)) { + throw new IllegalArgumentException("请先填写当前地图渠道对应的 Web Key,或关闭地图服务"); + } + } + writeValue(MAP, "PROVIDER", provider, false, currentUser.getId()); + writeValue(MAP, "ENABLED", String.valueOf(enabled), false, currentUser.getId()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) { + requirePlatformAdmin(currentUser); + requireEncryptionKey(); + + String provider = normalizedProvider(dto.getModerationProvider()); + if (!Arrays.asList("DISABLED", "WECHAT", "MOCK").contains(provider)) { + throw new IllegalArgumentException("内容审核渠道不受支持"); + } + if ("MOCK".equals(provider) && !isMockAllowed()) { + throw new IllegalArgumentException("当前环境不允许启用模拟审核"); + } + + String callbackUrl = StringUtils.trimWhitespace(dto.getModerationCallbackUrl()); + String token = resolveUpdatedSecret(MODERATION, "CALLBACK_TOKEN", dto.getModerationCallbackToken(), + dto.getClearModerationCallbackToken()); + String aesKey = resolveUpdatedSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(), + dto.getClearModerationEncodingAesKey()); + if (StringUtils.hasText(token) && !token.matches("[A-Za-z0-9]{3,32}")) { + throw new IllegalArgumentException("微信回调 Token 需要为 3-32 位英文字母或数字"); + } + if (StringUtils.hasText(aesKey) && !aesKey.matches("[A-Za-z0-9+/]{43}")) { + throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥"); + } + String effectiveCallbackUrl = StringUtils.hasText(callbackUrl) + ? callbackUrl : readValue(MODERATION, "CALLBACK_URL", ""); + if ("WECHAT".equals(provider)) { + if (!StringUtils.hasText(token) || token.length() < 3 || token.length() > 32) { + throw new IllegalArgumentException("微信回调 Token 需要为 3-32 位英文字母或数字"); + } + if (!StringUtils.hasText(aesKey) || !aesKey.matches("[A-Za-z0-9+/]{43}")) { + throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥"); + } + if (!isValidCallbackUrl(effectiveCallbackUrl)) { + throw new IllegalArgumentException("微信回调地址必须使用公网域名 HTTPS,并精确指向 /api/integration/wechat/content-moderation/callback"); + } + if (!isWechatMiniConfigured()) { + throw new IllegalArgumentException("当前环境未同时配置微信小程序 AppID 和 AppSecret,请先完成环境配置"); + } + } + if (StringUtils.hasText(callbackUrl)) { + writeValue(MODERATION, "CALLBACK_URL", callbackUrl, false, currentUser.getId()); + } + updateSecret(MODERATION, "CALLBACK_TOKEN", dto.getModerationCallbackToken(), + dto.getClearModerationCallbackToken(), currentUser.getId()); + updateSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(), + dto.getClearModerationEncodingAesKey(), currentUser.getId()); + writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) { + requirePlatformAdmin(currentUser); + requireEncryptionKey(); + + boolean enabled = Boolean.TRUE.equals(dto.getModerationForwardEnabled()); + Map targets = normalizeForwardTargets(dto.getModerationForwardTargets()); + for (Map.Entry entry : targets.entrySet()) { + if (!isValidForwardTarget(entry.getValue())) { + throw new IllegalArgumentException("跨环境转发地址不合法(" + entry.getKey() + + "),必须精确指向 /api/integration/wechat/content-moderation/callback,且 HTTP 仅允许内网主机"); + } + } + List order = normalizeForwardOrder(dto.getModerationForwardOrder(), targets); + Map orderedTargets = new LinkedHashMap<>(); + for (String env : order) orderedTargets.put(env, targets.get(env)); + + ModerationForwardConfig current = getModerationForwardConfig(); + String secret; + if (Boolean.TRUE.equals(dto.getClearModerationForwardSecret())) { + secret = ""; + } else if (StringUtils.hasText(dto.getModerationForwardSecret())) { + secret = dto.getModerationForwardSecret().trim(); + } else { + secret = current.getSecret(); + } + if (StringUtils.hasText(secret) && !secret.matches("[A-Za-z0-9+/=_\\-]{16,128}")) { + throw new IllegalArgumentException("跨环境转发共享密钥需要为 16-128 位字母、数字或常用符号"); + } + if (enabled) { + if (!StringUtils.hasText(secret)) { + throw new IllegalArgumentException("启用跨环境回调转发时必须配置共享密钥"); + } + if (targets.isEmpty()) { + throw new IllegalArgumentException("启用跨环境回调转发时至少需要配置一个目标环境地址"); + } + } + + int maxRetry = resolveForwardMaxRetry(dto.getModerationForwardMaxRetry()); + List backoffSeconds = resolveForwardBackoff(dto.getModerationForwardBackoffSeconds()); + + Map payload = new LinkedHashMap<>(); + payload.put("enabled", enabled); + payload.put("targets", orderedTargets); + payload.put("order", order); + payload.put("secret", secret); + payload.put("maxRetry", maxRetry); + payload.put("backoffSeconds", backoffSeconds); + try { + writeValue(MODERATION_FORWARD, "CONFIG", objectMapper.writeValueAsString(payload), true, currentUser.getId()); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("无法保存跨环境转发配置", exception); + } + } + + @Override + public ModerationForwardConfig getModerationForwardConfig() { + if (!encryptionService.isConfigured()) return ModerationForwardConfig.disabled(); + String json = readValue(MODERATION_FORWARD, "CONFIG", ""); + if (!StringUtils.hasText(json)) return ModerationForwardConfig.disabled(); + try { + JsonNode node = objectMapper.readTree(json); + boolean enabled = node.path("enabled").asBoolean(false); + Map targets = new LinkedHashMap<>(); + JsonNode targetsNode = node.path("targets"); + if (targetsNode.isObject()) { + targetsNode.fields().forEachRemaining(entry -> { + if (StringUtils.hasText(entry.getValue().asText(""))) { + targets.put(entry.getKey(), entry.getValue().asText("")); + } + }); + } + List order = new ArrayList<>(); + JsonNode orderNode = node.path("order"); + if (orderNode.isArray()) { + orderNode.forEach(item -> { + if (StringUtils.hasText(item.asText(""))) order.add(item.asText("")); + }); + } + int maxRetry = node.path("maxRetry").asInt(ModerationForwardConfig.DEFAULT_MAX_RETRY); + if (maxRetry < 1 || maxRetry > 10) maxRetry = ModerationForwardConfig.DEFAULT_MAX_RETRY; + List parsedBackoff = new ArrayList<>(); + JsonNode backoffNode = node.path("backoffSeconds"); + if (backoffNode.isArray()) { + backoffNode.forEach(item -> { + long seconds = item.asLong(0L); + if (seconds > 0) parsedBackoff.add(seconds); + }); + } + List backoffSeconds = parsedBackoff.isEmpty() + ? ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS : parsedBackoff; + return new ModerationForwardConfig(enabled, targets, node.path("secret").asText(""), order, + maxRetry, backoffSeconds); + } catch (JsonProcessingException exception) { + log.warn("跨环境转发配置解析失败,按未启用处理"); + return ModerationForwardConfig.disabled(); + } + } + + @Override + @Transactional + public Map getMapRuntimeConfig(UserDO currentUser) { + requirePlatformAdmin(currentUser); + migrateLegacyMapConfig(); + String provider = upper(readValue(MAP, "PROVIDER", "TENCENT"), "TENCENT"); + boolean enabled = Boolean.parseBoolean(readValue(MAP, "ENABLED", "false")); + String keyName = "AMAP".equals(provider) ? "AMAP_WEB_KEY" : "TENCENT_WEB_KEY"; + String key = enabled && encryptionService.isConfigured() ? readValue(MAP, keyName, "") : ""; + Map result = new HashMap<>(); + result.put("provider", provider); + result.put("enabled", String.valueOf(enabled)); + result.put("key", key); + return result; + } + + @Override + public ModerationRuntimeConfig getModerationRuntimeConfig() { + ModerationRuntimeConfig callbackConfig = getModerationCallbackConfig(); + if ("WECHAT".equals(callbackConfig.getProvider()) && callbackConfig.isReady()) return callbackConfig; + if ("MOCK".equals(callbackConfig.getProvider()) && isMockAllowed()) { + return new ModerationRuntimeConfig("MOCK", "", "", "", true); + } + return new ModerationRuntimeConfig("DISABLED", "", "", "", false); + } + + @Override + public ModerationRuntimeConfig getModerationCallbackConfig() { + if (!encryptionService.isConfigured()) { + if (!hasStoredValue(MODERATION, "PROVIDER") && isMockAllowed()) { + return new ModerationRuntimeConfig("MOCK", "", "", "", true); + } + return new ModerationRuntimeConfig("DISABLED", "", "", "", false); + } + String provider = normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider())); + String callbackUrl = readValue(MODERATION, "CALLBACK_URL", ""); + String token = readValue(MODERATION, "CALLBACK_TOKEN", ""); + String aesKey = readValue(MODERATION, "ENCODING_AES_KEY", ""); + boolean allowedMock = !"MOCK".equals(provider) || isMockAllowed(); + boolean configured = StringUtils.hasText(token) && StringUtils.hasText(aesKey) + && isValidCallbackUrl(callbackUrl) && isWechatMiniConfigured(); + if (!allowedMock) provider = "DISABLED"; + return new ModerationRuntimeConfig(provider, callbackUrl, token, aesKey, configured); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void migrateLegacyMapConfig() { + if (!encryptionService.isConfigured() || isLegacyMapMigrationComplete()) return; + List legacyConfigs = systemParameterConfigMapper.selectList( + new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, MAP) + .eq(SystemParameterConfigDO::getIsDelete, 0)); + Map legacyByKey = new HashMap<>(); + for (SystemParameterConfigDO legacy : legacyConfigs) { + legacyByKey.put(upper(legacy.getConfigKey(), ""), legacy); + } + moveLegacyValue(legacyByKey, "MAP_PROVIDER", MAP, "PROVIDER", false); + moveLegacyValue(legacyByKey, "TENCENT_MAP_KEY", MAP, "TENCENT_WEB_KEY", true); + moveLegacyValue(legacyByKey, "AMAP_WEB_KEY", MAP, "AMAP_WEB_KEY", true); + moveLegacyValue(legacyByKey, "AMAP_MINI_KEY", MAP, "AMAP_MINI_KEY", true); + SystemParameterConfigDO oldProvider = legacyByKey.get("MAP_PROVIDER"); + if (oldProvider != null) { + String provider = upper(oldProvider.getConfigValue(), "TENCENT"); + String activeKeyName = "AMAP".equals(provider) ? "AMAP_WEB_KEY" : "TENCENT_MAP_KEY"; + SystemParameterConfigDO activeKey = legacyByKey.get(activeKeyName); + boolean enabled = Integer.valueOf(1).equals(oldProvider.getEnabled()) + && activeKey != null + && Integer.valueOf(1).equals(activeKey.getEnabled()) + && StringUtils.hasText(activeKey.getConfigValue()); + writeValue(MAP, "ENABLED", String.valueOf(enabled), false, null); + } + for (SystemParameterConfigDO legacy : legacyConfigs) { + legacy.setConfigValue(""); + legacy.setEnabled(0); + systemParameterConfigMapper.updateById(legacy); + } + writeValue(SYSTEM, LEGACY_MAP_MIGRATED, "true", false, null); + } + + private void moveLegacyValue(Map legacyByKey, String oldKey, + String group, String newKey, boolean secret) { + SystemParameterConfigDO legacy = legacyByKey.get(oldKey); + if (legacy == null || !StringUtils.hasText(legacy.getConfigValue()) || hasStoredValue(group, newKey)) return; + writeValue(group, newKey, legacy.getConfigValue(), secret, null); + } + + private void updateSecret(String group, String key, String submittedValue, Boolean clear, Long updatedBy) { + if (Boolean.TRUE.equals(clear)) { + writeValue(group, key, "", true, updatedBy); + } else if (StringUtils.hasText(submittedValue)) { + writeValue(group, key, submittedValue.trim(), true, updatedBy); + } + } + + private String resolveUpdatedSecret(String group, String key, String submittedValue, Boolean clear) { + if (Boolean.TRUE.equals(clear)) return ""; + return StringUtils.hasText(submittedValue) ? submittedValue.trim() : readValue(group, key, ""); + } + + private void writeValue(String group, String key, String value, boolean secret, Long updatedBy) { + SecureIntegrationConfigDO record = select(group, key); + if (record == null) { + record = new SecureIntegrationConfigDO(); + record.setConfigGroup(group); + record.setConfigKey(key); + } + record.setConfigValue(StringUtils.hasText(value) ? encryptionService.encrypt(value) : null); + record.setSecret(secret ? 1 : 0); + record.setEnabled(StringUtils.hasText(value) ? 1 : 0); + record.setUpdatedBy(updatedBy); + if (record.getId() == null) secureConfigMapper.insert(record); + else secureConfigMapper.updateById(record); + } + + private String readValue(String group, String key, String fallback) { + SecureIntegrationConfigDO record = select(group, key); + if (record == null || !Integer.valueOf(1).equals(record.getEnabled()) + || !StringUtils.hasText(record.getConfigValue()) || !encryptionService.isConfigured()) return fallback; + return encryptionService.decrypt(record.getConfigValue()); + } + + private boolean hasStoredValue(String group, String key) { + SecureIntegrationConfigDO record = select(group, key); + return record != null && Integer.valueOf(1).equals(record.getEnabled()) && StringUtils.hasText(record.getConfigValue()); + } + + private SecureIntegrationConfigDO select(String group, String key) { + return secureConfigMapper.selectOne(new LambdaQueryWrapper() + .eq(SecureIntegrationConfigDO::getConfigGroup, group) + .eq(SecureIntegrationConfigDO::getConfigKey, key) + .last("LIMIT 1")); + } + + private boolean hasLegacyMapValues() { + return systemParameterConfigMapper.selectCount(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, MAP) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .apply("config_value IS NOT NULL AND config_value <> ''")) > 0; + } + + private boolean isLegacyMapMigrationComplete() { + return "true".equalsIgnoreCase(readValue(SYSTEM, LEGACY_MAP_MIGRATED, "false")); + } + + private java.time.LocalDateTime latestUpdateTime() { + List rows = secureConfigMapper.selectList(new LambdaQueryWrapper() + .orderByDesc(SecureIntegrationConfigDO::getUpdateTime).last("LIMIT 1")); + return rows == null || rows.isEmpty() ? null : rows.get(0).getUpdateTime(); + } + + private void requireEncryptionKey() { + if (!encryptionService.isConfigured()) { + throw new IllegalStateException("安全接入加密主密钥未配置,请先由部署维护人员设置 SALON_SECURE_CONFIG_MASTER_KEY 并重启 Core"); + } + } + + private void requirePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理安全接入配置"); + } + } + + private boolean isMockAllowed() { + return Boolean.TRUE.equals(moderationProperties.getAllowMock()); + } + + private String defaultModerationProvider() { + return isMockAllowed() ? "MOCK" : "DISABLED"; + } + + private boolean isWechatMiniConfigured() { + return StringUtils.hasText(wechatMiniProperties.getAppId()) + && StringUtils.hasText(wechatMiniProperties.getAppSecret()); + } + + private boolean isValidCallbackUrl(String value) { + if (!StringUtils.hasText(value)) return false; + try { + URI uri = new URI(value.trim()); + String host = uri.getHost(); + if (!"https".equalsIgnoreCase(uri.getScheme()) || !StringUtils.hasText(host) + || uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null + || !WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) { + return false; + } + String normalizedHost = host.toLowerCase(Locale.ROOT); + if (normalizedHost.endsWith(".")) normalizedHost = normalizedHost.substring(0, normalizedHost.length() - 1); + if ("localhost".equals(normalizedHost) || normalizedHost.endsWith(".localhost") + || normalizedHost.endsWith(".local") || normalizedHost.endsWith(".internal") + || normalizedHost.contains(":") || normalizedHost.matches("\\d{1,3}(\\.\\d{1,3}){3}")) { + return false; + } + return uri.getPort() == -1 || uri.getPort() == 443; + } catch (URISyntaxException exception) { + return false; + } + } + + private Map normalizeForwardTargets(Map raw) { + Map result = new LinkedHashMap<>(); + if (raw == null) return result; + for (String env : Arrays.asList("dev", "sit", "prod")) { + String value = raw.get(env); + if (StringUtils.hasText(value)) result.put(env, value.trim()); + } + return result; + } + + /** + * 归一化探测顺序:只保留已配置目标地址的环境,未在 order 中声明的按 dev→sit→prod 补齐。 + */ + private List normalizeForwardOrder(List rawOrder, Map targets) { + List result = new ArrayList<>(); + if (rawOrder != null) { + for (String item : rawOrder) { + String env = upper(item, ""); + if (targets.containsKey(env) && !result.contains(env)) result.add(env); + } + } + for (String env : Arrays.asList("dev", "sit", "prod")) { + if (targets.containsKey(env) && !result.contains(env)) result.add(env); + } + return result; + } + + /** + * 归一化最大重试次数:未填写回退默认值,允许范围 1-10。 + */ + private int resolveForwardMaxRetry(Integer raw) { + if (raw == null) return ModerationForwardConfig.DEFAULT_MAX_RETRY; + if (raw < 1 || raw > 10) { + throw new IllegalArgumentException("跨环境回调最大重试次数需要在 1-10 之间"); + } + return raw; + } + + /** + * 归一化退避秒数:未填写回退默认梯度,至少 1 个且每个值需在 1 秒-1 天之间。 + */ + private List resolveForwardBackoff(List raw) { + if (raw == null || raw.isEmpty()) return ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS; + List result = new ArrayList<>(); + for (Integer seconds : raw) { + if (seconds == null || seconds < 1 || seconds > 86400) { + throw new IllegalArgumentException("跨环境回调退避秒数需要为 1-86400 秒"); + } + result.add(seconds.longValue()); + } + return result; + } + + /** + * 只允许指向内容审核回调路径:HTTPS 放行(各环境对外地址通常为 HTTPS 域名), + * HTTP 仅允许私网/本机主机,避免被配置为任意公网地址造成 SSRF。 + */ + private boolean isValidForwardTarget(String value) { + if (!StringUtils.hasText(value)) return false; + try { + URI uri = new URI(value.trim()); + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + String host = uri.getHost(); + if (!"https".equals(scheme) && !"http".equals(scheme)) return false; + if (!StringUtils.hasText(host)) return false; + if (uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null) return false; + if (!WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) return false; + return !"http".equals(scheme) || isPrivateHost(host); + } catch (URISyntaxException exception) { + return false; + } + } + + private boolean isPrivateHost(String host) { + String normalized = host.toLowerCase(Locale.ROOT); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + normalized = normalized.substring(1, normalized.length() - 1); + } + if ("localhost".equals(normalized) || normalized.endsWith(".localhost") + || normalized.endsWith(".local") || normalized.endsWith(".internal")) { + return true; + } + if (normalized.contains(":")) { + return normalized.startsWith("::1") || normalized.startsWith("fc") || normalized.startsWith("fd"); + } + String[] parts = normalized.split("\\."); + if (parts.length != 4) return false; + try { + int first = Integer.parseInt(parts[0]); + int second = Integer.parseInt(parts[1]); + if (first == 10 || first == 127) return true; + if (first == 192 && second == 168) return true; + if (first == 172 && second >= 16 && second <= 31) return true; + return first == 169 && second == 254; + } catch (NumberFormatException exception) { + return false; + } + } + + private String normalizedProvider(String value) { + return upper(value, "DISABLED"); + } + + private String upper(String value, String fallback) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : fallback; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java index 545bfe3e..0c7c4a43 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java @@ -16,6 +16,7 @@ import org.springframework.util.StringUtils; import java.util.List; import java.util.Locale; +import java.util.Collections; import java.util.stream.Collectors; @Service @@ -25,6 +26,9 @@ import java.util.stream.Collectors; * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. */ public class SystemParameterConfigServiceImpl implements SystemParameterConfigService { + private static final String STORAGE_READ_ORDER_GROUP = "FILE"; + private static final String STORAGE_READ_ORDER_KEY = "IMAGE_READ_PROVIDER_ORDER"; + private static final java.util.Set STORAGE_PROVIDERS = java.util.Set.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"); /** * Purpose: configMapper supports SystemParameterConfigServiceImpl.java by holding or executing the config mapper business role. @@ -40,12 +44,17 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe */ public List listConfigs(UserDO currentUser, String configGroup) { ensurePlatformAdmin(currentUser); + if (StringUtils.hasText(configGroup) && "MAP".equalsIgnoreCase(configGroup.trim())) { + return Collections.emptyList(); + } LambdaQueryWrapper wrapper = new LambdaQueryWrapper() .eq(SystemParameterConfigDO::getIsDelete, 0) .orderByAsc(SystemParameterConfigDO::getConfigGroup) .orderByAsc(SystemParameterConfigDO::getConfigKey); if (StringUtils.hasText(configGroup)) { wrapper.eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)); + } else { + wrapper.ne(SystemParameterConfigDO::getConfigGroup, "MAP"); } return configMapper.selectList(wrapper).stream().map(this::toVO).collect(Collectors.toList()); } @@ -60,6 +69,15 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe ensurePlatformAdmin(currentUser); String group = normalize(dto.getConfigGroup()); String key = normalize(dto.getConfigKey()); + if ("MAP".equals(group)) { + throw new IllegalArgumentException("地图密钥已迁移至安全接入配置,不允许通过通用参数接口读写"); + } + if (STORAGE_READ_ORDER_KEY.equals(key)) { + if (!STORAGE_READ_ORDER_GROUP.equals(group)) { + throw new IllegalArgumentException("对象存储读取顺序只能保存在 FILE 配置分组"); + } + validateStorageReadOrder(dto.getConfigValue()); + } if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) { AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue()); } @@ -98,6 +116,7 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe if (!StringUtils.hasText(configGroup) || !StringUtils.hasText(configKey)) { return ""; } + if ("MAP".equalsIgnoreCase(configGroup.trim())) return ""; SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() .eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)) .eq(SystemParameterConfigDO::getConfigKey, normalize(configKey)) @@ -125,6 +144,14 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe return value.trim().toUpperCase(Locale.ROOT); } + private void validateStorageReadOrder(String value) { + List providers = value == null ? Collections.emptyList() : java.util.Arrays.stream(value.split(",")) + .map(String::trim).map(item -> item.toUpperCase(Locale.ROOT)).collect(Collectors.toList()); + if (providers.size() != STORAGE_PROVIDERS.size() || !STORAGE_PROVIDERS.equals(new java.util.HashSet<>(providers))) { + throw new IllegalArgumentException("对象存储读取顺序必须且仅能包含 MinIO、七牛云、阿里云 OSS 各一次"); + } + } + /** * Purpose: toVO supports SystemParameterConfigServiceImpl.java by holding or executing the to vo business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/support/AgreementVersionCacheService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/support/AgreementVersionCacheService.java new file mode 100644 index 00000000..3166cd26 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/support/AgreementVersionCacheService.java @@ -0,0 +1,115 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.support; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 协议版本缓存:当前发布版本缓存 4 分钟,用户已同意版本缓存 10 分钟。 + * 版本发布走 SQL 迁移,没有代码钩子,依赖短 TTL 自然收敛;accept 成功时主动清除该用户缓存。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AgreementVersionCacheService { + + private static final String CURRENT_VERSIONS_KEY = "jayucloud:agreement:current-versions:v1"; + + private static final String USER_VERSIONS_KEY_PREFIX = "jayucloud:agreement:user-versions:"; + + private static final Duration CURRENT_VERSIONS_TTL = Duration.ofMinutes(4); + + private static final Duration USER_VERSIONS_TTL = Duration.ofMinutes(10); + + private static final TypeReference> STRING_MAP_TYPE = new TypeReference>() { + }; + + private final LegalAgreementService legalAgreementService; + + private final UserAgreementConsentMapper consentMapper; + + private final ObjectMapper objectMapper; + + private final StringRedisTemplate stringRedisTemplate; + + public Map currentVersions() { + Map cached = readCache(CURRENT_VERSIONS_KEY); + if (cached != null) { + return cached; + } + Map loaded = legalAgreementService.getPendingAgreements(null).getCurrentVersions(); + writeCache(CURRENT_VERSIONS_KEY, loaded, CURRENT_VERSIONS_TTL); + return loaded == null ? Collections.emptyMap() : loaded; + } + + public Map acceptedVersions(Long userId) { + if (userId == null) { + return Collections.emptyMap(); + } + String key = userVersionsKey(userId); + Map cached = readCache(key); + if (cached != null) { + return cached; + } + Map loaded = consentMapper.selectList(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId)) + .stream() + .collect(Collectors.toMap( + UserAgreementConsentDO::getAgreementType, + UserAgreementConsentDO::getVersion, + (left, right) -> right, + LinkedHashMap::new)); + writeCache(key, loaded, USER_VERSIONS_TTL); + return loaded; + } + + public void evictUser(Long userId) { + if (userId == null) { + return; + } + try { + stringRedisTemplate.delete(userVersionsKey(userId)); + } catch (Exception exception) { + log.warn("清除协议同意缓存失败 userId={}", userId, exception); + } + } + + private String userVersionsKey(Long userId) { + return USER_VERSIONS_KEY_PREFIX + userId; + } + + private Map readCache(String key) { + try { + String json = stringRedisTemplate.opsForValue().get(key); + if (!StringUtils.hasText(json)) { + return null; + } + return objectMapper.readValue(json, STRING_MAP_TYPE); + } catch (Exception exception) { + log.warn("读取协议版本缓存失败,回退数据库 key={}", key, exception); + return null; + } + } + + private void writeCache(String key, Map value, Duration ttl) { + try { + stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), ttl); + } catch (Exception exception) { + log.warn("写入协议版本缓存失败 key={}", key, exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java new file mode 100644 index 00000000..df49a22a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; + +/** + * 协议重新同意状态:未登录时只返回当前版本,登录后额外返回已同意版本与待同意类型。 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AgreementPendingVO { + + private Boolean pending; + + private Map currentVersions; + + private Map acceptedVersions; + + private List pendingTypes; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java new file mode 100644 index 00000000..ae2cb197 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class IntegrationProbeCheckVO { + private String name; + private String status; + private String detail; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java new file mode 100644 index 00000000..b063ce4e --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class IntegrationProbeResultVO { + private String service; + private String operation; + private String mode; + private String provider; + private String status; + private String summary; + private String errorCode; + private LocalDateTime checkedAt; + private List checks = new ArrayList<>(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java new file mode 100644 index 00000000..5b0d4950 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java @@ -0,0 +1,22 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class ModerationForwardRecordVO { + private Long id; + private String traceId; + private String sourceEnv; + private String targetEnv; + private String status; + private Integer retryCount; + private String lastError; + /** 解密后的原始回调报文,仅平台管理员可查,用于 DEAD 任务人工排查。 */ + private String payload; + private LocalDateTime nextAttemptAt; + private LocalDateTime finishedAt; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java new file mode 100644 index 00000000..43ae12d9 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java @@ -0,0 +1,40 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +@Data +public class SecureIntegrationConfigVO { + private String mapProvider; + private Boolean mapEnabled; + private Boolean tencentWebKeyConfigured; + private Boolean amapWebKeyConfigured; + private Boolean amapMiniKeyConfigured; + private Boolean mapLegacyMigrationPending; + + private String moderationProvider; + private String moderationCallbackUrl; + private Boolean moderationCallbackTokenConfigured; + private Boolean moderationEncodingAesKeyConfigured; + private Boolean moderationCallbackReady; + private Boolean moderationReady; + private Boolean wechatMiniAppConfigured; + private String wechatMiniAppId; + private Boolean mockProviderAllowed; + + private Boolean moderationForwardEnabled; + private Map moderationForwardTargets; + private List moderationForwardOrder; + private Boolean moderationForwardSecretConfigured; + private Integer moderationForwardMaxRetry; + private List moderationForwardBackoffSeconds; + private List moderationForwardRecent; + + private Boolean encryptionKeyConfigured; + private LocalDateTime updatedAt; + /** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */ + private List probeResults; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java index 938c6780..b2ff295e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java @@ -3,22 +3,17 @@ package com.xiaowang.jayucloud.salon.core.modules.user.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.common.Result; -import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserBalanceChangeDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserVipOverrideDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserRelationUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import lombok.Data; @@ -42,10 +37,6 @@ public class AdminUserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; /** * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -334,101 +325,6 @@ public class AdminUserController { } } - @GetMapping("/{id}/asset") - @RequirePermission("user:balance: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 - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getUserAsset(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户资产"); - UserAssetVO assetVO = userAssetService.getUserAsset(targetUser.getId()); - return Result.success(assetVO); - } - - @GetMapping("/{id}/balance/history") - @RequirePermission("user:balance: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 - * @param id parameter `id` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getUserBalanceHistory(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户余额流水"); - List history = userAssetService.listBalanceHistory(targetUser.getId()); - return Result.success(history); - } - - @PostMapping("/{id}/balance/change") - @RequirePermission("user:balance:manage") - @OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result changeUserBalance( - HttpServletRequest request, - @PathVariable Long id, - @RequestBody AdminUserBalanceChangeDTO balanceChangeDTO - ) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额"); - try { - UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO); - securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/{id}/vip/override") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result overrideUserVip( - HttpServletRequest request, - @PathVariable Long id, - @RequestBody AdminUserVipOverrideDTO vipOverrideDTO - ) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP"); - try { - UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO); - securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/{id}/vip/recalculate") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - /** - * Run business method `recalculateUserVip`. - * 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 - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); - try { - UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId()); - securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - @GetMapping("/info") /** * Load data by the supplied parameter. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java index 5d18605d..f7c3d46a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java @@ -10,21 +10,22 @@ import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelp import com.xiaowang.jayucloud.salon.core.modules.file.vo.ChunkUploadSessionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.InviteCodeVO; import com.xiaowang.jayucloud.salon.core.modules.integration.vo.WechatMiniLoginResultVO; import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils; @@ -60,6 +61,7 @@ import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniQuick import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniBindPhoneRequestDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; +import com.xiaowang.jayucloud.salon.core.modules.user.vo.ProfileImageUploadVO; /** * 系统用户信息表 Controller * 对应数据库表 t_user @@ -75,14 +77,11 @@ public class UserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; /** * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final PrimaryObjectStorageService primaryObjectStorageService; + private final ObjectStorageDirectUploadService objectStorageDirectUploadService; /** * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -124,6 +123,7 @@ public class UserController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final LegalAgreementService legalAgreementService; + private final AccountClosureService accountClosureService; /** * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -226,30 +226,6 @@ public class UserController { return Result.success(success); } - @GetMapping("/asset/me") - /** - * 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 result consumed by the caller or returned to the frontend - */ - public Result getMyAsset(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.getUserAsset(userId)); - } - - @GetMapping("/balance/history/me") - /** - * 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> result consumed by the caller or returned to the frontend - */ - public Result> getMyBalanceHistory(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.listBalanceHistory(userId)); - } - /** * 根据ID查询用户 * @@ -343,10 +319,7 @@ public class UserController { */ public Result checkAccountAvailability(@PathVariable String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); + UserDO userDO = findUserByAccount(normalizedAccount); boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); String message = available ? "账号可用" : "账号已被注册"; return Result.success(new AvailabilityVO(available, message)); @@ -361,12 +334,7 @@ public class UserController { */ public Result checkLoginAccountAvailability(@PathVariable String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(normalizedAccount); boolean exists = userDO != null; String nickname = exists ? userDO.getNickname() : null; String message = exists @@ -405,11 +373,14 @@ public class UserController { * @return Result result consumed by the caller or returned to the frontend */ public Result checkPhoneAvailability(@PathVariable String phone) { - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - ); + String normalizedPhone = phone == null ? "" : phone.trim(); + UserDO userDO = userMapper.selectOne(com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone)) + .eq(UserDO::getIsDelete, 0)); + if (userDO == null) { + Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone); + userDO = legacyId == null ? null : userMapper.selectById(legacyId); + } boolean available = userDO == null; String message = available ? "手机号可用" : "该手机号已被注册"; return Result.success(new AvailabilityVO(available, message)); @@ -473,13 +444,18 @@ public class UserController { * @param requestDTO parameter `requestDTO` supplied by the caller * @return Result result consumed by the caller or returned to the frontend */ - public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { - return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); + public Result wechatMiniAutoLogin(HttpServletRequest request, + @Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.autoLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_AUTO_LOGIN", request); + return Result.success(result); } @PostMapping("/wechat-mini/status") @OperationGuard(action = "wechat-mini-status", ttlSeconds = 2, message = "状态检测中,请稍后重试") public Result wechatMiniStatus(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + legalAgreementService.requireAccepted(requestDTO); return Result.success(wechatMiniAuthService.status(requestDTO)); } @@ -553,12 +529,7 @@ public class UserController { legalAgreementService.requireAccepted(registerRequestDTO); try { boolean success = userService.register(registerRequestDTO); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())); if (userDO != null) { legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request); securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request); @@ -616,6 +587,30 @@ public class UserController { return Result.success(true); } + @PostMapping("/send-current-password-code") + @OperationGuard(action = "send-current-password-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作") + public Result sendCurrentPasswordVerificationCode(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + throw new RuntimeException("请登录后操作"); + } + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) + || (user.getStatus() != null && !Integer.valueOf(1).equals(user.getStatus())) + || !org.springframework.util.StringUtils.hasText(user.getPhone()) + || !Integer.valueOf(1).equals(user.getPhoneVerified())) { + throw new RuntimeException("当前账号未绑定已验证手机号"); + } + + String phone = user.getPhone(); + requestThrottleService.checkSendCode(request, phone); + if (!verificationCodeService.canResend(phone)) { + throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); + } + verificationCodeService.sendVerificationCode(phone, "USER_CHANGE_PASSWORD_SMS_CODE"); + return Result.success(true); + } + /** * 通过手机号验证码重置密码 * @@ -682,8 +677,7 @@ public class UserController { */ @GetMapping("/info") public Result getCurrentUserInfo(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - UserVO userVO = userService.getUserById(userId); + UserVO userVO = userService.getCurrentUserInfo(); return Result.success(userVO); } @@ -715,6 +709,20 @@ public class UserController { return Result.success(success); } + @PostMapping("/unbind-phone") + @OperationGuard(action = "user-unbind-phone", ttlSeconds = 10, message = "手机号解绑处理中,请勿重复提交") + public Result unbindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.unbindPhone(userId, requestDTO == null ? null : requestDTO.getVerificationCode())); + } + + @PostMapping("/unbind-phone/send-code") + @OperationGuard(action = "user-unbind-phone-send-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作") + public Result sendUnbindPhoneCode(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.sendUnbindPhoneCode(userId)); + } + @PostMapping("/wechat-mini/bind-phone") @OperationGuard(action = "wechat-mini-bind-phone", ttlSeconds = 10, message = "手机号绑定处理中,请勿重复提交") public Result bindWechatMiniPhone(HttpServletRequest request, @@ -776,14 +784,12 @@ public class UserController { try (ChunkUploadService.PreparedUploadFile preparedUploadFile = chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId()); FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { - String originalFilename = preparedUploadFile.getFileName(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - - String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); - userService.updateUserAvatar(userId, avatarUrl); + ObjectStorageFileVO file = objectStorageDirectUploadService.uploadUserProfileImage( + preparedUploadFile.getFileName(), inputStream, preparedUploadFile.getFileSize(), + preparedUploadFile.getContentType(), userId); + userService.updateUserAvatar(userId, file.getObjectName()); chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); - return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); + return Result.success(objectStorageUrlSupport.getSignedUrlOrThrow(file, 60)); } catch (Exception e) { e.printStackTrace(); return Result.error("头像上传失败: " + e.getMessage()); @@ -814,14 +820,9 @@ public class UserController { public Result uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) { try { Long userId = (Long) request.getAttribute("userId"); - String originalFilename = file.getOriginalFilename(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - - String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName); - userService.updateUserAvatar(userId, avatarUrl); - - return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); + ObjectStorageFileVO uploaded = objectStorageDirectUploadService.uploadUserProfileImage(file, userId); + userService.updateUserAvatar(userId, uploaded.getObjectName()); + return Result.success(objectStorageUrlSupport.getSignedUrlOrThrow(uploaded, 60)); } catch (Exception e) { e.printStackTrace(); return Result.error("头像上传失败: " + e.getMessage()); @@ -858,20 +859,16 @@ public class UserController { @PostMapping("/upload-profile-image/complete") @OperationGuard(action = "user-profile-image-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + public Result completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); try (ChunkUploadService.PreparedUploadFile preparedUploadFile = chunkUploadService.prepareUserProfileImageFile(userId, requestDTO.getUploadId()); FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { - String originalFilename = preparedUploadFile.getFileName(); - String fileExtension = ""; - if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { - fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - } - String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + ObjectStorageFileVO file = objectStorageDirectUploadService.uploadUserProfileImage( + preparedUploadFile.getFileName(), inputStream, preparedUploadFile.getFileSize(), + preparedUploadFile.getContentType(), userId); chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId()); - return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + return Result.success(toProfileImageUploadVO(file)); } catch (Exception e) { e.printStackTrace(); return Result.error("资料图片上传失败: " + e.getMessage()); @@ -888,26 +885,27 @@ public class UserController { @PostMapping("/upload-profile-image") @OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + public Result uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { try { if (file == null || file.isEmpty()) { return Result.error("请选择要上传的图片"); } Long userId = (Long) request.getAttribute("userId"); - String originalFilename = file.getOriginalFilename(); - String fileExtension = ""; - if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { - fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - } - String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String imageUrl = primaryObjectStorageService.uploadFile(file, objectName); - return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + ObjectStorageFileVO uploaded = objectStorageDirectUploadService.uploadUserProfileImage(file, userId); + return Result.success(toProfileImageUploadVO(uploaded)); } catch (Exception e) { e.printStackTrace(); return Result.error("资料图片上传失败: " + e.getMessage()); } } + private ProfileImageUploadVO toProfileImageUploadVO(ObjectStorageFileVO file) { + ProfileImageUploadVO result = new ProfileImageUploadVO(); + result.setFileId(file.getId()); + result.setFileUrl(objectStorageUrlSupport.getSignedUrlOrThrow(file, 60)); + return result; + } + /** * 重置用户密码。 */ @@ -981,8 +979,8 @@ public class UserController { return Result.error("管理员账号无法注销"); } - boolean success = userService.deleteUser(userId); - return Result.success(success); + accountClosureService.request(userId); + return Result.success(true); } /** @@ -1029,6 +1027,22 @@ public class UserController { return sanitized; } + private UserDO findUserByAccount(String account) { + String normalized = account == null ? "" : account.trim(); + boolean phoneAccount = PhoneCrypto.current().isMobilePhone(normalized); + com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper query = + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + .last("limit 1"); + query.eq(UserDO::getAccountHash, PhoneCrypto.current().index(normalized)); + UserDO user = userMapper.selectOne(query); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByAccount(normalized); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; + } + @Data /** * Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java index adfb021c..be38754f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java @@ -48,6 +48,9 @@ public class UserDTO { */ private String avatar; + /** 当前用户本人上传的头像文件 ID。 */ + private Long avatarFileId; + /** * 用户签名 */ @@ -88,6 +91,9 @@ public class UserDTO { */ private String wechatId; + /** 美甲师在规划页展示的专属颜色(#RRGGBB)。 */ + private String color; + /** * 微信二维码 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java index 8e7b2bb8..e1205a2a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java @@ -59,13 +59,6 @@ public class UserAgreementConsentDO extends BaseEntity { */ private String ipAddress; - @TableField("device_id") - /** - * Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - @TableField("consent_time") /** * Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java index 48845495..d00a31a0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java @@ -5,6 +5,9 @@ import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler; +import com.xiaowang.jayucloud.salon.core.support.privacy.AccountPhoneTypeHandler; import lombok.Getter; import lombok.Setter; import lombok.EqualsAndHashCode; @@ -22,7 +25,7 @@ import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; @Getter @Setter @EqualsAndHashCode(callSuper = true) -@TableName("t_user") +@TableName(value = "t_user", autoResultMap = true) public class UserDO extends BaseEntity { /** @@ -46,21 +49,34 @@ public class UserDO extends BaseEntity { /** * 用户账号(登录用) */ - @TableField("account") + @TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class) private String account; + @TableField(value = "account_hash", fill = FieldFill.INSERT_UPDATE) + private String accountHash; + /** * 手机号 */ - @TableField("phone") + @TableField(value = "phone", typeHandler = PhoneEncryptionTypeHandler.class) private String phone; + @TableField(value = "phone_hash", fill = FieldFill.INSERT_UPDATE) + private String phoneHash; + /** * 联系电话 */ - @TableField("contact_phone") + @TableField(value = "contact_phone", typeHandler = PhoneEncryptionTypeHandler.class) private String contactPhone; + @TableField(value = "contact_phone_hash", fill = FieldFill.INSERT_UPDATE) + private String contactPhoneHash; + + /** 客户姓名、微信号和手机号的组合HMAC,用于原子去重。 */ + @TableField("customer_identity_hash") + private String customerIdentityHash; + /** * 生日 */ @@ -115,6 +131,9 @@ public class UserDO extends BaseEntity { @TableField("signature") private String signature; + @TableField("profile_moderation_status") + private String profileModerationStatus; + /** * 用户等级 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java index 66cf4f64..5b2f95fb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java @@ -2,6 +2,10 @@ package com.xiaowang.jayucloud.salon.core.modules.user.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; /** * 系统用户信息表 Mapper @@ -11,4 +15,19 @@ import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; * @date 2026-02-13 */ public interface UserMapper extends BaseMapper { + + @Select("SELECT COUNT(1) FROM t_user WHERE is_delete = 0 AND status = 1 AND profile_moderation_status = 'APPROVED' AND (avatar = (SELECT file_url FROM t_object_storage_file WHERE id = #{fileId}) OR avatar = (SELECT primary_url FROM t_object_storage_file WHERE id = #{fileId}) OR avatar = (SELECT object_name FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT file_url FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT primary_url FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT object_name FROM t_object_storage_file WHERE id = #{fileId}))") + Long countPublicImageReference(@Param("fileId") Long fileId); + + @Select("SELECT id FROM t_user WHERE account = #{account} AND account_hash IS NULL AND is_delete = 0 LIMIT 1") + Long findLegacyIdByAccount(@Param("account") String account); + + @Select("SELECT id FROM t_user WHERE phone = #{phone} AND phone_hash IS NULL AND is_delete = 0 AND type <> 0 LIMIT 1") + Long findLegacyIdByPhone(@Param("phone") String phone); + + @Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0 LIMIT 1") + Long findLegacyIdByContactPhone(@Param("phone") String phone); + + @Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0") + List findLegacyIdsByContactPhone(@Param("phone") String phone); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java index e517db55..2949fa53 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java @@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import java.util.List; @@ -34,6 +35,19 @@ public interface UserService extends IService { */ Long createUser(UserDTO userDTO); + Long createUnlinkedEmployee(UserDTO userDTO, Long shopId); + + Long createManagerCustomer(String nickname, String phone, Long shopId); + + Long createManagerCustomer(String nickname, String wechatId, String phone, Long shopId); + + List findCustomerMatches(String nickname, String phone, Long shopId); + + List findCustomerIdentityMatches(String nickname, String wechatId, String phone, Long shopId); + + PageResultVO listCustomersForAppointment(Integer page, Integer size, String keyword, Long shopId); + + /** * Update an existing record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -203,6 +217,15 @@ public interface UserService extends IService { */ LoginResponseVO refreshToken(String refreshToken); + /** + * Refresh a token for the platform administrator console. + * + *

This is deliberately separate from the user-facing refresh flow so + * the admin controller cannot accidentally change the rules used by the + * mini-program and front-end sessions.

+ */ + LoginResponseVO adminRefreshToken(String refreshToken); + /** * Run business method `logout`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -236,6 +259,10 @@ public interface UserService extends IService { */ boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO); + boolean unbindPhone(Long userId, String verificationCode); + + boolean sendUnbindPhoneCode(Long userId); + /** * Run business method `bindEmail`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index 7b65f92f..db5c9ab5 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -1,6 +1,7 @@ package com.xiaowang.jayucloud.salon.core.modules.user.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -25,6 +26,8 @@ import com.xiaowang.jayucloud.salon.core.modules.security.mapper.UserShopRoleMap import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; @@ -35,13 +38,20 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRe import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionCatalog; import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionPolicy; import com.xiaowang.jayucloud.salon.core.support.RequestShopContext; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.salon.core.modules.user.support.UserProfileFieldSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils; import com.xiaowang.jayucloud.salon.core.utils.JwtUtil; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO; @@ -49,6 +59,7 @@ import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopSimpleVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; @@ -61,6 +72,7 @@ import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.time.Duration; +import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -69,6 +81,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import com.xiaowang.jayucloud.salon.core.modules.auth.dto.BindEmailRequestDTO; @@ -133,6 +146,9 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserMapper userMapper; + private final PhoneCrypto phoneCrypto; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; private final ShopMapper shopMapper; /** * Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. @@ -142,6 +158,8 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ShopService shopService; + private final ShopBusinessExpiryService shopBusinessExpiryService; + private final ShopBusinessScheduleService shopBusinessScheduleService; /** * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -182,6 +200,7 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ObjectStorageFileService objectStorageFileService; /** * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -356,13 +375,45 @@ public class UserServiceImpl extends ServiceImpl implements @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserDTO userDTO) { + return createUserInternal(userDTO); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Long createUnlinkedEmployee(UserDTO userDTO, Long shopId) { + if (userDTO == null || !Integer.valueOf(3).equals(userDTO.getType())) throw new IllegalArgumentException("仅支持新增美甲师"); + if (shopId == null || shopId <= 0) throw new IllegalArgumentException("门店不能为空"); + if (!StringUtils.hasText(userDTO.getNickname())) throw new IllegalArgumentException("美甲师姓名不能为空"); + String phone = validateUserPhone(userDTO.getPhone(), null, false); + UserDO userDO = new UserDO(); + userDO.setShopId(shopId); + userDO.setNickname(userDTO.getNickname().trim()); + userDO.setAccount(null); + userDO.setPassword(ENCODED_UNSET_PASSWORD); + userDO.setPhone(phone); + userDO.setContactPhone(StringUtils.hasText(userDTO.getContactPhone()) ? userDTO.getContactPhone().trim() : phone); + userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); + userDO.setType(3); + userDO.setStatus(1); + userDO.setIsDelete(0); + userDO.setProfileModerationStatus("PENDING"); + userDO.setAvatar(StringUtils.hasText(userDTO.getAvatar()) ? normalizeStoredAvatar(userDTO.getAvatar()) : DEFAULT_AVATAR_URL); + userMapper.insert(userDO); + assignDefaultPermissions(userDO.getId(), 3); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(shopId)); + NailArtistInfoDTO artist = new NailArtistInfoDTO(); + artist.setUserId(userDO.getId()); + artist.setIdentity(""); artist.setExperience(0); artist.setSkills(""); + artist.setRating(DEFAULT_NAIL_ARTIST_RATING); artist.setStatus(1); artist.setPortfolio(""); + artist.setColor(normalizeArtistColor(userDTO.getColor())); + nailArtistInfoService.saveOrUpdateNailArtistInfo(artist); + return userDO.getId(); + } + + private Long createUserInternal(UserDTO userDTO) { String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); // 检查账号是否已存在 - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) - .eq(UserDO::getIsDelete, 0) - ); + UserDO existingUser = findUserByAccount(validatedAccount); if (existingUser != null) { /** * Run business method `RuntimeException`. @@ -374,10 +425,14 @@ public class UserServiceImpl extends ServiceImpl implements List validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); Long validatedShopId = pickPrimaryShopId(validatedShopIds); - String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); Integer userType = userDTO.getType(); + String validatedPhone = Integer.valueOf(0).equals(userType) + ? validateCustomerPhone(userDTO.getPhone(), false) + : validateUserPhone(userDTO.getPhone(), null, true); String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); - UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); + if (Integer.valueOf(0).equals(userType)) { + ensureCustomerUnique(userDTO.getNickname(), validatedWechatId, validatedPhone); + } /** * Run business method `ensureShopBindingRequirement`. @@ -391,7 +446,8 @@ public class UserServiceImpl extends ServiceImpl implements // 创建用户实体并设置属性 UserDO userDO = new UserDO(); userDO.setShopId(validatedShopId); - userDO.setNickname(userDTO.getNickname()); + userDO.setNickname(Integer.valueOf(0).equals(userType) && userDTO.getNickname() != null + ? userDTO.getNickname().trim() : userDTO.getNickname()); userDO.setAccount(validatedAccount); String resolvedPassword = AdminDefaultPasswordSupport.resolveCreatePassword( userDTO.getPassword(), @@ -400,6 +456,9 @@ public class UserServiceImpl extends ServiceImpl implements validatePasswordStrength(resolvedPassword); userDO.setPassword(passwordEncoder.encode(resolvedPassword)); userDO.setPhone(validatedPhone); + if (Integer.valueOf(0).equals(userType)) { + userDO.setCustomerIdentityHash(customerIdentityHash(userDO.getNickname(), validatedWechatId, validatedPhone)); + } userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); userDO.setBirthday(userDTO.getBirthday()); userDO.setWechatId(validatedWechatId); @@ -410,6 +469,9 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setVipId(userDTO.getVipId()); userDO.setIsDelete(0); userDO.setStatus(1); + if (!Integer.valueOf(0).equals(userType)) { + userDO.setProfileModerationStatus("PENDING"); + } if (StringUtils.hasText(userDTO.getAvatar())) { userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } else { @@ -441,6 +503,20 @@ public class UserServiceImpl extends ServiceImpl implements throw e; } + if (!Integer.valueOf(0).equals(userType)) { + Map profile = new java.util.LinkedHashMap<>(); + profile.put("nickname", userDO.getNickname()); + profile.put("signature", userDO.getSignature()); + profile.put("avatar", userDO.getAvatar()); + profile.put("wechatQrCode", userDO.getWechatQrCode()); + List profileImages = new ArrayList<>(); + addImageFileId(profileImages, userDO.getAvatar()); + addImageFileId(profileImages, userDO.getWechatQrCode()); + contentModerationService.assessVersion("USER_PROFILE", userDO.getId(), userDO.getId(), + profile.values().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")), + serializeModerationPayload(profile), profileImages); + } + // 分配默认权限 assignDefaultPermissions(userDO.getId(), userDO.getType()); userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds); @@ -455,12 +531,159 @@ public class UserServiceImpl extends ServiceImpl implements nailArtistInfoDTO.setRating(DEFAULT_NAIL_ARTIST_RATING); // 默认评分为4.5 nailArtistInfoDTO.setStatus(1); // 默认状态为营业中 nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空 + nailArtistInfoDTO.setColor(normalizeArtistColor(userDTO.getColor())); nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); } return userDO.getId(); } + @Override + @Transactional(rollbackFor = Exception.class) + public Long createManagerCustomer(String nickname, String phone, Long shopId) { + return createManagerCustomer(nickname, null, phone, shopId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Long createManagerCustomer(String nickname, String wechatId, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) { + throw new RuntimeException("客户姓名不能为空"); + } + if (shopId == null || shopId <= 0) { + throw new RuntimeException("请先选择店铺后再新增客户"); + } + String normalizedPhone = phone == null || phone.trim().isEmpty() ? null : phone.trim(); + normalizedPhone = validateCustomerPhone(normalizedPhone, false); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + ensureCustomerUnique(nickname, normalizedWechatId, normalizedPhone); + UserDTO customer = new UserDTO(); + customer.setNickname(nickname.trim()); + customer.setWechatId(normalizedWechatId); + customer.setPhone(normalizedPhone); + customer.setContactPhone(normalizedPhone); + customer.setAccount("customer" + UUID.randomUUID().toString().replace("-", "")); + customer.setType(0); + customer.setShopId(shopId); + customer.setShopIds(List.of(shopId)); + customer.setLevel(VIP_LEVEL_NORMAL); + customer.setVipId(0L); + return createUserInternal(customer); + } + + @Override + public List findCustomerMatches(String nickname, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) { + return List.of(); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + String normalizedName = nickname.trim(); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + if (normalizedPhone != null) { + addPhoneMatch(wrapper, normalizedPhone); + } + if (shopId != null && shopId > 0) { + List shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (shopUserIds.isEmpty()) { + wrapper.eq(UserDO::getShopId, shopId); + } else { + wrapper.and(query -> query.eq(UserDO::getShopId, shopId) + .or().in(UserDO::getId, shopUserIds)); + } + } + return userMapper.selectList(wrapper).stream() + .filter(user -> java.util.Objects.equals(normalizedName, user.getNickname())) + .filter(user -> normalizedPhone == null || java.util.Objects.equals(normalizedPhone, decryptPhone(user.getPhone()))) + .map(user -> { + UserVO customer = new UserVO(); + customer.setId(user.getId()); + customer.setNickname(user.getNickname()); + customer.setAccount(phoneCrypto.mask(user.getAccount())); + customer.setPhone(phoneCrypto.mask(user.getPhone())); + customer.setContactPhone(phoneCrypto.mask(user.getContactPhone())); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + return customer; + }).collect(Collectors.toList()); + } + + @Override + public List findCustomerIdentityMatches(String nickname, String wechatId, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) return List.of(); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + applyCustomerShopScope(wrapper, shopId); + String normalizedName = nickname.trim(); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + return userMapper.selectList(wrapper).stream() + .filter(user -> Objects.equals(normalizedName, user.getNickname())) + .filter(user -> Objects.equals(normalizedWechatId, UserProfileFieldSupport.normalizeOptionalText(user.getWechatId()))) + .filter(user -> Objects.equals(normalizedPhone, resolveCustomerPhone(user))) + .map(user -> { + AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO(); + customer.setId(user.getId()); + customer.setName(user.getNickname()); + String plainPhone = resolveCustomerPhone(user); + customer.setPhone(phoneCrypto.mask(plainPhone)); + customer.setPhoneAvailable(StringUtils.hasText(plainPhone)); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + customer.setCreatedAt(user.getCreateTime()); + return customer; + }).collect(Collectors.toList()); + } + + @Override + public PageResultVO listCustomersForAppointment(Integer page, Integer size, String keyword, Long shopId) { + int safePage = page == null || page < 1 ? 1 : page; + int safeSize = size == null ? 30 : Math.max(1, Math.min(size, 100)); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0) + .orderByDesc(UserDO::getCreateTime); + applyCustomerShopScope(wrapper, shopId); + if (StringUtils.hasText(keyword)) { + String search = keyword.trim(); + wrapper.and(query -> { + query.like(UserDO::getNickname, search); + if (search.matches(PHONE_REGEX)) query.or(phoneQuery -> addPhoneMatch(phoneQuery, search)); + }); + } + Page users = userMapper.selectPage(new Page<>(safePage, safeSize), wrapper); + PageResultVO result = new PageResultVO<>(); + result.setList(users.getRecords().stream().map(user -> { + AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO(); + option.setId(user.getId()); + option.setName(user.getNickname()); + String plainPhone = resolveCustomerPhone(user); + option.setPhone(phoneCrypto.mask(plainPhone)); + option.setPhoneAvailable(StringUtils.hasText(plainPhone)); + option.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + option.setCreatedAt(user.getCreateTime()); + return option; + }).collect(Collectors.toList())); + result.setTotal(users.getTotal()); + result.setPage(safePage); + result.setSize(safeSize); + return result; + } + + private void applyCustomerShopScope(LambdaQueryWrapper wrapper, Long shopId) { + if (shopId == null || shopId <= 0) return; + List shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (shopUserIds.isEmpty()) wrapper.eq(UserDO::getShopId, shopId); + else wrapper.and(query -> query.eq(UserDO::getShopId, shopId).or().in(UserDO::getId, shopUserIds)); + } + + private String resolveCustomerPhone(UserDO customer) { + String contactPhone = decryptPhone(customer.getContactPhone()); + return StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(customer.getPhone()); + } + /** * 分配默认权限 * @param userId 用户ID @@ -519,15 +742,16 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null) { return false; } + String originalNickname = userDO.getNickname(); + String originalAvatar = userDO.getAvatar(); + String originalSignature = userDO.getSignature(); + String originalWechatQrCode = userDO.getWechatQrCode(); // 更新账号(如果提供且变更) String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount()); if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - ); + UserDO existingUser = findUserByAccount(normalizedAccount); + if (existingUser != null && Objects.equals(existingUser.getId(), id)) existingUser = null; if (existingUser != null) { /** * Run business method `RuntimeException`. @@ -544,14 +768,17 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setShopId(validateAndNormalizeShopId(userDTO.getShopId())); } if (userDTO.getNickname() != null) { - userDO.setNickname(userDTO.getNickname()); + userDO.setNickname(Integer.valueOf(0).equals(userDO.getType()) + ? userDTO.getNickname().trim() : userDTO.getNickname()); } if (userDTO.getPassword() != null) { validatePasswordStrength(userDTO.getPassword()); userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); } if (userDTO.getPhone() != null) { - userDO.setPhone(validateUserPhone(userDTO.getPhone(), id, true)); + userDO.setPhone(Integer.valueOf(0).equals(userDO.getType()) + ? validateCustomerPhone(userDTO.getPhone(), false) + : validateUserPhone(userDTO.getPhone(), id, true)); } if (userDTO.getContactPhone() != null) { userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); @@ -584,8 +811,44 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getVipId() != null) { userDO.setVipId(userDTO.getVipId()); } + boolean publicProfileChanged = !Objects.equals(originalNickname, userDO.getNickname()) + || !Objects.equals(originalAvatar, userDO.getAvatar()) + || !Objects.equals(originalSignature, userDO.getSignature()) + || !Objects.equals(originalWechatQrCode, userDO.getWechatQrCode()); + if (publicProfileChanged) { + Map profile = new java.util.LinkedHashMap<>(); + profile.put("nickname", userDO.getNickname()); + profile.put("signature", userDO.getSignature()); + profile.put("avatar", userDO.getAvatar()); + profile.put("wechatQrCode", userDO.getWechatQrCode()); + List profileImages = new ArrayList<>(); + if (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) { + addImageFileId(profileImages, userDO.getAvatar()); + } + if (userDTO.getWechatQrCode() != null) { + addImageFileId(profileImages, userDO.getWechatQrCode()); + } + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_PROFILE", id, id, + profile.values().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")), + serializeModerationPayload(profile), profileImages); + if (!moderationApproved(moderation)) { + userDO.setNickname(originalNickname); + userDO.setAvatar(originalAvatar); + userDO.setSignature(originalSignature); + userDO.setWechatQrCode(originalWechatQrCode); + } + } Integer targetUserType = userDO.getType(); - UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); + if (Integer.valueOf(0).equals(targetUserType)) { + String customerPhone = validateCustomerPhone(userDO.getPhone(), false); + ensureCustomerUnique(userDO.getNickname(), userDO.getWechatId(), customerPhone, id); + userDO.setCustomerIdentityHash(customerIdentityHash(userDO.getNickname(), userDO.getWechatId(), customerPhone)); + } else { + userDO.setCustomerIdentityHash(null); + if (StringUtils.hasText(userDO.getPhone()) && !isDeletedPlaceholderPhone(userDO.getPhone())) { + ensurePhoneNotUsed(userDO.getPhone(), id); + } + } List validatedShopIds = null; boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; if (shopBindingChanged) { @@ -650,7 +913,11 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getId, id) .eq(UserDO::getIsDelete, 0) .set(UserDO::getAccount, buildDeletedAccount(userDO)) - .set(UserDO::getPhone, buildDeletedPhone(userDO)) + .set(UserDO::getPhone, null) + .set(UserDO::getContactPhone, null) + .set(UserDO::getPhoneHash, null) + .set(UserDO::getContactPhoneHash, null) + .set(UserDO::getAccountHash, null) .set(UserDO::getStatus, 0) .set(UserDO::getIsDelete, 1) .set(UserDO::getUpdateTime, now) @@ -724,6 +991,7 @@ public class UserServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(UserDO.class) .eq(UserDO::getIsDelete, 0) .eq(UserDO::getType, type) + .eq(UserDO::getProfileModerationStatus, "APPROVED") ); return userDOs.stream() .map(this::convertToVO) @@ -738,11 +1006,7 @@ public class UserServiceImpl extends ServiceImpl implements @Override public UserVO getUserByAccount(String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - ); + UserDO userDO = findUserByAccount(normalizedAccount); if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { return null; } @@ -782,10 +1046,10 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userVO.setNickname(userDO.getNickname()); - userVO.setAccount(userDO.getAccount()); - userVO.setPhone(userDO.getPhone()); + userVO.setAccount(phoneCrypto.mask(userDO.getAccount())); + userVO.setPhone(phoneCrypto.mask(userDO.getPhone())); userVO.setPhoneVerified(userDO.getPhoneVerified()); - userVO.setContactPhone(userDO.getContactPhone()); + userVO.setContactPhone(phoneCrypto.mask(userDO.getContactPhone())); userVO.setBirthday(userDO.getBirthday()); userVO.setWechatId(userDO.getWechatId()); userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); @@ -859,12 +1123,7 @@ public class UserServiceImpl extends ServiceImpl implements } AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(normalizedAccount); if (userDO == null) { return buildLoginShopSelection(List.of(), false, "该账号不存在"); } @@ -909,12 +1168,7 @@ public class UserServiceImpl extends ServiceImpl implements return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺"); } - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByPhone(normalizedPhone); if (userDO == null) { return buildLoginShopSelection( userShopBindingSupport.listAllActiveShopOptions(), @@ -964,12 +1218,7 @@ public class UserServiceImpl extends ServiceImpl implements } AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(normalizedAccount); if (userDO == null) { return buildLoginShopSelection(List.of(), false, "该账号不存在"); } @@ -1012,10 +1261,7 @@ public class UserServiceImpl extends ServiceImpl implements */ public LoginResponseVO login(LoginRequestDTO loginRequestDTO) { String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); + UserDO userDO = findUserByAccount(normalizedAccount); /** * Run business method `assertLoginAccountAvailable`. @@ -1086,15 +1332,12 @@ public class UserServiceImpl extends ServiceImpl implements private LoginResponseVO phoneLoginByVerifiedPhone(String phone, Long shopId, boolean rememberMe) { String normalizedPhone = normalizeVerifiedPhone(phone); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) - .eq(UserDO::getIsDelete, 0) - ); + UserDO userDO = findUserByPhone(normalizedPhone); if (userDO == null) { return buildRegistrationRequiredResponse(normalizedPhone, null, "PHONE_NOT_REGISTERED"); } + assertWechatLinkedForStaffLogin(userDO); if (userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()).isEmpty()) { return buildRegistrationRequiredResponse(normalizedPhone, userDO, "NO_SHOP_BINDING"); } @@ -1147,12 +1390,7 @@ public class UserServiceImpl extends ServiceImpl implements * @return LoginResponseVO result consumed by the caller or returned to the frontend */ public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByPhone(phone); if (userDO == null) { if (shopId == null || shopId == 0) { @@ -1171,6 +1409,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return result consumed by the caller or returned to the frontend */ + assertWechatLinkedForStaffLogin(userDO); assertUserAvailable(userDO); clearLoginFailureCount(userDO.getAccount()); } @@ -1260,10 +1499,7 @@ public class UserServiceImpl extends ServiceImpl implements */ public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) { String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); + UserDO userDO = findUserByAccount(normalizedAccount); /** * Run business method `assertLoginAccountAvailable`. @@ -1273,6 +1509,10 @@ public class UserServiceImpl extends ServiceImpl implements */ assertLoginAccountAvailable(userDO); + if (!Integer.valueOf(4).equals(userDO.getType())) { + throw new RuntimeException("仅平台管理员可以登录后台管理系统"); + } + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { /** * Run business method `handleLoginPasswordFailure`. @@ -1283,17 +1523,6 @@ public class UserServiceImpl extends ServiceImpl implements handleLoginPasswordFailure(userDO); } - Integer userType = userDO.getType(); - if (userType == null || userType < 2) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号不是后台管理账号"); - } - - Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); clearLoginFailureCount(userDO.getAccount()); /** * Run business method `buildLoginResponse`. @@ -1303,7 +1532,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param false parameter `false` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + return buildLoginResponse(userDO, null, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); } @Override @@ -1469,10 +1698,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("验证码错误或已过期"); } - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) - ); + UserDO existingUser = findUserByAccount(validatedAccount); if (existingUser != null) { if (existingUser.getIsDelete() == 0) { @@ -1492,11 +1718,7 @@ public class UserServiceImpl extends ServiceImpl implements } } - UserDO existingPhoneUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, registerRequestDTO.getPhone()) - .eq(UserDO::getIsDelete, 0) - ); + UserDO existingPhoneUser = findUserByPhone(registerRequestDTO.getPhone()); if (existingPhoneUser != null) { /** @@ -1562,12 +1784,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("店铺名称不能为空"); } - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO existingUser = findUserByAccount(phone); if (existingUser != null) { throw new RuntimeException("该手机号已注册"); } @@ -1580,8 +1797,10 @@ public class UserServiceImpl extends ServiceImpl implements shop.setAuthorizationStartDate(LocalDateTime.now().minusDays(1).toLocalDate()); shop.setAuthorizationDays(0); shop.setAuthorizationExpireTime(LocalDateTime.now().minusSeconds(1)); + shop.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDate.now())); shop.setIsDelete(0); shopMapper.insert(shop); + shopBusinessScheduleService.initializeDefault(shop.getId(), shop.getBusinessHours()); UserDO manager = new UserDO(); manager.setShopId(shop.getId()); @@ -1613,6 +1832,15 @@ public class UserServiceImpl extends ServiceImpl implements * @return LoginResponseVO result consumed by the caller or returned to the frontend */ public LoginResponseVO refreshToken(String refreshToken) { + return refreshTokenInternal(refreshToken, false); + } + + @Override + public LoginResponseVO adminRefreshToken(String refreshToken) { + return refreshTokenInternal(refreshToken, true); + } + + private LoginResponseVO refreshTokenInternal(String refreshToken, boolean adminOnly) { if (!jwtUtil.validateToken(refreshToken)) { /** * Run business method `RuntimeException`. @@ -1635,7 +1863,7 @@ public class UserServiceImpl extends ServiceImpl implements Long userId = jwtUtil.getUserIdFromToken(refreshToken); String account = jwtUtil.getAccountFromToken(refreshToken); - Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); + Long currentShopId = adminOnly ? null : normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); String refreshJti = jwtUtil.getJtiFromToken(refreshToken); if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { @@ -1655,7 +1883,10 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ assertUserAvailable(userDO); - boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + if (adminOnly && !Integer.valueOf(4).equals(userDO.getType())) { + throw new RuntimeException("仅平台管理员可以刷新后台登录态"); + } + boolean adminLogin = adminOnly || (userDO.getType() != null && userDO.getType() >= 2); if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { /** * Run business method `RuntimeException`. @@ -1690,7 +1921,18 @@ public class UserServiceImpl extends ServiceImpl implements org.springframework.web.context.request.ServletRequestAttributes attributes = (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes(); Long userId = attributes == null ? null : (Long) attributes.getRequest().getAttribute("userId"); - return userId == null ? null : getUserById(userId); + if (userId == null) return null; + UserVO userInfo = getUserById(userId); + Long currentShopId = RequestShopContext.getCurrentShopId(); + Long expiryShopId = currentShopId == null && userInfo != null ? userInfo.getShopId() : currentShopId; + if (userInfo != null && expiryShopId != null) { + com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO expiry = + shopBusinessExpiryService.getExpiry(expiryShopId); + userInfo.setShopBusinessExpireTime(expiry.getBusinessExpireTime()); + userInfo.setShopBusinessExpired(expiry.getBusinessExpired()); + userInfo.setShopBusinessRemainingDays(expiry.getBusinessRemainingDays()); + } + return userInfo; } @Override @@ -1711,17 +1953,50 @@ public class UserServiceImpl extends ServiceImpl implements */ assertUserAvailable(userDO); - if (userDTO.getNickname() != null) { + String avatarForUpdate = userDTO.getAvatarFileId() == null + ? userDTO.getAvatar() + : resolveOwnedProfileFileReference(userId, userDTO.getAvatarFileId()); + if (avatarForUpdate != null && !avatarForUpdate.isEmpty()) { + avatarForUpdate = normalizeOwnedProfileImage(userId, avatarForUpdate, userDO.getAvatar()); + } + String qrForUpdate = userDTO.getWechatQrCode(); + if (qrForUpdate != null && !qrForUpdate.isEmpty()) { + qrForUpdate = normalizeOwnedProfileImage(userId, qrForUpdate, userDO.getWechatQrCode()); + } + + boolean profileApproved = true; + if (userDTO.getNickname() != null || userDTO.getSignature() != null + || (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) || userDTO.getAvatarFileId() != null + || userDTO.getWechatQrCode() != null) { + Map content = new java.util.LinkedHashMap<>(); + content.put("nickname", userDTO.getNickname() == null ? userDO.getNickname() : userDTO.getNickname()); + content.put("signature", userDTO.getSignature() == null ? userDO.getSignature() : userDTO.getSignature()); + content.put("avatar", avatarForUpdate == null + ? userDO.getAvatar() + : (avatarForUpdate.isEmpty() ? null : avatarForUpdate)); + content.put("wechatQrCode", userDTO.getWechatQrCode() == null + ? userDO.getWechatQrCode() : (qrForUpdate.isEmpty() ? null : qrForUpdate)); + String serialized = serializeModerationPayload(content); + List profileImages = new ArrayList<>(); + addImageFileId(profileImages, content.get("avatar")); + addImageFileId(profileImages, content.get("wechatQrCode")); + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_PROFILE", userId, userId, + String.join("\n", content.values().stream().filter(Objects::nonNull).toList()), serialized, profileImages); + profileApproved = moderation != null && "APPROVED".equals(moderation.getStatus()); + if (profileApproved) userDO = userMapper.selectById(userId); + } + + if (profileApproved && userDTO.getNickname() != null) { userDO.setNickname(userDTO.getNickname()); } - if (userDTO.getAvatar() != null) { - if (userDTO.getAvatar().isEmpty()) { + if (profileApproved && (userDTO.getAvatar() != null || userDTO.getAvatarFileId() != null)) { + if (avatarForUpdate == null || avatarForUpdate.isEmpty()) { userDO.setAvatar(null); } else { - userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + userDO.setAvatar(avatarForUpdate); } } - if (userDTO.getSignature() != null) { + if (profileApproved && userDTO.getSignature() != null) { userDO.setSignature(userDTO.getSignature()); } if (userDTO.getContactPhone() != null) { @@ -1733,10 +2008,9 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getWechatId() != null) { userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); } - if (userDTO.getWechatQrCode() != null) { - userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + if (profileApproved && userDTO.getWechatQrCode() != null) { + userDO.setWechatQrCode(qrForUpdate.isEmpty() ? null : qrForUpdate); } - UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); userDO.setUpdateTime(LocalDateTime.now()); boolean updated = userMapper.updateById(userDO) > 0; @@ -1919,10 +2193,15 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.eq(UserDO::getIsDelete, 0); // 不再过滤普通用户,由前端根据用户角色进行过滤 if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(UserDO::getAccount, keyword) - .or().like(UserDO::getNickname, keyword) - .or().like(UserDO::getPhone, keyword) - .or().like(UserDO::getContactPhone, keyword)); + wrapper.and(w -> { + w.like(UserDO::getAccount, keyword).or().like(UserDO::getNickname, keyword); + if (phoneCrypto.isMobilePhone(keyword.trim())) { + String hash = phoneCrypto.index(keyword.trim()); + w.or().eq(UserDO::getAccountHash, hash) + .or().eq(UserDO::getPhoneHash, hash) + .or().eq(UserDO::getContactPhoneHash, hash); + } + }); } if (shopId != null && shopId > 0) { List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); @@ -1964,10 +2243,10 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo)); } if (Boolean.TRUE.equals(hasPhone)) { - wrapper.isNotNull(UserDO::getPhone); + wrapper.and(w -> w.isNotNull(UserDO::getPhone).or().isNotNull(UserDO::getPhoneHash)); } if (Boolean.FALSE.equals(hasPhone)) { - wrapper.isNull(UserDO::getPhone); + wrapper.isNull(UserDO::getPhone).isNull(UserDO::getPhoneHash); } wrapper.orderByDesc(UserDO::getCreateTime); @@ -2183,9 +2462,80 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ assertUserAvailable(userDO); - userDO.setAvatar(avatarUrl); - userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; + String storedAvatar = normalizeOwnedProfileImage(userId, avatarUrl, userDO.getAvatar()); + List imageIds = new ArrayList<>(); + addImageFileId(imageIds, storedAvatar); + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_AVATAR", userId, userId, + "", serializeModerationPayload(java.util.Map.of("avatar", storedAvatar)), imageIds); + return moderation != null && ("APPROVED".equals(moderation.getStatus()) || "PENDING".equals(moderation.getStatus()) || "RETRY".equals(moderation.getStatus())); + } + + private void addImageFileId(List imageIds, String reference) { + if (!StringUtils.hasText(reference)) return; + if (DEFAULT_AVATAR_URL.equals(reference)) return; + Long fileId = objectStorageFileService.findFileIdByReference(reference); + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("个人资料图片必须引用已上传文件"); + } + if (!imageIds.contains(fileId)) imageIds.add(fileId); + } + + private String resolveOwnedProfileFileReference(Long userId, Long fileId) { + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("个人资料图片文件无效"); + } + ObjectStorageFileVO file = objectStorageFileService.getObjectStorageFileById(fileId); + String objectName = file == null ? null : file.getObjectName(); + String prefix = "profile/" + userId + "/"; + if (file == null || !Integer.valueOf(1).equals(file.getStatus()) || !StringUtils.hasText(objectName) + || !objectName.startsWith(prefix)) { + throw new IllegalArgumentException("个人资料图片必须引用本人上传的文件"); + } + return objectName; + } + + private String normalizeOwnedProfileImage(Long userId, String reference, String existingReference) { + if (!StringUtils.hasText(reference) || DEFAULT_AVATAR_URL.equals(reference)) return reference; + Long fileId; + if (reference.trim().matches("\\d+")) { + try { + fileId = Long.parseLong(reference.trim()); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("个人资料图片文件无效"); + } + } else { + fileId = objectStorageFileService.findFileIdByReference(reference); + } + if (fileId == null || fileId <= 0) throw new IllegalArgumentException("个人资料图片必须引用已上传文件"); + ObjectStorageFileVO file = objectStorageFileService.getObjectStorageFileById(fileId); + if (file == null || !Integer.valueOf(1).equals(file.getStatus()) || !StringUtils.hasText(file.getObjectName())) { + throw new IllegalArgumentException("个人资料图片不存在或不可用"); + } + String normalized = normalizeStoredProfileImage(file.getObjectName()); + boolean unchanged = Objects.equals(reference, existingReference) || Objects.equals(normalized, existingReference); + if (!unchanged && !file.getObjectName().startsWith("profile/" + userId + "/")) { + throw new IllegalArgumentException("个人资料图片必须引用本人上传的文件"); + } + return normalized; + } + + private String serializeModerationPayload(Object payload) { + try { + return objectMapper.writeValueAsString(payload); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("无法保存待复核内容", exception); + } + } + + private void requireApprovedContent(ContentModerationResultVO result) { + if (result == null || !"APPROVED".equals(result.getStatus())) { + String reason = result == null ? null : result.getReason(); + throw new IllegalStateException(StringUtils.hasText(reason) ? reason : "内容正在审核中,暂未更新"); + } + } + + private boolean moderationApproved(ContentModerationResultVO result) { + return result != null && "APPROVED".equals(result.getStatus()); } @Override @@ -2234,8 +2584,7 @@ public class UserServiceImpl extends ServiceImpl implements * @return boolean result consumed by the caller or returned to the frontend */ public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { - String oldPhone = updatePhoneDTO.getOldPhone(); - String newPhone = updatePhoneDTO.getNewPhone(); + String newPhone = validateUserPhone(updatePhoneDTO.getNewPhone(), userId, true); String verificationCode = updatePhoneDTO.getVerificationCode(); UserDO userDO = userMapper.selectById(userId); @@ -2254,15 +2603,6 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("当前账号未绑定手机号"); } - if (!userDO.getPhone().equals(oldPhone)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("原手机号不匹配"); - } - /** * Run business method `validateVerificationCode`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -2271,14 +2611,6 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ validateVerificationCode(newPhone, verificationCode); - /** - * Run business method `ensurePhoneNotUsed`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param newPhone parameter `newPhone` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePhoneNotUsed(newPhone, userId); userDO.setPhone(newPhone); userDO.setPhoneVerified(1); @@ -2286,6 +2618,37 @@ public class UserServiceImpl extends ServiceImpl implements return userMapper.updateById(userDO) > 0; } + @Override + @Transactional(rollbackFor = Exception.class) + public boolean unbindPhone(Long userId, String verificationCode) { + UserDO userDO = userMapper.selectById(userId); + assertUserAvailable(userDO); + String phone = userDO.getPhone(); + if (!StringUtils.hasText(phone) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) { + throw new RuntimeException("当前账号未绑定已验证手机号"); + } + validateVerificationCode(phone, verificationCode); + userDO.setPhone(null); + userDO.setPhoneHash(null); + userDO.setPhoneVerified(0); + userDO.setUpdateTime(LocalDateTime.now()); + return userMapper.updateById(userDO) > 0; + } + + @Override + public boolean sendUnbindPhoneCode(Long userId) { + UserDO userDO = userMapper.selectById(userId); + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone()) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) { + throw new RuntimeException("当前账号未绑定已验证手机号"); + } + if (!verificationCodeService.canResend(userDO.getPhone())) { + throw new RuntimeException("验证码发送过于频繁,请稍后重试"); + } + verificationCodeService.sendVerificationCode(userDO.getPhone(), "USER_UNBIND_PHONE"); + return true; + } + @Override /** * Run business method `resetPasswordByPhone`. @@ -2308,10 +2671,7 @@ public class UserServiceImpl extends ServiceImpl implements validateVerificationCode(phone, verificationCode); // 根据手机号查找用户 - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); - wrapper.eq(UserDO::getPhone, phone); - wrapper.eq(UserDO::getIsDelete, 0); - UserDO userDO = userMapper.selectOne(wrapper); + UserDO userDO = findUserByPhone(phone); if (userDO == null) { /** @@ -2321,6 +2681,7 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("未绑定手机号,请联系店员"); } + assertWechatLinkedForStaffLogin(userDO); if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { /** * Run business method `RuntimeException`. @@ -2449,6 +2810,13 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return private void result consumed by the caller or returned to the frontend */ + static void assertWechatLinkedForStaffLogin(UserDO userDO) { + if (userDO != null && Integer.valueOf(3).equals(userDO.getType()) + && !StringUtils.hasText(userDO.getAccount())) { + throw new RuntimeException("美甲师档案不能通过手机号登录,请使用关联微信身份或联系店长完成关联"); + } + } + private void handleLoginPasswordFailure(UserDO userDO) { if (userDO == null || !StringUtils.hasText(userDO.getAccount())) { /** @@ -2846,7 +3214,8 @@ public class UserServiceImpl extends ServiceImpl implements LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo(); userInfo.setId(userDO.getId()); - userInfo.setAccount(userDO.getAccount()); + // 登录响应只用于展示账号标识,手机号账号不得以明文返回。 + userInfo.setAccount(phoneCrypto.mask(userDO.getAccount())); userInfo.setNickname(userDO.getNickname()); userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); userInfo.setType(userDO.getType()); @@ -2855,6 +3224,13 @@ public class UserServiceImpl extends ServiceImpl implements ShopVO currentShop = normalizedCurrentShopId == null ? null : shopService.getShopById(normalizedCurrentShopId); userInfo.setShopAuthorizationExpireTime(currentShop == null ? null : currentShop.getAuthorizationExpireTime()); userInfo.setShopAuthorizationExpired(currentShop != null && Boolean.TRUE.equals(currentShop.getAuthorizationExpired())); + if (currentShop != null) { + com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO businessExpiry = + shopBusinessExpiryService.getExpiry(currentShop.getId()); + userInfo.setShopBusinessExpireTime(businessExpiry.getBusinessExpireTime()); + userInfo.setShopBusinessExpired(businessExpiry.getBusinessExpired()); + userInfo.setShopBusinessRemainingDays(businessExpiry.getBusinessRemainingDays()); + } userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userInfo.setCreateTime(userDO.getCreateTime()); @@ -3033,12 +3409,18 @@ public class UserServiceImpl extends ServiceImpl implements */ private void ensurePhoneNotUsed(String phone, Long currentUserId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) + .ne(UserDO::getType, 0) .eq(UserDO::getIsDelete, 0); if (currentUserId != null) { wrapper.ne(UserDO::getId, currentUserId); } - if (userMapper.selectOne(wrapper) != null) { + UserDO existing = userMapper.selectOne(wrapper); + if (existing == null) { + Long legacyId = userMapper.findLegacyIdByPhone(phone); + existing = legacyId == null || Objects.equals(legacyId, currentUserId) ? null : userMapper.selectById(legacyId); + } + if (existing != null) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -3047,6 +3429,119 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("手机号已被使用"); } } + + private void ensureCustomerUnique(String nickname, String wechatId, String phone) { + ensureCustomerUnique(nickname, wechatId, phone, null); + } + + private void ensureCustomerUnique(String nickname, String wechatId, String phone, Long ignoredCustomerId) { + if (!StringUtils.hasText(nickname)) { + throw new RuntimeException("客户姓名不能为空"); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + boolean duplicate = userMapper.selectList(wrapper).stream().anyMatch(existing -> + !java.util.Objects.equals(ignoredCustomerId, existing.getId()) + && java.util.Objects.equals(normalizedWechatId, UserProfileFieldSupport.normalizeOptionalText(existing.getWechatId())) + && java.util.Objects.equals(normalizedPhone, decryptPhone(existing.getPhone()))); + if (duplicate) { + throw new RuntimeException("客户已存在,请选择已有客户"); + } + } + + private String decryptPhone(String value) { + return StringUtils.hasText(value) ? phoneCrypto.decrypt(value).trim() : null; + } + + private String validateCustomerPhone(String phone, boolean required) { + String normalizedPhone = phone == null ? null : phone.trim(); + if (!StringUtils.hasText(normalizedPhone)) { + if (required) throw new RuntimeException("手机号不能为空"); + return null; + } + if (!normalizedPhone.matches(PHONE_REGEX)) { + throw new RuntimeException("手机号格式不正确"); + } + return normalizedPhone; + } + + private String customerIdentityHash(String nickname, String wechatId, String phone) { + String normalizedName = StringUtils.hasText(nickname) ? nickname.trim() : ""; + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + return phoneCrypto.index(identityPart(normalizedName) + + identityPart(normalizedWechatId == null ? "" : normalizedWechatId) + + identityPart(normalizedPhone == null ? "" : normalizedPhone)); + } + + private String identityPart(String value) { + return value.length() + ":" + value; + } + + private String normalizeArtistColor(String color) { + if (!StringUtils.hasText(color)) { + return null; + } + String value = color.trim().toUpperCase(java.util.Locale.ROOT); + if (!value.matches("#[0-9A-F]{6}")) { + throw new RuntimeException("美甲师专属颜色格式不正确"); + } + return value; + } + + private void addPhoneMatch(LambdaQueryWrapper wrapper, String phone) { + String hash = phoneCrypto.index(phone.trim()); + List legacyIds = new ArrayList<>(); + QueryWrapper legacyPhoneQuery = new QueryWrapper<>(); + legacyPhoneQuery.select("id") + .eq("phone", phone.trim()) + .isNull("phone_hash") + .eq("type", 0) + .eq("is_delete", 0); + for (UserDO legacyCustomer : userMapper.selectList(legacyPhoneQuery)) { + if (legacyCustomer.getId() != null && !legacyIds.contains(legacyCustomer.getId())) { + legacyIds.add(legacyCustomer.getId()); + } + } + for (Long legacyContactId : userMapper.findLegacyIdsByContactPhone(phone.trim())) { + if (!legacyIds.contains(legacyContactId)) legacyIds.add(legacyContactId); + } + wrapper.and(query -> { + query.eq(UserDO::getPhoneHash, hash).or().eq(UserDO::getContactPhoneHash, hash); + if (!legacyIds.isEmpty()) query.or().in(UserDO::getId, legacyIds); + }); + } + + private UserDO findUserByAccount(String account) { + if (!StringUtils.hasText(account)) return null; + LambdaQueryWrapper query = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getIsDelete, 0); + query.eq(UserDO::getAccountHash, phoneCrypto.index(account.trim())); + UserDO user = userMapper.selectOne(query.last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByAccount(account.trim()); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; + } + + private UserDO findUserByPhone(String phone) { + if (!StringUtils.hasText(phone)) return null; + String normalized = phone.trim(); + UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhoneHash, phoneCrypto.index(normalized)) + .ne(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0) + .last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByPhone(normalized); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; + } /** * Run business method `buildRelationVO`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java index 63180c62..01a3db79 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java @@ -13,11 +13,4 @@ public final class UserProfileFieldSupport { } return value.trim(); } - - public static void requireWechatIdForServiceUser(Integer userType, String wechatId) { - if ((Integer.valueOf(2).equals(userType) || Integer.valueOf(3).equals(userType)) - && !StringUtils.hasText(wechatId)) { - throw new IllegalArgumentException("店长和美甲师的微信号不能为空"); - } - } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/ProfileImageUploadVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/ProfileImageUploadVO.java new file mode 100644 index 00000000..0e8bb136 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/ProfileImageUploadVO.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.vo; + +import lombok.Data; + +@Data +public class ProfileImageUploadVO { + private Long fileId; + private String fileUrl; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java index 0a6628f7..c6b61a6f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java @@ -35,6 +35,10 @@ public class UserVO { */ private String shopName; + private LocalDateTime shopBusinessExpireTime; + private Boolean shopBusinessExpired; + private Integer shopBusinessRemainingDays; + /** * 绑定店铺ID列表 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/AccountPhoneTypeHandler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/AccountPhoneTypeHandler.java new file mode 100644 index 00000000..47978d51 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/AccountPhoneTypeHandler.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class AccountPhoneTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encryptAccount(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(cs.getString(columnIndex)); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneBackfillReport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneBackfillReport.java new file mode 100644 index 00000000..bc9b731b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneBackfillReport.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import lombok.Data; + +import java.util.List; + +@Data +public class PhoneBackfillReport { + private boolean dryRun; + private int userRowsToUpdate; + private int userRowsUpdated; + private int orderRowsToUpdate; + private int orderRowsUpdated; + private int accountConflictRows; + private int phoneConflictRows; + private List conflictingUserIds; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneCrypto.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneCrypto.java new file mode 100644 index 00000000..78150569 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneCrypto.java @@ -0,0 +1,124 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import com.xiaowang.jayucloud.salon.core.config.PhoneCryptoProperties; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PostConstruct; +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Base64; + +@Component +public class PhoneCrypto { + private static final String CIPHER_PREFIX = "enc:v1:"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static volatile PhoneCrypto current; + + private final PhoneCryptoProperties properties; + private byte[] encryptionKey; + private byte[] indexKey; + + public PhoneCrypto(PhoneCryptoProperties properties) { + this.properties = properties; + } + + @PostConstruct + public void initialize() { + encryptionKey = decodeKey(properties.getEncryptionKey(), "phone-crypto.encryption-key"); + indexKey = decodeKey(properties.getIndexKey(), "phone-crypto.index-key"); + if (encryptionKey.length != 32 || indexKey.length < 32) { + throw new IllegalStateException("手机号加密与索引密钥必须分别配置为至少32字节的Base64密钥"); + } + if (java.util.Arrays.equals(encryptionKey, indexKey)) { + throw new IllegalStateException("手机号加密密钥与索引密钥必须独立"); + } + current = this; + } + + public String encrypt(String value) { + if (!StringUtils.hasText(value) || value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] iv = new byte[12]; + RANDOM.nextBytes(iv); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); + byte[] payload = new byte[iv.length + encrypted.length]; + System.arraycopy(iv, 0, payload, 0, iv.length); + System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length); + return CIPHER_PREFIX + Base64.getEncoder().encodeToString(payload); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("手机号加密失败", exception); + } + } + + public String encryptAccount(String value) { + return isMobilePhone(value) ? encrypt(value) : value; + } + + public String decryptAccount(String value) { + return value != null && value.startsWith(CIPHER_PREFIX) ? decrypt(value) : value; + } + + public boolean isMobilePhone(String value) { + return value != null && value.trim().matches("1[3-9]\\d{9}"); + } + + public String decrypt(String value) { + if (!StringUtils.hasText(value) || !value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] payload = Base64.getDecoder().decode(value.substring(CIPHER_PREFIX.length())); + if (payload.length < 29) throw new IllegalArgumentException("手机号密文格式无效"); + byte[] iv = java.util.Arrays.copyOfRange(payload, 0, 12); + byte[] encrypted = java.util.Arrays.copyOfRange(payload, 12, payload.length); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (GeneralSecurityException | IllegalArgumentException exception) { + throw new IllegalStateException("手机号解密失败,请检查密钥或数据完整性", exception); + } + } + + public boolean isEncrypted(String value) { + return value != null && value.startsWith(CIPHER_PREFIX); + } + + public String mask(String value) { + if (!StringUtils.hasText(value)) return value; + String plain = isEncrypted(value) ? decrypt(value) : value; + return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain; + } + + public String index(String value) { + if (!StringUtils.hasText(value)) return null; + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(indexKey, "HmacSHA256")); + byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8)); + return java.util.HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("手机号索引生成失败", exception); + } + } + + public static PhoneCrypto current() { + PhoneCrypto instance = current; + if (instance == null) throw new IllegalStateException("手机号加密组件尚未初始化"); + return instance; + } + + private byte[] decodeKey(String value, String name) { + if (!StringUtils.hasText(value)) throw new IllegalStateException("缺少Nacos配置: jayucloud-salon.privacy." + name); + try { + return Base64.getDecoder().decode(value.trim()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneDataBackfillService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneDataBackfillService.java new file mode 100644 index 00000000..db0c16e3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneDataBackfillService.java @@ -0,0 +1,112 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.salon.core.config.PhoneCryptoProperties; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +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 PhoneDataBackfillService { + private final UserMapper userMapper; + private final OrderMapper orderMapper; + private final PhoneCrypto phoneCrypto; + private final PhoneCryptoProperties properties; + + @Transactional(rollbackFor = Exception.class) + public PhoneBackfillReport backfill(boolean dryRun) { + if (!dryRun && !properties.isBackfillEnabled()) { + throw new IllegalStateException("请先在 Salon Nacos secret.yaml 启用 phone-crypto.backfill-enabled"); + } + + List users = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class)); + Map> accountGroups = groupValues(users, UserDO::getAccount); + Map> phoneGroups = groupValues(users, UserDO::getPhone); + Set accountConflicts = duplicateIds(accountGroups); + Set phoneConflicts = duplicateIds(phoneGroups); + Set conflictingIds = new HashSet<>(accountConflicts); + conflictingIds.addAll(phoneConflicts); + + List usersToUpdate = users.stream() + .filter(user -> !conflictingIds.contains(user.getId())) + .filter(this::hasPendingUserFields) + .toList(); + List ordersToUpdate = orderMapper.selectList(Wrappers.lambdaQuery(OrderDO.class) + .isNotNull(OrderDO::getCustomerPhoneSnapshot) + .isNull(OrderDO::getCustomerPhoneSnapshotHash)) + .stream() + .filter(order -> StringUtils.hasText(order.getCustomerPhoneSnapshot())) + .toList(); + + PhoneBackfillReport report = new PhoneBackfillReport(); + report.setDryRun(dryRun); + report.setUserRowsToUpdate(usersToUpdate.size()); + report.setOrderRowsToUpdate(ordersToUpdate.size()); + report.setAccountConflictRows(accountConflicts.size()); + report.setPhoneConflictRows(phoneConflicts.size()); + report.setConflictingUserIds(conflictingIds.stream().sorted().toList()); + if (dryRun) return report; + if (!conflictingIds.isEmpty()) { + throw new IllegalStateException("检测到手机号或登录账号重复,已停止全部回填;请先处理冲突用户 ID:" + + report.getConflictingUserIds()); + } + + int pageSize = Math.max(1, Math.min(properties.getBackfillPageSize(), 2000)); + for (int start = 0; start < usersToUpdate.size(); start += pageSize) { + int end = Math.min(start + pageSize, usersToUpdate.size()); + List batch = usersToUpdate.subList(start, end); + for (UserDO user : batch) { + userMapper.updateById(user); + report.setUserRowsUpdated(report.getUserRowsUpdated() + 1); + } + } + for (int start = 0; start < ordersToUpdate.size(); start += pageSize) { + int end = Math.min(start + pageSize, ordersToUpdate.size()); + List batch = ordersToUpdate.subList(start, end); + for (OrderDO order : batch) { + orderMapper.updateById(order); + report.setOrderRowsUpdated(report.getOrderRowsUpdated() + 1); + } + } + return report; + } + + private Map> groupValues(List users, Function valueGetter) { + Map> groups = new HashMap<>(); + for (UserDO user : users) { + String value = valueGetter.apply(user); + if (StringUtils.hasText(value)) { + groups.computeIfAbsent(phoneCrypto.index(value), ignored -> new ArrayList<>()).add(user.getId()); + } + } + return groups; + } + + private Set duplicateIds(Map> groups) { + return groups.values().stream() + .filter(ids -> ids.size() > 1) + .flatMap(List::stream) + .collect(Collectors.toSet()); + } + + private boolean hasPendingUserFields(UserDO user) { + return (StringUtils.hasText(user.getAccount()) && !StringUtils.hasText(user.getAccountHash())) + || (StringUtils.hasText(user.getPhone()) && !StringUtils.hasText(user.getPhoneHash())) + || (StringUtils.hasText(user.getContactPhone()) && !StringUtils.hasText(user.getContactPhoneHash())); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneEncryptionTypeHandler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneEncryptionTypeHandler.java new file mode 100644 index 00000000..3f594ffb --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneEncryptionTypeHandler.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class PhoneEncryptionTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encrypt(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(cs.getString(columnIndex)); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java index 360b1961..4805a95b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java @@ -129,8 +129,7 @@ public class OperationGuardService { "public", safeAction, subject, - sanitize(resolveClientIp(request)), - sanitize(resolveDeviceId(request)) + sanitize(resolveClientIp(request)) ); } @@ -304,13 +303,6 @@ public class OperationGuardService { * Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ - private String resolveDeviceId(HttpServletRequest request) { - if (request == null) { - return "-"; - } - return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER); - } - /** * Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java index 47e2900b..2f895c52 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java @@ -24,7 +24,6 @@ public class RequestThrottleService { * Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ - public static final String DEVICE_ID_HEADER = "X-Device-Id"; /** * Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role. @@ -91,6 +90,14 @@ public class RequestThrottleService { assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试"); } + /** + * 客户拨号取号按用户维度限流,避免管理员批量拉取完整号码。 + */ + public void checkCustomerDial(HttpServletRequest request, Long userId) { + assertAllowed("customer-dial", request, userId == null ? "" : String.valueOf(userId), + rateLimitProperties.getCustomerDial(), "拨号取号过于频繁,请稍后再试"); + } + /** * Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. @@ -145,7 +152,6 @@ public class RequestThrottleService { String raw = String.join("|", category, sanitize(resolveClientIp(request)), - sanitize(resolveDeviceId(request)), sanitize(subject) ); String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); @@ -190,7 +196,7 @@ public class RequestThrottleService { * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ private String buildLoginLockRaw(HttpServletRequest request, String account) { - return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account)); + return String.join("|", sanitize(resolveClientIp(request)), sanitize(account)); } /** @@ -216,10 +222,6 @@ public class RequestThrottleService { * Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ - private String resolveDeviceId(HttpServletRequest request) { - return request == null ? null : request.getHeader(DEVICE_ID_HEADER); - } - /** * Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql new file mode 100644 index 00000000..a6ba4104 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql @@ -0,0 +1,35 @@ +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_shop' + AND column_name = 'appointment_business_hours' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_shop ADD COLUMN appointment_business_hours VARCHAR(20) NULL COMMENT ''预约运营营业时间'' AFTER business_hours', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_shop' + AND column_name = 'default_appointment_duration_minutes' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_shop ADD COLUMN default_appointment_duration_minutes INT NOT NULL DEFAULT 60 COMMENT ''默认预约服务时长(分钟)'' AFTER business_hours', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +UPDATE t_shop +SET default_appointment_duration_minutes = 60 +WHERE default_appointment_duration_minutes IS NULL OR default_appointment_duration_minutes <= 0; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V11__安全接入配置加密管理_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V11__安全接入配置加密管理_20261030.sql new file mode 100644 index 00000000..c58ddae4 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V11__安全接入配置加密管理_20261030.sql @@ -0,0 +1,13 @@ +CREATE TABLE IF NOT EXISTS t_secure_integration_config ( + id BIGINT NOT NULL COMMENT '主键ID', + config_group VARCHAR(64) NOT NULL COMMENT '安全配置分组', + config_key VARCHAR(100) NOT NULL COMMENT '安全配置键', + config_value LONGTEXT NULL COMMENT 'AES-GCM 加密后的配置值', + is_secret TINYINT NOT NULL DEFAULT 0 COMMENT '是否为密钥类配置', + enabled TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用', + updated_by BIGINT NULL COMMENT '最后修改管理员ID', + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_secure_integration_config_group_key (config_group, config_key) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Salon安全接入配置'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V12__微信订阅消息和预约取消原因_20261102.sql b/JC-Salon-Core/src/main/resources/db/migration/V12__微信订阅消息和预约取消原因_20261102.sql new file mode 100644 index 00000000..3346c041 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V12__微信订阅消息和预约取消原因_20261102.sql @@ -0,0 +1,35 @@ +SET @column_exists = ( + SELECT COUNT(1) FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'cancel_reason' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_order ADD COLUMN cancel_reason VARCHAR(255) NULL COMMENT ''预约取消原因'' AFTER customer_remark', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +CREATE TABLE IF NOT EXISTS t_wechat_subscribe_message_log ( + id BIGINT UNSIGNED NOT NULL COMMENT '订阅消息记录ID', + event_key VARCHAR(200) NOT NULL COMMENT '业务事件幂等键', + template_code VARCHAR(100) NOT NULL COMMENT '固定微信模板ID', + user_id BIGINT UNSIGNED NULL COMMENT '美甲师用户ID', + order_id BIGINT UNSIGNED NULL COMMENT '订单ID', + order_item_id BIGINT UNSIGNED NULL COMMENT '订单项ID', + open_id_hash VARCHAR(128) NULL COMMENT '接收OpenID摘要,不保存明文', + status VARCHAR(20) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/PROCESSING/RETRY/SENT/FAILED', + retry_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '重试次数', + err_code INT NULL COMMENT '微信错误码', + err_msg VARCHAR(500) NULL COMMENT '错误摘要', + next_retry_time DATETIME NULL COMMENT '下次处理时间', + sent_time DATETIME NULL COMMENT '发送成功时间', + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (id), + UNIQUE KEY uk_wechat_subscribe_event (event_key), + KEY idx_wechat_subscribe_due (status, next_retry_time, id), + KEY idx_wechat_subscribe_order (order_id, order_item_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信小程序订阅消息发送记录'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V13__门店每周营业排班_20261103.sql b/JC-Salon-Core/src/main/resources/db/migration/V13__门店每周营业排班_20261103.sql new file mode 100644 index 00000000..754885c1 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V13__门店每周营业排班_20261103.sql @@ -0,0 +1,53 @@ +-- 门店逐周营业安排,旧营业区间完整回填到周一至周日。 +CREATE TABLE IF NOT EXISTS t_shop_weekly_schedule +( + shop_id bigint unsigned NOT NULL COMMENT '门店ID', + day_of_week tinyint unsigned NOT NULL COMMENT '星期:1周一至7周日', + is_open tinyint NOT NULL DEFAULT 1 COMMENT '营业状态:1营业,0休息', + start_time time NULL COMMENT '营业开始时间', + end_time time NULL COMMENT '营业结束时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (shop_id, day_of_week), + KEY idx_shop_weekly_schedule_open (shop_id, is_open) +) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '门店每周营业安排'; + +DROP TEMPORARY TABLE IF EXISTS tmp_salon_weekly_hours; +CREATE TEMPORARY TABLE tmp_salon_weekly_hours +( + shop_id bigint unsigned NOT NULL PRIMARY KEY, + start_time time NOT NULL, + end_time time NOT NULL +) ENGINE = MEMORY; + +INSERT INTO tmp_salon_weekly_hours (shop_id, start_time, end_time) +SELECT source.id, + CASE + WHEN source.legacy_hours REGEXP '^([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9]$' + AND STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', 1), '%H:%i') + < STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', -1), '%H:%i') + THEN STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', 1), '%H:%i') + ELSE '10:00:00' + END, + CASE + WHEN source.legacy_hours REGEXP '^([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9]$' + AND STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', 1), '%H:%i') + < STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', -1), '%H:%i') + THEN STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', -1), '%H:%i') + ELSE '22:00:00' + END +FROM ( + SELECT id, COALESCE(NULLIF(appointment_business_hours, ''), NULLIF(business_hours, ''), '10:00-22:00') AS legacy_hours + FROM t_shop + WHERE is_delete = 0 +) source; + +INSERT IGNORE INTO t_shop_weekly_schedule (shop_id, day_of_week, is_open, start_time, end_time) +SELECT legacy.shop_id, days.day_of_week, 1, legacy.start_time, legacy.end_time +FROM tmp_salon_weekly_hours legacy +CROSS JOIN ( + SELECT 1 AS day_of_week UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL + SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 +) days; + +DROP TEMPORARY TABLE IF EXISTS tmp_salon_weekly_hours; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V14__图片读取渠道优先级和审核环境版本_20261103.sql b/JC-Salon-Core/src/main/resources/db/migration/V14__图片读取渠道优先级和审核环境版本_20261103.sql new file mode 100644 index 00000000..67b15356 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V14__图片读取渠道优先级和审核环境版本_20261103.sql @@ -0,0 +1,31 @@ +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_content_moderation_image_task' + AND column_name = 'source_env_version' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_content_moderation_image_task ADD COLUMN source_env_version VARCHAR(20) NOT NULL DEFAULT ''LEGACY'' COMMENT ''小程序来源环境:develop/trial/release/UNKNOWN;历史任务为LEGACY'' AFTER file_id', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, + create_time, update_time, is_delete +) +VALUES ( + 313931273555139021, 'FILE', 'IMAGE_READ_PROVIDER_ORDER', '对象存储图片读取优先级', + 'MINIO,QINIU_KODO,ALIYUN_OSS', 1, + '仅作用于签名访问 URL 生成和可用副本回退;不影响上传和副本修复顺序', + NOW(), NOW(), 0 +) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); diff --git a/JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql new file mode 100644 index 00000000..685f456c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql @@ -0,0 +1,22 @@ +CREATE TABLE IF NOT EXISTS t_integration_probe_result ( + id BIGINT NOT NULL, + service_code VARCHAR(64) NOT NULL, + operation_code VARCHAR(64) NOT NULL, + mode VARCHAR(32) NOT NULL, + provider VARCHAR(64) NULL, + status VARCHAR(16) NOT NULL, + summary VARCHAR(500) NULL, + error_code VARCHAR(64) NULL, + checks_json TEXT NULL, + remote_task_id VARCHAR(128) NULL, + correlation_key VARCHAR(128) NULL, + temporary_object_provider VARCHAR(64) NULL, + temporary_object_name VARCHAR(512) NULL, + expires_at DATETIME NULL, + checked_at DATETIME NOT NULL, + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uk_integration_probe_service_operation (service_code, operation_code), + KEY idx_integration_probe_checked_at (checked_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统接入最近一次诊断结果'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V16__订单线下收款登记_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V16__订单线下收款登记_20261104.sql new file mode 100644 index 00000000..c968c9e2 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V16__订单线下收款登记_20261104.sql @@ -0,0 +1,41 @@ +-- 订单线下收款登记:记录收款人、收款人类型与收款备注 +-- 说明:pay_time、payment_method、paid_amount、payment_status 已存在,本次不重复新增。 + +SET @column_exists = ( + SELECT COUNT(1) FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'paid_by' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_order ADD COLUMN paid_by BIGINT UNSIGNED NULL COMMENT ''收款登记人用户ID'' AFTER refund_status', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +SET @column_exists = ( + SELECT COUNT(1) FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'paid_by_type' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_order ADD COLUMN paid_by_type VARCHAR(20) NULL COMMENT ''收款登记人类型,线下收款固定为 SHOP_MANAGER'' AFTER paid_by', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +SET @column_exists = ( + SELECT COUNT(1) FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'paid_remark' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_order ADD COLUMN paid_remark VARCHAR(500) NULL COMMENT ''收款登记备注'' AFTER paid_by_type', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql new file mode 100644 index 00000000..58bb334b --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql @@ -0,0 +1,109 @@ +-- 隐私政策与用户协议条款修订:对齐手机号/账号 AES-GCM 加密存储、HMAC 不可逆索引与按场景脱敏展示 +-- 版本:2026.11.04 +-- 说明:仅停用旧版本并新增协议版本,不修改已在任一环境执行的 V1/V3 协议正文。 + +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) +VALUES + (313931273555140003, 'USER_TERMS', '用户协议', '2026.11.04', + '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。本协议与《隐私政策》共同构成你使用本服务的基础规则。 + +一、协议接受与版本 +你在登录前应完整阅读本协议和《隐私政策》,并主动选择同意。不同意时,我们不会交换微信登录凭证,你也不能继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。 + +二、账号与使用权限 +1. 微信 OpenID 用于识别和关联工作台账号;账号仅供本人使用,不得转借、出租或共享。 +2. 昵称和头像为可选资料;手机号可选绑定,不绑定不影响基础工作台功能。 +3. 你应妥善保管登录设备与账号,不得绕过权限校验访问他人数据。离职或不再获授权时,门店管理员可以调整或停用账号权限。 +4. 手机号及手机号形式的账号按《隐私政策》所述采用加密存储和不可逆索引;常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。你不得擅自收集、导出或向无关第三方提供完整号码。 + +三、业务资料与内容 +1. 你仅可录入履行门店业务所需且有权处理的客户、预约、作品、员工和经营资料,并确保上传文字、图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。 +2. 头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核;未通过、待复核或服务异常的内容不会公开。 +3. 客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动事务通知不纳入对外内容审核,但仍受门店权限和保密要求约束。 + +四、业务记录与金额 +订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值、订阅或平台虚拟权益购买。不得将工作台用于未经授权的资金收取、代收或虚拟权益交易。 + +五、账号注销与数据处理 +1. 你可在小程序“我的-账号设置”提交注销申请,并在处理前撤回。 +2. 管理员完成必要的门店移交或归档后,系统撤销会话并清理或匿名化 OpenID、昵称、头像、手机号等个人资料,目标处理期限为 15 个工作日。 +3. 解绑手机号经当前号码验证码核验后立即生效,系统清除手机号密文和检索索引。 +4. 必要的订单、预约和经营记录去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。 + +六、未成年人 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务。门店不得要求未成年人独立提交与其年龄不相适应的个人信息。 + +七、服务调整、责任与联系 +1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。 +2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。 +3. 隐私相关申请可从账号设置发起或联系所属门店管理员;其他问题请联系门店管理员或运营方公布的客服渠道【待业务确认】。 + +本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555140004, 'PRIVACY_POLICY', '隐私政策', '2026.11.04', + '欢迎使用甲屿手纪 Salon 门店工作台。本政策说明我们如何处理店长、员工账号及门店业务资料中的个人信息。本政策与《用户协议》共同构成你使用本服务的基础规则。 + +一、我们处理的信息及用途 +1. 登录与账号:经你主动同意后,通过微信登录获取 OpenID,用于识别和关联账号;如你使用手机号注册或绑定,手机号仅用于注册登录、验证码校验、账号找回、订单联系和售后处理,不用于营销。 +2. 账号标识:账号用于身份识别、权限校验和操作归属记录。当账号本身为手机号时,该账号按手机号同等强度加密存储;其他账号标识仅用于身份识别,并通过不可逆索引支持查询匹配。 +3. 可选资料:昵称、头像仅在你主动补充或更新时处理。 +4. 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品、订单和经营记录,用于履行门店服务管理;这些资料不构成客户的小程序登录账号。 +5. 安全运行:服务端处理请求所需的网络地址、登录会话和操作审计信息,用于安全防护、故障排查和审计。我们不主动采集 IMEI、MAC、麦克风或持续定位信息;仅当你主动使用地图选点功能时,才会调用微信地图能力获取你选择的地点。 +6. 内容审核:头像、作品、评论、店铺展示资料、公告和人工发布的消息在对外展示前进行内容安全审核。 + +二、加密存储与检索索引 +1. 手机号以及手机号形式的账号使用 AES-GCM 加密后落库,密文带版本标识,不以明文存入数据库。 +2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供;密钥访问受配置权限和审计约束。 +3. 为实现登录、去重和查询匹配,系统另以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引。该索引不能反推出手机号或账号原文,且不用于对外展示。 +4. 数据导出、备份和迁移沿用同等加密要求;如发生密钥轮换,按版本标识兼容解密并逐步重加密。 + +三、按场景脱敏展示 +1. 常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。 +2. 仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。 +3. 脱敏规则由服务端统一执行,不依赖前端隐藏;客户端不得缓存、截屏传播或在无权限场景转述完整号码。 +4. 客户本人资料页、员工账号资料页默认展示脱敏号码;修改绑定手机号时通过短信验证码核验,不以页面明文号码作为身份凭证。 + +四、第三方共享 +我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的: +1. 微信:微信登录、手机号授权、地图选点和内容安全审核(图片与文本)。 +2. 短信服务商:通过部署环境配置的短信通道发送验证码、绑定/解绑通知和必要的业务通知。 +3. 消息通道:通过 MessageHub 等已配置通道发送站内或订阅消息。 +4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。 +5. 地图服务:仅在你主动地图选点时,由微信内置地图能力(腾讯位置服务)处理所选位置。 +我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。 + +五、保存期限与删除 +1. 解绑手机号:通过当前号码验证码核验后,立即清除手机号密文及 phone_hash 索引。 +2. 账号注销:可在小程序“我的-账号设置”提交申请,处理前可撤回;管理员完成门店移交或归档后撤销会话,并在目标 15 个工作日内删除或匿名化 OpenID、昵称、头像和手机号等个人资料。 +3. 订单、预约和经营记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。 +4. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。 +5. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。 + +六、你的权利 +1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在账号设置中更换。 +2. 删除与注销:可在账号设置申请注销或解绑;也可请求删除非业务必需的资料。 +3. 撤回同意:可在账号设置或联系门店管理员撤回待处理的授权;撤回后不影响撤回前已进行的处理。 +4. 投诉与咨询:可联系所属门店管理员,或通过运营方公布的客服渠道提交隐私请求;具体客服渠道【待业务/法务确认】。 +5. 我们将在收到请求后按适用法律规定的期限响应;对于无法核验身份的请求,可能要求补充验证。 + +七、未成年人保护 +本服务主要面向门店经营人员。不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;我们不会在明知未取得监护人同意的情况下处理其个人信息。如发现误收集,将停止处理并删除。 + +八、安全措施与安全事件响应 +我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。 + +九、跨境传输 +目前我们不涉及向境外提供个人信息。如未来因业务需要发生跨境传输,我们将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。 + +十、政策更新与联系 +本政策版本为 2026.11.04,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在账号设置查看当前版本;其他问题请联系所属门店管理员。 + +本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。', + 1, NOW(), NOW(), NOW(), 0); diff --git a/JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql new file mode 100644 index 00000000..95a9601b --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql @@ -0,0 +1,51 @@ +-- 隐私政策与用户协议条款修订:对齐“全场景脱敏 + 拨号按需单次取号 + 可接隐私号码”口径 +-- 版本:2026.11.04(V18) +-- 说明:仅更新当前生效版本的条款正文,不新增协议版本、不触发重新同意;静态 HTML 正文由 public/legal 读库渲染,不再维护副本。 + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。', + '所有页面统一脱敏展示;确需联系客户时,须通过门店数据权限与预约/订单上下文校验后按需单次取号拨号,不批量展示完整号码;接入隐私号码服务时返回临时隐私号码。' + ), + update_time = NOW() +WHERE agreement_type = 'USER_TERMS' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。', + '全部客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。', + '确需与客户进行业务联系时,由授权人员在门店数据权限和预约/订单上下文校验通过后按需单次取号:直拨模式仅返回本次拨号号码,隐私号码模式返回临时隐私号码;完整号码不下发列表、不落库、不写日志、不进入缓存,且隐私号码未开通时不会回退为真实号码。' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '客户本人资料页、员工账号资料页默认展示脱敏号码;', + '客户本人资料页、员工账号资料页一律展示脱敏号码;' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%客户本人资料页、员工账号资料页默认展示脱敏号码;%'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql new file mode 100644 index 00000000..9accd378 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql @@ -0,0 +1,30 @@ +-- 隐私政策与用户协议新版本发布:停用当前生效版本,并从停用前正文复制新版本 +-- 版本:2026.11.04-R2 +-- 说明:正文通过 INSERT ... SELECT 复制 V18 已修订的当前生效文本,不在 SQL 中重复维护长文本; +-- V18 已在任一环境执行后不得修改,本文件仅新增版本。 + +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; + +INSERT INTO t_legal_agreement + (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +SELECT 313931273555140006, 'PRIVACY_POLICY', title, '2026.11.04-R2', content, 1, + '2026-11-04 00:00:00', NOW(), NOW(), 0 +FROM t_legal_agreement +WHERE agreement_type = 'PRIVACY_POLICY' + AND is_delete = 0 +ORDER BY effective_time DESC, create_time DESC +LIMIT 1; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V1__Salon空库初始化.sql b/JC-Salon-Core/src/main/resources/db/migration/V1__Salon空库初始化.sql new file mode 100644 index 00000000..d21e068e --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V1__Salon空库初始化.sql @@ -0,0 +1,2479 @@ +-- Flyway V1 baseline for JayuCloud Salon. +-- Derived from the frozen empty-database initialization SQL; applied once at Core startup. +-- The jayucloud_salon database must exist before the application starts. +-- 默认平台管理员账号:xiaowang,默认密码沿用当前 bcrypt 值。 +-- Linux MySQL 环境库名大小写敏感,数据源必须指向 jayucloud_salon。 +-- 2026-10-10 已吸收 docs/scripts/sql 下全部 Salon 版本 SQL 的最终状态: +-- 工作台注册审核、短信供应商全局切换、短信模板编码映射调整、短信模板编码统一修复。 + +-- auto-generated definition +create table t_balance +( + id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' + primary key comment '余额表主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) default 0.00 not null comment '当前余额', + total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', + last_recharge_time datetime null comment '最近一次充值时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', + last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_user_id + unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' +) + comment '用户余额信息表'; + + +-- auto-generated definition +create table t_balance_change_detail +( + id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' + primary key comment '余额变动明细主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', + type varchar(20) not null comment '变动类型(如充值、消费、退款)', + current_balance decimal(10, 2) not null comment '变动后的当前余额', + before_balance decimal(10, 2) null comment '变动前余额', + after_balance decimal(10, 2) null comment '变动后余额', + change_scene varchar(32) null comment '余额变动场景', + related_order_id bigint unsigned null comment '关联系统订单ID', + related_order_no varchar(64) null comment '关联系统订单号', + external_order_no varchar(64) null comment '手工录入的外部订单号', + operator_id bigint unsigned null comment '操作人ID', + remark varchar(255) null comment '备注', + change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' +) + comment '用户余额变动明细表'; + +create index idx_change_time + on t_balance_change_detail (change_time) + comment '按时间查询余额变动的索引'; + +create index idx_user_id + on t_balance_change_detail (user_id) + comment '按用户查询余额变动的索引'; + +-- auto-generated definition +create table t_cart +( + id bigint unsigned auto_increment comment '购物车主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned default 1 not null comment '商品数量', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '购物车表'; + +create index idx_user_id + on t_cart (user_id) + comment '按用户查询购物车的索引'; + +-- auto-generated definition +create table t_comment +( + id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' + primary key comment '评论主键索引', + user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', + shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', + product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', + comment_content text not null comment '评论内容', + parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', + rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', + image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', + moderation_status varchar(20) default 'APPROVED' not null comment '本地模拟审核状态:PENDING/APPROVED/REJECTED/RETRY', + like_count int unsigned default 0 null comment '评论点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '用户评论信息表'; + +create index idx_parent_comment_id + on t_comment (parent_comment_id) + comment '按父级评论查询回复的索引'; + +create index idx_product_id + on t_comment (product_id) + comment '按商品查询评论的索引'; + +create index idx_shop_id + on t_comment (shop_id) + comment '按店铺查询评论的索引'; + +create index idx_user_id + on t_comment (user_id) + comment '按用户查询评论的索引'; + +-- auto-generated definition +create table t_coupon +( + id bigint unsigned auto_increment comment '优惠券主键索引' + primary key, + coupon_code varchar(50) not null comment '优惠券编码', + coupon_name varchar(100) not null comment '优惠券名称', + coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', + discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', + min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', + reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', + total_count int unsigned default 100 not null comment '优惠券总数量', + used_count int unsigned default 0 not null comment '已使用数量', + start_time datetime not null comment '开始时间', + end_time datetime not null comment '结束时间', + status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '所属店铺ID', + coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', + required_vip_level varchar(20) null comment '要求的VIP等级', + auto_match tinyint unsigned default 0 not null comment '是否自动匹配', + constraint uk_coupon_code + unique (coupon_code) comment '优惠券编码唯一索引' +) + comment '优惠券信息表'; + +create index idx_status + on t_coupon (status) + comment '按状态查询优惠券的索引'; + +-- auto-generated definition +create table t_coupon_tag +( + id bigint unsigned auto_increment comment '优惠券标签关联主键索引' + primary key, + coupon_id bigint unsigned not null comment '关联优惠券表主键', + tag_id bigint unsigned not null comment '关联标签表主键', + is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_coupon_tag + unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' +) + comment '优惠券标签关联表'; + +create index idx_coupon_id + on t_coupon_tag (coupon_id) + comment '按优惠券查询标签的索引'; + +create index idx_tag_id + on t_coupon_tag (tag_id) + comment '按标签查询优惠券的索引'; + +-- auto-generated definition +create table t_effect_diagram +( + id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' + primary key comment '效果图主键索引', + product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', + category varchar(50) default '' null comment '效果图类别', + image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', + description text null comment '效果图描述', + price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', + duration varchar(50) default '' null comment '效果图对应服务耗时', + tag varchar(50) default '' null comment '效果图标签', + like_count int unsigned default 0 null comment '效果图点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '商品效果图信息表'; + +create index idx_product_id + on t_effect_diagram (product_id) + comment '按商品查询效果图的索引'; + +-- auto-generated definition +create table t_login_identity +( + id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' + primary key comment '登录标识主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', + input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', + input_time datetime not null comment '输入时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' +) + comment '用户登录标识信息表'; + +create index idx_login_method + on t_login_identity (login_method) + comment '按登录方式查询的索引'; + +create index idx_user_id + on t_login_identity (user_id) + comment '按用户查询登录标识的索引'; + +-- auto-generated definition +create table t_wechat_mini_binding +( + id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' + primary key, + user_id bigint unsigned not null comment '关联用户ID', + app_id varchar(64) not null comment '微信小程序appId', + openid varchar(100) not null comment '微信小程序openid', + unionid varchar(100) null comment '微信开放平台unionid', + status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_wechat_mini_app_openid + unique (app_id, openid), + constraint uk_wechat_mini_app_user + unique (app_id, user_id) +) + comment '微信小程序账号绑定表'; + +create index idx_wechat_mini_unionid + on t_wechat_mini_binding (unionid) + comment '按unionid查询的索引'; + +-- auto-generated definition +create table t_nail_artist_info +( + id bigint unsigned auto_increment comment '美甲师信息主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', + identity varchar(50) default '' null comment '身份', + experience int unsigned default 0 null comment '从业年限', + skills text null comment '技能标签ID集合,多个ID以逗号分隔', + rating decimal(3, 1) default 4.5 null comment '评分', + status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', + portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_id + unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' +) + comment '美甲师信息表'; + +create index idx_status + on t_nail_artist_info (status) + comment '按状态查询美甲师的索引'; + +create index idx_user_id + on t_nail_artist_info (user_id) + comment '按用户查询美甲师信息的索引'; + +create index idx_t_nail_artist_info_participate + on t_nail_artist_info (participate_production, status); + +-- auto-generated definition +create table t_object_storage_file +( + id bigint unsigned auto_increment comment '????ID' + primary key comment '????????', + file_name varchar(100) not null comment '????', + file_url text not null comment '??????', + object_name varchar(512) null comment '????Key', + primary_provider varchar(64) null comment '??????', + primary_url text null comment '???????', + backup_provider varchar(64) null comment '???????', + backup_url text null comment '????????', + content_type varchar(128) null comment '??Content-Type', + file_size bigint unsigned null comment '?????????', + primary_upload_status tinyint unsigned default 0 not null comment '????????0????1???2??', + backup_upload_status tinyint unsigned default 0 not null comment '?????????0????1???2??', + backup_retry_count int unsigned default 0 not null comment '??????', + backup_last_error varchar(500) null comment '??????????', + backup_uploaded_at datetime null comment '??????', + backup_last_retry_time datetime null comment '??????????', + create_time datetime default CURRENT_TIMESTAMP not null comment '??????', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '??????', + status tinyint unsigned default 1 null comment '?????1???0????2???', + delete_time datetime null comment '??????', + recycle_time datetime null comment '?????????' +) + comment '?????????'; + +create index idx_status + on t_object_storage_file (status) + comment '??????'; + +create index idx_object_storage_file_backup_retry + on t_object_storage_file (backup_upload_status, primary_upload_status, status) + comment '????????'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS `t_object_storage_file_replica` +( + `id` bigint unsigned NOT NULL COMMENT '副本ID', + `file_id` bigint unsigned NOT NULL COMMENT '文件ID', + `provider` varchar(64) NOT NULL COMMENT '对象存储提供方', + `object_name` varchar(512) NOT NULL COMMENT '对象Key', + `object_url` text NULL COMMENT '对象访问地址', + `upload_status` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '上传状态:0-待上传,1-成功,2-失败', + `retry_count` int unsigned NOT NULL DEFAULT 0 COMMENT '重试次数', + `last_error` varchar(500) NULL COMMENT '最近一次错误', + `uploaded_at` datetime NULL COMMENT '上传成功时间', + `last_retry_time` datetime NULL COMMENT '最近一次重试时间', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_object_storage_file_replica_file_provider` (`file_id`, `provider`), + KEY `idx_object_storage_file_replica_retry` (`upload_status`, `provider`, `file_id`), + KEY `idx_object_storage_file_replica_file_status` (`file_id`, `upload_status`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci + COMMENT = '对象存储文件副本表'; + +-- auto-generated definition +create table t_order +( + id bigint unsigned auto_increment comment '订单主键索引' + primary key, + order_no varchar(50) not null comment '订单编号', + user_id bigint unsigned null comment '关联用户表主键,历史补单可为空', + shop_id bigint unsigned null comment '所属店铺ID', + total_amount decimal(10, 2) not null comment '订单总金额', + actual_amount decimal(10, 2) not null comment '实际支付金额', + coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', + user_coupon_id bigint unsigned null comment '用户券ID', + coupon_source_type varchar(32) null comment '优惠来源类型', + customer_remark varchar(500) null comment '用户询价预约备注', + customer_name_snapshot varchar(100) null comment '补单客户名称快照', + customer_phone_snapshot varchar(128) null comment '加密补单客户手机号快照', + customer_phone_snapshot_hash char(64) null comment '补单客户手机号HMAC索引', + order_source varchar(32) default 'NORMAL_APPOINTMENT' not null comment '订单来源:NORMAL_APPOINTMENT/HISTORICAL_BACKFILL', + status tinyint unsigned default 1 not null comment '订单状态:0-价格确认中,1-待服务,2-已完成,3-已取消,4-服务中', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_order_no + unique (order_no) comment '订单编号唯一索引' +) + comment '订单表'; + +create index idx_status + on t_order (status) + comment '按状态查询订单的索引'; + +create index idx_user_id + on t_order (user_id) + comment '按用户查询订单的索引'; + +create index idx_order_source_status_delete + on t_order (order_source, status, is_delete) + comment '按订单来源和状态查询的索引'; + +-- auto-generated definition +create table t_order_item +( + id bigint unsigned auto_increment comment '订单商品主键索引' + primary key, + order_id bigint unsigned not null comment '关联订单表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned not null comment '商品数量', + price decimal(10, 2) not null comment '商品单价', + artist_id bigint unsigned null comment '关联美甲师ID', + appointment_time datetime null comment '预约开始时间', + service_date date null comment '业务服务日期,历史补单无具体时间时使用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单商品表'; + +create index idx_order_id + on t_order_item (order_id) + comment '按订单查询商品的索引'; + +create index idx_order_item_artist_service_date + on t_order_item (artist_id, service_date, is_delete) + comment '按员工和业务服务日期查询的索引'; + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +create unique index uk_order_artist_review_item + on t_order_artist_review (order_item_id, is_delete); + +create index idx_order_artist_review_customer + on t_order_artist_review (customer_id, status, create_time); + +create index idx_order_artist_review_artist + on t_order_artist_review (artist_id, status); + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +create index idx_order_artist_change_customer + on t_order_artist_change_request (customer_id, status, create_time); + +create index idx_order_artist_change_artist + on t_order_artist_change_request (from_artist_id, to_artist_id, status); + +create index idx_order_artist_change_shop + on t_order_artist_change_request (shop_id, status, create_time); + +create unique index uk_order_artist_change_pending_key + on t_order_artist_change_request (pending_key); + +-- auto-generated definition +create table t_permission +( + id bigint unsigned auto_increment comment '权限唯一主键ID' + primary key, + permission_code varchar(100) not null comment '权限编码(唯一标识)', + permission_name varchar(100) not null comment '权限名称', + permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', + description varchar(255) null comment '权限描述', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_permission_code + unique (permission_code) comment '权限编码唯一索引' +) + comment '系统权限表'; + +-- auto-generated definition +create table t_product +( + id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' + primary key comment '商品主键索引', + shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', + title varchar(100) not null comment '商品标题', + description text null comment '商品描述', + target_audience text null comment '适合人群说明', + precautions text null comment '注意事项说明', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', + price decimal(10, 2) not null comment '商品价格,保留2位小数', + tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', + like_count int unsigned default 0 null comment '商品点赞数', + collect_count int unsigned default 0 null comment '商品收藏数', + approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', + bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', + available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', + front_visible tinyint unsigned default 1 not null comment '前台是否展示:0-隐藏,1-展示', + source_type varchar(64) default 'BACKEND' not null comment '来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约', + create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '商品信息表'; + +create index idx_price + on t_product (price) + comment '按价格筛选商品的索引'; + +create index idx_shop_id + on t_product (shop_id) + comment '按所属店铺查询商品的索引'; + +create index idx_tags + on t_product (tags) + comment '按标签筛选商品的索引'; + +create index idx_title + on t_product (title) + comment '商品标题搜索的索引'; + +create index idx_t_product_front_visible + on t_product (shop_id, front_visible, source_type) + comment '按门店、前台展示和来源筛选商品'; + +-- auto-generated definition +create table t_product_like +( + id bigint unsigned auto_increment comment '商品点赞主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product_like + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品点赞记录表'; + +create index idx_product_id_like + on t_product_like (product_id) + comment '按商品查询点赞的索引'; + +create index idx_user_id_like + on t_product_like (user_id) + comment '按用户查询点赞的索引'; + +-- auto-generated definition +create table t_shop +( + id bigint unsigned auto_increment comment '店铺唯一主键ID' + primary key comment '店铺主键索引', + shop_name varchar(100) not null comment '店铺名称', + description text null comment '店铺描述', + address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', + business_hours varchar(100) default '' null comment '店铺营业时间', + cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', + theme_primary_color varchar(20) null comment '前台主题主色', + theme_secondary_color varchar(20) null comment '前台主题辅色', + theme_accent_color varchar(20) null comment '前台主题强调色', + theme_page_bg_color varchar(20) null comment '前台主题页面背景色', + theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', + theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', + status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', + authorization_start_date date null comment '店铺授权起始日', + authorization_days int null comment '店铺授权有效天数', + authorization_expire_time datetime null comment '店铺授权到期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' +) + comment '店铺信息表'; + +create index idx_shop_name + on t_shop (shop_name) + comment '按店铺名称查询的索引'; + +-- auto-generated definition +create table t_tag +( + id bigint unsigned auto_increment comment '标签唯一主键ID' + primary key comment '标签主键索引', + tag_name varchar(50) not null comment '标签名称', + text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', + bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', + border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', + scene_group varchar(50) null comment '前台场景筛选分组', + display_name varchar(80) null comment '前台展示名称', + sort_order int default 100 null comment '前台筛选排序', + front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '店铺ID', + constraint uk_tag_shop_name + unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' +) + comment '系统标签信息表'; + +-- auto-generated definition +create table t_user +( + id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' + primary key comment '用户主键索引', + shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', + nickname varchar(50) not null comment '用户昵称', + account varchar(128) null comment '用户账号(手机号账号加密存储)', + account_hash char(64) null comment '账号HMAC索引', + phone varchar(128) null comment '手机号AES-GCM密文', + phone_hash char(64) null comment '手机号HMAC索引', + contact_phone varchar(128) null comment '联系电话AES-GCM密文', + contact_phone_hash char(64) null comment '联系电话HMAC索引', + birthday date null comment '生日', + wechat_id varchar(100) null comment '微信号', + wechat_qr_code varchar(512) null comment '微信二维码', + email varchar(100) null comment '邮箱', + phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', + email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', + password varchar(100) null comment '用户密码(加密存储,微信快捷登录用户可为空)', + signature varchar(200) default '' null comment '用户签名', + level varchar(20) default '普通' null comment '用户等级', + type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', + vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', + avatar varchar(512) null comment '头像链接', + constraint uk_user_phone_hash + unique (phone_hash) comment '用户手机号HMAC唯一索引(允许多行NULL)', + constraint uk_user_account_hash + unique (account_hash) comment '手机号账号HMAC唯一索引(允许多行NULL)' +) + comment '系统用户信息表'; + +create index idx_email + on t_user (email) + comment '按邮箱查询的索引'; + +create index idx_shop_id + on t_user (shop_id) + comment '按店铺查询用户的索引'; + +create index idx_type + on t_user (type) + comment '按用户类型查询的索引'; + +-- 工作台注册审核申请 +CREATE TABLE IF NOT EXISTS `t_workbench_registration_application` +( + `id` bigint NOT NULL COMMENT '申请ID', + `application_no` varchar(40) NOT NULL COMMENT '申请编号', + `user_id` bigint NOT NULL COMMENT '申请用户ID', + `role_type` varchar(20) NOT NULL COMMENT '申请身份:MANAGER/STAFF', + `shop_id` bigint NULL COMMENT '目标店铺ID', + `shop_name` varchar(120) NULL COMMENT '店铺名称快照', + `shop_address` varchar(255) NULL COMMENT '店铺地址快照', + `status` varchar(30) NOT NULL COMMENT '状态:PENDING_ADMIN/PENDING_MANAGER/APPROVED/REJECTED', + `reviewer_id` bigint NULL COMMENT '审核人ID', + `reviewed_at` datetime NULL COMMENT '审核时间', + `reject_reason` varchar(500) NULL COMMENT '驳回原因', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_workbench_registration_application_no` (`application_no`), + KEY `idx_workbench_registration_user` (`user_id`), + KEY `idx_workbench_registration_shop_status` (`shop_id`, `status`), + KEY `idx_workbench_registration_status` (`status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Salon店务工作台注册审核申请'; + +-- auto-generated definition +create table t_user_coupon +( + id bigint unsigned auto_increment comment '用户优惠券关联主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + coupon_id bigint unsigned not null comment '关联优惠券表主键', + status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', + obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', + use_time datetime null comment '使用时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_coupon + unique (user_id, coupon_id) comment '用户-优惠券唯一索引' +) + comment '用户优惠券关联表'; + +create index idx_status + on t_user_coupon (status) + comment '按状态查询用户优惠券的索引'; + +create index idx_user_id + on t_user_coupon (user_id) + comment '按用户查询优惠券的索引'; + +-- auto-generated definition +create table t_user_permission +( + id bigint unsigned auto_increment comment '关联ID' + primary key, + user_id bigint unsigned not null comment '用户ID', + permission_id bigint unsigned not null comment '权限ID', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + create_by bigint unsigned null comment '创建人ID', + update_by bigint unsigned null comment '更新人ID', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_permission + unique (user_id, permission_id) comment '用户-权限唯一索引' +) + comment '用户权限关联表'; + +create index idx_permission_id + on t_user_permission (permission_id) + comment '权限ID索引'; + +create index idx_user_id + on t_user_permission (user_id) + comment '用户ID索引'; + +create table if not exists t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + business_type varchar(64) null comment '业务类型', + business_id bigint unsigned null comment '业务ID', + action_path varchar(255) null comment '业务跳转路径', + idempotency_key varchar(160) null comment '业务消息幂等键', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +create index idx_t_system_message_publish_time + on t_system_message (publish_time); + +create index idx_t_system_message_target + on t_system_message (target_type, status); + +create unique index uk_t_system_message_idempotency + on t_system_message (idempotency_key); + +create table if not exists t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +create index idx_t_system_message_user_state_user + on t_system_message_user_state (user_id, read_status, popup_shown); + +create table if not exists t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +create index idx_t_announcement_target + on t_announcement (target_type, status); + +create index idx_t_announcement_sort_time + on t_announcement (sort_order, publish_time); + +create table if not exists t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +create index idx_t_vip_recharge_plan_shop_status + on t_vip_recharge_plan (shop_id, status, sort_order); + +-- auto-generated definition +create table t_vip_benefit +( + id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' + primary key comment 'VIP权益主键索引', + benefit_info text not null comment '权益详情(如折扣、专属服务)', + required_vip_level varchar(20) not null comment '所需VIP等级', + level_rank int default 0 not null comment '等级序号', + recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', + status tinyint unsigned default 1 not null comment '状态', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment 'VIP权益信息表'; + +create index idx_required_vip_level + on t_vip_benefit (required_vip_level) + comment '按VIP等级查询权益的索引'; + +-- auto-generated definition +create table t_vip_info +( + id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' + primary key comment 'VIP信息主键索引', + user_id bigint unsigned null comment '所属用户ID', + vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', + start_time datetime not null comment 'VIP开通时间', + expire_time datetime null comment 'VIP到期时间', + activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', + benefit_id bigint unsigned null comment '关联VIP权益信息表主键', + manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment '用户VIP信息表'; + +create index idx_vip_level + on t_vip_info (vip_level) + comment '按VIP等级查询的索引'; + +-- auto-generated definition +create table t_wishlist_group +( + id bigint unsigned auto_increment comment '收藏分组主键' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', + sort_order int default 100 not null comment '分组排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' +) + comment '商品收藏分组表'; + +create index idx_t_wishlist_group_sort + on t_wishlist_group (user_id, sort_order, create_time) + comment '按用户和排序查询收藏分组的索引'; + +create index idx_t_wishlist_group_user + on t_wishlist_group (user_id) + comment '按用户查询收藏分组的索引'; + +-- auto-generated definition +create table t_wishlist +( + id bigint unsigned auto_increment comment '商品收藏主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + group_id bigint unsigned null comment '收藏分组ID', + note varchar(500) null comment '收藏灵感备注', + sort_order int default 100 not null comment '分组内排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品收藏表'; + +create index idx_product_id + on t_wishlist (product_id) + comment '按商品查询收藏的索引'; + +create index idx_user_id + on t_wishlist (user_id) + comment '按用户查询收藏的索引'; + +create index idx_t_wishlist_user_group_sort + on t_wishlist (user_id, group_id, sort_order, create_time) + comment '按用户分组查询收藏灵感的索引'; + +-- ======================================== +-- 首次部署整合区:用户资产 / VIP / 优惠券补丁 +-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +CREATE TABLE IF NOT EXISTS t_account_closure_request ( + id bigint unsigned NOT NULL COMMENT '账号注销申请ID', + user_id bigint unsigned NOT NULL COMMENT '申请人用户ID', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '申请状态:PENDING/APPROVED/REJECTED/WITHDRAWN', + requested_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间', + processed_at datetime NULL COMMENT '处理时间', + reviewer_id bigint unsigned NULL COMMENT '处理人用户ID', + reviewer_note varchar(500) NULL COMMENT '处理说明', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_account_closure_user_status (user_id, status), + KEY idx_account_closure_status_time (status, requested_at) +) COMMENT='账号注销申请记录'; + +CREATE TABLE IF NOT EXISTS t_content_moderation_record ( + id bigint unsigned NOT NULL COMMENT '内容审核记录ID', + content_type varchar(40) NOT NULL COMMENT '内容类型:USER_PROFILE/USER_AVATAR/PRODUCT/COMMENT', + business_id bigint unsigned NULL COMMENT '业务记录ID', + user_id bigint unsigned NULL COMMENT '内容提交人', + status varchar(20) NOT NULL COMMENT '审核状态:PENDING/APPROVED/REJECTED/RETRY', + provider varchar(30) NOT NULL DEFAULT 'LOCAL_MOCK' COMMENT '审核Provider标识', + result_code varchar(40) NULL COMMENT 'Provider结果代码', + reason varchar(500) NULL COMMENT '审核或复核说明', + payload_json mediumtext NULL COMMENT '隔离内容载荷,仅待审核记录可访问', + reviewed_by bigint unsigned NULL COMMENT '复核人用户ID', + reviewed_at datetime NULL COMMENT '复核时间', + attempt_count int NOT NULL DEFAULT 0 COMMENT '处理尝试次数', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_content_moderation_status_time (status, create_time), + KEY idx_content_moderation_business (content_type, business_id) +) COMMENT='本地内容审核隔离与复核记录'; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); +CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); +CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); + +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''????Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_provider', 'varchar(64) NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_url', 'text NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_provider', 'varchar(64) NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_url', 'text NULL COMMENT ''????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''??Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''?????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''?????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_error', 'varchar(500) NULL COMMENT ''??????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_uploaded_at', 'datetime NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_retry_time', 'datetime NULL COMMENT ''??????????'''); +UPDATE t_object_storage_file +SET primary_provider = COALESCE(primary_provider, 'QINIU_KODO'), + primary_url = COALESCE(primary_url, file_url), + backup_provider = COALESCE(backup_provider, 'ALIYUN_OSS'), + primary_upload_status = CASE WHEN primary_upload_status IS NULL OR primary_upload_status = 0 THEN 1 ELSE primary_upload_status END, + backup_upload_status = COALESCE(backup_upload_status, 0), + backup_retry_count = COALESCE(backup_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(`backup_upload_status`, `primary_upload_status`, `status`)'); +UPDATE t_balance +SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) +WHERE total_recharge_amount IS NULL; + +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); +CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); + +CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); +CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); +CALL sp_add_column_if_not_exists('t_user', 'account_hash', 'char(64) NULL COMMENT ''账号HMAC索引'''); +CALL sp_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号HMAC索引'''); +CALL sp_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话HMAC索引'''); +CALL sp_add_column_if_not_exists('t_comment', 'moderation_status', 'varchar(20) NOT NULL DEFAULT ''APPROVED'' COMMENT ''本地模拟审核状态:PENDING/APPROVED/REJECTED/RETRY'''); +ALTER TABLE t_user MODIFY COLUMN account varchar(128) NULL COMMENT '手机号账号AES-GCM密文'; +ALTER TABLE t_user MODIFY COLUMN phone varchar(128) NULL COMMENT '手机号AES-GCM密文'; +ALTER TABLE t_user MODIFY COLUMN contact_phone varchar(128) NULL COMMENT '联系电话AES-GCM密文'; +SET @drop_legacy_account_index_sql = IF( + EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user' AND INDEX_NAME = 'uk_account'), + 'ALTER TABLE t_user DROP INDEX uk_account', 'SELECT 1' +); +PREPARE stmt_drop_legacy_account_index FROM @drop_legacy_account_index_sql; +EXECUTE stmt_drop_legacy_account_index; +DEALLOCATE PREPARE stmt_drop_legacy_account_index; +SET @drop_legacy_phone_index_sql = IF( + EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user' AND INDEX_NAME = 'uk_user_phone'), + 'ALTER TABLE t_user DROP INDEX uk_user_phone', 'SELECT 1' +); +PREPARE stmt_drop_legacy_phone_index FROM @drop_legacy_phone_index_sql; +EXECUTE stmt_drop_legacy_phone_index; +DEALLOCATE PREPARE stmt_drop_legacy_phone_index; +CALL sp_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(`phone_hash`)'); +CALL sp_add_unique_index_if_not_exists('t_user', 'uk_user_account_hash', '(`account_hash`)'); +CALL sp_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(`contact_phone_hash`)'); +CALL sp_add_column_if_not_exists('t_order', 'customer_phone_snapshot_hash', 'char(64) NULL COMMENT ''补单客户手机号HMAC索引'''); +ALTER TABLE t_order MODIFY COLUMN customer_phone_snapshot varchar(128) NULL COMMENT '加密补单客户手机号快照'; +CALL sp_add_index_if_not_exists('t_order', 'idx_order_customer_phone_snapshot_hash', '(`customer_phone_snapshot_hash`)'); +SET @drop_consent_device_id_sql = IF( + EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user_agreement_consent' AND COLUMN_NAME = 'device_id'), + 'ALTER TABLE t_user_agreement_consent DROP COLUMN device_id', 'SELECT 1' +); +PREPARE stmt_drop_consent_device_id FROM @drop_consent_device_id_sql; +EXECUTE stmt_drop_consent_device_id; +DEALLOCATE PREPARE stmt_drop_consent_device_id; +SET @drop_audit_device_id_sql = IF( + EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_security_audit_log' AND COLUMN_NAME = 'device_id'), + 'ALTER TABLE t_security_audit_log DROP COLUMN device_id', 'SELECT 1' +); +PREPARE stmt_drop_audit_device_id FROM @drop_audit_device_id_sql; +EXECUTE stmt_drop_audit_device_id; +DEALLOCATE PREPARE stmt_drop_audit_device_id; +UPDATE t_balance_change_detail +SET before_balance = COALESCE(before_balance, current_balance - amount), + after_balance = COALESCE(after_balance, current_balance), + change_scene = COALESCE(NULLIF(change_scene, ''), type) +WHERE before_balance IS NULL + OR after_balance IS NULL + OR change_scene IS NULL + OR change_scene = ''; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); + +CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); +CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); + +SET @sql = (SELECT IF(COUNT(*) = 0, + 'ALTER TABLE t_order MODIFY COLUMN user_id BIGINT UNSIGNED NULL COMMENT ''关联用户表主键,历史补单可为空''', + 'SELECT 1') FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'user_id' AND is_nullable = 'YES'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'customer_name_snapshot', 'varchar(100) NULL COMMENT ''补单客户名称快照'''); +CALL sp_add_column_if_not_exists('t_order', 'customer_phone_snapshot', 'varchar(32) NULL COMMENT ''补单客户手机号快照'''); +CALL sp_add_column_if_not_exists('t_order', 'order_source', 'varchar(32) NOT NULL DEFAULT ''NORMAL_APPOINTMENT'' COMMENT ''订单来源:NORMAL_APPOINTMENT/HISTORICAL_BACKFILL'''); + +CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); +CALL sp_add_column_if_not_exists('t_order_item', 'service_date', 'date NULL COMMENT ''业务服务日期,历史补单无具体时间时使用'''); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_order_source_status_delete', '(`order_source`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_order_item_artist_service_date', '(`artist_id`, `service_date`, `is_delete`)'); + +SET @drop_old_tag_unique_sql = ( + SELECT IF( + EXISTS( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_tag' + AND INDEX_NAME = 'uk_tag_name' + ), + 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', + 'SELECT 1' + ) +); +PREPARE stmt FROM @drop_old_tag_unique_sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); +CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); +CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); +CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); +CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); +UPDATE t_tag +SET front_visible = 1 +WHERE front_visible IS NULL; +CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); + +CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); +CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); +CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); + +UPDATE t_coupon +SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), + auto_match = COALESCE(auto_match, 0) +WHERE coupon_scene IS NULL + OR coupon_scene = '' + OR auto_match IS NULL; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); + +CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); + +UPDATE t_vip_benefit +SET level_rank = CASE required_vip_level + WHEN '普通' THEN 0 + WHEN '青铜' THEN 1 + WHEN '白银' THEN 2 + WHEN '黄金' THEN 3 + ELSE level_rank + END, + recharge_threshold = CASE required_vip_level + WHEN '普通' THEN 0.00 + WHEN '青铜' THEN 500.00 + WHEN '白银' THEN 1000.00 + WHEN '黄金' THEN 2000.00 + ELSE recharge_threshold + END, + status = COALESCE(status, 1) +WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); + +CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); +CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); + +ALTER TABLE t_vip_info + MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', + MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; + +UPDATE t_vip_info vi +INNER JOIN t_user u ON u.vip_id = vi.id +SET vi.user_id = u.id +WHERE (vi.user_id IS NULL OR vi.user_id = 0) + AND u.vip_id IS NOT NULL + AND u.vip_id <> 0; + +UPDATE t_vip_info +SET start_time = COALESCE(start_time, create_time, NOW()), + activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), + manual_override = COALESCE(manual_override, 0); + +CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); + +UPDATE t_user u +LEFT JOIN t_vip_info vi ON vi.id = u.vip_id +SET u.level = CASE + WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level + WHEN u.type = 0 THEN '普通' + ELSE u.level + END, + u.vip_id = CASE + WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 + ELSE u.vip_id + END, + u.update_time = NOW() +WHERE u.is_delete = 0 + AND u.type = 0 + AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); + +UPDATE t_vip_benefit +SET benefit_info = '普通用户,无额外VIP折扣', + level_rank = 0, + recharge_threshold = 0.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '普通'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '普通' +); + +UPDATE t_vip_benefit +SET benefit_info = '青铜VIP,系统自动匹配9.5折券', + level_rank = 1, + recharge_threshold = 500.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '青铜'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '青铜' +); + +UPDATE t_vip_benefit +SET benefit_info = '白银VIP,系统自动匹配9.2折券', + level_rank = 2, + recharge_threshold = 1000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '白银'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '白银' +); + +UPDATE t_vip_benefit +SET benefit_info = '黄金VIP,系统自动匹配9.0折券', + level_rank = 3, + recharge_threshold = 2000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '黄金'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '黄金' +); + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 +-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); + +UPDATE t_shop +SET status = 1 +WHERE status IS NULL; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); + +CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', + `user_id` bigint unsigned NOT NULL COMMENT '用户ID', + `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', + `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (`id`) +) COMMENT='用户与店铺绑定关系表'; + +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); + +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); +CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); + +INSERT INTO t_user_shop_binding ( + user_id, + shop_id, + status, + create_time, + update_time, + is_delete +) +SELECT + u.id, + u.shop_id, + CASE + WHEN COALESCE(u.status, 1) = 1 THEN 1 + ELSE 0 + END AS binding_status, + COALESCE(u.create_time, NOW()), + COALESCE(u.update_time, NOW()), + 0 +FROM t_user u +INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 +LEFT JOIN t_user_shop_binding b + ON b.user_id = u.id + AND b.shop_id = u.shop_id + AND COALESCE(b.is_delete, 0) = 0 +WHERE COALESCE(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 + AND b.id IS NULL; + +UPDATE t_user_shop_binding b +INNER JOIN t_user u ON u.id = b.user_id +SET b.status = CASE + WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END + ELSE b.status + END, + b.is_delete = COALESCE(b.is_delete, 0), + b.update_time = COALESCE(b.update_time, NOW()) +WHERE b.status IS NULL + OR b.is_delete IS NULL + OR b.update_time IS NULL; + +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); +CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); +CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); +CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); +CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_business_event_outbox +( + id bigint unsigned auto_increment comment '事件ID' + primary key, + event_key varchar(160) not null comment '事件幂等键', + event_type varchar(64) not null comment '事件类型', + business_type varchar(64) not null comment '业务类型', + business_id bigint unsigned not null comment '业务ID', + payload_json text null comment '事件载荷', + status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', + retry_count int unsigned default 0 not null comment '重试次数', + next_retry_time datetime null comment '下次重试时间', + last_error varchar(500) null comment '最近错误', + claimed_at datetime null comment '认领时间', + processed_at datetime null comment '处理完成时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除' +) + comment '业务事件Outbox表'; + +CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); +CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); + +-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. +-- EXPIRED + +-- ======================================== +-- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth +-- ======================================== + +CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); +CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_artist_schedule +( + id bigint unsigned NOT NULL COMMENT '排班ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + work_date date NOT NULL COMMENT '工作日期', + start_time time NOT NULL COMMENT '班次开始时间', + end_time time NOT NULL COMMENT '班次结束时间', + slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', + capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', + remark varchar(255) NULL COMMENT '排班备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '美甲师排班表'; + +CREATE TABLE IF NOT EXISTS t_appointment_reservation +( + id bigint unsigned NOT NULL COMMENT '预约占用ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + product_title varchar(200) NULL COMMENT '预约作品标题快照', + appointment_start_time datetime NOT NULL COMMENT '预约开始时间', + appointment_end_time datetime NOT NULL COMMENT '预约结束时间', + status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', + client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单预约时段占用表'; + +CREATE TABLE IF NOT EXISTS t_payment_order +( + id bigint unsigned NOT NULL COMMENT '支付单ID', + pay_no varchar(64) NOT NULL COMMENT '支付单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_no varchar(64) NOT NULL COMMENT '订单号快照', + user_id bigint unsigned NOT NULL COMMENT '支付用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', + status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', + pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', + paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', + pay_time datetime NULL COMMENT '支付完成时间', + expire_time datetime NULL COMMENT '支付单过期时间', + operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', + remark varchar(255) NULL COMMENT '支付备注', + idempotency_key varchar(160) NULL COMMENT '支付幂等键', + raw_payload text NULL COMMENT '支付渠道原始载荷', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单支付单表'; + +CREATE TABLE IF NOT EXISTS t_refund_order +( + id bigint unsigned NOT NULL COMMENT '退款单ID', + refund_no varchar(64) NOT NULL COMMENT '退款单号', + after_sale_id bigint unsigned NULL COMMENT '售后单ID', + payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', + refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + refund_time datetime NULL COMMENT '退款完成时间', + channel varchar(32) NULL COMMENT '退款渠道', + external_refund_no varchar(64) NULL COMMENT '外部退款单号', + fail_reason varchar(255) NULL COMMENT '失败原因或备注', + idempotency_key varchar(160) NULL COMMENT '退款幂等键', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单退款单表'; + +CREATE TABLE IF NOT EXISTS t_after_sale +( + id bigint unsigned NOT NULL COMMENT '售后单ID', + after_sale_no varchar(64) NOT NULL COMMENT '售后单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NULL COMMENT '订单项ID', + user_id bigint unsigned NOT NULL COMMENT '申请用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + type varchar(32) NOT NULL COMMENT '售后类型', + reason varchar(1000) NULL COMMENT '申请原因', + refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', + audit_user_id bigint unsigned NULL COMMENT '审核人ID', + audit_reason varchar(500) NULL COMMENT '审核说明', + audit_time datetime NULL COMMENT '审核时间', + refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单售后申请表'; + +CREATE TABLE IF NOT EXISTS t_after_sale_log +( + id bigint unsigned NOT NULL COMMENT '售后日志ID', + after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', + action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', + from_status varchar(20) NULL COMMENT '变更前状态', + to_status varchar(20) NULL COMMENT '变更后状态', + operator_id bigint unsigned NULL COMMENT '操作人ID', + operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', + remark varchar(500) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '订单售后流转日志表'; + +CREATE TABLE IF NOT EXISTS t_inventory_item +( + id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + category varchar(50) NULL COMMENT '物料分类', + item_name varchar(100) NOT NULL COMMENT '物料名称', + unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', + stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', + warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '门店库存物料表'; + +CREATE TABLE IF NOT EXISTS t_inventory_record +( + id bigint unsigned NOT NULL COMMENT '库存流水ID', + inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', + change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', + before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', + after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', + operator_id bigint unsigned NULL COMMENT '操作人ID', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '门店库存变动流水表'; + +CREATE TABLE IF NOT EXISTS t_campaign +( + id bigint unsigned NOT NULL COMMENT '营销活动ID', + shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', + title varchar(120) NOT NULL COMMENT '活动标题', + description varchar(1000) NULL COMMENT '活动说明', + scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', + product_ids text NULL COMMENT '关联作品ID集合', + coupon_ids text NULL COMMENT '关联优惠券ID集合', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', + start_time datetime NULL COMMENT '开始时间', + end_time datetime NULL COMMENT '结束时间', + sort_order int NOT NULL DEFAULT 100 COMMENT '排序', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '营销活动配置表'; + +CREATE TABLE IF NOT EXISTS t_user_growth_record +( + id bigint unsigned NOT NULL COMMENT '成长值记录ID', + user_id bigint unsigned NOT NULL COMMENT '用户ID', + source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', + source_id bigint unsigned NULL COMMENT '来源业务ID', + growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '用户成长值流水表'; + +CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); +CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), + (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), + (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), + (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), + (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), + (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), + (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), + (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), + (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), + (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), + (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), + (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), + (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), + (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), + (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), + (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); + +CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); +CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); +CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); + +CREATE TABLE IF NOT EXISTS t_order_quote_message +( + id bigint unsigned auto_increment comment '报价交互消息主键' + primary key, + order_id bigint unsigned not null comment '订单ID', + actor_id bigint unsigned null comment '操作人ID', + actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', + action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', + remark varchar(500) null comment '备注', + items_snapshot text null comment '订单项报价快照JSON', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单询价报价交互消息表'; + +CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'jayucloud-salon' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='JayuCloud Salon 按业务场景投递 MessageHub 的配置'; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 +-- 来源:2026-03-20_init_admin_permission_template.sql +-- ======================================== + +SET NAMES utf8mb4; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + ('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + ('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + ('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + ('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + ('announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_user ( + shop_id, + nickname, + account, + phone_verified, + email_verified, + password, + signature, + level, + type, + vip_id, + create_time, + update_time, + is_delete, + status +) +SELECT + 0, + '系统管理员', + 'xiaowang', + 0, + 0, + '$2a$10$3ZC5HHVK6EYIfkjcU9IHZulGXwNZhy.6LU85HRJC9A.3LHm0IEdMO', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +-- ======================================== +-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT +-- 说明: +-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 +-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 +-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 +-- ======================================== + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) +BEGIN + DECLARE v_column_type VARCHAR(128) DEFAULT NULL; + DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; + DECLARE v_extra VARCHAR(128) DEFAULT NULL; + + SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA + INTO v_column_type, v_column_comment, v_extra + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = 'id' + LIMIT 1; + + IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN + SET @alter_sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', + v_column_type, + ' NOT NULL' + ); + + IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN + SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); + END IF; + + PREPARE stmt FROM @alter_sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); +CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); +CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); +CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); +CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); +CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); +CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); +CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); +CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); +CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); +CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NULL COMMENT '用户ID;注销后解除身份关联,保留最小同意凭证', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +ALTER TABLE t_user_agreement_consent MODIFY COLUMN user_id bigint NULL COMMENT '用户ID;注销后解除身份关联,保留最小同意凭证'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +SET @system_parameter_enabled_missing := ( + SELECT COUNT(1) = 0 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_system_parameter_config' + AND COLUMN_NAME = 'enabled' +); +SET @system_parameter_enabled_sql := IF( + @system_parameter_enabled_missing, + 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', + 'SELECT 1' +); +PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; +EXECUTE stmt_system_parameter_enabled; +DEALLOCATE PREPARE stmt_system_parameter_enabled; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.10.21', '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。登录前须阅读并明确同意本协议与隐私政策;不同意时不会交换微信登录凭证,也不能继续使用。微信 OpenID 用于识别账号,昵称和头像为可选资料,手机号绑定为可选,不绑定不影响基础工作台使用。页面中的预约金额仅为门店经营记录,不代表本平台已经收款;当前不提供充值、订阅或平台虚拟权益购买。请仅提交有权处理的业务信息,并确保上传的文字、图片具备合法来源。可在账号设置申请注销;管理员确认门店移交或归档后清理账号资料和登录身份。依法及履行必要业务所需的订单、预约和经营记录可能以匿名化形式保留,目标保留期为五年。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.10.21', '我们处理信息仅用于提供门店工作台:登录时由用户主动同意后调用微信登录并接收 OpenID;昵称、头像仅在用户主动补充或更新时处理;手机号仅在用户主动绑定或更换时获取,用于账号找回和必要的业务联系,不用于营销。店长和员工可能为预约及订单录入客户姓名、可选手机号和服务信息,这些是门店业务资料,不是客户小程序账号。我们不主动采集设备标识、IMEI、MAC、定位或麦克风信息;选择图片只在用户主动操作后调用。账号、客户和订单快照中的手机号使用 AES-GCM 加密保存,并用独立 HMAC 索引完成查重;常规界面、日志和导出对手机号脱敏。服务运行可能使用微信登录、短信服务商、消息通道和按环境配置的对象存储服务。用户可在账号设置申请注销或解绑手机号;注销申请经审核后撤销会话并在目标十五个工作日内删除或匿名化个人资料,订单、预约及经营凭证按产品目标保留五年并解除账号身份关联。头像、作品、评论等内容目前由本地模拟审核流程处理,结果仅用于开发验证,不代表已接入微信内容安全审核,正式上线前将另行完成实际审核平台和隐私指引配置。隐私内容上线前须由运营方核实数据处理方、时限和适用法律要求。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), + (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), + (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), + (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0), + (313931273555139010, 'SMS', 'SMS_PROVIDER', '短信供应商', 'SPUG', 1, '全局切换短信供应商时同步验证码模板和 MessageHub 通道', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), + is_delete = 0, + update_time = NOW(); + +-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + 313931273556000000 + p.id, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 最终权限兜底:确保平台管理员拥有当前权限目录中的全部基础权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + (CAST(u.id AS UNSIGNED) << 20) + (CAST(p.id AS UNSIGNED) & 1048575), + u.id, + p.id, + NOW(), + NOW(), + 0, + 0, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +-- 排班规则与例外 +CREATE TABLE IF NOT EXISTS t_artist_schedule_rule ( + id bigint unsigned NOT NULL COMMENT '排班规则ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', preset_type varchar(32) NOT NULL COMMENT '预设类型', work_days varchar(32) NOT NULL COMMENT '工作星期,1-7逗号分隔', start_time time NOT NULL COMMENT '常规开始时间', end_time time NOT NULL COMMENT '常规结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1启用,0停用', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_rule_artist (shop_id, artist_id, is_delete), KEY idx_artist_schedule_rule_shop_status (shop_id, status, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师常规排班规则表'; +CREATE TABLE IF NOT EXISTS t_artist_schedule_exception ( + id bigint unsigned NOT NULL COMMENT '排班例外ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', work_date date NOT NULL COMMENT '例外日期', exception_type varchar(32) NOT NULL COMMENT '例外类型:REST/EXTRA_WORK/CHANGE_SHIFT', start_time time NULL COMMENT '例外开始时间', end_time time NULL COMMENT '例外结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_exception_date (shop_id, artist_id, work_date, is_delete), KEY idx_artist_schedule_exception_artist_date (artist_id, work_date, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师排班例外表'; + +-- 店长员工审核提醒参数。 +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, + create_time, update_time, is_delete +) +VALUES ( + 313931273555139020, 'WORKBENCH', 'MANAGER_REGISTRATION_REVIEW_NOTICE', + '店长员工审核提醒', 'true', 1, + '控制店长登录小程序后是否显式提示当前门店的待审核员工申请', + NOW(), NOW(), 0 +) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +-- 历史命名兼容修正:整合已部署库迁移所需的数据修正,空库执行时无副作用。 +START TRANSACTION; +UPDATE t_messagehub_push_config +SET source_system = 'jayucloud-salon' +WHERE source_system IN ('fingertipdesigner', 'fingertip-designer', 'FingertipDesigner'); +ALTER TABLE t_messagehub_push_config +COMMENT = 'JayuCloud Salon 按业务场景投递 MessageHub 的配置'; +COMMIT; +SET FOREIGN_KEY_CHECKS = 0; +SET FOREIGN_KEY_CHECKS = 1; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql new file mode 100644 index 00000000..ee34e64c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS t_moderation_callback_forward ( + id BIGINT NOT NULL COMMENT '主键ID', + trace_id VARCHAR(128) NOT NULL COMMENT '微信异步图片审核任务标识 trace_id', + source_env VARCHAR(16) NOT NULL COMMENT '实际收到微信回调的部署环境', + target_env VARCHAR(16) NULL COMMENT '应处理该回调的部署环境', + extra_json VARCHAR(256) NULL COMMENT '微信回调透传的 extra 原始内容', + payload LONGTEXT NULL COMMENT '回调解密后的完整报文,仅用于补偿重放', + status VARCHAR(16) NOT NULL COMMENT 'PENDING/SUCCESS/RETRY/FAILED/NO_ENV/TARGET_MISSING', + retry_count INT NOT NULL DEFAULT 0 COMMENT '已重试次数', + last_error VARCHAR(500) NULL COMMENT '最近一次失败原因(脱敏)', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_moderation_callback_forward_trace (trace_id), + KEY idx_moderation_callback_forward_status (status, updated_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信审核回调跨环境转发记录'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V21__协议补充后台管理端豁免说明_20261105.sql b/JC-Salon-Core/src/main/resources/db/migration/V21__协议补充后台管理端豁免说明_20261105.sql new file mode 100644 index 00000000..331ced8b --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V21__协议补充后台管理端豁免说明_20261105.sql @@ -0,0 +1,28 @@ +-- 协议补充后台管理端豁免说明:仅为澄清性文字补充,不新增协议版本、不改变版本号与生效日期。 +-- 背景:后台管理端已豁免协议版本校验,协议正文需同步说明后台管理端不适用重新确认流程。 +-- 幂等:REPLACE 的匹配串以句号结尾,替换后原句号变为分号,重复执行不会再次匹配或二次拼接。 +-- 注意:V17/V18/V19/V20 已执行,不得修改;本文件只更新当前生效版本(status = 1)的正文。 + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '协议发生重要变更时,我们会通过小程序提示并重新征得同意。', + '协议发生重要变更时,我们会通过小程序提示并重新征得同意;后台管理端(运营管理后台)不适用重新确认流程,平台运营人员登录后台即视为已知悉当前版本。' + ), + update_time = NOW() +WHERE agreement_type = 'USER_TERMS' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%协议发生重要变更时,我们会通过小程序提示并重新征得同意。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。', + '处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知;后台管理端(运营管理后台)不适用重新确认流程。' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。%'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V22__微信审核回调异步认领任务补偿_20261107.sql b/JC-Salon-Core/src/main/resources/db/migration/V22__微信审核回调异步认领任务补偿_20261107.sql new file mode 100644 index 00000000..42f1e413 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V22__微信审核回调异步认领任务补偿_20261107.sql @@ -0,0 +1,12 @@ +ALTER TABLE t_moderation_callback_forward + MODIFY COLUMN status VARCHAR(16) NOT NULL COMMENT 'PENDING/PROCESSING/SUCCESS/NO_ENV/FAILED/DEAD', + ADD COLUMN next_attempt_at DATETIME NULL COMMENT '下次补偿执行时间', + ADD COLUMN locked_by VARCHAR(100) NULL COMMENT '处理实例与锁标识', + ADD COLUMN locked_at DATETIME NULL COMMENT '最近抢锁时间', + ADD COLUMN finished_at DATETIME NULL COMMENT '终态完成时间', + ADD KEY idx_moderation_callback_forward_due (status, next_attempt_at); + +UPDATE t_moderation_callback_forward + SET next_attempt_at = updated_at + WHERE status IN ('PENDING', 'RETRY', 'NO_ENV', 'FAILED', 'TARGET_MISSING') + AND next_attempt_at IS NULL; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql b/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql new file mode 100644 index 00000000..ea123a57 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql @@ -0,0 +1,216 @@ +ALTER TABLE t_content_moderation_record + ADD COLUMN version_no int NOT NULL DEFAULT 1 COMMENT '业务内容版本号', + ADD COLUMN image_count int NOT NULL DEFAULT 0 COMMENT '该版本图片总数', + ADD COLUMN text_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '文字审核状态', + ADD COLUMN text_content mediumtext NULL COMMENT '待审文字内容', + ADD COLUMN next_retry_at datetime NULL COMMENT '下次自动重试时间'; + +ALTER TABLE t_product + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '公开审核状态'; +ALTER TABLE t_comment + ADD COLUMN moderation_version int NOT NULL DEFAULT 1 COMMENT '评论审核版本号'; +ALTER TABLE t_shop + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '门店展示资料审核状态'; +ALTER TABLE t_announcement + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '公告审核状态', + ADD COLUMN image_file_ids text NULL COMMENT '公告图片文件ID集合,多个ID以逗号分隔'; +ALTER TABLE t_system_message + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '人工消息审核状态;自动事务消息默认通过'; +ALTER TABLE t_user + ADD COLUMN profile_moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '公开个人资料审核状态'; +ALTER TABLE t_order_artist_review + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '评价审核状态:PENDING/APPROVED/REJECTED/RETRY'; +ALTER TABLE t_effect_diagram + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '效果图审核状态:PENDING/APPROVED/REJECTED/RETRY'; + +CREATE TEMPORARY TABLE tmp_content_moderation_sequence ( + seq int NOT NULL PRIMARY KEY +); +INSERT INTO tmp_content_moderation_sequence (seq) +SELECT ones.n + tens.n * 10 + hundreds.n * 100 + 1 +FROM (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) ones +CROSS JOIN (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) tens +CROSS JOIN (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) hundreds; + +CREATE TABLE t_content_moderation_image_task ( + id bigint unsigned NOT NULL COMMENT '审核图片任务ID', + record_id bigint unsigned NOT NULL COMMENT '内容审核版本ID', + file_id bigint unsigned NOT NULL COMMENT '对象存储文件ID', + provider_task_id varchar(100) NULL COMMENT '微信异步审核任务标识', + status varchar(20) NOT NULL COMMENT '图片审核状态:PENDING/APPROVED/REJECTED/RETRY', + result_code varchar(80) NULL COMMENT '图片审核结果代码', + reason varchar(500) NULL COMMENT '图片审核说明', + attempt_count int NOT NULL DEFAULT 0 COMMENT '提交尝试次数', + next_retry_at datetime NULL COMMENT '下次重试时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_content_moderation_image_provider_task (provider_task_id), + KEY idx_content_moderation_image_record (record_id, status), + KEY idx_content_moderation_image_file (file_id), + KEY idx_content_moderation_image_retry (status, next_retry_at), + CONSTRAINT fk_content_moderation_image_record FOREIGN KEY (record_id) REFERENCES t_content_moderation_record (id) +) COMMENT='内容版本逐图审核与微信异步任务'; + +CREATE INDEX idx_product_moderation_public ON t_product (shop_id, moderation_status, front_visible, is_delete); +CREATE INDEX idx_shop_moderation_public ON t_shop (moderation_status, status, is_delete); +CREATE INDEX idx_announcement_moderation_public ON t_announcement (moderation_status, status, publish_time); +CREATE INDEX idx_system_message_moderation_public ON t_system_message (moderation_status, status, publish_time); +CREATE INDEX idx_order_artist_review_moderation_public ON t_order_artist_review (moderation_status, status, is_delete); +CREATE INDEX idx_effect_diagram_moderation_public ON t_effect_diagram (product_id, moderation_status, is_delete); + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:PRODUCT:', p.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'PRODUCT', p.id, NULL, 1, + (LENGTH(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(p.image_file_ids, '') = '', 0, 1)), + 'PENDING', CONCAT_WS(CHAR(10), p.title, p.description, p.target_audience, p.precautions, p.tags), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开作品等待审核', + JSON_OBJECT('shopId', p.shop_id, 'title', p.title, 'description', p.description, 'targetAudience', p.target_audience, 'precautions', p.precautions, 'imageFileIds', p.image_file_ids, 'price', p.price, 'tags', p.tags, 'approximateDuration', p.approximate_duration, 'bookableArtists', p.bookable_artists, 'availableCoupons', p.available_coupons, 'frontVisible', p.front_visible), 0, NOW(), NOW() +FROM t_product p WHERE p.is_delete = 0 AND p.front_visible = 1 AND COALESCE(p.source_type, '') <> 'MANAGER_APPOINTMENT'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('PRODUCT:', p.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:PRODUCT:', p.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量公开作品图片等待审核', 0, NOW(), NOW() +FROM t_product p +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(p.image_file_ids, '') = '', 0, 1)) +WHERE p.is_delete = 0 AND p.front_visible = 1 AND COALESCE(p.source_type, '') <> 'MANAGER_APPOINTMENT' + AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(p.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_product p JOIN t_content_moderation_record r ON r.content_type = 'PRODUCT' AND r.business_id = p.id SET p.moderation_status = 'PENDING', p.front_visible = 0; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SHOP:', s.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SHOP', s.id, NULL, 1, + (LENGTH(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, ''))) - LENGTH(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ',', '')) + IF(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')) = '', 0, 1)), + 'PENDING', CONCAT_WS(CHAR(10), s.shop_name, s.description, s.address, s.business_hours), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量门店展示资料等待审核', + JSON_OBJECT('shopName', s.shop_name, 'description', s.description, 'address', s.address, 'businessHours', s.business_hours, 'coverImageFileId', s.cover_image_file_id, 'imageFileIds', s.image_file_ids, 'themeBackgroundImageFileId', s.theme_background_image_file_id), 0, NOW(), NOW() +FROM t_shop s WHERE s.is_delete = 0 AND s.status = 1; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:SHOP:', s.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SHOP:', s.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量门店图片等待审核', 0, NOW(), NOW() +FROM t_shop s +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, ''))) - LENGTH(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ',', '')) + IF(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')) = '', 0, 1)) +WHERE s.is_delete = 0 AND s.status = 1 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_shop s JOIN t_content_moderation_record r ON r.content_type = 'SHOP' AND r.business_id = s.id SET s.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:COMMENT:', c.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'COMMENT', c.id, c.user_id, 1, + (LENGTH(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(c.image_file_ids, '') = '', 0, 1)), + 'PENDING', c.comment_content, 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开评论等待审核', + JSON_OBJECT('commentContent', c.comment_content, 'imageFileIds', c.image_file_ids), 0, NOW(), NOW() +FROM t_comment c WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:COMMENT:', c.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:COMMENT:', c.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量评论图片等待审核', 0, NOW(), NOW() +FROM t_comment c +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(c.image_file_ids, '') = '', 0, 1)) +WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED' AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(c.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_comment c JOIN t_content_moderation_record r ON r.content_type = 'COMMENT' AND r.business_id = c.id SET c.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ANNOUNCEMENT:', a.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'ANNOUNCEMENT', a.id, a.publisher_id, 1, + (CASE WHEN TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) REGEXP '^[0-9]+(,[0-9]+)*$' THEN (LENGTH(REPLACE(a.image_file_ids, ' ', '')) - LENGTH(REPLACE(REPLACE(a.image_file_ids, ' ', ''), ',', '')) + 1) ELSE 0 END), + 'PENDING', CONCAT_WS(CHAR(10), a.title, a.content), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开公告等待审核', + JSON_OBJECT('title', a.title, 'content', a.content, 'imageFileIds', a.image_file_ids, 'status', a.status), 0, NOW(), NOW() +FROM t_announcement a WHERE a.is_delete = 0 AND a.status = 1; +UPDATE t_announcement a JOIN t_content_moderation_record r ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id SET a.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:ANNOUNCEMENT:', a.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ANNOUNCEMENT:', a.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量公告图片等待审核', 0, NOW(), NOW() +FROM t_announcement a +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(a.image_file_ids, '') = '', 0, 1)) +WHERE a.is_delete = 0 AND a.status = 1 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SYSTEM_MESSAGE', m.id, m.publisher_id, 1, + IF(m.image_file_id IS NULL, 0, 1), 'PENDING', CONCAT_WS(CHAR(10), m.title, m.content), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量人工发布消息等待审核', + JSON_OBJECT('title', m.title, 'content', m.content, 'imageFileId', m.image_file_id, 'status', m.status), 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NULL; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:SYSTEM_MESSAGE:', m.id, ':1'), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), m.image_file_id, 'PENDING', 'LEGACY_REVIEW', '存量人工消息图片等待审核', 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NULL AND m.image_file_id IS NOT NULL; +UPDATE t_system_message m JOIN t_content_moderation_record r ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id SET m.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:USER_PROFILE:', u.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'USER_PROFILE', u.id, u.id, 1, + (SELECT COUNT(DISTINCT profile_file.id) FROM t_object_storage_file profile_file + WHERE profile_file.file_url IN (u.avatar, u.wechat_qr_code) + OR profile_file.primary_url IN (u.avatar, u.wechat_qr_code) + OR profile_file.object_name IN (u.avatar, u.wechat_qr_code)), 'PENDING', CONCAT_WS(CHAR(10), u.nickname, u.signature), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量个人资料等待审核', + JSON_OBJECT( + 'nickname', u.nickname, + 'signature', u.signature, + 'avatar', CASE WHEN EXISTS (SELECT 1 FROM t_object_storage_file avatar_file WHERE avatar_file.file_url = u.avatar OR avatar_file.primary_url = u.avatar OR avatar_file.object_name = u.avatar) THEN u.avatar ELSE NULL END, + 'wechatQrCode', CASE WHEN EXISTS (SELECT 1 FROM t_object_storage_file qr_file WHERE qr_file.file_url = u.wechat_qr_code OR qr_file.primary_url = u.wechat_qr_code OR qr_file.object_name = u.wechat_qr_code) THEN u.wechat_qr_code ELSE NULL END + ), 0, NOW(), NOW() +FROM t_user u WHERE u.is_delete = 0 AND u.status = 1 + AND (u.nickname IS NOT NULL OR u.signature IS NOT NULL OR u.avatar IS NOT NULL OR u.wechat_qr_code IS NOT NULL); +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:USER_PROFILE:', u.id, ':', f.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:USER_PROFILE:', u.id), 256), 1, 15), 16, 10) AS UNSIGNED), f.id, 'PENDING', 'LEGACY_REVIEW', '存量个人资料图片等待审核', 0, NOW(), NOW() +FROM t_user u JOIN t_object_storage_file f + ON f.file_url IN (u.avatar, u.wechat_qr_code) + OR f.primary_url IN (u.avatar, u.wechat_qr_code) + OR f.object_name IN (u.avatar, u.wechat_qr_code) +WHERE u.is_delete = 0 AND u.status = 1 AND (u.avatar IS NOT NULL OR u.wechat_qr_code IS NOT NULL) +GROUP BY u.id, f.id; +UPDATE t_user u JOIN t_content_moderation_record r ON r.content_type = 'USER_PROFILE' AND r.business_id = u.id SET u.profile_moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:AUTO_SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SYSTEM_MESSAGE', m.id, m.publisher_id, 1, 0, + 'APPROVED', '', 'APPROVED', 'LEGACY_SYSTEM', 'AUTO_TRANSACTION_MESSAGE', '自动事务消息不送审', NULL, 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NOT NULL; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ORDER_ARTIST_REVIEW:', r.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'ORDER_ARTIST_REVIEW', r.id, r.customer_id, 1, + (LENGTH(REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(r.image_file_ids, '') = '', 0, 1)), + 'PENDING', r.content, 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量订单评价等待审核', + JSON_OBJECT('content', r.content, 'imageFileIds', r.image_file_ids), 0, NOW(), NOW() +FROM t_order_artist_review r WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED'; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:ORDER_ARTIST_REVIEW:', r.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ORDER_ARTIST_REVIEW:', r.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量订单评价图片等待审核', 0, NOW(), NOW() +FROM t_order_artist_review r +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(r.image_file_ids, '') = '', 0, 1)) +WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(r.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; +UPDATE t_order_artist_review r JOIN t_content_moderation_record m ON m.content_type = 'ORDER_ARTIST_REVIEW' AND m.business_id = r.id SET r.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:EFFECT_DIAGRAM:', e.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'EFFECT_DIAGRAM', e.id, NULL, 1, + (CASE WHEN TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) REGEXP '^[0-9]+(,[0-9]+)*$' THEN (LENGTH(REPLACE(e.image_file_ids, ' ', '')) - LENGTH(REPLACE(REPLACE(e.image_file_ids, ' ', ''), ',', '')) + 1) ELSE 0 END), + 'PENDING', CONCAT_WS(CHAR(10), e.category, e.description, e.tag), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量效果图等待审核', + JSON_OBJECT('productId', e.product_id, 'category', e.category, 'imageFileIds', e.image_file_ids, 'description', e.description, 'price', e.price, 'duration', e.duration, 'tag', e.tag), 0, NOW(), NOW() +FROM t_effect_diagram e WHERE e.is_delete = 0; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:EFFECT_DIAGRAM:', e.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:EFFECT_DIAGRAM:', e.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量效果图图片等待审核', 0, NOW(), NOW() +FROM t_effect_diagram e +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(e.image_file_ids, '') = '', 0, 1)) +WHERE e.is_delete = 0 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(e.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; +UPDATE t_effect_diagram e JOIN t_content_moderation_record m ON m.content_type = 'EFFECT_DIAGRAM' AND m.business_id = e.id SET e.moderation_status = 'PENDING'; + +DROP TEMPORARY TABLE tmp_content_moderation_sequence; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql new file mode 100644 index 00000000..b9073f52 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql @@ -0,0 +1,176 @@ +ALTER TABLE t_comment + MODIFY COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' + COMMENT '内容审核状态:PENDING/APPROVED/REJECTED/RETRY'; + +CREATE TEMPORARY TABLE tmp_content_moderation_invalid_legacy_record ( + record_id bigint unsigned NOT NULL PRIMARY KEY +); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_product p ON r.content_type = 'PRODUCT' AND r.business_id = p.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_comment c ON r.content_type = 'COMMENT' AND r.business_id = c.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_order_artist_review business_review ON r.content_type = 'ORDER_ARTIST_REVIEW' AND r.business_id = business_review.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_announcement a ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_effect_diagram e ON r.content_type = 'EFFECT_DIAGRAM' AND r.business_id = e.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_shop s ON r.content_type = 'SHOP' AND r.business_id = s.id +WHERE r.provider = 'LEGACY_REVIEW' + AND ( + (COALESCE(TRIM(s.cover_image_file_id), '') <> '' AND TRIM(s.cover_image_file_id) NOT REGEXP '^[0-9]+$') + OR (COALESCE(TRIM(s.theme_background_image_file_id), '') <> '' AND TRIM(s.theme_background_image_file_id) NOT REGEXP '^[0-9]+$') + OR (COALESCE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), '') <> '' AND ( + TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + )) + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_system_message m ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id +LEFT JOIN t_object_storage_file f ON f.id = m.image_file_id AND f.status = 1 +WHERE r.provider = 'LEGACY_REVIEW' AND m.image_file_id IS NOT NULL AND f.id IS NULL; + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT DISTINCT r.id +FROM t_content_moderation_record r +JOIN t_content_moderation_image_task task ON task.record_id = r.id +LEFT JOIN t_object_storage_file f ON f.id = task.file_id AND f.status = 1 +WHERE r.provider = 'LEGACY_REVIEW' AND f.id IS NULL; + +UPDATE t_content_moderation_image_task task +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = task.record_id +SET task.status = 'REJECTED', + task.provider_task_id = NULL, + task.result_code = 'LEGACY_IMAGE_REFERENCE_INVALID', + task.reason = '历史图片引用无法安全核验,内容保持隐藏', + task.next_retry_at = NULL; + +UPDATE t_content_moderation_record r +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET r.status = 'REJECTED', + r.text_status = 'REJECTED', + r.result_code = 'LEGACY_IMAGE_REFERENCE_INVALID', + r.reason = '历史图片引用格式无效、超出迁移范围或文件不可用,内容保持隐藏', + r.payload_json = CASE r.content_type + WHEN 'SHOP' THEN JSON_SET(r.payload_json, '$.coverImageFileId', NULL, '$.imageFileIds', NULL, '$.themeBackgroundImageFileId', NULL) + WHEN 'USER_PROFILE' THEN JSON_SET(r.payload_json, '$.avatar', NULL, '$.wechatQrCode', NULL) + WHEN 'SYSTEM_MESSAGE' THEN JSON_SET(r.payload_json, '$.imageFileId', NULL) + ELSE JSON_SET(r.payload_json, '$.imageFileIds', NULL) + END; + +UPDATE t_product p +JOIN t_content_moderation_record r ON r.content_type = 'PRODUCT' AND r.business_id = p.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET p.moderation_status = 'REJECTED', p.front_visible = 0; + +UPDATE t_comment c +JOIN t_content_moderation_record r ON r.content_type = 'COMMENT' AND r.business_id = c.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET c.moderation_status = 'REJECTED'; + +UPDATE t_order_artist_review business_review +JOIN t_content_moderation_record r ON r.content_type = 'ORDER_ARTIST_REVIEW' AND r.business_id = business_review.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET business_review.moderation_status = 'REJECTED'; + +UPDATE t_announcement a +JOIN t_content_moderation_record r ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET a.moderation_status = 'REJECTED', a.status = 0; + +UPDATE t_effect_diagram e +JOIN t_content_moderation_record r ON r.content_type = 'EFFECT_DIAGRAM' AND r.business_id = e.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET e.moderation_status = 'REJECTED'; + +UPDATE t_shop s +JOIN t_content_moderation_record r ON r.content_type = 'SHOP' AND r.business_id = s.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET s.moderation_status = 'REJECTED'; + +UPDATE t_system_message m +JOIN t_content_moderation_record r ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET m.moderation_status = 'REJECTED', m.status = 0; + +UPDATE t_user u +JOIN t_content_moderation_record r ON r.content_type = 'USER_PROFILE' AND r.business_id = u.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET u.profile_moderation_status = 'REJECTED'; + +UPDATE t_content_moderation_record r +SET r.image_count = (SELECT COUNT(1) FROM t_content_moderation_image_task task WHERE task.record_id = r.id) +WHERE r.provider = 'LEGACY_REVIEW'; + +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) +VALUES + (313931273555140001, 'USER_TERMS', '用户协议', '2026.10.25', + '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。登录前须阅读并明确同意本协议与隐私政策;不同意时不会交换微信登录凭证,也不能继续使用。微信 OpenID 用于识别账号,昵称和头像为可选资料,手机号绑定为可选,不绑定不影响基础工作台使用。头像、作品、评论、店铺展示资料、公告和人工发布的消息在公开前进行内容安全审核。DEV 使用本地模拟服务;其他环境未启用审核平台时保持隔离或进入人工复核;只有完成审核资质、回调域名、隐私指引和环境配置后启用微信审核服务时,必要文本、作者 OpenID 与图片短期授权地址才会提交给微信。拒绝、待复核、无法核验作者身份或服务异常的内容不会公开。客户业务资料及自动事务通知不纳入对外内容审核。页面中的预约金额仅为门店经营记录,不代表本平台已经收款;当前不提供充值、订阅或平台虚拟权益购买。请仅提交有权处理的业务信息并确保上传内容来源合法。可在账号设置申请注销;门店移交或归档后清理个人账号资料。必要订单、预约和经营记录按产品目标去身份化保留五年。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555140002, 'PRIVACY_POLICY', '隐私政策', '2026.10.25', + '我们处理信息仅用于提供门店工作台:用户主动同意后使用微信 OpenID 识别账号;昵称和头像仅在用户主动补充或更新时处理;手机号仅在用户主动绑定或更换时获取,用于账号找回和必要业务联系,不用于营销。店长和员工可能录入客户姓名、可选联系电话、预约和订单信息,这些是门店业务资料,不是客户的小程序账号。头像、作品文字和图片、评论文字和图片、店铺展示资料、公告及人工发布的系统消息在对外展示前进行内容安全审核;开发环境使用本地模拟服务,其他环境以实际启用的审核 Provider 为准,未配置、待复核、拒绝、缺少作者 OpenID 或服务异常时内容保持隔离。仅在已完成微信资质、回调域名和隐私指引配置并于目标环境启用微信审核服务时,必要的待审文字、作者微信 OpenID 和图片短时授权地址会提交给微信内容安全接口。客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外审核。我们不主动采集设备标识、IMEI、MAC、定位或麦克风信息。手机号使用 AES-GCM 加密并以独立 HMAC 索引支持查重,常规页面、日志和导出脱敏。用户可在账号设置申请注销或解绑手机号;注销完成后目标十五个工作日内删除或匿名化个人资料,必要订单、预约和经营记录去除账号身份关联后按产品目标保留五年。隐私内容上线前由运营方核实实际服务商、微信后台指引和适用要求。', + 1, NOW(), NOW(), NOW(), 0); + +DROP TEMPORARY TABLE tmp_content_moderation_invalid_legacy_record; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql new file mode 100644 index 00000000..bb4bd81c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql @@ -0,0 +1,46 @@ +-- Legacy shop media can span three columns. V2 expands at most 1000 files per record; +-- reject snapshots whose source references do not have an exact matching task set. +UPDATE t_content_moderation_record r +JOIN t_shop s + ON r.content_type = 'SHOP' + AND r.business_id = s.id +LEFT JOIN ( + SELECT record_id, COUNT(1) AS task_count + FROM t_content_moderation_image_task + GROUP BY record_id +) image_tasks + ON image_tasks.record_id = r.id +SET r.status = 'REJECTED', + r.text_status = 'REJECTED', + r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE', + r.reason = '门店存量图片审核任务不完整,内容保持隐藏,请重新提交资料', + r.next_retry_at = NULL +WHERE r.provider = 'LEGACY_REVIEW' + AND r.status IN ('PENDING', 'RETRY') + AND ( + CASE WHEN NULLIF(TRIM(s.cover_image_file_id), '') IS NULL THEN 0 ELSE 1 END + + CASE WHEN NULLIF(TRIM(s.theme_background_image_file_id), '') IS NULL THEN 0 ELSE 1 END + + CASE + WHEN NULLIF(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), '') IS NULL THEN 0 + ELSE LENGTH(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), ',', '')) + 1 + END + ) <> COALESCE(image_tasks.task_count, 0); + +UPDATE t_content_moderation_image_task task +JOIN t_content_moderation_record r ON r.id = task.record_id +SET task.status = 'REJECTED', + task.provider_task_id = NULL, + task.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE', + task.reason = '门店存量图片审核任务不完整,内容保持隐藏', + task.next_retry_at = NULL +WHERE r.provider = 'LEGACY_REVIEW' + AND r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE'; + +UPDATE t_shop s +JOIN t_content_moderation_record r + ON r.content_type = 'SHOP' + AND r.business_id = s.id + AND r.provider = 'LEGACY_REVIEW' + AND r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE' +SET s.moderation_status = 'REJECTED'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql new file mode 100644 index 00000000..714d0520 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql @@ -0,0 +1,87 @@ +SET @salon_v5_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_nail_artist_info' + AND COLUMN_NAME = 'moderation_status' + ), + 'SELECT 1', + 'ALTER TABLE t_nail_artist_info ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT ''PENDING'' COMMENT ''美甲师对外资料审核状态:PENDING/APPROVED/REJECTED/RETRY'' AFTER portfolio' +); +PREPARE salon_v5_stmt FROM @salon_v5_ddl; +EXECUTE salon_v5_stmt; +DEALLOCATE PREPARE salon_v5_stmt; + +SET @salon_v5_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_nail_artist_info' + AND INDEX_NAME = 'idx_nail_artist_moderation_public' + ), + 'SELECT 1', + 'CREATE INDEX idx_nail_artist_moderation_public ON t_nail_artist_info (moderation_status, status, is_delete)' +); +PREPARE salon_v5_stmt FROM @salon_v5_ddl; +EXECUTE salon_v5_stmt; +DEALLOCATE PREPARE salon_v5_stmt; + +CREATE TEMPORARY TABLE tmp_legacy_artist_profile_moderation ( + artist_info_id bigint unsigned NOT NULL PRIMARY KEY, + user_id bigint unsigned NOT NULL, + has_public_content tinyint unsigned NOT NULL, + text_content mediumtext NULL, + identity varchar(50) NULL, + experience int NULL, + skills text NULL, + portfolio text NULL +); + +INSERT INTO tmp_legacy_artist_profile_moderation + (artist_info_id, user_id, has_public_content, text_content, identity, experience, skills, portfolio) +SELECT ai.id, + ai.user_id, + CASE WHEN NULLIF(TRIM(ai.identity), '') IS NOT NULL + OR COALESCE(ai.experience, 0) > 0 + OR NULLIF(TRIM(ai.skills), '') IS NOT NULL + OR NULLIF(TRIM(ai.portfolio), '') IS NOT NULL THEN 1 ELSE 0 END, + CONCAT_WS(CHAR(10), NULLIF(TRIM(ai.identity), ''), + CASE WHEN COALESCE(ai.experience, 0) > 0 THEN CONCAT(ai.experience, '年从业经验') END, + (SELECT GROUP_CONCAT(COALESCE(NULLIF(t.display_name, ''), t.tag_name) ORDER BY t.id SEPARATOR ',') + FROM t_tag t + WHERE t.is_delete = 0 AND t.front_visible = 1 + AND FIND_IN_SET( + CONVERT(CAST(t.id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci, + CONVERT(REPLACE(COALESCE(ai.skills, ''), ' ', '') USING utf8mb4) COLLATE utf8mb4_unicode_ci + ) > 0)), + ai.identity, ai.experience, ai.skills, ai.portfolio +FROM t_nail_artist_info ai +JOIN t_user u ON u.id = ai.user_id +WHERE ai.is_delete = 0 AND u.is_delete = 0 AND u.status = 1 AND u.type IN (2, 3); + +UPDATE t_nail_artist_info ai +JOIN tmp_legacy_artist_profile_moderation legacy ON legacy.artist_info_id = ai.id +SET ai.moderation_status = CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, + provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:NAIL_ARTIST_PROFILE:', legacy.artist_info_id), 256), 1, 15), 16, 10) AS UNSIGNED), + 'NAIL_ARTIST_PROFILE', legacy.artist_info_id, NULL, 1, 0, + CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END, + legacy.text_content, + CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END, + CASE WHEN legacy.has_public_content = 1 THEN 'LEGACY_REVIEW' ELSE 'LEGACY_SYSTEM' END, + CASE WHEN legacy.has_public_content = 1 THEN 'LEGACY_PUBLIC_CONTENT' ELSE 'EMPTY_PROFILE_BASELINE' END, + CASE WHEN legacy.has_public_content = 1 THEN '存量美甲师公开资料等待审核' ELSE '系统默认美甲师资料无需审核' END, + JSON_OBJECT('identity', legacy.identity, 'experience', legacy.experience, + 'skills', legacy.skills, 'portfolio', legacy.portfolio), + 0, NOW(), NOW() +FROM tmp_legacy_artist_profile_moderation legacy +WHERE NOT EXISTS ( + SELECT 1 FROM t_content_moderation_record current_record + WHERE current_record.content_type = 'NAIL_ARTIST_PROFILE' + AND current_record.business_id = legacy.artist_info_id +); + +DROP TEMPORARY TABLE tmp_legacy_artist_profile_moderation; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V6__Salon店长审核模式与门店经营有效期_20261026.sql b/JC-Salon-Core/src/main/resources/db/migration/V6__Salon店长审核模式与门店经营有效期_20261026.sql new file mode 100644 index 00000000..5b29771a --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V6__Salon店长审核模式与门店经营有效期_20261026.sql @@ -0,0 +1,58 @@ +-- 店长申请内容审核关联与门店经营有效期。 +-- 当前没有存量门店,不执行任何门店数据回填。 + +SET @salon_v6_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_shop' + AND COLUMN_NAME = 'business_expire_time' + ), + 'SELECT 1', + 'ALTER TABLE t_shop ADD COLUMN business_expire_time datetime NULL COMMENT ''门店经营有效期,空表示未设置'' AFTER authorization_expire_time' +); +PREPARE salon_v6_stmt FROM @salon_v6_ddl; +EXECUTE salon_v6_stmt; +DEALLOCATE PREPARE salon_v6_stmt; + +SET @salon_v6_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_workbench_registration_application' + AND COLUMN_NAME = 'content_moderation_record_id' + ), + 'SELECT 1', + 'ALTER TABLE t_workbench_registration_application ADD COLUMN content_moderation_record_id bigint NULL COMMENT ''店长申请关联的确切内容审核记录ID'' AFTER reject_reason' +); +PREPARE salon_v6_stmt FROM @salon_v6_ddl; +EXECUTE salon_v6_stmt; +DEALLOCATE PREPARE salon_v6_stmt; + +SET @salon_v6_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_workbench_registration_application' + AND INDEX_NAME = 'idx_registration_moderation_record' + ), + 'SELECT 1', + 'CREATE INDEX idx_registration_moderation_record ON t_workbench_registration_application (content_moderation_record_id)' +); +PREPARE salon_v6_stmt FROM @salon_v6_ddl; +EXECUTE salon_v6_stmt; +DEALLOCATE PREPARE salon_v6_stmt; + +INSERT INTO t_system_parameter_config + (id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete) +VALUES + (CAST(CONV(SUBSTR(SHA2('SALON:WORKBENCH:MANAGER_REGISTRATION_AUTO_APPROVE', 256), 1, 15), 16, 10) AS UNSIGNED), + 'WORKBENCH', 'MANAGER_REGISTRATION_AUTO_APPROVE', '店长注册自动审核', 'false', 1, + '开启后仅在申请关联的门店资料内容审核通过时自动批准店长注册;关闭后由平台管理员人工复核', NOW(), NOW(), 0), + (CAST(CONV(SUBSTR(SHA2('SALON:SHOP:SHOP_DEFAULT_VALID_DAYS', 256), 1, 15), 16, 10) AS UNSIGNED), + 'SHOP', 'SHOP_DEFAULT_VALID_DAYS', '新门店默认有效期天数', '30', 1, + '店长注册审核通过后新门店的默认经营有效期天数,范围1-3650', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + update_time = NOW(); diff --git a/JC-Salon-Core/src/main/resources/db/migration/V7__门店默认有效期缺失修复_20261027.sql b/JC-Salon-Core/src/main/resources/db/migration/V7__门店默认有效期缺失修复_20261027.sql new file mode 100644 index 00000000..7159701d --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V7__门店默认有效期缺失修复_20261027.sql @@ -0,0 +1,55 @@ +-- 修复历史门店经营有效期为空的问题,并保证默认天数参数有有效值。 +-- 已有有效期的门店不会被覆盖;已审核通过的店长注册按审核日期起算,其余存量门店从迁移日获得默认期限。 + +INSERT INTO t_system_parameter_config + (id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete) +VALUES + (CAST(CONV(SUBSTR(SHA2('SALON:SHOP:SHOP_DEFAULT_VALID_DAYS', 256), 1, 15), 16, 10) AS UNSIGNED), + 'SHOP', 'SHOP_DEFAULT_VALID_DAYS', '新门店默认有效期天数', '30', 1, + '店长注册审核通过后新门店的默认经营有效期天数,范围1-3650', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + config_value = CASE + WHEN config_value REGEXP '^[0-9]+$' + AND CAST(config_value AS UNSIGNED) BETWEEN 1 AND 3650 THEN config_value + ELSE '30' + END, + enabled = 1, + is_delete = 0, + remark = VALUES(remark), + update_time = NOW(); + +SET @salon_shop_default_valid_days = ( + SELECT CASE + WHEN config_value REGEXP '^[0-9]+$' + AND CAST(config_value AS UNSIGNED) BETWEEN 1 AND 3650 THEN CAST(config_value AS UNSIGNED) + ELSE 30 + END + FROM t_system_parameter_config + WHERE config_group = 'SHOP' + AND config_key = 'SHOP_DEFAULT_VALID_DAYS' + AND enabled = 1 + AND is_delete = 0 + ORDER BY id + LIMIT 1 +); +SET @salon_shop_default_valid_days = COALESCE(@salon_shop_default_valid_days, 30); + +UPDATE t_shop s +LEFT JOIN ( + SELECT shop_id, MAX(reviewed_at) AS approved_at + FROM t_workbench_registration_application + WHERE role_type = 'MANAGER' + AND status = 'APPROVED' + AND is_delete = 0 + GROUP BY shop_id +) approved_application ON approved_application.shop_id = s.id +SET s.business_expire_time = TIMESTAMP( + DATE_ADD( + COALESCE(DATE(approved_application.approved_at), CURDATE()), + INTERVAL (@salon_shop_default_valid_days - 1) DAY + ), + '23:59:59' +) +WHERE s.business_expire_time IS NULL + AND s.is_delete = 0; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V8__客户联系方式去重和美甲师专属颜色_20261029.sql b/JC-Salon-Core/src/main/resources/db/migration/V8__客户联系方式去重和美甲师专属颜色_20261029.sql new file mode 100644 index 00000000..ca0b4603 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V8__客户联系方式去重和美甲师专属颜色_20261029.sql @@ -0,0 +1,117 @@ +-- 客户允许重名及重复手机号;仅姓名、微信号、手机号组合完全相同时拒绝创建。 +-- 美甲师专属颜色持久化到资料表,规划页与员工页面共用同一颜色。 + +DROP PROCEDURE IF EXISTS salon_v8_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_unique_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_drop_index_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE salon_v8_add_column_if_missing( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_definition); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v8_add_index_if_missing( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', p_columns); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v8_add_unique_index_if_missing( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', p_columns); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v8_drop_index_if_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` DROP INDEX `', p_index_name, '`'); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +DELIMITER ; + +CALL salon_v8_add_column_if_missing( + 't_user', 'customer_identity_hash', + 'char(64) NULL COMMENT ''客户姓名、微信号和手机号组合HMAC''' +); +CALL salon_v8_add_column_if_missing( + 't_user', 'active_customer_identity_hash', + 'char(64) GENERATED ALWAYS AS (CASE WHEN type = 0 AND COALESCE(is_delete, 0) = 0 THEN customer_identity_hash ELSE NULL END) STORED COMMENT ''有效客户组合身份索引''' +); +CALL salon_v8_add_column_if_missing( + 't_user', 'active_service_phone_hash', + 'char(64) GENERATED ALWAYS AS (CASE WHEN type <> 0 AND COALESCE(is_delete, 0) = 0 THEN phone_hash ELSE NULL END) STORED COMMENT ''有效員工和管理員手机号唯一索引''' +); +CALL salon_v8_add_column_if_missing( + 't_nail_artist_info', 'color', + 'varchar(7) NULL COMMENT ''美甲师规划专属颜色''' +); + +CALL salon_v8_drop_index_if_exists('t_user', 'uk_user_phone_hash'); +CALL salon_v8_add_index_if_missing('t_user', 'idx_user_phone_hash', '(`phone_hash`)'); +CALL salon_v8_add_unique_index_if_missing( + 't_user', 'uk_user_active_customer_identity_hash', '(`active_customer_identity_hash`)' +); +CALL salon_v8_add_unique_index_if_missing( + 't_user', 'uk_user_active_service_phone_hash', '(`active_service_phone_hash`)' +); + +DROP PROCEDURE IF EXISTS salon_v8_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_unique_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_drop_index_if_exists; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V9__美甲师注册申请目标员工关联_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V9__美甲师注册申请目标员工关联_20261030.sql new file mode 100644 index 00000000..73f6e926 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V9__美甲师注册申请目标员工关联_20261030.sql @@ -0,0 +1,70 @@ +-- 为美甲师申请保存审核资料与目标员工,并保证一个待审核申请最多预关联一个员工。 + +DROP PROCEDURE IF EXISTS salon_v9_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v9_add_unique_index_if_missing; + +DELIMITER $$ + +CREATE PROCEDURE salon_v9_add_column_if_missing( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @salon_v9_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_definition); + PREPARE salon_v9_stmt FROM @salon_v9_sql; + EXECUTE salon_v9_stmt; + DEALLOCATE PREPARE salon_v9_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v9_add_unique_index_if_missing( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v9_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', p_columns); + PREPARE salon_v9_stmt FROM @salon_v9_sql; + EXECUTE salon_v9_stmt; + DEALLOCATE PREPARE salon_v9_stmt; + END IF; +END$$ + +DELIMITER ; + +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'target_artist_user_id', + 'bigint NULL COMMENT ''店长预关联或审核确认的目标美甲师用户ID''' +); +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'applicant_nickname', + 'varchar(100) NULL COMMENT ''美甲师申请昵称,审核通过前不展示''' +); +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'applicant_avatar_file_id', + 'bigint NULL COMMENT ''美甲师申请头像文件ID,审核通过前不展示''' +); +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'pending_target_artist_user_id', + 'bigint GENERATED ALWAYS AS (CASE WHEN role_type = ''STAFF'' AND status = ''PENDING_MANAGER'' AND COALESCE(is_delete, 0) = 0 THEN target_artist_user_id ELSE NULL END) STORED COMMENT ''待审核申请预关联员工唯一值''' +); +CALL salon_v9_add_unique_index_if_missing( + 't_workbench_registration_application', 'uk_registration_pending_target_artist', + '(`pending_target_artist_user_id`)' +); + +DROP PROCEDURE IF EXISTS salon_v9_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v9_add_unique_index_if_missing; diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptorTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptorTest.java new file mode 100644 index 00000000..a0b7c040 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptorTest.java @@ -0,0 +1,119 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class AgreementAcceptanceInterceptorTest { + + @Mock private AgreementVersionCacheService agreementVersionCacheService; + + private AgreementAcceptanceInterceptor interceptor; + private final ObjectMapper objectMapper = new ObjectMapper(); + + @BeforeEach + void setUp() { + interceptor = new AgreementAcceptanceInterceptor(agreementVersionCacheService, objectMapper); + } + + @Test + void allowsUnauthenticatedRequest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertTrue(interceptor.preHandle(request, response, new Object())); + } + + @Test + void allowsWhenAcceptedVersionsMatchCurrent() throws Exception { + Map versions = currentVersions(); + when(agreementVersionCacheService.currentVersions()).thenReturn(versions); + when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(new LinkedHashMap<>(versions)); + + assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object())); + } + + @Test + void rejectsWithBusinessCodeWhenVersionPending() throws Exception { + Map versions = currentVersions(); + Map accepted = new LinkedHashMap<>(); + accepted.put("USER_TERMS", "2026.11.04"); + when(agreementVersionCacheService.currentVersions()).thenReturn(versions); + when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(accepted); + + MockHttpServletResponse response = new MockHttpServletResponse(); + assertFalse(interceptor.preHandle(authenticatedRequest(9L), response, new Object())); + + assertEquals(200, response.getStatus()); + JsonNode body = objectMapper.readTree(response.getContentAsString()); + assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_CODE, body.get("code").asInt()); + assertEquals("2026.11.04-R2", body.get("data").get("currentVersions").get("USER_TERMS").asText()); + assertEquals("USER_TERMS", body.get("data").get("pendingTypes").get(0).asText()); + assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE, + body.get("data").get("businessCode").asText()); + } + + @Test + void failsOpenWhenGuardComponentThrows() throws Exception { + when(agreementVersionCacheService.currentVersions()).thenThrow(new IllegalStateException("redis down")); + + assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object())); + } + + @Test + void allowsAdminPathWithoutAgreementCheck() throws Exception { + MockHttpServletRequest request = authenticatedRequest(9L); + request.setRequestURI("/admin/dashboard/overview"); + + assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), new Object())); + verifyNoInteractions(agreementVersionCacheService); + } + + @Test + void allowsLegacyAdminApiPrefixWithoutAgreementCheck() throws Exception { + MockHttpServletRequest request = authenticatedRequest(9L); + request.setRequestURI("/admin/api/dashboard/overview"); + + assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), new Object())); + verifyNoInteractions(agreementVersionCacheService); + } + + @Test + void allowsBusinessPrefixedAdminPathWithoutAgreementCheck() throws Exception { + MockHttpServletRequest request = authenticatedRequest(9L); + request.setRequestURI("/order/admin/list"); + + assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), new Object())); + verifyNoInteractions(agreementVersionCacheService); + } + + private MockHttpServletRequest authenticatedRequest(Long userId) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setAttribute("userId", userId); + return request; + } + + private Map currentVersions() { + Map versions = new LinkedHashMap<>(); + versions.put("USER_TERMS", "2026.11.04-R2"); + versions.put("PRIVACY_POLICY", "2026.11.04-R2"); + return versions; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/MetaObjectHandlerRegistrationTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/MetaObjectHandlerRegistrationTest.java new file mode 100644 index 00000000..cc4ea9d6 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/MetaObjectHandlerRegistrationTest.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.type.filter.AssignableTypeFilter; + +import java.util.Set; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +class MetaObjectHandlerRegistrationTest { + + @Test + void onlyOneMetaObjectHandlerImplementationIsRegistered() { + ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); + scanner.addIncludeFilter(new AssignableTypeFilter(MetaObjectHandler.class)); + + Set handlerClasses = scanner + .findCandidateComponents("com.xiaowang.jayucloud.salon.core") + .stream() + .map(beanDefinition -> beanDefinition.getBeanClassName()) + .collect(Collectors.toSet()); + + assertThat(handlerClasses) + .containsExactly(MyMetaObjectHandler.class.getName()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadControllerMappingTest.java new file mode 100644 index 00000000..bba8f7f8 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadControllerMappingTest.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.controller.front; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class MiniProgramObjectStorageUploadControllerMappingTest { + + @Test + void miniProgramRouteExposesOnlyDirectUpload() throws Exception { + RequestMapping mapping = MiniProgramObjectStorageUploadController.class.getAnnotation(RequestMapping.class); + assertNotNull(mapping); + assertArrayEquals(new String[]{"/object-storage-file"}, mapping.value()); + + Method uploadMethod = MiniProgramObjectStorageUploadController.class.getMethod( + "uploadFile", javax.servlet.http.HttpServletRequest.class, + org.springframework.web.multipart.MultipartFile.class); + PostMapping uploadMapping = uploadMethod.getAnnotation(PostMapping.class); + assertNotNull(uploadMapping); + assertArrayEquals(new String[]{"/upload"}, uploadMapping.value()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileControllerMappingTest.java new file mode 100644 index 00000000..b54ed962 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileControllerMappingTest.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.controller.front; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.RequestMapping; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ObjectStorageFileControllerMappingTest { + + @Test + void keepsFileManagementRoutesAdminOnly() { + RequestMapping mapping = ObjectStorageFileController.class.getAnnotation(RequestMapping.class); + + assertNotNull(mapping); + assertArrayEquals(new String[]{"/admin/object-storage-file"}, mapping.value()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProviderTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProviderTest.java new file mode 100644 index 00000000..56eae799 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProviderTest.java @@ -0,0 +1,121 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.service.impl; + +import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.config.MinioStorageConfig; +import io.minio.GetObjectArgs; +import io.minio.GetPresignedObjectUrlArgs; +import io.minio.MinioClient; +import io.minio.PutObjectArgs; +import io.minio.RemoveObjectArgs; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; + +import java.io.ByteArrayInputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class MinioObjectStorageProviderTest { + + @Test + void signsClientUrlsWithPublicEndpointWhenConfigured() throws Exception { + ObjectProvider internalClientProvider = mock(ObjectProvider.class); + MinioClient signingClient = mock(MinioClient.class); + when(signingClient.getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class))) + .thenReturn("https://sit.minio.yunail.art/jayucloud-salon-sit/style.jpg?signature=ok"); + + MinioStorageConfig config = new MinioStorageConfig(); + config.setEnabled(true); + config.setEndpoint("http://192.168.10.14:9000"); + config.setPublicEndpoint("https://sit.minio.yunail.art"); + config.setAccessKey("access-key"); + config.setSecretKey("secret-key"); + config.setBucketName("jayucloud-salon-sit"); + config.setPrivateBucket(true); + + MinioObjectStorageProvider provider = new MinioObjectStorageProvider( + internalClientProvider, + config, + new ObjectStorageProperties(), + signingClient + ); + + String signedUrl = provider.getPresignedUrl("style.jpg", 60); + + assertTrue(signedUrl.startsWith("https://sit.minio.yunail.art/jayucloud-salon-sit/style.jpg?")); + verify(internalClientProvider, org.mockito.Mockito.never()).getIfAvailable(); + verify(signingClient).getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class)); + } + + @Test + void resolvesSigningRegionThroughInternalEndpointInsteadOfPublicEndpoint() throws Exception { + MinioClient internalClient = mock(MinioClient.class); + ObjectProvider internalClientProvider = mock(ObjectProvider.class); + when(internalClientProvider.getIfAvailable()).thenReturn(internalClient); + when(internalClient.getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class))) + .thenReturn("http://192.168.10.14:9000/jayucloud-salon-sit/integration-probe/region-probe.txt" + + "?X-Amz-Algorithm=AWS4-HMAC-SHA256" + + "&X-Amz-Credential=access-key%2F20261108%2Fcn-sit-1%2Fs3%2Faws4_request" + + "&X-Amz-Date=20261108T000000Z&X-Amz-Expires=60&X-Amz-SignedHeaders=host" + + "&X-Amz-Signature=probe"); + + MinioStorageConfig config = new MinioStorageConfig(); + config.setEnabled(true); + config.setEndpoint("http://192.168.10.14:9000"); + config.setPublicEndpoint("https://sit.minio.yunail.art"); + config.setAccessKey("access-key"); + config.setSecretKey("secret-key"); + config.setBucketName("jayucloud-salon-sit"); + config.setPrivateBucket(true); + + MinioObjectStorageProvider provider = new MinioObjectStorageProvider( + internalClientProvider, + config, + new ObjectStorageProperties() + ); + + String signedUrl = provider.getPresignedUrl("style.jpg", 60); + String signedAgain = provider.getPresignedUrl("style.jpg", 60); + + assertTrue(signedUrl.startsWith("https://sit.minio.yunail.art/jayucloud-salon-sit/style.jpg?")); + assertTrue(signedUrl.contains("X-Amz-Credential=access-key%2F")); + assertTrue(signedUrl.contains("cn-sit-1%2Fs3%2Faws4_request")); + assertTrue(signedAgain.contains("cn-sit-1%2Fs3%2Faws4_request")); + verify(internalClient, org.mockito.Mockito.times(1)) + .getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class)); + } + + @Test + void usesInternalMinioClientForUploadDownloadAndDelete() throws Exception { + MinioClient internalClient = mock(MinioClient.class); + ObjectProvider internalClientProvider = mock(ObjectProvider.class); + when(internalClientProvider.getIfAvailable()).thenReturn(internalClient); + + MinioStorageConfig config = new MinioStorageConfig(); + config.setEnabled(true); + config.setEndpoint("http://192.168.10.14:9000"); + config.setAccessKey("access-key"); + config.setSecretKey("secret-key"); + config.setBucketName("jayucloud-salon-sit"); + + MinioObjectStorageProvider provider = new MinioObjectStorageProvider( + internalClientProvider, + config, + new ObjectStorageProperties() + ); + + provider.uploadStream(new ByteArrayInputStream(new byte[]{1}), 1, "image/jpeg", "style.jpg"); + provider.downloadFile("style.jpg"); + provider.deleteFile("style.jpg"); + + assertEquals("http://192.168.10.14:9000/jayucloud-salon-sit/style.jpg", provider.getFileUrl("style.jpg")); + verify(internalClient).putObject(org.mockito.ArgumentMatchers.any(PutObjectArgs.class)); + verify(internalClient).getObject(org.mockito.ArgumentMatchers.any(GetObjectArgs.class)); + verify(internalClient).removeObject(org.mockito.ArgumentMatchers.any(RemoveObjectArgs.class)); + verify(internalClient, never()).getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class)); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImplTest.java new file mode 100644 index 00000000..1527c677 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImplTest.java @@ -0,0 +1,126 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.service.impl; + +import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ObjectStorageOrchestrationServiceImplTest { + @Test + void savedOrderControlsSignedUrlsButNotUploadPreference() throws Exception { + ObjectStorageProvider minio = provider("MINIO", "minio"); + ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu"); + ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss"); + ObjectStorageProperties properties = new ObjectStorageProperties(); + properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS")); + properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS")); + ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class); + ObjectStorageReplicaDO minioReplica = replica("MINIO"); + ObjectStorageReplicaDO qiniuReplica = replica("QINIU_KODO"); + ObjectStorageReplicaDO ossReplica = replica("ALIYUN_OSS"); + when(replicaService.listByFileId(7L)).thenReturn(List.of(minioReplica, qiniuReplica, ossReplica)); + SystemParameterConfigService configService = mock(SystemParameterConfigService.class); + when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER")) + .thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO"); + ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl( + List.of(minio, qiniu, oss), properties, replicaService, configService); + + assertEquals("oss:signed", service.getPresignedUrl(7L, "object", 5)); + service.uploadPrimary(new ByteArrayInputStream(new byte[] {1}), 1, "image/png", "object"); + + verify(oss).getPresignedUrl("oss-object", 5); + verify(minio, never()).getPresignedUrl(any(), any()); + verify(minio).uploadStream(any(InputStream.class), eq(1L), eq("image/png"), eq("object")); + verify(configService).getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"); + } + + @Test + void signedUrlFallsBackToNextConfiguredReadableReplica() throws Exception { + ObjectStorageProvider minio = provider("MINIO", "minio"); + ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu"); + ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss"); + when(oss.getPresignedUrl("oss-object", 5)).thenThrow(new IllegalStateException("OSS unavailable")); + when(qiniu.getPresignedUrl("qiniu_kodo-object", 5)).thenReturn("qiniu:signed"); + ObjectStorageProperties properties = new ObjectStorageProperties(); + properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS")); + ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class); + when(replicaService.listByFileId(8L)).thenReturn(List.of( + replica("MINIO"), replica("QINIU_KODO"), replica("ALIYUN_OSS"))); + SystemParameterConfigService configService = mock(SystemParameterConfigService.class); + when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER")) + .thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO"); + ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl( + List.of(minio, qiniu, oss), properties, replicaService, configService); + + assertEquals("qiniu:signed", service.getPresignedUrl(8L, "object", 5)); + + org.mockito.InOrder providerOrder = inOrder(oss, qiniu); + providerOrder.verify(oss).getPresignedUrl("oss-object", 5); + providerOrder.verify(qiniu).getPresignedUrl("qiniu_kodo-object", 5); + verify(minio, never()).getPresignedUrl(any(), any()); + } + + @Test + void replicaRepairKeepsEnvironmentSourceReadOrder() throws Exception { + ObjectStorageProvider minio = provider("MINIO", "minio"); + ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu"); + ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss"); + when(minio.downloadFile("minio-object")).thenReturn(new ByteArrayInputStream(new byte[] {1})); + ObjectStorageProperties properties = new ObjectStorageProperties(); + properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS")); + properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS")); + ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class); + when(replicaService.listByFileId(9L)).thenReturn(List.of(replica("MINIO"), replica("QINIU_KODO"))); + SystemParameterConfigService configService = mock(SystemParameterConfigService.class); + when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER")) + .thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO"); + ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl( + List.of(minio, qiniu, oss), properties, replicaService, configService); + ObjectStorageFileDO file = new ObjectStorageFileDO(); + file.setId(9L); + file.setObjectName("object"); + file.setFileSize(1L); + file.setContentType("image/png"); + + service.completeReplicas(file); + + verify(minio).downloadFile("minio-object"); + verify(qiniu, never()).downloadFile(any()); + verify(oss).uploadStream(any(InputStream.class), eq(1L), eq("image/png"), eq("object")); + verify(configService, never()).getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"); + } + + private ObjectStorageProvider provider(String code, String name) throws Exception { + ObjectStorageProvider provider = mock(ObjectStorageProvider.class); + when(provider.providerCode()).thenReturn(code); + when(provider.isEnabled()).thenReturn(true); + when(provider.getPresignedUrl("oss-object", 5)).thenReturn("oss:signed"); + when(provider.uploadStream(any(InputStream.class), anyLong(), any(), any())).thenReturn(name + ":uploaded"); + return provider; + } + + private ObjectStorageReplicaDO replica(String code) { + ObjectStorageReplicaDO replica = new ObjectStorageReplicaDO(); + replica.setProvider(code); + replica.setObjectName(code.equals("ALIYUN_OSS") ? "oss-object" : code.toLowerCase() + "-object"); + replica.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED); + return replica; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java new file mode 100644 index 00000000..d28d07b5 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java @@ -0,0 +1,61 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.support; + +import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.config.AliyunOssConfig; +import com.xiaowang.jayucloud.salon.core.modules.file.config.MinioStorageConfig; +import com.xiaowang.jayucloud.salon.core.modules.file.config.QiniuKodoConfig; +import com.xiaowang.jayucloud.salon.core.modules.file.service.AliyunOssService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ObjectStorageUrlSupportTest { + + private ObjectStorageUrlSupport support; + private ObjectStorageOrchestrationService orchestrationService; + + @BeforeEach + void setUp() { + MinioStorageConfig minio = new MinioStorageConfig(); + minio.setEndpoint("http://192.168.10.14:9000"); + minio.setPublicEndpoint("https://sit.minio.yunail.art"); + minio.setBucketName("jayucloud-salon-sit"); + AliyunOssConfig aliyun = new AliyunOssConfig(); + aliyun.setEndpoint("https://oss-cn-hangzhou.aliyuncs.com"); + aliyun.setBucketName("salon"); + QiniuKodoConfig qiniu = new QiniuKodoConfig(); + qiniu.setDomain("https://sit.qiniu.yunail.art"); + ObjectStorageProperties properties = new ObjectStorageProperties(); + properties.setSignedUrlExpireMinutes(60); + orchestrationService = mock(ObjectStorageOrchestrationService.class); + support = new ObjectStorageUrlSupport(mock(PrimaryObjectStorageService.class), minio, aliyun, + qiniu, mock(AliyunOssService.class), properties, orchestrationService); + } + + @Test + void extractsObjectNameFromMinioInternalAndPublicUrls() { + assertEquals("avatar/7/photo.jpg", support.extractObjectName( + "http://192.168.10.14:9000/jayucloud-salon-sit/avatar/7/photo.jpg")); + assertEquals("avatar/7/photo.jpg", support.extractObjectName( + "https://sit.minio.yunail.art/jayucloud-salon-sit/avatar/7/photo.jpg?X-Amz-Signature=test")); + } + + @Test + void keepsQiniuAndOssReferencesSupported() { + assertEquals("avatar/7/photo.jpg", support.extractObjectName("https://sit.qiniu.yunail.art/avatar/7/photo.jpg")); + assertEquals("avatar/7/photo.jpg", support.extractObjectName("oss://salon/avatar/7/photo.jpg")); + } + + @Test + void doesNotReturnKnownPrivateUrlWhenSigningFails() { + when(orchestrationService.getPresignedUrl("avatar/7/photo.jpg", 60)) + .thenThrow(new IllegalStateException("storage unavailable")); + assertNull(support.toAccessibleUrl("https://sit.minio.yunail.art/jayucloud-salon-sit/avatar/7/photo.jpg")); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImplTest.java new file mode 100644 index 00000000..6de8fe40 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImplTest.java @@ -0,0 +1,142 @@ +package com.xiaowang.jayucloud.salon.core.modules.integration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatSubscribeMessageLogMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class WechatSubscribeMessageServiceImplTest { + + @Mock private WechatSubscribeMessageLogMapper logMapper; + @Mock private WechatMiniBindingMapper bindingMapper; + @Mock private WechatMiniClientService clientService; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private UserMapper userMapper; + @Mock private PhoneCrypto phoneCrypto; + + private WechatMiniProperties properties; + private WechatSubscribeMessageServiceImpl service; + + @BeforeEach + void setUp() { + properties = new WechatMiniProperties(); + properties.setSubscribeMessageEnabled(true); + properties.setSubscribeMessageProvider("mock"); + properties.setServiceStartReminderLeadMinutes(30); + properties.setSubscribeMessagePage("/pages/appointment-detail/index"); + properties.setSubscribeMessageMiniprogramState("developer"); + properties.setSubscribeMessageMaxRetries(3); + service = new WechatSubscribeMessageServiceImpl(logMapper, bindingMapper, clientService, properties, + orderMapper, orderItemMapper, productMapper, userMapper, phoneCrypto); + } + + @Test + void doesNotEnqueueUnassignedAppointment() { + OrderItemDO item = new OrderItemDO(); + item.setId(101L); + when(orderItemMapper.selectById(101L)).thenReturn(item); + + service.enqueueAppointmentReminder(1L, 101L); + + verify(logMapper, never()).insert(any(WechatSubscribeMessageLogDO.class)); + } + + @Test + void enqueueIncludesCurrentArtistInIdempotencyKey() { + OrderItemDO item = new OrderItemDO(); + item.setId(101L); + item.setArtistId(7L); + when(orderItemMapper.selectById(101L)).thenReturn(item); + + service.enqueueAppointmentReminder(1L, 101L); + + ArgumentCaptor captor = ArgumentCaptor.forClass(WechatSubscribeMessageLogDO.class); + verify(logMapper).insert(captor.capture()); + assertEquals("APPOINTMENT:101:7", captor.getValue().getEventKey()); + assertEquals(7L, captor.getValue().getUserId()); + } + + @Test + void sendsOnlyCurrentPendingAppointmentToBoundArtist() { + LocalDateTime appointmentTime = LocalDateTime.now().plusHours(2); + WechatSubscribeMessageLogDO log = new WechatSubscribeMessageLogDO(); + log.setId(1L); + log.setTemplateCode("Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo"); + log.setOrderId(11L); + log.setOrderItemId(101L); + log.setUserId(7L); + log.setStatus("PENDING"); + log.setRetryCount(0); + OrderItemDO item = new OrderItemDO(); + item.setId(101L); + item.setOrderId(11L); + item.setArtistId(7L); + item.setProductId(31L); + item.setAppointmentTime(appointmentTime); + item.setIsDelete(0); + OrderDO order = new OrderDO(); + order.setId(11L); + order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setIsDelete(0); + order.setCustomerNameSnapshot("小周"); + UserDO artist = new UserDO(); + artist.setId(7L); + artist.setNickname("小美"); + WechatMiniBindingDO binding = new WechatMiniBindingDO(); + binding.setOpenId("openid-value"); + ProductDO product = new ProductDO(); + product.setTitle("纯色美甲"); + when(logMapper.selectDue(any(), any(Integer.class))).thenReturn(List.of(log)); + when(logMapper.claimForProcessing(1L)).thenReturn(1); + when(orderItemMapper.selectById(101L)).thenReturn(item); + when(orderMapper.selectById(11L)).thenReturn(order); + when(userMapper.selectById(7L)).thenReturn(artist); + when(bindingMapper.selectOne(any(Wrapper.class))).thenReturn(binding); + when(productMapper.selectById(31L)).thenReturn(product); + when(phoneCrypto.index("openid-value")).thenReturn("hash"); + when(clientService.sendSubscribeMessage(any(), any(), any(), any(), any())) + .thenReturn(new WechatMiniClientService.SubscribeMessageResult(true, 0, "ok")); + + service.processDueMessages(); + + verify(clientService).sendSubscribeMessage(eq("openid-value"), eq(log.getTemplateCode()), + any(), any(), any()); + assertEquals("hash", log.getOpenIdHash()); + assertEquals("SENT", log.getStatus()); + verify(logMapper, times(2)).updateById(log); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerControllerMappingTest.java new file mode 100644 index 00000000..5cd9001e --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerControllerMappingTest.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.manager.controller.admin; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.RequestMapping; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class AdminManagerControllerMappingTest { + + @Test + void exposesAdminCompatibilityAndMiniProgramBusinessRoutes() { + RequestMapping mapping = AdminManagerController.class.getAnnotation(RequestMapping.class); + + assertNotNull(mapping); + assertArrayEquals(new String[]{"/admin/manager", "/manager"}, mapping.value()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapperMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapperMappingTest.java new file mode 100644 index 00000000..4400d786 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapperMappingTest.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.MybatisConfiguration; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class OrderArtistReviewMapperMappingTest { + @Test + void registersReviewScopedAndGlobalImageReferenceStatementsSeparately() { + MybatisConfiguration configuration = new MybatisConfiguration(); + configuration.addMapper(OrderArtistReviewMapper.class); + + String mapperName = OrderArtistReviewMapper.class.getName(); + assertTrue(configuration.hasStatement(mapperName + ".countPublicImageReferenceByReviewId")); + assertTrue(configuration.hasStatement(mapperName + ".countPublicImageReference")); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java new file mode 100644 index 00000000..f6ec598a --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java @@ -0,0 +1,126 @@ +package com.xiaowang.jayucloud.salon.core.modules.order.service.impl; + +import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class OrderServiceImplOfflinePaymentTest { + + @Mock + private OrderMapper orderMapper; + + @Mock + private OrderItemMapper orderItemMapper; + + @Mock + private ShopMapper shopMapper; + + @Mock + private UserMapper userMapper; + + @InjectMocks + private OrderServiceImpl service; + + @Test + void rejectsUnknownPaymentMethod() { + OrderOfflinePaymentDTO dto = offlinePayment(new BigDecimal("100"), LocalDateTime.now()); + dto.setPayMethod("CARD"); + + RuntimeException error = assertThrows(RuntimeException.class, + () -> service.registerOfflinePayment(1L, 9L, 2L, dto)); + + assertEquals("payMethod 只能为 OFFLINE、CASH、WECHAT 或 ALIPAY", error.getMessage()); + } + + @Test + void allowsAmountAdjustment() { + OrderDO order = order(1L, OrderStatus.PENDING_SERVICE.getCode(), "UNPAID"); + order.setPayAmount(new BigDecimal("100.00")); + when(orderMapper.selectByIdForUpdate(1L)).thenReturn(order); + when(orderItemMapper.selectByOrderId(1L)).thenReturn(java.util.Collections.emptyList()); + OrderOfflinePaymentDTO dto = offlinePayment(new BigDecimal("90"), LocalDateTime.now()); + dto.setPayMethod("CASH"); + + service.registerOfflinePayment(1L, 9L, 2L, dto); + + assertEquals("PAID", order.getPaymentStatus()); + assertEquals("CASH", order.getPaymentMethod()); + assertEquals(new BigDecimal("90"), order.getPaidAmount()); + } + + @Test + void rejectsCancelledOrder() { + OrderDO order = order(1L, OrderStatus.CANCELLED.getCode(), "UNPAID"); + order.setPayAmount(new BigDecimal("100")); + when(orderMapper.selectByIdForUpdate(1L)).thenReturn(order); + OrderOfflinePaymentDTO dto = offlinePayment(new BigDecimal("100"), LocalDateTime.now()); + + RuntimeException error = assertThrows(RuntimeException.class, + () -> service.registerOfflinePayment(1L, 9L, 2L, dto)); + + assertEquals("订单已取消,不能登记收款", error.getMessage()); + } + + @Test + void rejectsRepeatedRegistrationWithDifferentTime() { + OrderDO order = order(1L, OrderStatus.PENDING_SERVICE.getCode(), "PAID"); + order.setPayAmount(new BigDecimal("100")); + order.setPaymentMethod("OFFLINE"); + order.setPaidAmount(new BigDecimal("100")); + order.setPayTime(LocalDateTime.of(2026, 11, 4, 10, 0, 0)); + when(orderMapper.selectByIdForUpdate(1L)).thenReturn(order); + OrderOfflinePaymentDTO dto = offlinePayment(new BigDecimal("100"), LocalDateTime.of(2026, 11, 4, 11, 0, 0)); + + RuntimeException error = assertThrows(RuntimeException.class, + () -> service.registerOfflinePayment(1L, 9L, 2L, dto)); + + assertEquals("该订单已登记收款,金额或收款方式与首次登记不一致,不能重复登记", error.getMessage()); + } + + @Test + void rejectsCompletingUnpaidOrder() { + OrderDO order = order(1L, OrderStatus.PENDING_SERVICE.getCode(), "UNPAID"); + order.setOrderSource("NORMAL"); + when(orderMapper.selectById(1L)).thenReturn(order); + + RuntimeException error = assertThrows(RuntimeException.class, + () -> service.processOrder(1L, OrderStatus.COMPLETED.getCode())); + + assertEquals("订单未收款,不能完成;请先登记线下收款", error.getMessage()); + } + + private OrderOfflinePaymentDTO offlinePayment(BigDecimal amount, LocalDateTime paidAt) { + OrderOfflinePaymentDTO dto = new OrderOfflinePaymentDTO(); + dto.setPayMethod("OFFLINE"); + dto.setPaidAmount(amount); + dto.setPaidAt(paidAt); + return dto; + } + + private OrderDO order(Long id, Integer status, String paymentStatus) { + OrderDO order = new OrderDO(); + order.setId(id); + order.setShopId(2L); + order.setStatus(status); + order.setPaymentStatus(paymentStatus); + order.setIsDelete(0); + return order; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java new file mode 100644 index 00000000..945cf325 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -0,0 +1,617 @@ +package com.xiaowang.jayucloud.salon.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService; +import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PlanningServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserMapper userMapper; + @Mock private UserService userService; + @Mock private NailArtistInfoMapper nailArtistInfoMapper; + @Mock private ArtistScheduleMapper artistScheduleMapper; + @Mock private ArtistScheduleExceptionMapper artistScheduleExceptionMapper; + @Mock private AppointmentReservationMapper appointmentReservationMapper; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private ShopMapper shopMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private ShopBusinessScheduleService shopBusinessScheduleService; + @Mock private AppointmentCapacityService appointmentCapacityService; + @Mock private OrderService orderService; + @Mock private WechatSubscribeMessageService wechatSubscribeMessageService; + @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private ObjectStorageFileService objectStorageFileService; + @Mock private PhoneCrypto phoneCrypto; + + private PlanningServiceImpl service; + + @BeforeEach + void setUp() { + service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, + artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, + productMapper, shopMapper, shopBusinessExpiryService, shopBusinessScheduleService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator, + objectStorageUrlSupport, objectStorageFileService, phoneCrypto); + ShopBusinessHoursDayVO defaultOpenDay = new ShopBusinessHoursDayVO(); + defaultOpenDay.setOpen(true); + defaultOpenDay.setStartTime("10:00"); + defaultOpenDay.setEndTime("22:00"); + lenient().when(shopBusinessScheduleService.forDate(any(), any(), org.mockito.ArgumentMatchers.nullable(String.class))) + .thenReturn(defaultOpenDay); + } + + @Test + void rejectsCompletingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(11L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(11L)).thenReturn(order); + when(orderItemMapper.selectCount(any(Wrapper.class))).thenReturn(1L); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.updateStatus(operator, 11L, dto)); + + assertEquals("请先分配员工", error.getMessage()); + verify(orderService, never()).processOrder(11L, OrderStatus.COMPLETED.getCode()); + } + + @Test + void rejectsAppointmentCreationWhenShopValidityHasExpired() { + UserDO operator = new UserDO(); + operator.setType(2); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + org.mockito.Mockito.doThrow(new IllegalStateException("门店经营有效期已到期")) + .when(shopBusinessExpiryService).assertShopActive(21L); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("门店经营有效期已到期", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + verify(orderItemMapper, never()).insert(any(OrderItemDO.class)); + } + + @Test + void rejectsCreatingAppointmentForPastDate() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().minusDays(1).toString()); + dto.setAppointmentTime("14:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("历史日期请使用历史补单", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void rejectsAppointmentOutsideBusinessHours() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-20:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("19:30"); + dto.setDurationMinutes(60); + ShopBusinessHoursDayVO openDay = new ShopBusinessHoursDayVO(); + openDay.setOpen(true); + openDay.setStartTime("10:00"); + openDay.setEndTime("20:00"); + when(shopBusinessScheduleService.forDate(org.mockito.ArgumentMatchers.eq(21L), + org.mockito.ArgumentMatchers.eq(java.time.LocalDate.parse(dto.getAppointmentDate())), + org.mockito.ArgumentMatchers.nullable(String.class))).thenReturn(openDay); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void rejectsAppointmentWhenShopIsClosedOnRequestedWeekday() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + ShopBusinessHoursDayVO closedDay = new ShopBusinessHoursDayVO(); + closedDay.setOpen(false); + when(shopBusinessScheduleService.forDate(org.mockito.ArgumentMatchers.eq(21L), + org.mockito.ArgumentMatchers.eq(java.time.LocalDate.parse(dto.getAppointmentDate())), + org.mockito.ArgumentMatchers.nullable(String.class))).thenReturn(closedDay); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约日期门店休息,暂不可新建普通预约", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void calendarHasNoFallbackHoursWhenEveryShopDayIsClosed() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(shopBusinessScheduleService.mapByDay(21L, "10:00-22:00")).thenReturn(closedWeeklySchedule()); + mockEmptyCalendarRows(); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningCalendarVO calendar = service.getCalendar( + operator, java.time.LocalDate.of(2026, 11, 2), java.time.LocalDate.of(2026, 11, 2), null); + + assertNull(calendar.getBusinessStartTime()); + assertNull(calendar.getBusinessEndTime()); + assertEquals(false, calendar.getDaySummaries().get(0).getShopOpen()); + assertEquals("rest", calendar.getDaySummaries().get(0).getDayStatus()); + } + + @Test + void calendarUsesWeeklyHoursInsteadOfLegacyHoursWhenAnyShopDayIsOpen() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + java.util.Map weeklyHours = closedWeeklySchedule(); + ShopBusinessHoursDayVO monday = new ShopBusinessHoursDayVO(); + monday.setDayOfWeek(1); + monday.setOpen(true); + monday.setStartTime("12:00"); + monday.setEndTime("19:00"); + weeklyHours.put(1, monday); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(shopBusinessScheduleService.mapByDay(21L, "10:00-22:00")).thenReturn(weeklyHours); + mockEmptyCalendarRows(); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningCalendarVO calendar = service.getCalendar( + operator, java.time.LocalDate.of(2026, 11, 2), java.time.LocalDate.of(2026, 11, 2), null); + + assertEquals("12:00", calendar.getBusinessStartTime()); + assertEquals("19:00", calendar.getBusinessEndTime()); + assertEquals(true, calendar.getDaySummaries().get(0).getShopOpen()); + assertEquals("12:00", calendar.getDaySummaries().get(0).getShopStartTime()); + assertEquals("19:00", calendar.getDaySummaries().get(0).getShopEndTime()); + } + + @Test + void usesShopDefaultDurationWhenRequestOmitsDuration() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-22:00"); + shop.setDefaultAppointmentDurationMinutes(90); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("21:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void productDurationTakesPriorityOverShopDefaultWhenRequestOmitsDuration() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-22:00"); + shop.setDefaultAppointmentDurationMinutes(60); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setIsDelete(0); + product.setApproximateDuration("120分钟"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(productMapper.selectById(41L)).thenReturn(product); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setProductId(41L); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("21:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void backfillOrderDoesNotCheckShopBusinessExpiry() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO artist = new UserDO(); + artist.setId(31L); + artist.setType(3); + artist.setShopId(21L); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setIsDelete(0); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(userMapper.selectById(31L)).thenReturn(artist); + when(productMapper.selectById(41L)).thenReturn(product); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(54L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(64L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 64L); + PlanningBackfillOrderCreateDTO dto = new PlanningBackfillOrderCreateDTO(); + dto.setServiceDate("2025-01-01"); + dto.setProductId(41L); + dto.setArtistId(31L); + dto.setAmount(java.math.BigDecimal.valueOf(80)); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + service.createBackfillOrder(operator, dto); + + verify(shopBusinessExpiryService, never()).assertShopActive(any()); + } + + @Test + void allowsCancellingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(12L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(12L)).thenReturn(order); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.CANCELLED.getCode()); + + service.updateStatus(operator, 12L, dto); + + verify(orderService).processOrder(12L, OrderStatus.CANCELLED.getCode()); + } + + @Test + void createsUnassignedAppointmentWithoutReservation() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(31L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(31L)).thenReturn(customer); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10001"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(51L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(61L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 61L); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(31L); + dto.setProductId(41L); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertNull(itemCaptor.getValue().getArtistId()); + verify(appointmentCapacityService, never()).reserveConfirmedOrThrow( + any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithPhotoOnlyStyleAndSnapshotAmount() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10002"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(42L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(52L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(62L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 62L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小鹿"); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-42"); + dto.setAmount(java.math.BigDecimal.valueOf(168)); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("小鹿", productCaptor.getValue().getTitle()); + assertEquals("file-42", productCaptor.getValue().getImageFileIds()); + assertEquals(java.math.BigDecimal.valueOf(168), productCaptor.getValue().getPrice()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertEquals("小鹿", orderCaptor.getValue().getCustomerNameSnapshot()); + assertEquals(java.math.BigDecimal.valueOf(168), orderCaptor.getValue().getActualAmount()); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertEquals(0, itemCaptor.getValue().getPrice().compareTo(java.math.BigDecimal.valueOf(168))); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithManualStyleTitle() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10003"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(43L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(53L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(63L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 63L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCreateCustomerRecord(false); + dto.setManualProductTitle("手绘款"); + dto.setManualProductImageFileIds("file-43"); + dto.setAmount(java.math.BigDecimal.valueOf(88)); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(45); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("手绘款", productCaptor.getValue().getTitle()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + assertNull(orderCaptor.getValue().getCustomerPhoneSnapshot()); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void readsWalkInAppointmentCustomerSnapshotWithoutLookingUpNullUserId() { + UserDO operator = new UserDO(); + operator.setType(2); + OrderDO order = order(54L, OrderStatus.PENDING_SERVICE.getCode()); + order.setCustomerNameSnapshot("散客预约"); + order.setCustomerPhoneSnapshot("13800138000"); + order.setCancelReason("门店临时闭店"); + OrderItemDO item = new OrderItemDO(); + item.setId(64L); + item.setOrderId(54L); + item.setQuantity(1); + item.setAppointmentTime(java.time.LocalDateTime.of(2026, 10, 22, 14, 0)); + + when(orderItemMapper.selectById(64L)).thenReturn(item); + when(orderMapper.selectById(54L)).thenReturn(order); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + when(phoneCrypto.mask("13800138000")).thenReturn("138****8000"); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result = + service.getAppointment(operator, 64L); + + assertNull(result.getCustomerId()); + assertEquals("散客预约", result.getCustomerName()); + assertEquals("138****8000", result.getCustomerPhone()); + assertEquals(Boolean.TRUE, result.getCustomerPhoneAvailable()); + assertEquals("门店临时闭店", result.getCancelReason()); + verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull()); + } + + @Test + void createsCustomerInAppointmentFlowWhenConfirmed() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(71L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(71L)).thenReturn(customer); + when(userService.findCustomerIdentityMatches("小周", null, "13800138000", 21L)).thenReturn(java.util.List.of()); + when(userService.createManagerCustomer("小周", null, "13800138000", 21L)).thenReturn(71L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(55L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(65L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 65L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小周"); + dto.setPhone("13800138000"); + dto.setCreateCustomerRecord(true); + dto.setProductId(41L); + dto.setAmount(java.math.BigDecimal.valueOf(128)); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + verify(userService).createManagerCustomer("小周", null, "13800138000", 21L); + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertEquals(71L, orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + } + + private OrderDO order(Long id, int status) { + OrderDO order = new OrderDO(); + order.setId(id); + order.setShopId(21L); + order.setStatus(status); + order.setIsDelete(0); + return order; + } + + private java.util.Map closedWeeklySchedule() { + java.util.Map days = new java.util.HashMap<>(); + for (int dayOfWeek = 1; dayOfWeek <= 7; dayOfWeek++) { + ShopBusinessHoursDayVO day = new ShopBusinessHoursDayVO(); + day.setDayOfWeek(dayOfWeek); + day.setOpen(false); + days.put(dayOfWeek, day); + } + return days; + } + + private void mockEmptyCalendarRows() { + when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + when(artistScheduleMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + when(appointmentReservationMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + when(orderItemMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java new file mode 100644 index 00000000..525ea414 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java @@ -0,0 +1,309 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class WechatContentModerationCallbackControllerTest { + private static final String CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; + + @Test + void aesHandshakeVerifiesEncryptedEchoAndReturnsDecryptedValue() { + SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); + when(secureConfig.getModerationCallbackConfig()).thenReturn( + new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true)); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-echo", "message-signature")) + .thenReturn(true); + when(crypto.decrypt("encrypted-echo", "encoding-aes-key", "mini-app-id")) + .thenReturn("verified-echo"); + WechatContentModerationCallbackController controller = controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), + mock(ContentModerationForwardService.class)); + + String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo"); + + assertEquals("verified-echo", result); + verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-echo", "message-signature"); + verify(crypto).decrypt("encrypted-echo", "encoding-aes-key", "mini-app-id"); + } + + @Test + void plaintextHandshakeStillUsesPlainSignature() { + SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); + when(secureConfig.getModerationCallbackConfig()).thenReturn( + new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true)); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + when(crypto.verifyPlain("callback-token", "1000", "nonce", "plain-signature")).thenReturn(true); + WechatContentModerationCallbackController controller = controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), + mock(ContentModerationForwardService.class)); + + assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo")); + verify(crypto).verifyPlain("callback-token", "1000", "nonce", "plain-signature"); + } + + @Test + void callbackPersistsBeforeReturningSuccess() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true); + String decoded = "{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"}}"; + when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")).thenReturn(decoded); + when(forwardService.persistCallback(decoded)).thenReturn(42L); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + InOrder order = inOrder(forwardService); + order.verify(forwardService).persistCallback(decoded); + order.verify(forwardService).submit(42L); + } + + @Test + void callbackReturnsNon200WhenPersistFails() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(crypto.decrypt(anyString(), anyString(), anyString())) + .thenReturn("{\"trace_id\":\"task-persist-fail\"}"); + when(forwardService.persistCallback(anyString())) + .thenThrow(new IllegalStateException("数据库不可用")); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isInternalServerError()) + .andExpect(content().string("persist_failed")); + + verify(forwardService, never()).submit(any()); + verify(forwardService, never()).reserveTrace(anyString()); + } + + @Test + void duplicateCallbackReusesTaskAndStillReturnsSuccess() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(crypto.decrypt(anyString(), anyString(), anyString())) + .thenReturn("{\"trace_id\":\"task-dup\",\"suggest\":\"review\"}"); + when(forwardService.persistCallback(anyString())).thenReturn(7L); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build(); + + for (int attempt = 0; attempt < 2; attempt++) { + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + } + + verify(forwardService, times(2)).persistCallback(anyString()); + verify(forwardService, times(2)).submit(7L); + } + + @Test + void keepsXmlEnvelopeSupportForAesEncryptedCallback() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + String xml = "encrypted-xml"; + when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml"); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true); + String decodedXml = "task-xmlreview"; + when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml); + when(forwardService.persistCallback(decodedXml)).thenReturn(11L); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_XML) + .content(xml)) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService).persistCallback(decodedXml); + verify(forwardService).submit(11L); + } + + @Test + void forwardedCallbackClaimsLocally() throws Exception { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + ContentModerationService moderationService = mock(ContentModerationService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(forwardService.reserveTrace("task-claim")).thenReturn(true); + when(moderationService.handleWechatImageResult("task-claim", "review", "微信异步图片审核回调")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class), + moderationService, mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .header("X-Moderation-Forward-By", "prod") + .header("X-Moderation-Forward-Hop", "1") + .header("X-Timestamp", "1000") + .header("X-Nonce", "forward-nonce") + .header("X-Signature", "forward-signature") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"trace_id\":\"task-claim\",\"suggest\":\"review\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("CLAIMED")); + + verify(forwardService, never()).submit(any()); + } + + @Test + void forwardedCallbackReturnsNotMineWhenLocalMiss() throws Exception { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + ContentModerationService moderationService = mock(ContentModerationService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(forwardService.reserveTrace("task-other")).thenReturn(true); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString())).thenReturn(false); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class), + moderationService, mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .header("X-Moderation-Forward-By", "prod") + .header("X-Moderation-Forward-Hop", "1") + .header("X-Timestamp", "1000") + .header("X-Nonce", "forward-nonce") + .header("X-Signature", "forward-signature") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"trace_id\":\"task-other\",\"suggest\":\"review\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("NOT_MINE")); + + verify(forwardService).releaseTrace("task-other"); + } + + @Test + void forwardedDuplicateReturnsClaimed() throws Exception { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(forwardService.reserveTrace("task-dup-forward")).thenReturn(false); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class), + mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .header("X-Moderation-Forward-By", "prod") + .header("X-Moderation-Forward-Hop", "1") + .header("X-Timestamp", "1000") + .header("X-Nonce", "forward-nonce") + .header("X-Signature", "forward-signature") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"trace_id\":\"task-dup-forward\",\"suggest\":\"review\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("CLAIMED")); + } + + @Test + void forwardedHopGreaterThanOneIsRejected() { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + WechatContentModerationCallbackController controller = controller(readyWechatConfig(), + mock(WechatCallbackCrypto.class), mock(ContentModerationService.class), + mock(IntegrationProbeService.class), forwardService); + + assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null, + "prod", "2", "1000", "forward-nonce", "forward-signature", + "{\"trace_id\":\"loop-task\"}", new MockHttpServletResponse())); + } + + @Test + void forwardedSourceEqualToSelfIsRejected() { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + WechatContentModerationCallbackController controller = controller(readyWechatConfig(), + mock(WechatCallbackCrypto.class), mock(ContentModerationService.class), + mock(IntegrationProbeService.class), forwardService); + + assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null, + "sit", "1", "1000", "forward-nonce", "forward-signature", + "{\"trace_id\":\"self-task\"}", new MockHttpServletResponse())); + } + + @Test + void forwardedSignatureFailureIsRejected() { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(false); + WechatContentModerationCallbackController controller = controller(readyWechatConfig(), + mock(WechatCallbackCrypto.class), mock(ContentModerationService.class), + mock(IntegrationProbeService.class), forwardService); + + assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null, + "prod", "1", "1000", "forward-nonce", "bad-signature", + "{\"trace_id\":\"task-1\"}", new MockHttpServletResponse())); + } + + private SecureIntegrationConfigService readyWechatConfig() { + SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); + when(secureConfig.getModerationCallbackConfig()).thenReturn( + new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true)); + return secureConfig; + } + + private WechatContentModerationCallbackController controller(SecureIntegrationConfigService secureConfig, + WechatCallbackCrypto crypto, + ContentModerationService moderationService, + IntegrationProbeService probeService, + ContentModerationForwardService forwardService) { + WechatMiniProperties wechatProperties = new WechatMiniProperties(); + wechatProperties.setAppId("mini-app-id"); + SalonDeployProperties deployProperties = new SalonDeployProperties(); + deployProperties.setEnv("sit"); + return new WechatContentModerationCallbackController(secureConfig, wechatProperties, crypto, + moderationService, probeService, forwardService, deployProperties, new ObjectMapper()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProviderTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProviderTest.java new file mode 100644 index 00000000..f407654c --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProviderTest.java @@ -0,0 +1,93 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpEntity; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class WechatContentModerationProviderTest { + @Test + void textReviewSendsWechatIdentityAndSceneAndAcceptsOnlyExplicitPass() { + RestTemplate restTemplate = mock(RestTemplate.class); + WechatMiniClientService wechatClient = mock(WechatMiniClientService.class); + when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token"); + when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class))) + .thenReturn("{\"errcode\":0,\"result\":{\"suggest\":\"pass\"}}"); + ContentModerationProperties properties = new ContentModerationProperties(); + properties.setScene(3); + WechatContentModerationProvider provider = provider(restTemplate, wechatClient, properties); + + ModerationOutcome outcome = provider.reviewText("COMMENT", "内容", "openid-1"); + + assertEquals(ModerationOutcome.Status.APPROVED, outcome.status()); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpEntity.class); + verify(restTemplate).postForObject(org.mockito.ArgumentMatchers.contains("access_token=cached-token"), + requestCaptor.capture(), eq(String.class)); + Map payload = (Map) requestCaptor.getValue().getBody(); + assertEquals("内容", payload.get("content")); + assertEquals("openid-1", payload.get("openid")); + assertEquals(3, payload.get("scene")); + } + + @Test + void imageReviewSendsImageTypeAndDoesNotSendUnsupportedExtraField() { + RestTemplate restTemplate = mock(RestTemplate.class); + WechatMiniClientService wechatClient = mock(WechatMiniClientService.class); + when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token"); + when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class))) + .thenReturn("{\"errcode\":0,\"trace_id\":\"task-123\"}"); + WechatContentModerationProvider provider = provider(restTemplate, wechatClient, new ContentModerationProperties()); + + ModerationOutcome outcome = provider.submitImage("PRODUCT", "https://storage.test/signed/image", "openid-1", "trial"); + + assertEquals(ModerationOutcome.Status.PENDING, outcome.status()); + assertEquals("task-123", outcome.remoteTaskId()); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpEntity.class); + verify(restTemplate).postForObject(anyString(), requestCaptor.capture(), eq(String.class)); + Map payload = (Map) requestCaptor.getValue().getBody(); + assertEquals("https://storage.test/signed/image", payload.get("media_url")); + assertEquals(2, payload.get("media_type")); + assertEquals(1, payload.get("version")); + assertEquals("openid-1", payload.get("openid")); + assertFalse(payload.containsKey("extra")); + } + + @Test + void testImageUsesSameSupportedFieldSet() { + RestTemplate restTemplate = mock(RestTemplate.class); + WechatMiniClientService wechatClient = mock(WechatMiniClientService.class); + when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token"); + when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class))) + .thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}"); + WechatContentModerationProvider provider = provider(restTemplate, wechatClient, new ContentModerationProperties()); + + provider.submitTestImage("https://storage.test/signed/image", "private-open-id"); + + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpEntity.class); + verify(restTemplate).postForObject(anyString(), requestCaptor.capture(), eq(String.class)); + Map payload = (Map) requestCaptor.getValue().getBody(); + assertEquals(2, payload.get("media_type")); + assertEquals(1, payload.get("version")); + assertFalse(payload.containsKey("extra")); + } + + private WechatContentModerationProvider provider(RestTemplate restTemplate, + WechatMiniClientService wechatClient, + ContentModerationProperties properties) { + return new WechatContentModerationProvider(restTemplate, new ObjectMapper(), wechatClient, properties); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java new file mode 100644 index 00000000..8bcc2a1a --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java @@ -0,0 +1,412 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationProbeResult; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ContentModerationForwardServiceImplTest { + private static final String SECRET = "forward-secret-1234567890"; + private static final String DEV_TARGET = "https://dev.example.test/api/integration/wechat/content-moderation/callback"; + private static final String PROD_TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback"; + + private ModerationCallbackForwardMapper forwardMapper; + private SecureIntegrationConfigService secureIntegrationConfigService; + private RedisTemplate redisTemplate; + private ValueOperations valueOperations; + private ModerationForwardHttpClient forwardHttpClient; + private IntegrationProbeService probeService; + private ContentModerationService moderationService; + private ContentModerationForwardServiceImpl service; + + @BeforeEach + void setUp() { + forwardMapper = mock(ModerationCallbackForwardMapper.class); + secureIntegrationConfigService = mock(SecureIntegrationConfigService.class); + redisTemplate = mock(RedisTemplate.class); + valueOperations = mock(ValueOperations.class); + forwardHttpClient = mock(ModerationForwardHttpClient.class); + probeService = mock(IntegrationProbeService.class); + moderationService = mock(ContentModerationService.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(true); + SalonDeployProperties deployProperties = new SalonDeployProperties(); + deployProperties.setEnv("sit"); + service = new ContentModerationForwardServiceImpl(forwardMapper, secureIntegrationConfigService, + deployProperties, redisTemplate, forwardHttpClient, probeService, moderationService, + new ObjectMapper(), mock(WechatCallbackCrypto.class)); + } + + // ---------- 接收侧:先落库 ---------- + + @Test + void persistCallbackInsertsPendingTaskWithDecodedPayload() { + doAnswer(invocation -> { + ModerationCallbackForwardDO row = invocation.getArgument(0); + row.setId(101L); + return 1; + }).when(forwardMapper).insert(any(ModerationCallbackForwardDO.class)); + + Long taskId = service.persistCallback("{\"trace_id\":\"trace-1\",\"result\":{\"suggest\":\"review\"}}"); + + assertEquals(101L, taskId); + ModerationCallbackForwardDO row = capturedInsert(); + assertEquals("trace-1", row.getTraceId()); + assertEquals("sit", row.getSourceEnv()); + assertEquals("PENDING", row.getStatus()); + assertEquals(0, row.getRetryCount()); + assertNotNull(row.getNextAttemptAt()); + assertEquals("{\"trace_id\":\"trace-1\",\"result\":{\"suggest\":\"review\"}}", row.getPayload()); + } + + @Test + void persistCallbackReturnsExistingTaskForDuplicateTrace() { + ModerationCallbackForwardDO existing = row(9L, "trace-dup", "SUCCESS", 0); + when(forwardMapper.selectOne(any())).thenReturn(existing); + + assertEquals(9L, service.persistCallback("{\"trace_id\":\"trace-dup\"}")); + + verify(forwardMapper, never()).insert(any(ModerationCallbackForwardDO.class)); + } + + @Test + void persistCallbackRecoversWhenConcurrentInsertHitsDuplicateKey() { + ModerationCallbackForwardDO existing = row(9L, "trace-race", "PENDING", 0); + when(forwardMapper.selectOne(any())).thenReturn(null, existing); + when(forwardMapper.insert(any(ModerationCallbackForwardDO.class))) + .thenThrow(new DuplicateKeyException("duplicate trace")); + + assertEquals(9L, service.persistCallback("{\"trace_id\":\"trace-race\"}")); + + verify(forwardMapper, times(1)).insert(any(ModerationCallbackForwardDO.class)); + } + + @Test + void persistCallbackStoresUntracedPayloadAsDead() { + doAnswer(invocation -> { + ModerationCallbackForwardDO row = invocation.getArgument(0); + row.setId(102L); + return 1; + }).when(forwardMapper).insert(any(ModerationCallbackForwardDO.class)); + + assertEquals(102L, service.persistCallback("{\"result\":{\"suggest\":\"review\"}}")); + + ModerationCallbackForwardDO row = capturedInsert(); + assertTrue(row.getTraceId().startsWith("untraced-")); + assertEquals("DEAD", row.getStatus()); + assertNotNull(row.getLastError()); + assertNull(row.getNextAttemptAt()); + assertNotNull(row.getFinishedAt()); + } + + // ---------- 异步执行与状态机 ---------- + + @Test + void executeTaskProcessesLocalHitAndMarksSuccess() { + ModerationCallbackForwardDO row = row(1L, "trace-local", "PENDING", 0); + when(forwardMapper.selectById(1L)).thenReturn(row); + when(forwardMapper.update(isNull(), any())).thenReturn(1); + when(probeService.handleImageCallback(eq("trace-local"), eq("review"), isNull())).thenReturn(true); + + service.executeTask(1L); + + UpdateWrapper outcome = outcomeWrapper(); + assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS")); + assertTrue(outcome.getParamNameValuePairs().containsValue("sit")); + verify(forwardHttpClient, never()).probe(anyString(), anyString(), any()); + } + + @Test + void executeTaskForwardsInOrderAndStopsOnClaimed() { + ModerationCallbackForwardDO row = row(2L, "trace-forward", "PENDING", 0); + when(forwardMapper.selectById(2L)).thenReturn(row); + when(forwardMapper.update(isNull(), any())).thenReturn(1); + when(secureIntegrationConfigService.getModerationForwardConfig()) + .thenReturn(config(Arrays.asList("dev", "prod"))); + when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE); + when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED); + + service.executeTask(2L); + + InOrder order = inOrder(forwardHttpClient); + order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any()); + order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any()); + UpdateWrapper outcome = outcomeWrapper(); + assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS")); + assertTrue(outcome.getParamNameValuePairs().containsValue("prod")); + } + + @Test + void executeTaskRecordsNoEnvAndSchedulesBackoff() { + ModerationCallbackForwardDO row = row(3L, "trace-no-env", "PENDING", 0); + when(forwardMapper.selectById(3L)).thenReturn(row); + when(forwardMapper.update(isNull(), any())).thenReturn(1); + when(secureIntegrationConfigService.getModerationForwardConfig()) + .thenReturn(ModerationForwardConfig.disabled()); + + service.executeTask(3L); + + UpdateWrapper outcome = outcomeWrapper(); + assertTrue(outcome.getParamNameValuePairs().containsValue("NO_ENV")); + assertTrue(outcome.getParamNameValuePairs().containsValue(1)); + assertTrue(hasFutureAttempt(outcome, 25), "首次补偿应至少等待默认 30 秒"); + verify(redisTemplate).delete("salon:content-moderation:claim:trace-no-env"); + } + + @Test + void executeTaskMarksDeadAndAlertsWhenRetryLimitExceeded() { + ModerationCallbackForwardDO row = row(4L, "trace-dead", "FAILED", 4); + when(forwardMapper.selectById(4L)).thenReturn(row); + when(forwardMapper.update(isNull(), any())).thenReturn(1); + when(secureIntegrationConfigService.getModerationForwardConfig()) + .thenReturn(ModerationForwardConfig.disabled()); + List logs = attachLogAppender(); + + service.executeTask(4L); + + UpdateWrapper outcome = outcomeWrapper(); + assertTrue(outcome.getParamNameValuePairs().containsValue("DEAD")); + assertTrue(outcome.getParamNameValuePairs().containsValue(5)); + assertNull(firstLocalDateTimeIgnoringNull(outcome)); + assertTrue(logs.stream().anyMatch(message -> message.contains("MODERATION_CALLBACK_DEAD")), + "达到最大重试后必须输出告警日志"); + } + + @Test + void executeTaskShortCircuitsWhenTraceAlreadyReserved() { + ModerationCallbackForwardDO row = row(5L, "trace-idempotent", "PENDING", 0); + when(forwardMapper.selectById(5L)).thenReturn(row); + when(forwardMapper.update(isNull(), any())).thenReturn(1); + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false); + + service.executeTask(5L); + + UpdateWrapper outcome = outcomeWrapper(); + assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS")); + verify(probeService, never()).handleImageCallback(anyString(), anyString(), any()); + verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString()); + } + + @Test + void executeTaskSkipsWhenClaimLosesToAnotherInstance() { + ModerationCallbackForwardDO row = row(6L, "trace-locked", "PENDING", 0); + when(forwardMapper.selectById(6L)).thenReturn(row); + when(forwardMapper.update(isNull(), any())).thenReturn(0); + + service.executeTask(6L); + + verify(forwardMapper, times(1)).selectById(6L); + verify(probeService, never()).handleImageCallback(anyString(), anyString(), any()); + verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString()); + } + + @Test + void recoverPendingTasksDispatchesUnfinishedRecords() { + ModerationCallbackForwardDO first = row(7L, "trace-r1", "PENDING", 0); + ModerationCallbackForwardDO second = row(8L, "trace-r2", "FAILED", 2); + when(forwardMapper.selectList(any())).thenReturn(Arrays.asList(first, second)); + + assertEquals(2, service.recoverPendingTasks()); + } + + @Test + void retryDueTasksDispatchesDueRecords() { + when(forwardMapper.selectList(any())).thenReturn(Collections.singletonList(row(9L, "trace-due", "NO_ENV", 1))); + + assertEquals(1, service.retryDueTasks()); + } + + // ---------- Redis 幂等占位 ---------- + + @Test + void reserveTraceReturnsFalseForDuplicate() { + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false); + + assertFalse(service.reserveTrace("trace-dup")); + } + + @Test + void reserveTraceFailsOpenWhenRedisUnavailable() { + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))) + .thenThrow(new IllegalStateException("redis down")); + + assertTrue(service.reserveTrace("trace-redis-down")); + } + + @Test + void releaseTraceDeletesClaimKey() { + service.releaseTrace("trace-release"); + + verify(redisTemplate).delete("salon:content-moderation:claim:trace-release"); + } + + // ---------- 转发验签 ---------- + + @Test + void verifySignatureAcceptsValidRequest() { + when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev"))); + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String nonce = "nonce-1"; + String body = "{\"trace_id\":\"trace-1\"}"; + String signature = sign(SECRET, timestamp, nonce, body); + + assertTrue(service.verifySignature(timestamp, nonce, signature, body)); + } + + @Test + void verifySignatureRejectsExpiredTimestamp() { + when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev"))); + String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600); + + assertFalse(service.verifySignature(timestamp, "nonce-2", "bad", "{}")); + } + + @Test + void verifySignatureRejectsReplayedNonce() { + when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev"))); + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false); + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String body = "{}"; + String signature = sign(SECRET, timestamp, "nonce-3", body); + + assertFalse(service.verifySignature(timestamp, "nonce-3", signature, body)); + } + + private ModerationForwardConfig config(List order) { + Map targets = new LinkedHashMap<>(); + targets.put("dev", DEV_TARGET); + targets.put("prod", PROD_TARGET); + return new ModerationForwardConfig(true, targets, SECRET, order, + ModerationForwardConfig.DEFAULT_MAX_RETRY, ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS); + } + + private ModerationCallbackForwardDO row(Long id, String traceId, String status, int retryCount) { + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setId(id); + row.setTraceId(traceId); + row.setPayload("{\"trace_id\":\"" + traceId + "\",\"result\":{\"suggest\":\"review\"}}"); + row.setSourceEnv("sit"); + row.setStatus(status); + row.setRetryCount(retryCount); + row.setCreatedAt(LocalDateTime.now().minusMinutes(10)); + return row; + } + + private ModerationCallbackForwardDO capturedInsert() { + ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class); + verify(forwardMapper).insert(captor.capture()); + return captor.getValue(); + } + + @SuppressWarnings("unchecked") + private UpdateWrapper outcomeWrapper() { + ArgumentCaptor> captor = + ArgumentCaptor.forClass(UpdateWrapper.class); + verify(forwardMapper, times(2)).update(isNull(), captor.capture()); + return captor.getAllValues().get(1); + } + + private LocalDateTime firstLocalDateTimeIgnoringNull(UpdateWrapper wrapper) { + LocalDateTime now = LocalDateTime.now(); + for (Object value : wrapper.getParamNameValuePairs().values()) { + if (value instanceof LocalDateTime && ((LocalDateTime) value).isAfter(now.plusSeconds(1))) { + return (LocalDateTime) value; + } + } + return null; + } + + private boolean hasFutureAttempt(UpdateWrapper wrapper, int minSeconds) { + LocalDateTime threshold = LocalDateTime.now().plusSeconds(minSeconds); + return wrapper.getParamNameValuePairs().values().stream() + .filter(LocalDateTime.class::isInstance) + .map(LocalDateTime.class::cast) + .anyMatch(value -> value.isAfter(threshold)); + } + + private List attachLogAppender() { + List messages = new CopyOnWriteArrayList<>(); + AbstractAppender appender = new AbstractAppender("moderation-test", null, null, false) { + @Override + public void append(LogEvent event) { + messages.add(event.getMessage().getFormattedMessage()); + } + }; + appender.start(); + Logger logger = (Logger) LogManager.getLogger(ContentModerationForwardServiceImpl.class); + logger.addAppender(appender); + return messages; + } + + private String sign(String secret, String timestamp, String nonce, String body) { + try { + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body); + byte[] digest = mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)); + StringBuilder builder = new StringBuilder(); + for (byte item : digest) builder.append(String.format("%02x", item)); + return builder.toString(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private String sha256Hex(String value) { + try { + java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder builder = new StringBuilder(); + for (byte item : bytes) builder.append(String.format("%02x", item)); + return builder.toString(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java new file mode 100644 index 00000000..d9c89eb0 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java @@ -0,0 +1,221 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.DialProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialMode; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DirectDialTargetProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.PlaceholderPrivacyNumberProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CustomerDialServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserService userService; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private RequestThrottleService requestThrottleService; + @Mock private SecurityAuditSupport securityAuditSupport; + @Mock private PhoneCrypto phoneCrypto; + @Mock private HttpServletRequest request; + + private CustomerDialServiceImpl service; + private UserDO currentUser; + private UserDO customer; + private OrderDO order; + + @BeforeEach + void setUp() { + DialProperties properties = new DialProperties(); + List providers = List.of( + new DirectDialTargetProvider(phoneCrypto), + new PlaceholderPrivacyNumberProvider()); + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, orderItemMapper, + requestThrottleService, securityAuditSupport, properties, providers); + + currentUser = new UserDO(); + currentUser.setId(9L); + currentUser.setType(2); + currentUser.setShopId(1L); + + customer = new UserDO(); + customer.setId(100L); + customer.setType(0); + customer.setIsDelete(0); + + order = new OrderDO(); + order.setId(10L); + order.setUserId(100L); + order.setShopId(1L); + order.setIsDelete(0); + } + + @Test + void directProviderReturnsFullNumberOnceAndWritesAudit() { + customer.setPhone("encrypted-phone"); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + CustomerDialVO result = service.dial(currentUser, 100L, null, 10L, request); + + assertEquals(DialMode.DIRECT, result.getMode()); + assertEquals("13800138000", result.getDialNumber()); + verify(requestThrottleService).checkCustomerDial(request, 9L); + verify(securityAuditSupport).success(eq(request), anyString(), anyString()); + } + + @Test + void guestOrderUsesSnapshotWithoutRequiringCustomerAccount() { + order.setUserId(null); + order.setCustomerPhoneSnapshot("encrypted-snapshot"); + when(phoneCrypto.decrypt("encrypted-snapshot")).thenReturn("13900139000"); + when(orderMapper.selectById(10L)).thenReturn(order); + + CustomerDialVO result = service.dial(currentUser, null, null, 10L, request); + + assertEquals("13900139000", result.getDialNumber()); + assertEquals(DialMode.DIRECT, result.getMode()); + verify(securityAuditSupport).success(eq(request), anyString(), anyString()); + } + + @Test + void orderSnapshotTakesPriorityOverCustomerProfile() { + order.setCustomerPhoneSnapshot("encrypted-snapshot"); + customer.setPhone("encrypted-customer-phone"); + when(phoneCrypto.decrypt("encrypted-snapshot")).thenReturn("13900139000"); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + CustomerDialVO result = service.dial(currentUser, 100L, null, 10L, request); + + assertEquals("13900139000", result.getDialNumber()); + } + + @Test + void appointmentLocatorResolvesOrderItemThenOrder() { + OrderItemDO item = new OrderItemDO(); + item.setId(5L); + item.setOrderId(10L); + item.setIsDelete(0); + when(orderItemMapper.selectById(5L)).thenReturn(item); + when(orderMapper.selectById(10L)).thenReturn(order); + when(userService.getById(100L)).thenReturn(customer); + customer.setPhone("encrypted-phone"); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + + CustomerDialVO result = service.dial(currentUser, null, 5L, null, request); + + assertEquals("13800138000", result.getDialNumber()); + verify(securityAuditSupport).success(eq(request), anyString(), anyString()); + } + + @Test + void rejectsWhenAppointmentAndOrderDoNotMatch() { + OrderItemDO item = new OrderItemDO(); + item.setId(5L); + item.setOrderId(10L); + item.setIsDelete(0); + when(orderItemMapper.selectById(5L)).thenReturn(item); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, null, 5L, 11L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void guestOrderWithoutAnyPhoneReturnsExplicitBusinessCode() { + order.setUserId(null); + order.setCustomerPhoneSnapshot(null); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, null, null, 10L, request)); + + assertEquals(DirectDialTargetProvider.NUMBER_UNAVAILABLE_CODE, error.getCode()); + assertTrue(error.getMessage().contains(DirectDialTargetProvider.NUMBER_UNAVAILABLE_BUSINESS_CODE)); + verify(securityAuditSupport).fail(eq(request), anyString(), anyString()); + } + + @Test + void rejectsWhenNoLocatorProvided() { + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, null, null, null, request)); + + assertEquals(400, error.getCode()); + } + + @Test + void rejectsOrderOfAnotherShop() { + order.setShopId(2L); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, null, 10L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void rejectsOrderThatDoesNotBelongToCustomer() { + order.setUserId(101L); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, null, 10L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void privacyNumberProviderReportsNotConfiguredWithoutFallingBackToRealNumber() { + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, orderItemMapper, + requestThrottleService, securityAuditSupport, privacyProperties(), List.of( + new DirectDialTargetProvider(phoneCrypto), + new PlaceholderPrivacyNumberProvider())); + customer.setPhone("encrypted-phone"); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, null, 10L, request)); + + assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, error.getCode()); + verify(securityAuditSupport).fail(eq(request), anyString(), anyString()); + } + + private DialProperties privacyProperties() { + DialProperties properties = new DialProperties(); + properties.setProvider("privacy-number"); + return properties; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java new file mode 100644 index 00000000..8ff5e146 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java @@ -0,0 +1,484 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniRegistrationTicket; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.LocalMockContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; + +import java.util.Collection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doAnswer; + +@ExtendWith(MockitoExtension.class) +class WorkbenchRegistrationServiceImplTest { + + @Mock private WorkbenchRegistrationApplicationMapper applicationMapper; + @Mock private UserMapper userMapper; + @Mock private ShopMapper shopMapper; + @Mock private UserService userService; + @Mock private UserShopBindingSupport userShopBindingSupport; + @Mock private UserShopBindingMapper userShopBindingMapper; + @Mock private WechatMiniAuthService wechatMiniAuthService; + @Mock private SystemParameterConfigService systemParameterConfigService; + @Mock private ContentModerationService contentModerationService; + @Mock private ContentModerationRecordMapper contentModerationRecordMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private ShopBusinessScheduleService shopBusinessScheduleService; + @Mock private PlatformTransactionManager transactionManager; + @Mock private WechatMiniBindingMapper wechatMiniBindingMapper; + @Mock private ObjectStorageFileService objectStorageFileService; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + + private WorkbenchRegistrationServiceImpl service; + + @BeforeEach + void setUp() { + service = new WorkbenchRegistrationServiceImpl(applicationMapper, userMapper, shopMapper, userService, + userShopBindingSupport, userShopBindingMapper, wechatMiniAuthService, systemParameterConfigService, + contentModerationService, contentModerationRecordMapper, shopBusinessExpiryService, shopBusinessScheduleService, transactionManager, + wechatMiniBindingMapper, objectStorageFileService, objectStorageUrlSupport); + } + + @Test + void returnsManagerReviewSummaryFromCurrentShopAndSwitch() { + UserDO manager = manager(7L, 21L); + when(userMapper.selectById(7L)).thenReturn(manager); + when(applicationMapper.countPendingStaffApplicationsForReview(21L)).thenReturn(3L); + when(systemParameterConfigService.getEnabledValue("WORKBENCH", "MANAGER_REGISTRATION_REVIEW_NOTICE")) + .thenReturn("true"); + + WorkbenchRegistrationReviewSummaryVO summary = service.getReviewSummary(7L); + + assertEquals(3L, summary.getPendingCount()); + assertEquals(true, summary.isNoticeEnabled()); + } + + @Test + void rejectsSummaryForNonManager() { + UserDO staff = new UserDO(); + staff.setId(8L); + staff.setType(3); + staff.setShopId(21L); + when(userMapper.selectById(8L)).thenReturn(staff); + + assertThrows(IllegalArgumentException.class, () -> service.getReviewSummary(8L)); + } + + @Test + void hidesApplicantProfileUntilItsContentModerationPasses() { + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(31L); + application.setUserId(9L); + application.setApplicationNo("SALON-001"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setShopId(21L); + when(applicationMapper.selectPendingStaffApplicationsForReview(21L)).thenReturn(List.of(application)); + UserDO applicant = new UserDO(); + applicant.setId(9L); + applicant.setNickname("小周"); + applicant.setPhone("13812345678"); + when(userMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(applicant)); + + List result = service.listForReviewer(7L, false); + + assertEquals(0, result.size()); + } + + @Test + void returnsApplicantProfileOnlyAfterLinkedModerationIsApproved() { + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + WorkbenchRegistrationApplicationDO application = staffReviewApplication(31L, 9L, 81L); + application.setApplicantNickname("真实申请昵称"); + application.setApplicantAvatarFileId(73L); + when(applicationMapper.selectPendingStaffApplicationsForReview(21L)).thenReturn(List.of(application)); + UserDO applicant = new UserDO(); + applicant.setId(9L); + applicant.setPhone("13812345678"); + when(userMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(applicant)); + ContentModerationRecordDO moderation = staffModeration(81L, 31L, 9L, "APPROVED"); + when(contentModerationRecordMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(moderation)); + when(objectStorageFileService.createTemporaryModerationUrl(73L, 30)).thenReturn("https://example.test/avatar"); + + List result = service.listForReviewer(7L, false); + + assertEquals(1, result.size()); + assertEquals("真实申请昵称", result.get(0).getApplicantNickname()); + assertEquals("https://example.test/avatar", result.get(0).getApplicantAvatar()); + assertEquals("APPROVED", result.get(0).getContentModerationStatus()); + assertEquals("138****5678", result.get(0).getApplicantMaskedPhone()); + } + + @Test + void transitionsStaffApplicationAfterAsynchronousContentModeration() { + WorkbenchRegistrationApplicationDO application = staffReviewApplication(31L, 9L, 81L); + application.setStatus(WorkbenchRegistrationStatus.PENDING_CONTENT); + when(applicationMapper.selectByIdForUpdate(31L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(81L)).thenReturn(staffModeration(81L, 31L, 9L, "APPROVED")); + + service.processStaffModeration(31L); + + assertEquals(WorkbenchRegistrationStatus.PENDING_MANAGER, application.getStatus()); + verify(applicationMapper).updateById(application); + + application.setStatus(WorkbenchRegistrationStatus.PENDING_CONTENT); + when(contentModerationRecordMapper.selectById(81L)).thenReturn(staffModeration(81L, 31L, 9L, "REJECTED")); + service.processStaffModeration(31L); + + assertEquals(WorkbenchRegistrationStatus.REJECTED, application.getStatus()); + assertEquals(WorkbenchRegistrationStatus.REJECTED, application.getStatus()); + verify(applicationMapper, org.mockito.Mockito.times(2)).updateById(application); + } + + @Test + void locksApplicationAndRejectsAlreadyProcessedReview() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(31L); + application.setShopId(21L); + application.setStatus(WorkbenchRegistrationStatus.APPROVED); + when(applicationMapper.selectByIdForUpdate(31L)).thenReturn(application); + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + + assertThrows(IllegalArgumentException.class, () -> service.approve(7L, false, 31L)); + verify(applicationMapper).selectByIdForUpdate(31L); + } + + @Test + void approvesStaffApplicationByTransferringWechatIdentityToSelectedEmployee() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(41L); + application.setUserId(99L); + application.setShopId(21L); + application.setRoleType("STAFF"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setContentModerationRecordId(82L); + when(applicationMapper.selectByIdForUpdate(41L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(82L)).thenReturn(staffModeration(82L, 41L, 99L, "APPROVED")); + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + UserDO applicant = new UserDO(); + applicant.setId(99L); + when(userMapper.selectById(99L)).thenReturn(applicant); + UserDO target = new UserDO(); + target.setId(51L); + target.setType(3); + target.setShopId(21L); + target.setStatus(1); + target.setIsDelete(0); + target.setNickname("门店员工"); + when(userMapper.selectOne(any(Wrapper.class))).thenReturn(target); + when(wechatMiniBindingMapper.selectCount(any(Wrapper.class))).thenReturn(0L); + when(applicationMapper.selectOne(any(Wrapper.class))).thenReturn(null); + + WorkbenchRegistrationApproveDTO request = new WorkbenchRegistrationApproveDTO(); + request.setTargetArtistUserId(51L); + assertEquals(true, service.approve(7L, false, 41L, request)); + + assertEquals(WorkbenchRegistrationStatus.APPROVED, application.getStatus()); + assertEquals(51L, application.getTargetArtistUserId()); + assertEquals(0, applicant.getStatus()); + assertEquals(1, target.getStatus()); + verify(wechatMiniAuthService).transferRegistrationBinding(99L, 51L); + verify(userShopBindingSupport).updateBindingStatus(51L, 21L, 1); + verify(userService).syncManagedPermissions(51L); + } + + @Test + void managerApplicationCannotBeApprovedBeforeContentModerationPasses() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(32L); + application.setUserId(9L); + application.setShopId(21L); + application.setRoleType("MANAGER"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_ADMIN); + application.setContentModerationRecordId(81L); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(81L); + moderation.setStatus("PENDING"); + when(applicationMapper.selectByIdForUpdate(32L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(81L)).thenReturn(moderation); + + assertThrows(IllegalArgumentException.class, () -> service.approve(1L, true, 32L)); + + verify(shopMapper, org.mockito.Mockito.never()).updateById(any()); + verify(userMapper, org.mockito.Mockito.never()).updateById(any()); + } + + @Test + void platformAdminListShowsManagerApplicationsAcrossStatuses() { + WorkbenchRegistrationApplicationDO pending = managerApplication(33L, WorkbenchRegistrationStatus.PENDING_ADMIN); + pending.setContentModerationRecordId(82L); + WorkbenchRegistrationApplicationDO approved = managerApplication(34L, WorkbenchRegistrationStatus.APPROVED); + WorkbenchRegistrationApplicationDO rejected = managerApplication(35L, WorkbenchRegistrationStatus.REJECTED); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(82L); + moderation.setStatus("PENDING"); + when(applicationMapper.selectList(any(Wrapper.class))).thenReturn(List.of(pending, approved, rejected)); + UserDO applicant = new UserDO(); + applicant.setId(9L); + when(userMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(applicant)); + when(contentModerationRecordMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(moderation)); + + List result = service.listForReviewer(1L, true); + + assertEquals(3, result.size()); + assertEquals(WorkbenchRegistrationStatus.PENDING_ADMIN, result.get(0).getStatus()); + assertEquals("PENDING", result.get(0).getContentModerationStatus()); + assertEquals(WorkbenchRegistrationStatus.APPROVED, result.get(1).getStatus()); + assertEquals(WorkbenchRegistrationStatus.REJECTED, result.get(2).getStatus()); + } + + @Test + void devMockApprovesUnmarkedContentAndKeepsExplicitReviewScenarios() { + LocalMockContentModerationProvider provider = new LocalMockContentModerationProvider(); + + assertEquals(ModerationOutcome.Status.APPROVED, + provider.reviewText("SHOP", "普通门店资料", "openid").status()); + assertEquals(ModerationOutcome.Status.REJECTED, + provider.reviewText("SHOP", "[[MOCK:REJECT]]", "openid").status()); + assertEquals(ModerationOutcome.Status.PENDING, + provider.reviewText("SHOP", "[[MOCK:PENDING]]", "openid").status()); + } + + @Test + void autoApprovesManagerOnlyWhenLinkedShopContentPassed() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(34L); + application.setUserId(9L); + application.setShopId(21L); + application.setRoleType("MANAGER"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_ADMIN); + application.setContentModerationRecordId(83L); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(83L); + moderation.setContentType("SHOP"); + moderation.setUserId(9L); + moderation.setStatus("APPROVED"); + UserDO applicant = new UserDO(); + applicant.setId(9L); + ShopDO shop = new ShopDO(); + shop.setId(21L); + when(applicationMapper.selectByIdForUpdate(34L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(83L)).thenReturn(moderation); + when(systemParameterConfigService.getEnabledValue("WORKBENCH", "MANAGER_REGISTRATION_AUTO_APPROVE")) + .thenReturn("true"); + when(userMapper.selectById(9L)).thenReturn(applicant); + when(shopMapper.selectById(21L)).thenReturn(shop); + + service.processManagerModeration(34L); + + assertEquals(WorkbenchRegistrationStatus.APPROVED, application.getStatus()); + verify(shopBusinessExpiryService).startDefaultValidity(org.mockito.ArgumentMatchers.eq(21L), any()); + verify(userShopBindingSupport).updateBindingStatus(9L, 21L, 1); + verify(userService).syncManagedPermissions(9L); + } + + @Test + void automaticApprovalSwitchDoesNotApproveUntilContentReviewPasses() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(36L); + application.setUserId(9L); + application.setShopId(21L); + application.setRoleType("MANAGER"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_ADMIN); + application.setContentModerationRecordId(84L); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(84L); + moderation.setContentType("SHOP"); + moderation.setUserId(9L); + moderation.setStatus("PENDING"); + when(applicationMapper.selectByIdForUpdate(36L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(84L)).thenReturn(moderation); + when(systemParameterConfigService.getEnabledValue("WORKBENCH", "MANAGER_REGISTRATION_AUTO_APPROVE")) + .thenReturn("true"); + + service.processManagerModeration(36L); + + assertEquals(WorkbenchRegistrationStatus.PENDING_ADMIN, application.getStatus()); + verify(userMapper, org.mockito.Mockito.never()).updateById(any()); + verify(shopMapper, org.mockito.Mockito.never()).updateById(any()); + } + + @Test + void rejectsStaffRegistrationWithoutRequiredNicknameOrAvatarBeforeConsumingTicket() { + when(shopMapper.selectOne(any(Wrapper.class))).thenReturn(availableShop()); + + WorkbenchRegistrationRequestDTO missingNickname = staffRegistrationRequest(); + missingNickname.setApplicantNickname(" "); + assertThrows(IllegalArgumentException.class, () -> service.register(missingNickname)); + + WorkbenchRegistrationRequestDTO missingAvatar = staffRegistrationRequest(); + missingAvatar.setApplicantAvatarFileId(null); + assertThrows(IllegalArgumentException.class, () -> service.register(missingAvatar)); + + verify(wechatMiniAuthService, org.mockito.Mockito.never()).consumeRegistrationTicket(any()); + } + + @Test + void allowsRepeatedStaffResubmissionAndKeepsEachRejectedApplicationVersion() { + when(shopMapper.selectOne(any(Wrapper.class))).thenReturn(availableShop()); + UserDO applicant = new UserDO(); + applicant.setId(9L); + applicant.setNickname("微信用户测试"); + applicant.setType(3); + applicant.setStatus(0); + applicant.setIsDelete(0); + when(userMapper.selectById(9L)).thenReturn(applicant); + when(wechatMiniAuthService.validateRegistrationTicket(any())) + .thenReturn(new WechatMiniRegistrationTicket(9L, "app-id", "openid")); + + ContentModerationResultVO moderationResult = new ContentModerationResultVO(); + moderationResult.setRecordId(501L); + moderationResult.setStatus("PENDING"); + when(contentModerationService.assessVersion(any(), any(), any(), any(), any(), any())).thenReturn(moderationResult); + ContentModerationRecordDO moderationRecord = new ContentModerationRecordDO(); + moderationRecord.setId(501L); + moderationRecord.setStatus("PENDING"); + when(contentModerationRecordMapper.selectById(501L)).thenReturn(moderationRecord); + + Map applications = new HashMap<>(); + WorkbenchRegistrationApplicationDO firstRejected = rejectedStaffApplication(41L, 9L, 21L); + applications.put(firstRejected.getId(), firstRejected); + when(applicationMapper.selectById(any())).thenAnswer(invocation -> applications.get(invocation.getArgument(0))); + List inserted = new ArrayList<>(); + AtomicLong nextId = new AtomicLong(100L); + doAnswer(invocation -> { + WorkbenchRegistrationApplicationDO application = invocation.getArgument(0); + application.setId(nextId.getAndIncrement()); + inserted.add(application); + applications.put(application.getId(), application); + return 1; + }).when(applicationMapper).insert(any(WorkbenchRegistrationApplicationDO.class)); + + WorkbenchRegistrationRequestDTO firstRequest = staffRegistrationRequest(); + firstRequest.setApplicationId(firstRejected.getId()); + WorkbenchRegistrationStatusVO firstResult = service.register(firstRequest); + inserted.get(0).setStatus(WorkbenchRegistrationStatus.REJECTED); + inserted.get(0).setRejectReason("需要修改资料"); + + WorkbenchRegistrationRequestDTO secondRequest = staffRegistrationRequest(); + secondRequest.setRegistrationTicket("ticket-2"); + secondRequest.setApplicationId(inserted.get(0).getId()); + WorkbenchRegistrationStatusVO secondResult = service.register(secondRequest); + + assertEquals(WorkbenchRegistrationStatus.PENDING_CONTENT, firstResult.getStatus()); + assertEquals(WorkbenchRegistrationStatus.PENDING_CONTENT, secondResult.getStatus()); + assertEquals(2, inserted.size()); + assertEquals(false, inserted.get(0).getId().equals(inserted.get(1).getId())); + assertEquals(WorkbenchRegistrationStatus.REJECTED, firstRejected.getStatus()); + assertEquals(WorkbenchRegistrationStatus.REJECTED, inserted.get(0).getStatus()); + verify(wechatMiniAuthService, org.mockito.Mockito.times(2)).consumeRegistrationTicket(any()); + } + + private WorkbenchRegistrationRequestDTO staffRegistrationRequest() { + WorkbenchRegistrationRequestDTO request = new WorkbenchRegistrationRequestDTO(); + request.setRegistrationTicket("ticket-1"); + request.setRoleType("STAFF"); + request.setShopId(21L); + request.setApplicantNickname("小周"); + request.setApplicantAvatarFileId(301L); + request.setAgreementAccepted(true); + return request; + } + + private WorkbenchRegistrationApplicationDO staffReviewApplication(Long id, Long userId, Long moderationId) { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(id); + application.setUserId(userId); + application.setRoleType("STAFF"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setShopId(21L); + application.setContentModerationRecordId(moderationId); + return application; + } + + private ContentModerationRecordDO staffModeration(Long id, Long applicationId, Long userId, String status) { + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(id); + moderation.setContentType("STAFF_REGISTRATION"); + moderation.setBusinessId(applicationId); + moderation.setUserId(userId); + moderation.setStatus(status); + return moderation; + } + + private ShopDO availableShop() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setShopName("Salon中央店"); + shop.setAddress("杭州市西湖区"); + shop.setStatus(1); + shop.setIsDelete(0); + return shop; + } + + private WorkbenchRegistrationApplicationDO rejectedStaffApplication(Long id, Long userId, Long shopId) { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(id); + application.setUserId(userId); + application.setRoleType("STAFF"); + application.setShopId(shopId); + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setIsDelete(0); + return application; + } + + private UserDO manager(Long id, Long shopId) { + UserDO manager = new UserDO(); + manager.setId(id); + manager.setType(2); + manager.setShopId(shopId); + return manager; + } + + private WorkbenchRegistrationApplicationDO managerApplication(Long id, String status) { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(id); + application.setUserId(9L); + application.setRoleType("MANAGER"); + application.setShopId(21L); + application.setStatus(status); + return application; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java new file mode 100644 index 00000000..22d4df10 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java @@ -0,0 +1,134 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MapService; +import com.xiaowang.jayucloud.salon.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.salon.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.eq; + +@ExtendWith(MockitoExtension.class) +class ShopAppointmentSettingsTest { + + @Mock private ShopMapper shopMapper; + @Mock private ContentModerationRecordMapper contentModerationRecordMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private ShopBusinessScheduleService shopBusinessScheduleService; + @Mock private CouponService couponService; + @Mock private CouponMapper couponMapper; + @Mock private ProductMapper productMapper; + @Mock private TagMapper tagMapper; + @Mock private CommentMapper commentMapper; + @Mock private UserCouponMapper userCouponMapper; + @Mock private OrderArtistReviewMapper orderArtistReviewMapper; + @Mock private ObjectStorageFileService objectStorageFileService; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private UserShopBindingSupport userShopBindingSupport; + @Mock private NailArtistInfoService nailArtistInfoService; + @Mock private com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService multiLevelCacheService; + @Mock private AppCacheProperties appCacheProperties; + @Mock private MapService mapService; + @Mock private ContentModerationService contentModerationService; + @Mock private ObjectMapper objectMapper; + + @InjectMocks + private ShopServiceImpl shopService; + + @Test + void savesAppointmentSettingsWithoutSubmittingPublicProfileForReview() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(shopMapper.updateById(any(ShopDO.class))).thenReturn(1); + ShopAppointmentSettingsDTO dto = new ShopAppointmentSettingsDTO(); + dto.setWeeklyHours(weeklyHours("09:30", "21:00")); + dto.setDefaultAppointmentDurationMinutes(75); + when(shopBusinessScheduleService.list(21L, "10:00-22:00")).thenReturn(weeklyHoursVO("09:30", "21:00")); + + assertTrue(shopService.updateAppointmentSettings(21L, dto)); + + ArgumentCaptor saved = ArgumentCaptor.forClass(ShopDO.class); + verify(shopMapper).updateById(saved.capture()); + assertEquals("09:30-21:00", saved.getValue().getAppointmentBusinessHours()); + assertEquals(75, saved.getValue().getDefaultAppointmentDurationMinutes()); + verify(shopBusinessScheduleService).save(eq(21L), eq(dto.getWeeklyHours()), eq(null)); + verifyNoInteractions(contentModerationService); + } + + @Test + void returnsDefaultDurationForExistingShopWithoutConfiguredValue() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setShopName("薄荷美甲"); + shop.setBusinessHours("09:00-21:00"); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(contentModerationRecordMapper.selectOne(any(Wrapper.class))).thenReturn(null); + when(shopBusinessScheduleService.list(21L, "09:00-21:00")).thenReturn(weeklyHoursVO("09:00", "21:00")); + + ShopAppointmentSettingsVO settings = shopService.getAppointmentSettings(21L); + + assertEquals("09:00-21:00", settings.getBusinessHours()); + assertEquals(7, settings.getWeeklyHours().size()); + assertEquals(60, settings.getDefaultAppointmentDurationMinutes()); + } + + private java.util.List weeklyHours(String start, String end) { + java.util.List result = new java.util.ArrayList<>(); + for (int day = 1; day <= 7; day++) { + com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO item = new com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO(); + item.setDayOfWeek(day); + item.setOpen(true); + item.setStartTime(start); + item.setEndTime(end); + result.add(item); + } + return result; + } + + private java.util.List weeklyHoursVO(String start, String end) { + java.util.List result = new java.util.ArrayList<>(); + for (int day = 1; day <= 7; day++) { + ShopBusinessHoursDayVO item = new ShopBusinessHoursDayVO(); + item.setDayOfWeek(day); + item.setOpen(true); + item.setStartTime(start); + item.setEndTime(end); + result.add(item); + } + return result; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java new file mode 100644 index 00000000..9fb0e17d --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java @@ -0,0 +1,172 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegrationConfigDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.impl.SecureIntegrationConfigServiceImpl; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; + +import java.util.Base64; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SecureIntegrationConfigServiceImplTest { + private static final String MASTER_KEY = Base64.getEncoder().encodeToString(new byte[32]); + private static final String CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; + + @Test + void devMockRemainsAvailableWithoutAnEncryptionKeyUntilAProviderWasSaved() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(null); + ContentModerationProperties moderationProperties = new ContentModerationProperties(); + moderationProperties.setAllowMock(true); + SecureIntegrationConfigServiceImpl service = service(mapper, + new SecureConfigEncryptionService(""), moderationProperties, configuredWechat()); + + ModerationRuntimeConfig config = service.getModerationRuntimeConfig(); + + assertEquals("MOCK", config.getProvider()); + assertTrue(config.isReady()); + } + + @Test + void savedWechatProviderFailsClosedWhenMasterKeyIsMissing() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(config("CONTENT_MODERATION", "PROVIDER", "WECHAT", + new SecureConfigEncryptionService(MASTER_KEY))); + ContentModerationProperties moderationProperties = new ContentModerationProperties(); + moderationProperties.setAllowMock(true); + SecureIntegrationConfigServiceImpl service = service(mapper, + new SecureConfigEncryptionService(""), moderationProperties, configuredWechat()); + + ModerationRuntimeConfig config = service.getModerationRuntimeConfig(); + + assertEquals("DISABLED", config.getProvider()); + assertFalse(config.isReady()); + } + + @Test + void savedWechatCallbackRequiresPublicExactPathAndBothMiniProgramCredentials() { + SecureConfigEncryptionService encryption = new SecureConfigEncryptionService(MASTER_KEY); + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn( + config("CONTENT_MODERATION", "PROVIDER", "DISABLED", encryption), + config("CONTENT_MODERATION", "CALLBACK_URL", "https://sit.yunail.art" + CALLBACK_PATH, encryption), + config("CONTENT_MODERATION", "CALLBACK_TOKEN", "callback-token", encryption), + config("CONTENT_MODERATION", "ENCODING_AES_KEY", "A".repeat(43), encryption)); + SecureIntegrationConfigServiceImpl service = service(mapper, encryption, + new ContentModerationProperties(), configuredWechat()); + + ModerationRuntimeConfig callback = service.getModerationCallbackConfig(); + + assertEquals("DISABLED", callback.getProvider()); + assertTrue(callback.isReady()); + assertEquals("callback-token", callback.getCallbackToken()); + } + + @Test + void rejectsLocalCallbackAddressAndMissingAppSecret() { + SecureConfigEncryptionService encryption = new SecureConfigEncryptionService(MASTER_KEY); + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn( + config("CONTENT_MODERATION", "PROVIDER", "WECHAT", encryption), + config("CONTENT_MODERATION", "CALLBACK_URL", "https://localhost" + CALLBACK_PATH, encryption), + config("CONTENT_MODERATION", "CALLBACK_TOKEN", "callback-token", encryption), + config("CONTENT_MODERATION", "ENCODING_AES_KEY", "A".repeat(43), encryption)); + WechatMiniProperties incompleteWechat = configuredWechat(); + incompleteWechat.setAppSecret(""); + SecureIntegrationConfigServiceImpl service = service(mapper, encryption, + new ContentModerationProperties(), incompleteWechat); + + ModerationRuntimeConfig config = service.getModerationRuntimeConfig(); + + assertEquals("DISABLED", config.getProvider()); + assertFalse(config.isReady()); + } + + @Test + void rejectsNonAlphanumericCallbackTokenEvenBeforeWechatProviderIsEnabled() { + SecureIntegrationConfigServiceImpl service = service( + mock(SecureIntegrationConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), + new ContentModerationProperties(), configuredWechat()); + SecureIntegrationConfigDTO dto = new SecureIntegrationConfigDTO(); + dto.setModerationProvider("DISABLED"); + dto.setModerationCallbackToken("token-with-dash"); + + assertThrows(IllegalArgumentException.class, + () -> service.saveModerationConfig(adminUser(), dto)); + } + + @Test + void mapRuntimeKeyRequiresPlatformAdminBeforeReadingStoredValues() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + UserDO currentUser = new UserDO(); + currentUser.setType(2); + SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( + mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), + new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper()); + + assertThrows(RuntimeException.class, () -> service.getMapRuntimeConfig(currentUser)); + verify(mapper, never()).selectOne(any()); + } + + @Test + void platformAdminCanReadMapRuntimeConfig() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(null); + when(mapper.selectList(any())).thenReturn(java.util.Collections.emptyList()); + when(mapper.selectCount(any())).thenReturn(0L); + UserDO currentUser = adminUser(); + SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( + mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), + new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper()); + + assertEquals("false", service.getMapRuntimeConfig(currentUser).get("enabled")); + verify(mapper, org.mockito.Mockito.atLeastOnce()).selectOne(any()); + } + + private SecureIntegrationConfigServiceImpl service(SecureIntegrationConfigMapper mapper, + SecureConfigEncryptionService encryption, + ContentModerationProperties moderationProperties, + WechatMiniProperties wechatProperties) { + return new SecureIntegrationConfigServiceImpl(mapper, mock(SystemParameterConfigMapper.class), encryption, + moderationProperties, wechatProperties, new com.fasterxml.jackson.databind.ObjectMapper()); + } + + private UserDO adminUser() { + UserDO user = new UserDO(); + user.setId(1L); + user.setType(4); + return user; + } + + private WechatMiniProperties configuredWechat() { + WechatMiniProperties properties = new WechatMiniProperties(); + properties.setAppId("mini-app-id"); + properties.setAppSecret("mini-app-secret"); + return properties; + } + + private SecureIntegrationConfigDO config(String group, String key, String value, + SecureConfigEncryptionService encryption) { + SecureIntegrationConfigDO record = new SecureIntegrationConfigDO(); + record.setConfigGroup(group); + record.setConfigKey(key); + record.setConfigValue(encryption.encrypt(value)); + record.setEnabled(1); + record.setSecret(1); + return record; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java new file mode 100644 index 00000000..9e285666 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java @@ -0,0 +1,249 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.WechatContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.IntegrationProbeResultMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import java.io.ByteArrayInputStream; +import java.net.URI; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import org.mockito.ArgumentCaptor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class IntegrationProbeServiceImplTest { + private final IntegrationProbeResultMapper results = mock(IntegrationProbeResultMapper.class); + private final SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); + private final WechatMiniProperties wechatProperties = new WechatMiniProperties(); + private final WechatMiniClientService wechatClient = mock(WechatMiniClientService.class); + private final WechatMiniBindingMapper bindings = mock(WechatMiniBindingMapper.class); + private final WechatContentModerationProvider moderationProvider = mock(WechatContentModerationProvider.class); + private final ObjectStorageProvider storageProvider = mock(ObjectStorageProvider.class); + private final MessageHubPushConfigService smsConfigs = mock(MessageHubPushConfigService.class); + private final MessageHubClientService smsClient = mock(MessageHubClientService.class); + private final RestTemplate restTemplate = mock(RestTemplate.class); + private final Environment environment = mock(Environment.class); + private final IntegrationProbeServiceImpl service = new IntegrationProbeServiceImpl( + results, new ObjectMapper(), secureConfig, wechatProperties, wechatClient, bindings, + moderationProvider, List.of(storageProvider), smsConfigs, smsClient, restTemplate, environment); + + @Test + void rejectsNonAdminBeforeAnyProbeSideEffect() { + UserDO manager = new UserDO(); + manager.setType(2); + + assertThrows(RuntimeException.class, () -> service.probe(manager, request("SMS", "CONFIG", "DIAGNOSTIC", false))); + verify(smsConfigs, never()).listConfigs(any()); + } + + @Test + void realSmsCannotBeSentWithoutExplicitConfirmation() { + assertThrows(IllegalArgumentException.class, + () -> service.probe(admin(), request("SMS", "SEND", "REAL", false))); + verify(smsClient, never()).sendSmsVerificationCode(any(), any(), any()); + } + + @Test + void devMockIsNotReportedAsAnAllowedMockWhenEnvironmentDisallowsIt() { + SecureIntegrationConfigVO config = new SecureIntegrationConfigVO(); + config.setModerationProvider("MOCK"); + config.setMockProviderAllowed(false); + when(secureConfig.getAdminConfig(any())).thenReturn(config); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("CONTENT_MODERATION", "CONFIG", "DIAGNOSTIC", false)); + + assertEquals("FAIL", result.getStatus()); + verify(moderationProvider, never()).reviewText(any(), any(), any()); + } + + @Test + void subscribeDiagnosticInMockModeDoesNotFetchTokenOrSendAnything() { + wechatProperties.setAppId("test-app"); + wechatProperties.setAppSecret("test-secret"); + wechatProperties.setSubscribeMessageEnabled(true); + wechatProperties.setSubscribeMessageProvider("mock"); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("SUBSCRIBE_MESSAGE", "CONFIG", "DIAGNOSTIC", false)); + + assertEquals("WARN", result.getStatus()); + verify(wechatClient, never()).getAccessTokenForContentModeration(); + verify(wechatClient, never()).sendSubscribeMessage(any(), any(), any(), any(), any()); + } + + @Test + void anOutstandingImageProbePreventsAnotherTemporaryUpload() throws Exception { + wechatProperties.setAppId("test-app"); + SecureIntegrationConfigVO config = new SecureIntegrationConfigVO(); + config.setModerationProvider("WECHAT"); + config.setModerationReady(true); + config.setModerationCallbackReady(true); + config.setEncryptionKeyConfigured(true); + config.setWechatMiniAppConfigured(true); + when(secureConfig.getAdminConfig(any())).thenReturn(config); + WechatMiniBindingDO binding = new WechatMiniBindingDO(); + binding.setOpenId("private-open-id"); + when(bindings.selectOne(any())).thenReturn(binding); + IntegrationProbeResultDO pending = new IntegrationProbeResultDO(); + pending.setId(10L); + pending.setServiceCode("CONTENT_MODERATION"); + pending.setOperationCode("IMAGE_CALLBACK"); + pending.setStatus("PENDING"); + pending.setExpiresAt(LocalDateTime.now().plusMinutes(2)); + when(results.selectOne(any())).thenReturn(pending); + + var result = service.probe(admin(), request("CONTENT_MODERATION", "IMAGE_CALLBACK", "DIAGNOSTIC", false)); + + assertEquals("PENDING", result.getStatus()); + verify(storageProvider, never()).uploadStream(any(), anyLong(), any(), any()); + verify(moderationProvider, never()).submitTestImage(any(), any()); + } + + @Test + void imageProbeSubmitsMediaAsImageType() { + when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token"); + when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class))) + .thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}"); + WechatContentModerationProvider provider = new WechatContentModerationProvider( + restTemplate, new ObjectMapper(), wechatClient, + new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); + + provider.submitTestImage("https://storage.test/probe.png", "private-open-id"); + + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpEntity.class); + verify(restTemplate).postForObject(anyString(), requestCaptor.capture(), eq(String.class)); + Map payload = (Map) requestCaptor.getValue().getBody(); + assertEquals(2, payload.get("media_type")); + assertEquals(1, payload.get("version")); + org.junit.jupiter.api.Assertions.assertFalse(payload.containsKey("extra")); + } + + @Test + void wechatInvalidImageRequestIsReportedAsParameterFormatError() { + when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token"); + when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class))) + .thenReturn("{\"errcode\":47001}"); + WechatContentModerationProvider provider = new WechatContentModerationProvider( + restTemplate, new ObjectMapper(), wechatClient, + new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); + + var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id"); + + assertEquals("47001", result.code()); + assertEquals("微信审核请求参数格式无效,请核对接口字段", result.reason()); + } + + @Test + void signedReadPassesRawPresignedUrlAsUriWithoutReencoding() throws Exception { + String signed = "https://jayucloud-salon-sit.oss-cn-chengdu.aliyuncs.com/integration-probe/probe.txt" + + "?Expires=1762600000&OSSAccessKeyId=LTAI-test&Signature=abc%2Bdef%2Fghi%3D"; + byte[] payload = "salon-integration-probe".getBytes(StandardCharsets.UTF_8); + when(storageProvider.providerCode()).thenReturn("ALIYUN_OSS"); + when(storageProvider.isEnabled()).thenReturn(true); + when(storageProvider.downloadFile(anyString())).thenReturn(new ByteArrayInputStream(payload)); + when(storageProvider.getPresignedUrl(anyString(), any())).thenReturn(signed); + when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(), eq(byte[].class))) + .thenReturn(new ResponseEntity<>(payload, HttpStatus.OK)); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("OBJECT_STORAGE", "ROUND_TRIP", "DIAGNOSTIC", false)); + + ArgumentCaptor uriCaptor = ArgumentCaptor.forClass(URI.class); + verify(restTemplate).exchange(uriCaptor.capture(), eq(HttpMethod.GET), any(), eq(byte[].class)); + assertEquals(signed, uriCaptor.getValue().toString(), "签名地址必须以 URI 原样传入,不能再被 URI_COMPONENT 编码"); + assertTrue(uriCaptor.getValue().toString().contains("%2B")); + verify(restTemplate, never()).getForObject(anyString(), eq(byte[].class)); + assertEquals("PASS", result.getStatus()); + } + + @Test + void storageFailureDetailCarriesStageAndExceptionType() throws Exception { + when(storageProvider.providerCode()).thenReturn("MINIO"); + when(storageProvider.isEnabled()).thenReturn(true); + when(storageProvider.downloadFile(anyString())).thenThrow(new UnknownHostException("sit.minio.yunail.art")); + + var result = service.probe(admin(), request("OBJECT_STORAGE", "ROUND_TRIP", "DIAGNOSTIC", false)); + + String detail = result.getChecks().get(0).getDetail(); + assertEquals("FAIL", result.getStatus()); + assertTrue(detail.contains("服务端读取失败"), detail); + assertTrue(detail.contains("UnknownHostException"), detail); + assertTrue(detail.contains("sit.minio.yunail.art"), detail); + } + + @Test + void storageFailureDetailMasksSignedUrlInsteadOfLeakingSignature() throws Exception { + String signed = "https://jayucloud-salon-sit.oss-cn-chengdu.aliyuncs.com/integration-probe/probe.txt" + + "?Expires=1762600000&OSSAccessKeyId=LTAI-test&Signature=abc%2Bdef%3D"; + byte[] payload = "salon-integration-probe".getBytes(StandardCharsets.UTF_8); + when(storageProvider.providerCode()).thenReturn("ALIYUN_OSS"); + when(storageProvider.isEnabled()).thenReturn(true); + when(storageProvider.downloadFile(anyString())).thenReturn(new ByteArrayInputStream(payload)); + when(storageProvider.getPresignedUrl(anyString(), any())).thenReturn(signed); + when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(), eq(byte[].class))) + .thenThrow(new IllegalStateException("403 SignatureDoesNotMatch for URL: " + signed)); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("OBJECT_STORAGE", "ROUND_TRIP", "DIAGNOSTIC", false)); + + String detail = result.getChecks().get(0).getDetail(); + assertTrue(detail.contains("签名访问失败"), detail); + assertTrue(detail.contains("IllegalStateException"), detail); + assertTrue(detail.contains("jayucloud-salon-sit.oss-cn-chengdu.aliyuncs.com"), detail); + assertFalse(detail.contains("Signature="), detail); + assertFalse(detail.contains("OSSAccessKeyId"), detail); + assertFalse(detail.contains("%2B"), detail); + } + + private UserDO admin() { + UserDO user = new UserDO(); + user.setId(1L); + user.setType(4); + return user; + } + + private IntegrationProbeRequestDTO request(String service, String operation, String mode, boolean confirmed) { + IntegrationProbeRequestDTO request = new IntegrationProbeRequestDTO(); + request.setService(service); + request.setOperation(operation); + request.setMode(mode); + request.setConfirmed(confirmed); + request.setTargetPhone("13800138000"); + return request; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java new file mode 100644 index 00000000..c1f85ece --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java @@ -0,0 +1,130 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.xiaowang.jayucloud.salon.core.modules.system.entity.LegalAgreementDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.LegalAgreementMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class LegalAgreementServiceImplTest { + + private static final String CURRENT_VERSION = "2026.11.04-R2"; + + @Mock private LegalAgreementMapper agreementMapper; + @Mock private UserAgreementConsentMapper consentMapper; + @Mock private HttpServletRequest request; + + private LegalAgreementServiceImpl service; + private LegalAgreementDO userTerms; + private LegalAgreementDO privacyPolicy; + + @BeforeEach + void setUp() { + service = new LegalAgreementServiceImpl(agreementMapper, consentMapper); + userTerms = currentAgreement(LegalAgreementServiceImpl.USER_TERMS); + privacyPolicy = currentAgreement(LegalAgreementServiceImpl.PRIVACY_POLICY); + } + + @Test + void anonymousPendingReturnsCurrentVersionsOnly() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + + AgreementPendingVO result = service.getPendingAgreements(null); + + assertEquals(CURRENT_VERSION, result.getCurrentVersions().get(LegalAgreementServiceImpl.USER_TERMS)); + assertEquals(CURRENT_VERSION, result.getCurrentVersions().get(LegalAgreementServiceImpl.PRIVACY_POLICY)); + assertTrue(result.getAcceptedVersions().isEmpty()); + assertNull(result.getPending()); + } + + @Test + void loggedInUserWithoutConsentIsPending() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectList(any())).thenReturn(new ArrayList<>()); + + AgreementPendingVO result = service.getPendingAgreements(8L); + + assertEquals(Boolean.TRUE, result.getPending()); + assertEquals(List.of(LegalAgreementServiceImpl.USER_TERMS, LegalAgreementServiceImpl.PRIVACY_POLICY), + result.getPendingTypes()); + } + + @Test + void oldVersionConsentIsPending() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectList(any())).thenReturn(List.of( + consent(LegalAgreementServiceImpl.USER_TERMS, "2026.11.04"), + consent(LegalAgreementServiceImpl.PRIVACY_POLICY, "2026.11.04"))); + + AgreementPendingVO result = service.getPendingAgreements(8L); + + assertEquals(Boolean.TRUE, result.getPending()); + assertEquals("2026.11.04", result.getAcceptedVersions().get(LegalAgreementServiceImpl.USER_TERMS)); + assertEquals(2, result.getPendingTypes().size()); + } + + @Test + void acceptedCurrentVersionsAreNotPending() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectList(any())).thenReturn(List.of( + consent(LegalAgreementServiceImpl.USER_TERMS, CURRENT_VERSION), + consent(LegalAgreementServiceImpl.PRIVACY_POLICY, CURRENT_VERSION))); + + AgreementPendingVO result = service.getPendingAgreements(8L); + + assertEquals(Boolean.FALSE, result.getPending()); + assertTrue(result.getPendingTypes().isEmpty()); + } + + @Test + void acceptRecordsBothCurrentVersions() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectOne(any())).thenReturn(null); + + service.acceptCurrentAgreements(8L, "WECHAT_MINI", request); + + ArgumentCaptor captor = ArgumentCaptor.forClass(UserAgreementConsentDO.class); + verify(consentMapper, times(2)).insert(captor.capture()); + assertEquals(8L, captor.getAllValues().get(0).getUserId()); + assertEquals(CURRENT_VERSION, captor.getAllValues().get(0).getVersion()); + assertEquals(CURRENT_VERSION, captor.getAllValues().get(1).getVersion()); + assertEquals("WECHAT_MINI", captor.getAllValues().get(0).getClientType()); + assertEquals("agreement-gate", captor.getAllValues().get(0).getEntry()); + } + + private LegalAgreementDO currentAgreement(String type) { + LegalAgreementDO agreement = new LegalAgreementDO(); + agreement.setAgreementType(type); + agreement.setVersion(CURRENT_VERSION); + agreement.setStatus(1); + agreement.setIsDelete(0); + return agreement; + } + + private UserAgreementConsentDO consent(String type, String version) { + UserAgreementConsentDO consent = new UserAgreementConsentDO(); + consent.setUserId(8L); + consent.setAgreementType(type); + consent.setVersion(version); + return consent; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImplTest.java new file mode 100644 index 00000000..fa284c37 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImplTest.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SystemParameterConfigServiceImplTest { + @Test + void objectStorageReadOrderMustContainEachProviderExactlyOnce() { + SystemParameterConfigMapper mapper = mock(SystemParameterConfigMapper.class); + SystemParameterConfigServiceImpl service = new SystemParameterConfigServiceImpl( + mapper, mock(MessageHubPushConfigService.class)); + UserDO admin = new UserDO(); + admin.setType(4); + SystemParameterConfigDTO config = new SystemParameterConfigDTO(); + config.setConfigGroup("FILE"); + config.setConfigKey("IMAGE_READ_PROVIDER_ORDER"); + config.setConfigName("对象存储图片读取优先级"); + config.setConfigValue("MINIO,MINIO,ALIYUN_OSS"); + + assertThrows(IllegalArgumentException.class, () -> service.saveConfig(admin, config)); + verify(mapper, never()).selectOne(any()); + verify(mapper, never()).insert(any()); + } + + @Test + void validObjectStorageReadOrderIsSavedAsProvided() { + SystemParameterConfigMapper mapper = mock(SystemParameterConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(null); + SystemParameterConfigServiceImpl service = new SystemParameterConfigServiceImpl( + mapper, mock(MessageHubPushConfigService.class)); + UserDO admin = new UserDO(); + admin.setType(4); + SystemParameterConfigDTO config = new SystemParameterConfigDTO(); + config.setConfigGroup("FILE"); + config.setConfigKey("IMAGE_READ_PROVIDER_ORDER"); + config.setConfigName("对象存储图片读取优先级"); + config.setConfigValue("ALIYUN_OSS,QINIU_KODO,MINIO"); + + service.saveConfig(admin, config); + + org.mockito.ArgumentCaptor captor = + org.mockito.ArgumentCaptor.forClass(com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO.class); + verify(mapper).insert(captor.capture()); + org.junit.jupiter.api.Assertions.assertEquals("ALIYUN_OSS,QINIU_KODO,MINIO", captor.getValue().getConfigValue()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java new file mode 100644 index 00000000..ebfe3620 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java @@ -0,0 +1,109 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.controller.front; + +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; +import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; +import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import org.junit.jupiter.api.Test; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class UserControllerPhonePrivacyTest { + + @Test + void currentUserInfoUsesServiceEnrichedWithShopExpiry() { + UserService userService = mock(UserService.class); + UserVO profile = new UserVO(); + profile.setShopBusinessExpireTime(java.time.LocalDate.of(2026, 12, 31).atTime(23, 59, 59)); + profile.setShopBusinessExpired(false); + profile.setShopBusinessRemainingDays(66); + when(userService.getCurrentUserInfo()).thenReturn(profile); + UserController controller = new UserController(userService, + mock(PrimaryObjectStorageService.class), mock(ObjectStorageDirectUploadService.class), mock(ChunkUploadService.class), + mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class), + mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class), + mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class), + mock(RequestThrottleService.class), mock(LegalAgreementService.class), + mock(AccountClosureService.class), mock(SecurityAuditLogService.class)); + + Result result = controller.getCurrentUserInfo(mock(HttpServletRequest.class)); + + assertSame(profile, result.getData()); + assertEquals(66, result.getData().getShopBusinessRemainingDays()); + verify(userService).getCurrentUserInfo(); + } + + @Test + void sendsPasswordCodeToVerifiedPhoneFromCurrentAccount() { + UserService userService = mock(UserService.class); + PrimaryObjectStorageService primaryObjectStorageService = mock(PrimaryObjectStorageService.class); + ChunkUploadService chunkUploadService = mock(ChunkUploadService.class); + VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + UserMapper userMapper = mock(UserMapper.class); + AdminScopeHelper adminScopeHelper = mock(AdminScopeHelper.class); + ShopRoleService shopRoleService = mock(ShopRoleService.class); + TimeOrderedSnowflakeIdGenerator idGenerator = mock(TimeOrderedSnowflakeIdGenerator.class); + WechatMiniAuthService wechatMiniAuthService = mock(WechatMiniAuthService.class); + ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class); + RequestThrottleService requestThrottleService = mock(RequestThrottleService.class); + LegalAgreementService legalAgreementService = mock(LegalAgreementService.class); + AccountClosureService accountClosureService = mock(AccountClosureService.class); + SecurityAuditLogService securityAuditLogService = mock(SecurityAuditLogService.class); + UserController controller = new UserController(userService, primaryObjectStorageService, + mock(ObjectStorageDirectUploadService.class), chunkUploadService, verificationCodeService, userMapper, adminScopeHelper, shopRoleService, + idGenerator, wechatMiniAuthService, objectStorageUrlSupport, requestThrottleService, + legalAgreementService, accountClosureService, securityAuditLogService); + + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getAttribute("userId")).thenReturn(27L); + UserDO user = new UserDO(); + user.setId(27L); + user.setPhone("13812345678"); + user.setPhoneVerified(1); + user.setStatus(1); + user.setIsDelete(0); + when(userMapper.selectById(27L)).thenReturn(user); + when(verificationCodeService.canResend(user.getPhone())).thenReturn(true); + + Result result = controller.sendCurrentPasswordVerificationCode(request); + + assertEquals(true, result.getData()); + verify(requestThrottleService).checkSendCode(request, user.getPhone()); + verify(verificationCodeService).sendVerificationCode(user.getPhone(), "USER_CHANGE_PASSWORD_SMS_CODE"); + } + + @Test + void rejectsPasswordCodeRequestWithoutAuthenticatedUser() { + UserController controller = new UserController(mock(UserService.class), + mock(PrimaryObjectStorageService.class), mock(ObjectStorageDirectUploadService.class), mock(ChunkUploadService.class), + mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class), + mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class), + mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class), + mock(RequestThrottleService.class), mock(LegalAgreementService.class), + mock(AccountClosureService.class), mock(SecurityAuditLogService.class)); + HttpServletRequest request = mock(HttpServletRequest.class); + + assertThrows(RuntimeException.class, () -> controller.sendCurrentPasswordVerificationCode(request)); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java new file mode 100644 index 00000000..35d9b893 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java @@ -0,0 +1,121 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserServiceCustomerMatchingTest { + + @Mock private UserMapper userMapper; + @Mock private PhoneCrypto phoneCrypto; + @InjectMocks private UserServiceImpl userService; + + @Test + void findsLegacyCustomerPhoneWithoutUsingServicePhoneLookup() { + UserDO customer = new UserDO(); + customer.setId(91L); + customer.setNickname("周女士"); + customer.setType(0); + customer.setIsDelete(0); + customer.setPhone("13800138000"); + + when(phoneCrypto.index("13800138000")).thenReturn("phone-hash"); + when(phoneCrypto.decrypt("13800138000")).thenReturn("13800138000"); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(customer), List.of(customer)); + when(userMapper.findLegacyIdsByContactPhone("13800138000")).thenReturn(List.of()); + + assertEquals(1, userService.findCustomerMatches("周女士", "13800138000", null).size()); + org.mockito.ArgumentCaptor> queries = org.mockito.ArgumentCaptor.forClass((Class) Wrapper.class); + verify(userMapper, times(2)).selectList(queries.capture()); + QueryWrapper legacyPhoneQuery = (QueryWrapper) queries.getAllValues().get(0); + assertTrue(legacyPhoneQuery.getSqlSegment().contains("phone")); + assertTrue(legacyPhoneQuery.getSqlSegment().contains("phone_hash")); + assertTrue(legacyPhoneQuery.getSqlSegment().contains("type")); + assertTrue(legacyPhoneQuery.getParamNameValuePairs().containsValue("13800138000")); + } + + @Test + void rejectsOnlyAnExactNameWechatAndPhoneDuplicate() throws Exception { + UserDO existing = new UserDO(); + existing.setId(91L); + existing.setNickname("周女士"); + existing.setWechatId("wx-existing"); + existing.setPhone("encrypted-phone"); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + + Method ensureUnique = UserServiceImpl.class.getDeclaredMethod( + "ensureCustomerUnique", String.class, String.class, String.class, Long.class); + ensureUnique.setAccessible(true); + ensureUnique.invoke(userService, "周女士", "wx-other", "13800138000", null); + + InvocationTargetException duplicate = assertThrows(InvocationTargetException.class, + () -> ensureUnique.invoke(userService, "周女士", "wx-existing", "13800138000", null)); + assertEquals("客户已存在,请选择已有客户", duplicate.getCause().getMessage()); + } + + @Test + void appointmentIdentityLookupReturnsOnlyExactTupleAndMaskedPhone() { + UserDO existing = new UserDO(); + existing.setId(92L); + existing.setNickname("周女士"); + existing.setWechatId("wx-zhou"); + existing.setPhone("encrypted-phone"); + existing.setType(0); + existing.setIsDelete(0); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + when(phoneCrypto.mask("13800138000")).thenReturn("138****8000"); + + List matches = + userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); + List wrongWechat = + userService.findCustomerIdentityMatches("周女士", "wx-another", "13800138000", null); + + assertEquals(1, matches.size()); + assertEquals("138****8000", matches.get(0).getPhone()); + assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable()); + assertTrue(wrongWechat.isEmpty()); + } + + @Test + void appointmentIdentityLookupFallsBackToLegacyContactPhoneWithMaskedPhone() { + UserDO existing = new UserDO(); + existing.setId(93L); + existing.setNickname("周女士"); + existing.setWechatId("wx-zhou"); + existing.setContactPhone("encrypted-contact-phone"); + existing.setType(0); + existing.setIsDelete(0); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + when(phoneCrypto.decrypt("encrypted-contact-phone")).thenReturn("13800138000"); + when(phoneCrypto.mask("13800138000")).thenReturn("138****8000"); + + List matches = + userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); + + assertEquals(1, matches.size()); + assertEquals("138****8000", matches.get(0).getPhone()); + assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServicePhoneUpdateTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServicePhoneUpdateTest.java new file mode 100644 index 00000000..b3adadc8 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServicePhoneUpdateTest.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserServicePhoneUpdateTest { + + @Mock private UserMapper userMapper; + @Mock private PhoneCrypto phoneCrypto; + @Mock private VerificationCodeService verificationCodeService; + @InjectMocks private UserServiceImpl userService; + + @Test + void updatesPhoneWithoutTrustingMaskedOldPhoneFromClient() { + UserDO currentUser = new UserDO(); + currentUser.setId(27L); + currentUser.setPhone("13812345678"); + currentUser.setPhoneVerified(1); + currentUser.setStatus(1); + currentUser.setIsDelete(0); + when(userMapper.selectById(27L)).thenReturn(currentUser); + when(phoneCrypto.index("13912345678")).thenReturn("new-phone-hash"); + when(userMapper.selectOne(any(Wrapper.class))).thenReturn(null); + when(userMapper.findLegacyIdByPhone("13912345678")).thenReturn(null); + when(verificationCodeService.verifyCode("13912345678", "123456")).thenReturn(true); + when(userMapper.updateById(currentUser)).thenReturn(1); + + UpdatePhoneRequestDTO request = new UpdatePhoneRequestDTO(); + request.setOldPhone("138****5678"); + request.setNewPhone("13912345678"); + request.setVerificationCode("123456"); + + assertTrue(userService.updatePhone(27L, request)); + verify(userMapper).updateById(currentUser); + assertTrue("13912345678".equals(currentUser.getPhone())); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupportTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupportTest.java new file mode 100644 index 00000000..875e9b9e --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupportTest.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.support; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class UserProfileFieldSupportTest { + + /** + * 微信号已改为选填:空值与空白统一归一为 null,不再抛出必填异常。 + */ + @Test + void blankWechatIdIsNormalizedToNull() { + assertNull(UserProfileFieldSupport.normalizeOptionalText(null)); + assertNull(UserProfileFieldSupport.normalizeOptionalText("")); + assertNull(UserProfileFieldSupport.normalizeOptionalText(" ")); + } + + @Test + void nonBlankWechatIdIsTrimmed() { + assertEquals("wx_123", UserProfileFieldSupport.normalizeOptionalText(" wx_123 ")); + } +} diff --git a/JC-Salon-Frontend/package-lock.json b/JC-Salon-Frontend/package-lock.json index 8f0cf12a..4f3eed53 100644 --- a/JC-Salon-Frontend/package-lock.json +++ b/JC-Salon-Frontend/package-lock.json @@ -13,6 +13,7 @@ "ant-design-vue": "^4.2.6", "axios": "^1.13.5", "element-plus": "^2.13.2", + "heic2any": "^0.0.4", "pinia": "^3.0.4", "vue": "^3.5.25", "vue-router": "^4.6.4" @@ -2693,6 +2694,12 @@ "node": ">= 0.4" } }, + "node_modules/heic2any": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/heic2any/-/heic2any-0.0.4.tgz", + "integrity": "sha512-3lLnZiDELfabVH87htnRolZ2iehX9zwpRyGNz22GKXIu0fznlblf0/ftppXKNqS26dqFSeqfIBhAmAj/uSp0cA==", + "license": "MIT" + }, "node_modules/hookable": { "version": "5.5.3", "resolved": "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", diff --git a/JC-Salon-Frontend/package.json b/JC-Salon-Frontend/package.json index bbcfa3d7..753af3ad 100644 --- a/JC-Salon-Frontend/package.json +++ b/JC-Salon-Frontend/package.json @@ -15,6 +15,7 @@ "ant-design-vue": "^4.2.6", "axios": "^1.13.5", "element-plus": "^2.13.2", + "heic2any": "^0.0.4", "pinia": "^3.0.4", "vue": "^3.5.25", "vue-router": "^4.6.4" diff --git a/JC-Salon-Frontend/public/legal/privacy-policy.html b/JC-Salon-Frontend/public/legal/privacy-policy.html new file mode 100644 index 00000000..33b45fae --- /dev/null +++ b/JC-Salon-Frontend/public/legal/privacy-policy.html @@ -0,0 +1,259 @@ + + + + + + + + 甲屿手纪 Salon 隐私政策 + + + +
+

甲屿手纪 Salon 隐私政策

+ + + + +
+ + + + diff --git a/JC-Salon-Frontend/public/legal/user-terms.html b/JC-Salon-Frontend/public/legal/user-terms.html new file mode 100644 index 00000000..c6ff6c13 --- /dev/null +++ b/JC-Salon-Frontend/public/legal/user-terms.html @@ -0,0 +1,237 @@ + + + + + + + + 甲屿手纪 Salon 用户协议 + + + +
+

甲屿手纪 Salon 用户协议

+ + + + +
+ + + + diff --git a/JC-Salon-Frontend/src/App.vue b/JC-Salon-Frontend/src/App.vue index f444f52c..8632575b 100644 --- a/JC-Salon-Frontend/src/App.vue +++ b/JC-Salon-Frontend/src/App.vue @@ -34,7 +34,7 @@ * App page script. * Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events. */ -import { computed, h, onMounted, onUnmounted, provide, ref, watch } from 'vue' +import { computed, h, onMounted, onUnmounted, ref, watch } from 'vue' import { useRoute, useRouter } from 'vue-router' import { ConfigProvider, Modal } from 'ant-design-vue' import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes' @@ -42,7 +42,6 @@ import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context' import { CheckOutlined } from '@ant-design/icons-vue' import BottomNav from './components/BottomNav.vue' import SystemMessageCard from './components/SystemMessageCard.vue' -import { cartApi } from './api/cart' /** * Purpose: SystemMessageVO supports App.vue by holding or executing the system message vo page or API role. * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. @@ -78,7 +77,7 @@ const adminThemeRefreshOptions = { mode: 'admin' as const } const customerThemeRefreshOptions = { mode: 'customer' as const } const isAdminShell = computed(() => route.path.startsWith('/admin') || route.matched.some(r => r.meta.isAdmin)) -const bottomNavRouteNames = new Set(['home', 'products', 'cart', 'profile']) +const bottomNavRouteNames = new Set(['home', 'products', 'profile']) /** isHiddenNav is a reactive state variable used by the template and event handlers. */ const isHiddenNav = computed(() => { @@ -119,39 +118,9 @@ const antdTheme = computed(() => ({ } })) -// 全局购物车数量状态 -/** cartCount is a reactive state variable used by the template and event handlers. */ -const cartCount = ref(0) /** checkingPopupMessages is a reactive state variable used by the template and event handlers. */ const checkingPopupMessages = ref(false) -// 加载购物车数量 -/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const loadCartCount = async () => { - try { - // 检查用户是否已登录 - const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') - if (!token) { - cartCount.value = 0 - return - } - - const response = await cartApi.getCartList() as any - const data = response || [] - const cartList = Array.isArray(data) ? data : [] - const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0) - cartCount.value = totalQuantity - } catch (error) { - cartCount.value = 0 - } -} - -// 提供更新购物车数量的方法 -/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const updateCartCount = async () => { - await loadCartCount() -} - /** * Purpose: resolveSystemMessageActionPath supports App.vue by holding or executing the resolve system message action path page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -235,23 +204,14 @@ const checkPopupMessages = async () => { } } -provide('updateCartCount', updateCartCount) -provide('cartCount', cartCount) - -// 监听路由变化,更新购物车数量 watch(() => route.path, async () => { - // 检查当前是否是后台页面,如果是则不加载购物车数据 const isAdminPage = route.matched.some(r => r.meta.isAdmin) await refreshShopTheme(isAdminPage ? adminThemeRefreshOptions : customerThemeRefreshOptions) if (!isAdminPage) { - await loadCartCount() await checkPopupMessages() } }) -// 页面加载时获取购物车数量 -loadCartCount() - onMounted(async () => { stopThemeSync = setupShopThemeSync() await router.isReady() diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 90a90a39..fa616ba4 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -247,7 +247,6 @@ adminApi.interceptors.response.use( export interface AdminLoginRequest { account: string password: string - shopId?: IdType } /** @@ -260,19 +259,15 @@ export interface AdminLoginResponse { userInfo: any } +export interface AdminPasswordChangeRequest { + currentPassword: string + newPassword: string +} + /** * Purpose: LoginShopSelectionResponse supports admin.ts by holding or executing the login shop selection response page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ -export interface LoginShopSelectionResponse { - allowShoplessLogin: boolean - message: string - shops: Array<{ - id: IdType - shopName: string - }> -} - /** * Purpose: LegalAgreementAdminVO supports admin.ts by holding or executing the legal agreement admin vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -315,14 +310,6 @@ export const adminAuthApi = { login: (data: AdminLoginRequest) => { return adminApi.post('/auth/login', data) }, - /** - * `getLoginShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param account: string caller-supplied value for `account: string` - */ - getLoginShops: (account: string) => { - return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) - }, /** * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -330,14 +317,6 @@ export const adminAuthApi = { logout: () => { return adminApi.post('/auth/logout') }, - /** - * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - switchShop: (shopId?: IdType) => { - return adminApi.post('/auth/switch-shop', { shopId }) - }, /** * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -345,6 +324,9 @@ export const adminAuthApi = { */ refreshToken: (refreshToken: string) => { return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }) + }, + changePassword: (data: AdminPasswordChangeRequest) => { + return adminApi.post('/auth/password', data) } } @@ -596,86 +578,6 @@ export const adminArtistApi = { } } -/** - * Purpose: Coupon supports admin.ts by holding or executing the coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Coupon { - id: IdType - couponCode?: string - couponName: string - couponType: number - couponTypeName?: string - discountValue?: string - minAmount?: number - reduceAmount?: string - totalCount?: number - usedCount?: number - remainingCount?: number - startTime: string - endTime: string - status?: number - statusName?: string - shopId?: IdType - shopName?: string - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTags?: Tag[] - unavailableTags?: Tag[] - createTime: string - updateTime: string -} - -/** - * adminCouponApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const adminCouponApi = { - /** - * `listAllCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - listAllCoupons: (shopId?: IdType) => { - const params = shopId ? { shopId } : {} - return adminApi.get('/coupon/list/all', { params }) as unknown as Promise - }, - /** - * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: any caller-supplied value for `data: any` - */ - createCoupon: (data: any) => { - return adminApi.post('/coupon/create', data) - }, - /** - * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: any caller-supplied value for `data: any` - */ - updateCoupon: (id: IdType, data: any) => { - return adminApi.put(`/coupon/update/${id}`, data) - }, - /** - * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - deleteCoupon: (id: IdType) => { - return adminApi.delete(`/coupon/delete/${id}`) - }, - /** - * `distributeCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: any caller-supplied value for `data: any` - */ - distributeCoupon: (data: any) => { - return adminApi.post('/coupon/distribute', null, { params: data }) - } -} - /** * Purpose: AdminCommentVO supports admin.ts by holding or executing the admin comment vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -737,11 +639,8 @@ export interface Product { imageFileIds?: string imageUrls?: string[] bookableArtists?: string - availableCoupons?: string frontVisible?: number sourceType?: string - likeCount?: number - collectCount?: number createTime: string updateTime: string } @@ -822,6 +721,9 @@ export interface Shop { authorizationExpireTime?: string authorizationExpired?: boolean authorizationStatusText?: string + businessExpireTime?: string + businessExpired?: boolean + businessRemainingDays?: number createTime: string updateTime: string } @@ -837,6 +739,13 @@ export interface ShopListResponse { size: number } +export interface ShopBusinessExpiry { + shopId: IdType + businessExpireTime?: string + businessExpired?: boolean + businessRemainingDays?: number +} + /** * Purpose: CreateShopRequest supports admin.ts by holding or executing the create shop request page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -883,6 +792,12 @@ export const adminShopApi = { listAllShops: () => { return adminApi.get('/shops/list/all') as unknown as Promise }, + listBusinessExpiries: (shopIds: IdType[]) => { + return adminApi.get('/shops/business-expiries', { params: { shopIds: shopIds.join(',') } }) as unknown as Promise + }, + updateBusinessExpiry: (id: IdType, expireDate: string) => { + return adminApi.put(`/shops/${id}/business-expiry`, { expireDate }) + }, /** * `createShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -1016,22 +931,6 @@ export interface ArtistScheduleQuery { endDate?: string } -export interface PaymentOrderVO { - id: IdType - payNo?: string - orderId: IdType - orderNo?: string - userId?: IdType - shopId?: IdType - channel?: string - status?: string - payAmount?: number - paidAmount?: number - payTime?: string - expireTime?: string - remark?: string -} - export interface AfterSaleVO { id: IdType afterSaleNo?: string @@ -1088,43 +987,33 @@ export interface InventoryAdjustRequest { remark?: string } -export interface CampaignVO { - id: IdType - shopId?: IdType - title: string - description?: string - scene?: string - productIds?: string - couponIds?: string - status?: number - startTime?: string - endTime?: string - sortOrder?: number -} - -export interface CampaignRequest { - shopId?: IdType - title?: string - description?: string - scene?: string - productIds?: string - couponIds?: string - status?: number - startTime?: string - endTime?: string - sortOrder?: number -} - -export interface OperationsAnalyticsVO { - viewCount?: number - favoriteCount?: number - cartCount?: number - orderCount?: number - paidOrderCount?: number - completedOrderCount?: number - reviewCount?: number - rebookCount?: number - totalAmount?: number +export interface SalonDashboardOverviewVO { + date: string + degraded?: boolean + degradedMessage?: string + platform: { + activeShopCount: number + activeManagerCount: number + activeStaffCount: number + customerCount: number + styleCount: number + } + today: { + appointmentCount: number + serviceInProgressCount: number + completedServiceCount: number + orderAmount: number + pendingOrderCount: number + } + attention: { + registrationReviewCount: number + contentReviewCount: number + afterSaleCount: number + artistChangeCount: number + lowStockCount: number + } + trend: Array<{ date: string; appointmentCount: number; completedCount: number; amount: number }> + shopRanking: Array<{ shopId: IdType; shopName: string; appointmentCount: number; completedCount: number; amount: number }> } export const adminArtistScheduleApi = { @@ -1136,14 +1025,6 @@ export const adminArtistScheduleApi = { } } -export const adminPaymentApi = { - manualConfirmOrder: (orderId: IdType, remark?: string) => { - return adminApi.post(`/payment/order/${orderId}/manual-confirm`, undefined, { - params: { remark } - }) as unknown as Promise - } -} - export const adminAfterSaleApi = { listAfterSales: (params: AfterSaleQuery) => { return adminApi.get>('/after-sale/list', { params }) as unknown as Promise> @@ -1168,15 +1049,6 @@ export const adminInventoryApi = { } } -export const adminCampaignApi = { - listCampaigns: (params: { status?: number; page: number; size: number }) => { - return adminApi.get>('/campaign/list', { params }) as unknown as Promise> - }, - saveCampaign: (data: CampaignRequest) => { - return adminApi.post('/campaign/save', data) as unknown as Promise - } -} - /** * adminUserApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. @@ -1281,110 +1153,6 @@ export const adminUserApi = { getUserInfo: () => { return adminApi.get('/user/info') as unknown as Promise }, - /** - * `getUserAsset` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getUserAsset: (id: IdType) => { - return adminApi.get(`/user/${id}/asset`) as unknown as Promise - }, - /** - * `getUserBalanceHistory` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getUserBalanceHistory: (id: IdType) => { - return adminApi.get(`/user/${id}/balance/history`) as unknown as Promise - }, - /** - * `changeUserBalance` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: AdminUserBalanceChangeRequest caller-supplied value for `data: AdminUserBalanceChangeRequest` - */ - changeUserBalance: (id: IdType, data: AdminUserBalanceChangeRequest) => { - return adminApi.post(`/user/${id}/balance/change`, data) as unknown as Promise - }, - /** - * `overrideUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: AdminUserVipOverrideRequest caller-supplied value for `data: AdminUserVipOverrideRequest` - */ - overrideUserVip: (id: IdType, data: AdminUserVipOverrideRequest) => { - return adminApi.post(`/user/${id}/vip/override`, data) as unknown as Promise - }, - /** - * `recalculateUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - recalculateUserVip: (id: IdType) => { - return adminApi.post(`/user/${id}/vip/recalculate`) as unknown as Promise - } -} - -/** - * Purpose: UserAssetVO supports admin.ts by holding or executing the user asset vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserAssetVO { - userId: IdType - nickname: string - balance: number - totalRechargeAmount: number - lastRechargeTime?: string - vipInfoId?: IdType - vipLevel: string - benefitId?: IdType - benefitInfo?: string - manualOverride: boolean - vipStartTime?: string - vipExpireTime?: string -} - -/** - * Purpose: UserBalanceHistoryItem supports admin.ts by holding or executing the user balance history item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserBalanceHistoryItem { - id: IdType - userId: IdType - userNickname?: string - amount: number - type?: string - currentBalance?: number - beforeBalance?: number - afterBalance?: number - changeScene?: string - relatedOrderId?: IdType - relatedOrderNo?: string - externalOrderNo?: string - operatorId?: IdType - remark?: string - changeTime: string -} - -/** - * Purpose: AdminUserBalanceChangeRequest supports admin.ts by holding or executing the admin user balance change request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface AdminUserBalanceChangeRequest { - amount: number - changeScene: string - relatedOrderId?: IdType - externalOrderNo?: string - remark?: string -} - -/** - * Purpose: AdminUserVipOverrideRequest supports admin.ts by holding or executing the admin user vip override request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface AdminUserVipOverrideRequest { - vipLevel: string - remark?: string } /** @@ -1471,9 +1239,6 @@ export const adminOrderApi = { updateOrderStatus: (id: IdType, status: number) => { return adminApi.put(`/order/update-status/${id}`, {}, { params: { status } }) }, - manualConfirmPayment: (id: IdType, remark?: string) => { - return adminPaymentApi.manualConfirmOrder(id, remark) - }, submitQuote: (id: IdType, data: { remark?: string; items: Array<{ orderItemId: IdType; quotedPrice: number }> }) => { return adminApi.post(`/order/${id}/quote`, data) }, @@ -1482,68 +1247,13 @@ export const adminOrderApi = { } } -/** - * Purpose: HotProductVO supports admin.ts by holding or executing the hot product vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface HotProductVO { - id: IdType - title: string - price: number - likeCount: number - collectCount: number -} - -/** - * Purpose: RecentActivityVO supports admin.ts by holding or executing the recent activity vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface RecentActivityVO { - id: IdType - type: string - title?: string - description: string - time: string - color?: string -} - -/** - * Purpose: DashboardStats supports admin.ts by holding or executing the dashboard stats page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface DashboardStats { - totalUsers: number - totalProducts: number - totalShops: number - todayOrders: number - totalOrderAmount?: number - todayOrderAmount?: number - weekOrderAmount?: number - totalCustomers?: number - totalArtists?: number - newCustomersToday?: number - newCustomers7Days?: number - newOrders7Days?: number - pendingOrders?: number - completedOrders?: number - hotProducts: HotProductVO[] - recentActivities: RecentActivityVO[] -} - /** * adminDashboardApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. */ export const adminDashboardApi = { - /** - * `getStats` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - getStats: () => { - return adminApi.get('/dashboard/stats') - }, - getAnalytics: () => { - return adminApi.get('/dashboard/analytics') as unknown as Promise + getOverview: (params?: { date?: string; days?: 7 | 30 }) => { + return adminApi.get('/dashboard/overview', { params }) as unknown as Promise } } @@ -1560,6 +1270,7 @@ export interface NailArtistInfoVO { rating: number status: number portfolio: string + moderationStatus?: string nickname: string shopId: IdType shopName: string @@ -1694,6 +1405,7 @@ export interface AnnouncementVO { id: IdType title: string content: string + imageFileIds?: IdType[] publisherId?: IdType publisherName?: string publisherType?: number @@ -1713,6 +1425,7 @@ export interface AnnouncementVO { export interface AnnouncementCreateRequest { title: string content: string + imageFileIds?: string targetType: string shopIds?: IdType[] userIds?: IdType[] @@ -1757,91 +1470,6 @@ export const adminAnnouncementApi = { } } -/** - * Purpose: VipRechargePlanVO supports admin.ts by holding or executing the vip recharge plan vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface VipRechargePlanVO { - id: IdType - shopId: IdType - shopName?: string - title: string - rechargeAmount: number - giftAmount: number - vipLevel: string - description?: string - sortOrder?: number - status: number - createTime?: string - updateTime?: string -} - -/** - * Purpose: VipRechargePlanRequest supports admin.ts by holding or executing the vip recharge plan request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface VipRechargePlanRequest { - shopId?: IdType - title: string - rechargeAmount: number - giftAmount: number - vipLevel: string - description?: string - sortOrder?: number - status?: number -} - -/** - * adminVipRechargePlanApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const adminVipRechargePlanApi = { - /** - * `listPlans` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - listPlans: (shopId?: IdType) => { - const params = shopId ? { shopId } : {} - return adminApi.get('/vip-recharge-plan/admin/list', { params }) as unknown as Promise - }, - /** - * `createPlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` - */ - createPlan: (data: VipRechargePlanRequest) => { - return adminApi.post('/vip-recharge-plan/admin/create', data) - }, - /** - * `updatePlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` - */ - updatePlan: (id: IdType, data: VipRechargePlanRequest) => { - return adminApi.put(`/vip-recharge-plan/admin/${id}`, data) - }, - /** - * `updateStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param status: number caller-supplied value for `status: number` - */ - updateStatus: (id: IdType, status: number) => { - return adminApi.put(`/vip-recharge-plan/admin/${id}/status`, null, { params: { status } }) - }, - /** - * `listVipLevelOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - listVipLevelOptions: (shopId?: IdType) => { - const params = shopId ? { shopId } : {} - return adminApi.get('/vip-recharge-plan/admin/vip-level-options', { params }) as unknown as Promise - } -} - /** * Purpose: MessageHubPushConfigVO supports admin.ts by holding or executing the message hub push config vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -1950,6 +1578,99 @@ export interface AdminDefaultPasswordResponse { password: string } +export interface SecureIntegrationConfigVO { + mapProvider: 'TENCENT' | 'AMAP' + mapEnabled: boolean + tencentWebKeyConfigured: boolean + amapWebKeyConfigured: boolean + amapMiniKeyConfigured: boolean + mapLegacyMigrationPending: boolean + moderationProvider: 'DISABLED' | 'MOCK' | 'WECHAT' + moderationCallbackUrl: string + moderationCallbackTokenConfigured: boolean + moderationEncodingAesKeyConfigured: boolean + moderationCallbackReady: boolean + moderationReady: boolean + wechatMiniAppConfigured: boolean + wechatMiniAppId: string + mockProviderAllowed: boolean + moderationForwardEnabled?: boolean + moderationForwardTargets?: Record + moderationForwardOrder?: string[] + moderationForwardSecretConfigured?: boolean + moderationForwardMaxRetry?: number + moderationForwardBackoffSeconds?: number[] + moderationForwardRecent?: ModerationForwardRecordVO[] + encryptionKeyConfigured: boolean + updatedAt?: string + probeResults?: IntegrationProbeResultVO[] +} + +export interface ModerationForwardRecordVO { + id: IdType + traceId: string + sourceEnv?: string + targetEnv?: string + status: 'CLAIMED' | 'PENDING' | 'PROCESSING' | 'SUCCESS' | 'NO_ENV' | 'FAILED' | 'DEAD' | 'RETRY' | 'TARGET_MISSING' | string + retryCount?: number + lastError?: string + payload?: string + nextAttemptAt?: string + finishedAt?: string + createdAt?: string + updatedAt?: string +} + +export interface IntegrationProbeCheckVO { + name: string + status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' + detail: string +} + +export interface IntegrationProbeResultVO { + service: 'CONTENT_MODERATION' | 'MAP' | 'OBJECT_STORAGE' | 'SMS' | 'SUBSCRIBE_MESSAGE' | string + operation: string + mode: 'DIAGNOSTIC' | 'REAL' | string + provider?: string + status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' | string + summary: string + errorCode?: string + checkedAt?: string + checks?: IntegrationProbeCheckVO[] +} + +export interface IntegrationProbeRequest { + service: string + operation: string + mode?: 'DIAGNOSTIC' | 'REAL' + targetPhone?: string + confirmed?: boolean +} + +export interface SecureIntegrationConfigUpdate { + mapProvider?: 'TENCENT' | 'AMAP' + mapEnabled?: boolean + tencentWebKey?: string + amapWebKey?: string + amapMiniKey?: string + clearTencentWebKey?: boolean + clearAmapWebKey?: boolean + clearAmapMiniKey?: boolean + moderationProvider?: 'DISABLED' | 'MOCK' | 'WECHAT' + moderationCallbackUrl?: string + moderationCallbackToken?: string + moderationEncodingAesKey?: string + clearModerationCallbackToken?: boolean + clearModerationEncodingAesKey?: boolean + moderationForwardEnabled?: boolean + moderationForwardTargets?: Record + moderationForwardOrder?: string[] + moderationForwardSecret?: string + clearModerationForwardSecret?: boolean + moderationForwardMaxRetry?: number + moderationForwardBackoffSeconds?: number[] +} + /** * Purpose: adminSystemParameterConfigApi supports admin.ts by holding or executing the admin system parameter config api page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -1961,17 +1682,21 @@ export const adminSystemParameterConfigApi = { saveConfig: (data: SystemParameterConfigVO) => { return adminApi.post('/system-parameter-config/admin/save', data) }, - getTencentMapKey: () => { - return adminApi.get<{ key: string }>('/system-parameter-config/admin/tencent-map') as unknown as Promise<{ key: string }> - }, - getMapConfig: () => { - return adminApi.get<{ provider: 'TENCENT' | 'AMAP'; tencentWebKey?: string; amapWebKey?: string; amapMiniKey?: string }>('/system-parameter-config/admin/map-config') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; tencentWebKey?: string; amapWebKey?: string; amapMiniKey?: string }> - }, getUserDefaultPassword: () => { return adminApi.get('/system-parameter-config/admin/user-default-password') as unknown as Promise } } +export const adminSecureIntegrationConfigApi = { + getConfig: () => adminApi.get('/system-settings/secure-integration') as unknown as Promise, + listProbeResults: () => adminApi.get('/system-settings/secure-integration/probe-results') as unknown as Promise, + probe: (data: IntegrationProbeRequest) => adminApi.post('/system-settings/secure-integration/probe', data) as unknown as Promise, + getMapRuntimeConfig: () => adminApi.get<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>('/system-settings/secure-integration/map-runtime') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>, + saveMapConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/map', data) as unknown as Promise, + saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation', data) as unknown as Promise, + saveModerationForwardConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation-forward', data) as unknown as Promise +} + export interface WorkbenchRegistrationApplication { id: IdType applicationNo: string @@ -1987,6 +1712,8 @@ export interface WorkbenchRegistrationApplication { applicantNickname?: string applicantAvatar?: string applicantMaskedPhone?: string + contentModerationStatus?: string + contentModerationReason?: string } export const adminWorkbenchRegistrationApi = { @@ -2001,5 +1728,74 @@ export const adminWorkbenchRegistrationApi = { } } +export interface AccountClosureRequestVO { + id: IdType + userId: IdType + nickname: string + userType?: number + shopIds?: IdType[] + shopNames?: string[] + status: string + requestedAt?: string + processingTargetText?: string + processedAt?: string + reviewerNote?: string +} + +export interface ClosureSuccessorManagerVO { + id: IdType + nickname?: string + shopId?: IdType +} + +export interface ContentModerationRecordVO { + id: IdType + contentType: string + businessId?: IdType + authorName?: string + status: string + resultCode?: string + reason?: string + textPreview?: string + images?: Array<{ fileId: IdType; url?: string; status?: string }> + attemptCount?: number + createTime?: string +} + +export interface PhoneBackfillReportVO { + dryRun: boolean + userRowsToUpdate: number + orderRowsToUpdate: number + userRowsUpdated: number + orderRowsUpdated: number + accountConflictRows: number + phoneConflictRows: number + conflictingUserIds: IdType[] +} + +export const adminPrivacyComplianceApi = { + listClosures() { + return adminApi.get('/privacy/account-closure/pending') as unknown as Promise + }, + listSuccessorManagers() { + return adminApi.get('/privacy/account-closure/successor-managers') as unknown as Promise + }, + processClosure(id: IdType, data: { decision: string; successorManagerId?: IdType; archiveShopIds?: IdType[]; note?: string }) { + return adminApi.post(`/privacy/account-closure/${id}/process`, data) + }, + listModeration() { + return adminApi.get('/privacy/content-moderation/pending') as unknown as Promise + }, + reviewContent(id: IdType, data: { approved: boolean; reason: string }) { + return adminApi.post(`/privacy/content-moderation/${id}/review`, data) + }, + phoneBackfillReport() { + return adminApi.get('/privacy/phone-backfill/report') as unknown as Promise + }, + runPhoneBackfill() { + return adminApi.post('/privacy/phone-backfill/run') as unknown as Promise + } +} + export { adminApi } export default adminApi diff --git a/JC-Salon-Frontend/src/api/auth-free-paths.ts b/JC-Salon-Frontend/src/api/auth-free-paths.ts index 6bee7e67..8b45d59c 100644 --- a/JC-Salon-Frontend/src/api/auth-free-paths.ts +++ b/JC-Salon-Frontend/src/api/auth-free-paths.ts @@ -26,7 +26,6 @@ export const WEB_API_AUTH_FREE_PATHS = [ '/tag/list/filter-options', '/file/get-signed-url/', '/admin/auth/login', - '/admin/auth/login-shops/', '/admin/auth/refresh' ] as const @@ -36,7 +35,6 @@ export const WEB_API_AUTH_FREE_PATHS = [ */ export const ADMIN_API_AUTH_FREE_PATHS = [ '/auth/login', - '/auth/login-shops/', '/auth/refresh' ] as const diff --git a/JC-Salon-Frontend/src/api/auth.ts b/JC-Salon-Frontend/src/api/auth.ts index 9fe657a0..79c03be0 100644 --- a/JC-Salon-Frontend/src/api/auth.ts +++ b/JC-Salon-Frontend/src/api/auth.ts @@ -234,6 +234,13 @@ export const authApi = { } } +export interface AgreementPending { + pending: boolean | null + currentVersions: Record + acceptedVersions: Record + pendingTypes: string[] +} + /** * Purpose: legalAgreementApi supports auth.ts by holding or executing the legal agreement api page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -247,5 +254,13 @@ export const legalAgreementApi = { }, getMyConsent: () => { return api.get<{ consentVersions: Record }>('/user/agreement-consent/me') + }, + getPending: () => { + return api.get('/legal-agreement/pending') + }, + accept: (clientType = 'WEB') => { + return api.post('/legal-agreement/accept', null, { + params: { clientType } + }) } } diff --git a/JC-Salon-Frontend/src/api/cart.ts b/JC-Salon-Frontend/src/api/cart.ts deleted file mode 100644 index 5586962e..00000000 --- a/JC-Salon-Frontend/src/api/cart.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -interface CartItem { - productId: IdType - quantity: number -} - -/** - * cartApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const cartApi = { - // 添加作品到购物车 - /** - * `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param item: CartItem caller-supplied value for `item: CartItem` - */ - addToCart: (item: CartItem) => { - return api.post('/cart/add', item) - }, - - // 从购物车移除作品 - /** - * `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - removeFromCart: (productId: IdType) => { - return api.delete(`/cart/remove/${productId}`) - }, - - // 批量从购物车移除作品 - /** - * `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]` - */ - batchRemoveFromCart: (cartItemIds: IdType[]) => { - return api.post('/cart/batch-remove', cartItemIds) - }, - - // 更新购物车作品数量 - /** - * `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param item: CartItem caller-supplied value for `item: CartItem` - */ - updateCartQuantity: (item: CartItem) => { - return api.put('/cart/update', item) - }, - - // 获取购物车列表 - /** - * `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - getCartList: () => { - return api.get('/cart/list') - }, - - // 清空购物车 - /** - * `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - clearCart: () => { - return api.delete('/cart/clear') - } -} diff --git a/JC-Salon-Frontend/src/api/coupon.ts b/JC-Salon-Frontend/src/api/coupon.ts deleted file mode 100644 index edc87861..00000000 --- a/JC-Salon-Frontend/src/api/coupon.ts +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import request from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Coupon { - id: IdType - couponCode: string - couponName: string - couponType: number - couponTypeName: string - discountValue?: number - minAmount?: number - reduceAmount?: number - totalCount: number - usedCount: number - remainingCount: number - startTime: string - endTime: string - status: number - statusName: string - shopId?: IdType - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTags: Tag[] - unavailableTags: Tag[] -} - -/** - * Purpose: Tag supports coupon.ts by holding or executing the tag page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Tag { - id: IdType - tagName?: string -} - -/** - * Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserCoupon { - id: IdType - couponId: IdType - couponName: string - couponType: number - couponTypeName: string - discountValue: string - minAmount: string - reduceAmount: string - startTime: string - endTime: string - status: number - statusName: string - obtainTime: string - useTime: string - sourceType?: string - requiredVipLevel?: string - autoMatched?: boolean -} - -/** - * Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface CreateCouponRequest { - couponCode: string - couponName: string - couponType: number - discountValue?: number - minAmount?: number - reduceAmount?: number - totalCount: number - startTime: string - endTime: string - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTagIds: IdType[] - unavailableTagIds: IdType[] -} - -/** - * Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface CouponListResponse { - list: Coupon[] - total: number - page: number - size: number -} - -/** - * couponApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const couponApi = { - // 创建优惠券 - /** - * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` - */ - createCoupon: (data: CreateCouponRequest) => { - return request({ - url: '/coupon/create', - method: 'post', - data - }) - }, - - // 更新优惠券 - /** - * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` - */ - updateCoupon: (id: IdType, data: CreateCouponRequest) => { - return request({ - url: `/coupon/update/${id}`, - method: 'put', - data - }) - }, - - // 删除优惠券 - /** - * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - deleteCoupon: (id: IdType) => { - return request({ - url: `/coupon/delete/${id}`, - method: 'delete' - }) - }, - - // 获取优惠券详情 - /** - * `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getCouponById: (id: IdType) => { - return request({ - url: `/coupon/detail/${id}`, - method: 'get' - }) - }, - - // 获取优惠券列表 - /** - * `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }` - */ - listCoupons: (params: { page: number; size: number; shopId?: IdType }) => { - return request({ - url: '/coupon/list', - method: 'get', - params - }) - }, - - // 为用户分配优惠券 - /** - * `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param userId: IdType caller-supplied value for `userId: IdType` - * @param couponId: IdType caller-supplied value for `couponId: IdType` - */ - assignCouponToUser: (userId: IdType, couponId: IdType) => { - return request({ - url: '/coupon/assign', - method: 'post', - params: { userId, couponId } - }) - }, - - // 获取用户优惠券列表 - listUserCoupons: async (status?: number): Promise => { - return await request({ - url: '/coupon/user/list', - method: 'get', - params: { status } - }) as UserCoupon[] - }, - - // 使用优惠券 - /** - * `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param userCouponId: IdType caller-supplied value for `userCouponId: IdType` - */ - useCoupon: (userCouponId: IdType) => { - return request({ - url: '/coupon/use', - method: 'post', - params: { userCouponId } - }) - }, - - // 获取作品可用的优惠券 - getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise => { - return await request({ - url: '/coupon/available', - method: 'get', - params: { productTags, productPrice, shopId } - }) as UserCoupon[] - } -} diff --git a/JC-Salon-Frontend/src/api/index.ts b/JC-Salon-Frontend/src/api/index.ts index f45d9081..4009ae60 100644 --- a/JC-Salon-Frontend/src/api/index.ts +++ b/JC-Salon-Frontend/src/api/index.ts @@ -5,13 +5,13 @@ import axios, { AxiosError } from 'axios' import { authApi } from './auth' import { adminAuthApi } from './admin' -import { wishlistApi } from './wishlist' import { message, Modal } from 'ant-design-vue' import { API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' import { attachRequestSignature } from '@/utils/request-signature' import { isApiAuthFreePath } from './auth-free-paths' +import { AGREEMENT_REQUIRED_EVENT, isAgreementPending, setAgreementPending } from '../utils/agreement-gate' import { getApiResponseMessage, isPermissionErrorMessage, @@ -78,6 +78,24 @@ const getStoredAccessToken = (isAdmin = false) => { : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) } +/** + * 协议门禁接口在后台登录态下也需要使用管理员 token;其余沿用原有 admin 路径判断。 + */ +const isAdminScopedUrl = (url?: string) => { + if (!url) return false + if (url.includes('/admin/') || url.includes('/order/admin/')) return true + const hasAdminToken = Boolean(localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) + return hasAdminToken && (url.includes('/legal-agreement/pending') || url.includes('/legal-agreement/accept')) +} + +const AGREEMENT_GATE_ALLOWLIST = ['/legal-agreement/', '/admin/auth/', '/user/logout', '/user/info'] +/** + * 服务端协议同意拦截返回的业务码。收到后前端锁定业务请求并引导用户去阅读/同意最新版协议。 + */ +const AGREEMENT_VERSION_REQUIRED_CODE = 4510 +const AGREEMENT_REQUIRED_DEDUPE_MS = 5000 +let lastAgreementRequiredTime = 0 + /** * Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -142,6 +160,26 @@ const showError = (msg: string) => { message.error(msg) } +/** + * 处理服务端 4510(未同意最新协议): + * 仅用于用户端(小程序由独立实现处理,C 端页面走这里):锁定后续业务请求、提示用户并打开协议阅读页。 + * 后台管理端不做协议版本校验,不会进入该分支。 + */ +const handleAgreementRequired = (res: any) => { + setAgreementPending(true) + if (typeof window !== 'undefined') { + window.dispatchEvent(new CustomEvent(AGREEMENT_REQUIRED_EVENT, { detail: res?.data || {} })) + } + if (Date.now() - lastAgreementRequiredTime < AGREEMENT_REQUIRED_DEDUPE_MS) { + return + } + lastAgreementRequiredTime = Date.now() + showError(normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用')) + if (typeof window !== 'undefined') { + window.open('/legal/user-terms.html', '_blank', 'noopener') + } +} + const resetSystemFailureWindow = () => { systemFailureTimes = [] } @@ -239,7 +277,12 @@ const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) api.interceptors.request.use( async config => { - const isAdminRequest = config.url?.includes('/admin/') || config.url?.includes('/order/admin/') + const isAdminRequest = isAdminScopedUrl(config.url) + // 后台管理端不做协议版本校验:既不进入未同意门禁,也不因门禁状态被拦截。 + if (!isAdminRequest && isAgreementPending() && !AGREEMENT_GATE_ALLOWLIST.some(path => config.url?.includes(path))) { + return Promise.reject(new Error('请先阅读并同意最新版用户协议与隐私政策')) + } + let token = isAdminRequest ? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) @@ -269,6 +312,14 @@ api.interceptors.response.use( response => { resetSystemFailureWindow() const res = response.data + if (Number(res?.code) === AGREEMENT_VERSION_REQUIRED_CODE) { + const errorMsg = normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用') + // 后台管理端已由服务端放行,若历史服务端仍返回 4510,也不触发门禁/提示,避免后台被锁死。 + if (!isAdminScopedUrl(response.config?.url)) { + handleAgreementRequired(res) + } + return Promise.reject(new Error(errorMsg)) + } if (res.code !== 200) { const errorMsg = normalizeApiErrorMessage(res.message || '请求失败') if (!isPermissionErrorMessage(errorMsg)) { @@ -287,7 +338,7 @@ api.interceptors.response.use( if (error.response?.status === 401) { // 检查是否是后台管理的API请求 - const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/') + const isAdminRequest = isAdminScopedUrl(originalRequest.url) const requestToken = getRequestToken(originalRequest) const isRealTokenExpired = isTokenExpiredResponse(error, requestToken) @@ -393,6 +444,4 @@ export const fileApi = { } } -export { wishlistApi } - export default api diff --git a/JC-Salon-Frontend/src/api/order.ts b/JC-Salon-Frontend/src/api/order.ts index 4a12e9a8..0586b6c6 100644 --- a/JC-Salon-Frontend/src/api/order.ts +++ b/JC-Salon-Frontend/src/api/order.ts @@ -21,74 +21,11 @@ export interface OrderItem { * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface CreateOrderRequest { - couponId?: IdType - couponSourceType?: string remark?: string clientRequestId?: string items: OrderItem[] } -export type CheckoutPreviewRequest = CreateOrderRequest - -export interface CheckoutCouponPreview { - id: IdType - couponId?: IdType - userCouponId?: IdType - sourceType?: string - couponName: string - couponType: number - couponTypeName?: string - discountValue?: number - minAmount?: number - reduceAmount?: number - discountAmount?: number - available?: boolean - best?: boolean - vipAuto?: boolean - displayText?: string - savingText?: string - unavailableReason?: string - startTime?: string - endTime?: string -} - -export interface CheckoutIssue { - code: string - message: string - itemId?: IdType - productId?: IdType - productTitle?: string -} - -export interface CheckoutPreview { - subtotalAmount: number - savedAmount: number - payableAmount: number - bestCoupon?: CheckoutCouponPreview - availableCoupons: CheckoutCouponPreview[] - unavailableCoupons: CheckoutCouponPreview[] - bookingAvailable?: boolean - bookingIssues?: CheckoutIssue[] - vipTip?: string - summaryText?: string -} - -export interface PaymentOrderVO { - id: IdType - payNo?: string - orderId: IdType - orderNo?: string - userId?: IdType - shopId?: IdType - channel?: string - status?: string - payAmount?: number - paidAmount?: number - payTime?: string - expireTime?: string - remark?: string -} - export interface OrderQuoteItem { orderItemId: IdType quotedPrice?: number @@ -147,23 +84,6 @@ export interface PageResult { size: number } -export interface GrowthSummaryVO { - userId?: IdType - growthValue?: number - levelName?: string - appointmentCount?: number - reviewCount?: number -} - -export const paymentApi = { - prepareOrderPayment: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO - }, - mockSuccess: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO - } -} - export const afterSaleApi = { apply: async (data: AfterSaleApplyRequest): Promise => { return await api.post('/after-sale/apply', data) as unknown as AfterSaleVO @@ -173,12 +93,6 @@ export const afterSaleApi = { } } -export const growthApi = { - getSummary: async (): Promise => { - return await api.get('/growth/summary') as unknown as GrowthSummaryVO - } -} - /** * Purpose: ArtistCalendarAppointment supports order.ts by holding or executing the artist calendar appointment page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -338,10 +252,6 @@ export const orderApi = { return api.post('/order/create', data) }, - checkoutPreview: async (data: CheckoutPreviewRequest): Promise => { - return await api.post('/order/checkout-preview', data) as unknown as CheckoutPreview - }, - replyQuote: async (orderId: IdType, data?: OrderQuoteReplyRequest): Promise => { return await api.post(`/order/${orderId}/quote/reply`, data || {}) as unknown as any }, @@ -417,8 +327,10 @@ export const orderApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. * @param orderId: IdType caller-supplied value for `orderId: IdType` */ - cancelOrder: (orderId: IdType) => { - return api.put(`/order/cancel/${orderId}`) + cancelOrder: (orderId: IdType, cancelReason?: string) => { + return api.put(`/order/cancel/${orderId}`, undefined, { + params: cancelReason ? { cancelReason } : undefined + }) }, // 后台获取所有订单 diff --git a/JC-Salon-Frontend/src/api/product.ts b/JC-Salon-Frontend/src/api/product.ts index 292db2ac..92e824d8 100644 --- a/JC-Salon-Frontend/src/api/product.ts +++ b/JC-Salon-Frontend/src/api/product.ts @@ -28,14 +28,11 @@ export interface ProductVO { bookableArtists?: string availableBookableArtistCount?: number bookableArtistRestricted?: boolean - availableCoupons?: string category: string tags?: string tagList?: string[] tagInfos?: TagInfo[] status: number - likeCount?: number - collectCount?: number createTime: string updateTime: string } @@ -111,14 +108,6 @@ export const productApi = { return await api.get(`/product/list/tag/${tag}`) as unknown as ProductVO[] }, - likeProduct: async (productId: IdType): Promise => { - return await api.post(`/product-like/like/${productId}`) as unknown as boolean - }, - - unlikeProduct: async (productId: IdType): Promise => { - return await api.post(`/product-like/unlike/${productId}`) as unknown as boolean - }, - searchProducts: async (keyword: string): Promise => { return await api.get('/product/list/search', { params: { diff --git a/JC-Salon-Frontend/src/api/productLike.ts b/JC-Salon-Frontend/src/api/productLike.ts deleted file mode 100644 index 5ce0831d..00000000 --- a/JC-Salon-Frontend/src/api/productLike.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * productLikeApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const productLikeApi = { - /** - * 点赞作品 - * @param productId 作品ID - */ - /** - * `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - likeProduct: (productId: IdType) => { - return api.post(`/product-like/like/${productId}`) - }, - - /** - * 取消点赞作品 - * @param productId 作品ID - */ - /** - * `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - unlikeProduct: (productId: IdType) => { - return api.post(`/product-like/unlike/${productId}`) - }, - - /** - * 检查用户是否已点赞作品 - * @param productId 作品ID - */ - /** - * `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - checkLikeStatus: (productId: IdType) => { - return api.get(`/product-like/check/${productId}`) - } -} diff --git a/JC-Salon-Frontend/src/api/user.ts b/JC-Salon-Frontend/src/api/user.ts index 4c6fc5df..b8e70888 100644 --- a/JC-Salon-Frontend/src/api/user.ts +++ b/JC-Salon-Frontend/src/api/user.ts @@ -202,51 +202,10 @@ export interface InviteCodeVO { * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface UpdatePhoneRequest { - oldPhone: string newPhone: string verificationCode: string } -/** - * Purpose: UserAssetVO supports user.ts by holding or executing the user asset vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserAssetVO { - userId: IdType - nickname: string - balance: number - totalRechargeAmount: number - lastRechargeTime?: string - vipInfoId?: IdType - vipLevel: string - benefitId?: IdType - benefitInfo?: string - manualOverride?: boolean - vipStartTime?: string - vipExpireTime?: string -} - -/** - * Purpose: BalanceHistoryItem supports user.ts by holding or executing the balance history item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface BalanceHistoryItem { - id: IdType - userId: IdType - userNickname?: string - amount: number - type?: string - currentBalance?: number - beforeBalance?: number - afterBalance?: number - changeScene?: string - relatedOrderId?: IdType - relatedOrderNo?: string - externalOrderNo?: string - remark?: string - changeTime?: string -} - /** * Purpose: SystemMessageVO supports user.ts by holding or executing the system message vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -285,23 +244,6 @@ export interface AnnouncementVO { publishTime?: string } -/** - * Purpose: VipRechargePlanVO supports user.ts by holding or executing the vip recharge plan vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface VipRechargePlanVO { - id: IdType - shopId: IdType - shopName?: string - title: string - rechargeAmount: number - giftAmount: number - vipLevel: string - description?: string - sortOrder?: number - status: number -} - /** * Purpose: ContactInfoVO supports user.ts by holding or executing the contact info vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -319,11 +261,32 @@ export interface ContactInfoVO { platformContactText?: string } +/** + * 后台单次拨号取号响应。 + */ +export interface CustomerDialResult { + mode: 'DIRECT' | 'PRIVACY_NUMBER' + dialNumber: string + expiresInSeconds: number +} + /** * userApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. */ export const userApi = { + /** + * 后台管理员按预约/订单上下文单次取号,号码不入库、不缓存。 + */ + dialCustomer: async (params: { customerId?: IdType; appointmentId?: IdType; orderId?: IdType }): Promise => { + return await api.post('/manager/customers/dial', null, { + params: { + customerId: params.customerId || undefined, + appointmentId: params.appointmentId || undefined, + orderId: params.orderId || undefined + } + }) as unknown as CustomerDialResult + }, getUserInfo: async (): Promise => { return await api.get('/user/info') as unknown as UserVO }, @@ -388,6 +351,9 @@ export const userApi = { sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { return api.post('/user/send-verification-code', data) }, + sendCurrentPasswordVerificationCode: () => { + return api.post('/user/send-current-password-code') + }, /** * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -396,12 +362,6 @@ export const userApi = { switchShop: (shopId?: string | number) => { return api.post('/user/switch-shop', { shopId }) }, - getMyAsset: async (): Promise => { - return await api.get('/user/asset/me') as unknown as UserAssetVO - }, - getMyBalanceHistory: async (): Promise => { - return await api.get('/user/balance/history/me') as unknown as BalanceHistoryItem[] - }, listMyMessages: async (): Promise => { return await api.get('/system-message/my/list') as unknown as SystemMessageVO[] }, @@ -433,9 +393,6 @@ export const userApi = { listMyAnnouncements: async (): Promise => { return await api.get('/announcement/my/list') as unknown as AnnouncementVO[] }, - listMyVipRechargePlans: async (): Promise => { - return await api.get('/vip-recharge-plan/my/list') as unknown as VipRechargePlanVO[] - }, getMyRelation: async (): Promise => { return await api.get('/user/relation/me') as unknown as UserRelationVO }, @@ -464,6 +421,14 @@ export const userApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. */ deactivateAccount: () => { - return api.delete('/user/deactivate') - } + return api.post('/user/account-closure', {}) + }, + getAccountClosure: async () => await api.get('/user/account-closure/me') as unknown as Promise<{ + id: IdType + status: string + requestedAt?: string + processingTargetText?: string + reviewerNote?: string + } | null>, + withdrawAccountClosure: () => api.delete('/user/account-closure/me') } diff --git a/JC-Salon-Frontend/src/api/wishlist.ts b/JC-Salon-Frontend/src/api/wishlist.ts deleted file mode 100644 index aacabd9f..00000000 --- a/JC-Salon-Frontend/src/api/wishlist.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface WishlistItem { - id: IdType - userId: IdType - productId: IdType - groupId?: IdType | null - groupName?: string | null - note?: string | null - sortOrder?: number | null - product: { - id: IdType - shopId: IdType | null - shopName?: string - title: string - description: string - imageFileIds?: string - imageUrls?: string[] - price: number - tags?: string - tagList?: string[] - tagInfos?: any[] - likeCount?: number - collectCount?: number - approximateDuration?: string - bookableArtists?: string - availableCoupons?: string - createTime: string - updateTime: string - } -} - -export interface WishlistGroup { - id: IdType - name: string - sortOrder: number - itemCount: number - items?: WishlistItem[] -} - -export interface WishlistInspiration { - total: number - groups: WishlistGroup[] -} - -export interface WishlistGroupPayload { - name: string - sortOrder?: number -} - -export interface WishlistAddWithGroupPayload { - productId: IdType - groupId?: IdType | null - note?: string - sortOrder?: number -} - -export interface WishlistMovePayload { - wishlistId?: IdType - productId?: IdType - groupId?: IdType | null - note?: string - sortOrder?: number -} - -/** - * wishlistApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const wishlistApi = { - addToWishlist: async (productId: IdType): Promise => { - return await api.post('/wishlist/add', { productId }) as unknown as boolean - }, - - removeFromWishlist: async (productId: IdType): Promise => { - return await api.post('/wishlist/remove', { productId }) as unknown as boolean - }, - - checkWishlist: async (productId: IdType): Promise => { - return await api.get(`/wishlist/check?productId=${productId}`) as unknown as boolean - }, - - getWishlist: async (): Promise => { - return await api.get('/wishlist/list') as unknown as WishlistItem[] - }, - - getGroups: async (): Promise => { - return await api.get('/wishlist/groups') as unknown as WishlistGroup[] - }, - - createGroup: async (payload: WishlistGroupPayload): Promise => { - return await api.post('/wishlist/groups', payload) as unknown as IdType - }, - - updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise => { - return await api.put(`/wishlist/groups/${id}`, payload) as unknown as boolean - }, - - deleteGroup: async (id: IdType): Promise => { - return await api.delete(`/wishlist/groups/${id}`) as unknown as boolean - }, - - addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise => { - return await api.post('/wishlist/add-with-group', payload) as unknown as boolean - }, - - moveWishlist: async (payload: WishlistMovePayload): Promise => { - return await api.post('/wishlist/move', payload) as unknown as boolean - }, - - getInspiration: async (): Promise => { - return await api.get('/wishlist/inspiration') as unknown as WishlistInspiration - } -} diff --git a/JC-Salon-Frontend/src/components/BottomNav.vue b/JC-Salon-Frontend/src/components/BottomNav.vue index af791df6..247cd91e 100644 --- a/JC-Salon-Frontend/src/components/BottomNav.vue +++ b/JC-Salon-Frontend/src/components/BottomNav.vue @@ -19,15 +19,6 @@ 作品集 - - -
diff --git a/JC-Salon-Frontend/src/views/admin/AdminLoginView.vue b/JC-Salon-Frontend/src/views/admin/AdminLoginView.vue index 878a9dbb..9ea9199e 100644 --- a/JC-Salon-Frontend/src/views/admin/AdminLoginView.vue +++ b/JC-Salon-Frontend/src/views/admin/AdminLoginView.vue @@ -1,514 +1,78 @@ diff --git a/JC-Salon-Frontend/src/views/admin/AfterSalesView.vue b/JC-Salon-Frontend/src/views/admin/AfterSalesView.vue index 2b9ead61..50a043d7 100644 --- a/JC-Salon-Frontend/src/views/admin/AfterSalesView.vue +++ b/JC-Salon-Frontend/src/views/admin/AfterSalesView.vue @@ -1,15 +1,5 @@