From 94f3f3a4fa1cf7d89ae6bcd160d26a2492cdb7ec Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Fri, 16 Oct 2026 15:25:37 +0800 Subject: [PATCH 001/165] =?UTF-8?q?=E6=95=B4=E7=90=86=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E9=85=8D=E7=BD=AE=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- docs/README.md | 2 +- docs/handoff/CURRENT-STATE.md | 4 +- docs/handoff/PROJECT-MAP.md | 2 +- docs/handoff/TASK-PLAYBOOKS.md | 2 +- .../0.0.1版本基线与后续迭代规则_20260628.md | 54 ------- .../Gitea工作流YAML兼容性修复说明_20261016.md | 21 --- .../Gitea环境分支保护配置说明_20261012.md | 35 ----- .../JayuCloudArtList配置整理说明20260617.md | 42 ------ .../scripts/SIT中间件业务账号修复_20261012.md | 27 ---- ...n Core接入MessageHub标准MQ说明_20260906.md | 19 --- ...Hub Token迁入Nacos密钥配置说明_20261014.md | 22 --- .../Salon SIT自动发布配置说明_20260901.md | 32 ---- .../Salon初始化SQL历史脚本合并_20261010.md | 34 ----- .../Salon小程序OpenID快捷登录说明_20261010.md | 40 ----- .../Salon生产发布共享目录配置说明_20260901.md | 25 ---- .../三环境中间件配置分层整理_20261014.md | 32 ---- .../历史补单与服务中状态说明_20261013.md | 5 - docs/scripts/双端命名统一迁移说明_20261014.md | 13 -- docs/scripts/双端独立部署配置说明20260825.md | 44 ------ .../后端Nacos启动引导环境变量修复_20261012.md | 56 ------- .../后端配置统一由Nacos明文管理_20261010.md | 63 -------- .../开发环境Nacos配置发布说明_20260826.md | 42 ------ .../开发环境Nacos默认地址配置说明_20260623.md | 21 --- .../指尖管理师上线配置说明_20260622.md | 32 ---- ...回MinIO三副本对象存储配置说明_20260624.md | 140 ------------------ .../环境发布与回退工作流说明_20261015.md | 22 --- ...tea流水线发布Nacos配置准备说明_20260826.md | 65 -------- ... Core与Gateway环境变量准备说明_20260827.md | 108 -------------- .../生产Salon Gitea流水线配置说明_20260827.md | 36 ----- .../生产与测试环境Nacos配置说明_20260826.md | 49 ------ ...产对象存储与中间件配置调整说明_20260825.md | 26 ---- ...理师小程序本地接口地址配置说明_20260623.md | 10 -- .../统一JayuCloud数据库名配置说明_20260617.md | 19 --- docs/scripts/运行与发布配置总说明.md | 88 +++++++++++ docs/运维配置与集成说明.md | 6 +- docs/项目功能概览.md | 2 +- 37 files changed, 98 insertions(+), 1144 deletions(-) delete mode 100644 docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md delete mode 100644 docs/scripts/Gitea工作流YAML兼容性修复说明_20261016.md delete mode 100644 docs/scripts/Gitea环境分支保护配置说明_20261012.md delete mode 100644 docs/scripts/JayuCloudArtList配置整理说明20260617.md delete mode 100644 docs/scripts/SIT中间件业务账号修复_20261012.md delete mode 100644 docs/scripts/Salon Core接入MessageHub标准MQ说明_20260906.md delete mode 100644 docs/scripts/Salon SIT MessageHub Token迁入Nacos密钥配置说明_20261014.md delete mode 100644 docs/scripts/Salon SIT自动发布配置说明_20260901.md delete mode 100644 docs/scripts/Salon初始化SQL历史脚本合并_20261010.md delete mode 100644 docs/scripts/Salon小程序OpenID快捷登录说明_20261010.md delete mode 100644 docs/scripts/Salon生产发布共享目录配置说明_20260901.md delete mode 100644 docs/scripts/三环境中间件配置分层整理_20261014.md delete mode 100644 docs/scripts/历史补单与服务中状态说明_20261013.md delete mode 100644 docs/scripts/双端命名统一迁移说明_20261014.md delete mode 100644 docs/scripts/双端独立部署配置说明20260825.md delete mode 100644 docs/scripts/后端Nacos启动引导环境变量修复_20261012.md delete mode 100644 docs/scripts/后端配置统一由Nacos明文管理_20261010.md delete mode 100644 docs/scripts/开发环境Nacos配置发布说明_20260826.md delete mode 100644 docs/scripts/开发环境Nacos默认地址配置说明_20260623.md delete mode 100644 docs/scripts/指尖管理师上线配置说明_20260622.md delete mode 100644 docs/scripts/接回MinIO三副本对象存储配置说明_20260624.md delete mode 100644 docs/scripts/环境发布与回退工作流说明_20261015.md delete mode 100644 docs/scripts/生产Gitea流水线发布Nacos配置准备说明_20260826.md delete mode 100644 docs/scripts/生产Salon Core与Gateway环境变量准备说明_20260827.md delete mode 100644 docs/scripts/生产Salon Gitea流水线配置说明_20260827.md delete mode 100644 docs/scripts/生产与测试环境Nacos配置说明_20260826.md delete mode 100644 docs/scripts/生产对象存储与中间件配置调整说明_20260825.md delete mode 100644 docs/scripts/管理师小程序本地接口地址配置说明_20260623.md delete mode 100644 docs/scripts/统一JayuCloud数据库名配置说明_20260617.md create mode 100644 docs/scripts/运行与发布配置总说明.md diff --git a/AGENTS.md b/AGENTS.md index cee9ecb9..5636c33d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat - 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。 - 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。 - 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。 -- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `scripts/0.0.1版本基线与后续迭代规则_20260628.md`,并在任务记录中写明新增或调整的版本化文件。 +- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `docs/scripts/运行与发布配置总说明.md`,并在任务记录中写明新增或调整的版本化文件。 - 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。 ## Browser MCP Preference diff --git a/docs/README.md b/docs/README.md index af1b3a9f..e3aaa7ac 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,5 +21,5 @@ 1. `handoff/CURRENT-STATE.md` 2. `handoff/PROJECT-MAP.md` 3. `handoff/RISK-REGISTER.md` -4. `scripts/0.0.1版本基线与后续迭代规则_20260628.md` +4. `scripts/运行与发布配置总说明.md` 5. `项目变更记录.md` 和 `运维配置与集成说明.md` diff --git a/docs/handoff/CURRENT-STATE.md b/docs/handoff/CURRENT-STATE.md index e40f445e..e73d55e2 100644 --- a/docs/handoff/CURRENT-STATE.md +++ b/docs/handoff/CURRENT-STATE.md @@ -19,7 +19,7 @@ - 该初始化 SQL 只保留一名平台管理员 `xiaowang`、完整权限、管理员授权、协议、系统参数、MessageHub 和 VIP 基础配置,不写入门店、商品、订单、客户等业务样例数据。 - 当前每端仅保留一份完整初始化 SQL;后续新 SQL 变更仍通过独立版本 SQL 管理。 - 生产已部署库的历史数据升级不在初始化 SQL 范围内,如需升级已有库必须单独制定迁移方案。 -- 脚本、配置、SQL 的后续迭代规则见 `docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md`。 +- 脚本、配置、SQL 的后续迭代规则见 `docs/scripts/运行与发布配置总说明.md`。 ## 对象存储状态 @@ -48,7 +48,7 @@ ## 最近验证 -- 2026-10-14:Salon SIT MessageHub Token 配置已调整为从 Nacos `secret.yaml` 读取;Token 尚未人工填入,变更只在本地 `dev` 提交,未推送、未发布 SIT。说明见 `docs/scripts/Salon SIT MessageHub Token迁入Nacos密钥配置说明_20261014.md`。 +- 2026-10-14:Salon SIT MessageHub Token 配置已调整为从 Nacos `secret.yaml` 读取;Token 尚未人工填入,变更只在本地 `dev` 提交,未推送、未发布 SIT。详见 `docs/scripts/运行与发布配置总说明.md` 的 MessageHub 章节。 - MinIO 连通性验证通过:`192.168.5.15:9000/minio/health/live` 返回 200。 - 开发 bucket `jayucloud-artlist` 已创建。 - manager 边界目标测试和 Gateway 路由测试已通过。 diff --git a/docs/handoff/PROJECT-MAP.md b/docs/handoff/PROJECT-MAP.md index f850f5a3..86a934c8 100644 --- a/docs/handoff/PROJECT-MAP.md +++ b/docs/handoff/PROJECT-MAP.md @@ -78,7 +78,7 @@ - `docs/scripts/sql/init/jayucloud-salon.sql` - `docs/scripts/sql/init/jayucloud-artlist.sql` -- `docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md` +- `docs/scripts/运行与发布配置总说明.md` - `docs/scripts/deploy-jayucloud-artlist-production.ps1` - `docs/scripts/package-release.ps1` diff --git a/docs/handoff/TASK-PLAYBOOKS.md b/docs/handoff/TASK-PLAYBOOKS.md index 219c1ddc..096415d0 100644 --- a/docs/handoff/TASK-PLAYBOOKS.md +++ b/docs/handoff/TASK-PLAYBOOKS.md @@ -62,7 +62,7 @@ 先读: - `docs/design/上线初始化SQL基线说明_20260624.md` -- `docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md` +- `docs/scripts/运行与发布配置总说明.md` - `RISK-REGISTER.md` - `CURRENT-STATE.md` diff --git a/docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md b/docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md deleted file mode 100644 index 3bda24a0..00000000 --- a/docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md +++ /dev/null @@ -1,54 +0,0 @@ -# 0.0.1 版本基线与后续迭代规则 - -更新时间:2026-06-28 - -## 版本基线 - -当前仓库代码、脚本、配置、SQL 和项目文档固定为 `0.0.1` 版本基线。 - -纳入本次基线的运行入口: - -- `JC-ArtList-Core`:`pom.xml` 版本为 `0.0.1`。 -- `JC-ArtList-Gateway`:`pom.xml` 版本为 `0.0.1`。 -- `JC-ArtList-Frontend`:`package.json` 和 `package-lock.json` 版本为 `0.0.1`。 -- `JC-ArtList-WeChat`:以当前微信小程序项目配置、页面和脚本作为 `0.0.1` 用户端小程序基线。 -- `JC-Salon-WeChat`:以当前微信小程序项目配置、页面和脚本作为 `0.0.1` 管理师小程序基线。 -- `docs/scripts/sql/init/jayucloud-salon.sql`:作为店务端空库初始化 SQL 基线。 -- `docs/scripts/sql/init/jayucloud-artlist.sql`:作为设计师端空库初始化 SQL 基线。 - -## 初始化 SQL 冻结规则 - -从当前双端基线起,`docs/scripts/sql/init/jayucloud-salon.sql` 与 `docs/scripts/sql/init/jayucloud-artlist.sql` 只作为各自空库首次初始化入口。 - -后续涉及表结构、补列、索引、权限种子、系统参数、运行必需种子数据或数据修复时,必须新增版本变更 SQL,不得回写初始化 SQL。 - -## 后续迭代文件规则 - -- 后续 SQL 变更必须创建独立的版本化脚本,文件名使用中文并体现功能和日期,例如 `员工排班规则和例外_20260626.sql`。 -- SQL 内容必须是完整可执行脚本,包含必要的幂等判断、过程清理和明确失败条件。 -- 配置变更必须新增说明文档,放在 `docs/scripts/` 目录。 -- 配置说明文档文件名必须使用中文,体现功能和日期。 -- 脚本、配置、SQL 的新增或修改必须在对应任务的记忆和交接文档中记录原因、影响范围和验证方式。 - -## 已发现问题与处理 - -- 问题:旧记忆和交接文档仍记录“新增表字段后同步更新初始化 SQL”。 -- 原因:`0.0.1` 前的上线基线阶段曾把历史 SQL 合并回唯一初始化脚本。 -- 处理:初始化入口按端侧拆分;后续变更通过版本化 SQL 与 `docs/scripts/` 中的说明文件迭代。 - -## 2026-10-10 Salon 基线重整例外 - -经项目负责人明确要求,将 `docs/scripts/sql/` 下截至 2026-10-10 的全部 Salon 版本 SQL -最终状态重新合并到 `docs/scripts/sql/init/jayucloud-salon.sql`,解决仅执行初始化 SQL 的空库 -缺少工作台注册审核表和短信供应商参数的问题。 - -本次只重整空库基线;经项目负责人确认,已经完整合入初始化基线的历史版本 SQL 已删除, -避免同一结构和种子配置存在多个执行入口。完成本次重整后,后续数据库变更仍遵循上述冻结规则, -除非项目负责人再次明确要求重整初始化基线。 - -## 2026-10-14 双端初始化基线重整例外 - -经项目负责人明确要求,将现存的 Salon 员工审核提醒参数 SQL 和双端旧来源标识修正 SQL -分别合入 `jayucloud-salon.sql` 与 `jayucloud-artlist.sql` / `jayucloud-salon.sql`,并删除独立版本 SQL。 -当前 `docs/scripts/sql/` 只保留两个端侧初始化 SQL 入口。该变更仅用于空库基线;已部署数据库不得重跑完整初始化脚本, -需要升级时另行制定并确认专用迁移方案。之后新增数据库变更仍按版本化 SQL 规则执行,除非负责人再次明确要求整合基线。 diff --git a/docs/scripts/Gitea工作流YAML兼容性修复说明_20261016.md b/docs/scripts/Gitea工作流YAML兼容性修复说明_20261016.md deleted file mode 100644 index da155456..00000000 --- a/docs/scripts/Gitea工作流YAML兼容性修复说明_20261016.md +++ /dev/null @@ -1,21 +0,0 @@ -# Gitea 工作流 YAML 兼容性修复说明 - -## 问题 - -Gitea `27.3.4` 扫描仓库工作流时,将包含 Actions 表达式的 YAML 行内映射判定为无效。例如 `env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}}` 会触发行内映射解析错误,导致工作流被忽略,页面显示文件名和无效警告,推送触发器也不会注册。 - -## 处理 - -- 将 10 个环境发布、部署和回退工作流中的步骤级 `env` 全部改为块状映射。 -- 将同一批工作流中的手动输入和 `concurrency` 配置改为块状映射,避免 Gitea 解析器继续处理不兼容的流式写法。 -- 修复 Nacos 发布脚本对配置目录层级的校验,使其读取仓库实际使用的 `namespace/DEFAULT_GROUP/dataId` 路径。 -- 为 Gitea Runner 的任务容器配置 `/salon-release` 宿主持久 bind mount,使发布记录、配置快照和应用包能跨任务使用。 -- 不调整工作流名称、分支触发条件、Secret 名称、部署脚本和回退逻辑。 - -## 验证 - -- 使用 YAML 解析器逐个读取 `.gitea/workflows/` 下的 11 个工作流,确认均能解析并包含 `name`、`on`、`jobs`。 -- 对 dev、sit、prod 三个环境的全部 Nacos YAML 执行路径解析测试,确认每个文件都能得到正确的 namespace 和 data ID。 -- 在 dev 的 Gitea Actions 实际运行中确认 Nacos 发布成功;在 SIT 晋级运行中验证发布记录能由后续部署任务读取。 -- 使用 Gitea 容器日志确认修复提交后不再出现 `DetectWorkflows() ignore invalid workflow`。 -- 推送 `dev` 后确认开发环境 Nacos 发布工作流被识别并进入运行队列;SIT/PROD 仍按环境分支晋级链路触发。 diff --git a/docs/scripts/Gitea环境分支保护配置说明_20261012.md b/docs/scripts/Gitea环境分支保护配置说明_20261012.md deleted file mode 100644 index 36fdcd8d..00000000 --- a/docs/scripts/Gitea环境分支保护配置说明_20261012.md +++ /dev/null @@ -1,35 +0,0 @@ -# Gitea 环境分支保护配置说明 - -日期:2026-10-12 - -## 目的 - -JayuCloud 的环境分支按以下唯一链路晋级: - -```text -dev -> sit -> prod -``` - -`sit` 和 `prod` 禁止任何用户(包括管理员)直接推送、强制推送或通过网页直接修改。`sit` 只接受 `dev` 来源的拉取请求,`prod` 只接受 `sit` 来源的拉取请求。 - -来源分支必须位于当前 JayuCloud 仓库;外部仓库中的同名 `dev` 或 `sit` 分支同样会被拒绝。 - -## 配置组成 - -- Gitea 原生分支保护:禁止直接写入、强推和管理员绕过。 -- Gitea Actions 必需检查:验证拉取请求的来源和目标分支组合。 -- 检查使用 `pull_request_target` 执行目标分支中的固定定义,不执行来源分支代码、不读取 Secret,来源分支无法篡改检查逻辑。 -- 不新增人工审批数量要求。 - -## 运维注意事项 - -- 发布到 SIT:创建或更新 `dev -> sit` 拉取请求。 -- 发布到生产:SIT 验证完成后创建或更新 `sit -> prod` 拉取请求。 -- 不要为了紧急发布关闭保护规则;修复应先进入 `dev`,再按环境链路晋级。 -- 如果来源检查本身故障,按设计文档中的恢复方式处理并记录临时放宽。 - -## 首次引导记录 - -启用保护时三个环境分支存在尚未晋级的业务差异。为避免安装检查时发布这些差异,经项目负责人确认,只将来源检查工作流以 `[skip ci]` 独立提交直接引导到尚未保护的 `sit`、`prod`。保护启用后该例外永久失效。 - -详细规则、启用顺序和验证方法见 `docs/superpowers/specs/2026-10-12-Gitea环境分支保护-design.md`。 diff --git a/docs/scripts/JayuCloudArtList配置整理说明20260617.md b/docs/scripts/JayuCloudArtList配置整理说明20260617.md deleted file mode 100644 index 6102810a..00000000 --- a/docs/scripts/JayuCloudArtList配置整理说明20260617.md +++ /dev/null @@ -1,42 +0,0 @@ -# jayucloud-artlist 配置整理说明 - -> 历史说明:后端环境变量注入方式已于 2026-10-10 停用。当前配置方式见 `后端配置统一由Nacos明文管理_20261010.md`。 - -## 命名空间 - -- `jayucloud-artlist`:开发环境配置。 -- `jayucloud-artlist`:正式环境配置。 - -## 配置文件 - -- `core.yaml`:Core 服务独有配置,包括端口、业务缓存、慢请求、对象存储业务规则和 MessageHub 客户端参数。 -- `gateway.yaml`:Gateway 服务独有配置,包括端口、路由、鉴权白名单和网关慢请求参数。 -- `infra.yaml`:公共基础设施配置,包括数据库、Redis、MyBatis-Plus 和 RabbitMQ。 -- `secret.yaml`:敏感配置,包括数据库密码、Redis 密码、RabbitMQ 密码、JWT、微信小程序和对象存储密钥。 -- `logging.yaml`:公共日志配置。 - -## 本地启动配置 - -`JC-ArtList-Core` 和 `JC-ArtList-Gateway` 默认读取开发环境命名空间: - -```powershell -$env:NACOS_SERVER_ADDR='192.168.5.103:8848' -$env:NACOS_NAMESPACE='jayucloud-artlist' -$env:NACOS_USERNAME='xiaowang' -$env:NACOS_PASSWORD='122503wcy....' -``` - -正式环境部署时设置: - -```powershell -$env:NACOS_SERVER_ADDR='192.168.5.101:8848,192.168.5.102:8848,192.168.10.145:8848' -$env:NACOS_NAMESPACE='jayucloud-artlist' -``` - -如 Nacos 地址、账号、密码发生变化,通过以下环境变量覆盖: - -```powershell -$env:NACOS_SERVER_ADDR='192.168.5.103:8848' -$env:NACOS_USERNAME='nacos' -$env:NACOS_PASSWORD='122503wcy....' -``` diff --git a/docs/scripts/SIT中间件业务账号修复_20261012.md b/docs/scripts/SIT中间件业务账号修复_20261012.md deleted file mode 100644 index 4f24de29..00000000 --- a/docs/scripts/SIT中间件业务账号修复_20261012.md +++ /dev/null @@ -1,27 +0,0 @@ -# SIT 中间件业务账号修复 - -日期:2026-10-12 - -## 问题 - -Salon SIT 自动发布工作流完成构建和文件部署后失败: - -- Core 使用 Nacos 中的 `rabbitmq` 账号连接 `192.168.10.13:5672`,但 SIT RabbitMQ 尚未创建该业务账号,监听器认证失败并导致应用退出。 -- RabbitMQ 修复后,业务接口仍因 MySQL 认证失败而超时。Salon 和 ArtList 的 SIT `infra.yaml` 同时保留了错误地址 `192.168.10.102` 和旧密码,`secret.yaml` 中的 `spring.datasource.password` 也会后加载并覆盖 `infra.yaml` 的新值。 - -## 处理 - -- 在 SIT RabbitMQ 创建与 Nacos 配置一致的 `rabbitmq` 业务账号,只授予 `/jayucloud-salon-sit` vhost 的配置、写入和读取权限,不授予管理员标签。 -- 将 Salon、ArtList 的 SIT `database.business.jdbc-url` 统一修正为 `192.168.10.11:3306`。 -- 将两套 SIT `database.business`、`security.database` 和 `spring.datasource` 的 root 密码同步为当前中间件信息表中的 MySQL 凭据。 -- 普通业务参数继续由 Nacos 提供,应用服务器环境变量不增加 MySQL 或 RabbitMQ 参数。 -- 清理 Salon Core systemd 环境文件中的 MySQL、RabbitMQ、Redis 和对象存储覆盖项,仅保留 Nacos 启动引导参数与服务端口;MessageHub Token 继续由独立的受限环境文件提供。 - -## 验证 - -- RabbitMQ 业务账号认证成功,且仅在 `/jayucloud-salon-sit` vhost 具备权限。 -- MySQL 当前凭据在 `192.168.10.11` 本机认证成功,存在允许远程连接的 `root@'%'`。 -- 校验 Nacos `infra.yaml` 中的 MySQL 密码与信息表一致,并确认 `secret.yaml` 不再以旧值覆盖数据源密码。 -- Nacos 发布后重启 Salon Core,确认 RabbitMQ、MySQL 连接不再出现认证失败。 -- 验证 Core、Gateway、公网健康检查和 `/api/shop/list`。 -- 重跑失败的 Salon SIT 自动发布工作流并确认成功。 diff --git a/docs/scripts/Salon Core接入MessageHub标准MQ说明_20260906.md b/docs/scripts/Salon Core接入MessageHub标准MQ说明_20260906.md deleted file mode 100644 index 2ff818a4..00000000 --- a/docs/scripts/Salon Core接入MessageHub标准MQ说明_20260906.md +++ /dev/null @@ -1,19 +0,0 @@ -# Salon Core 接入 MessageHub 标准 MQ - -## 运行时配置 - -在 Nacos 对应命名空间的 `core.yaml` 中配置以下非敏感项,在 `secret.yaml` 中配置访问 Token: - -```text -MESSAGEHUB_BASE_URL=http://:8080 -messagehub.client.access-token=<人工填入 Nacos secret.yaml> -MESSAGEHUB_INGRESS_EXCHANGE=messagehub.ingress.exchange -MESSAGEHUB_INGRESS_ROUTING_KEY=message.send -MESSAGEHUB_SOURCE_SYSTEM=jayucloud-salon -``` - -SIT 的 `core.yaml` 提供非敏感的 `messagehub.client.*` 连接参数,敏感的 `messagehub.client.access-token` 放在同一命名空间的 `secret.yaml` 中,由 Nacos 在运行时提供。SIT 发布工作流不再读取 Gitea Actions Secret,也不再写入 Core 专用的 systemd 环境文件。Token 由维护人员人工填入 Nacos 配置源后随配置发布。短信发送流程先调用 `/api/v1/messages/ids` 预留消息 ID,再向 RabbitMQ ingress 交换机投递,并在 AMQP Header 中携带 `X-MessageHub-Access-Token`。 - -## 验证 - -验证时检查 Core 日志中仅出现场景、手机号、交换机和模板编码,不得输出 Token;再通过 MessageHub 状态接口确认消息进入 `ACCEPTED` 或后续成功状态。 diff --git a/docs/scripts/Salon SIT MessageHub Token迁入Nacos密钥配置说明_20261014.md b/docs/scripts/Salon SIT MessageHub Token迁入Nacos密钥配置说明_20261014.md deleted file mode 100644 index 6c19bf34..00000000 --- a/docs/scripts/Salon SIT MessageHub Token迁入Nacos密钥配置说明_20261014.md +++ /dev/null @@ -1,22 +0,0 @@ -# Salon SIT MessageHub Token 迁入 Nacos 密钥配置 - -日期:2026-10-14 - -## 原因与目标 - -SIT Salon Core 的 MessageHub Token 原由 Gitea Actions Secret 提供,并通过 systemd 环境文件覆盖应用配置。现在统一由 SIT Salon Nacos 命名空间的 `secret.yaml` 提供运行时值。 - -## 配置与发布行为 - -- 非敏感的 MessageHub 地址、交换机和路由参数保留在 `core.yaml`。 -- 敏感项使用 `messagehub.client.access-token`,放在 `nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/secret.yaml`。 -- SIT 部署工作流不再读取 `MESSAGEHUB_SIT_ACCESS_TOKEN`,也不再写入旧的 systemd 环境文件;部署时会删除旧文件和 drop-in,并重新加载 systemd。 -- 当前仓库中的 Token 值留空,需由维护人员人工填入后再发布。该 YAML 是 Gitea 配置源,填入真实值会使其进入 Git 版本历史;应确认仓库访问权限符合凭据管理要求。 -- 填入非空值之前不要将当前空值配置晋级到 `sit`,否则 Nacos 会收到空 Token。 - -## 验证与发布 - -- 已静态确认 Salon Core `bootstrap.yaml` 共享导入 `secret.yaml`。 -- 已静态确认 SIT 部署工作流不再引用 Gitea MessageHub Token Secret,并会清理旧的 systemd 覆盖。 -- 已运行 `git diff --check`。 -- 本次未发布 Nacos、未连接 SIT 服务器、未触发部署。填入 Token 后按 `dev -> sit` 晋级流程发布 Nacos 配置并部署,随后验证 MessageHub 短信发送。 diff --git a/docs/scripts/Salon SIT自动发布配置说明_20260901.md b/docs/scripts/Salon SIT自动发布配置说明_20260901.md deleted file mode 100644 index c698f396..00000000 --- a/docs/scripts/Salon SIT自动发布配置说明_20260901.md +++ /dev/null @@ -1,32 +0,0 @@ -# Salon SIT 自动发布配置 - -推送到 `sit` 分支后,`.gitea/workflows/salon-sit-deploy.yml` 自动构建并部署 Salon Core、Gateway 和前端;数据库 SQL 只随发布包归档,不自动执行。 - -## 部署目标 - -- Core/Gateway:`192.168.10.15:22`,独立目录 `/opt/jc-salon-core-sit`、`/opt/jc-salon-gateway-sit`,服务名 `jc-salon-core-sit`、`jc-salon-gateway-sit`。 -- 前端:与生产共用阿里云入口服务器,独立目录 `/opt/jc-salon-frontend-sit`,域名 `sit.yunail.art`。 -- 前端构建阶段显式注入 `VITE_API_BASE_URL=https://sit.yunail.art/api` 和 `VITE_ADMIN_API_BASE_URL=https://sit.yunail.art/admin/api`,避免构建产物使用生产接口默认值。 -- SIT 中间件:Nacos `192.168.10.10:8848`、MySQL `192.168.10.11:3306`、Redis `192.168.10.12:6379`、RabbitMQ `192.168.10.13:5672`、MinIO `192.168.10.14:9000`,由 SIT Nacos 配置注入。 -- 工作流显式传入 `-AllowSitTarget`,仅允许 `Environment=sit` 的目标;生产工作流不传入该开关,仍拒绝非生产节点。 - -## 前置配置 - -1. Gitea Secret 中配置 `SALON_PROD_SSH_PASSWORD`,用于连接 SIT 后端和共用的阿里云前端服务器;工作流使用账号 `root`、SSH 端口 `22`。 -2. 阿里云 Nginx 新增 `sit.yunail.art` server 配置,将站点根目录指向 `/opt/jc-salon-frontend-sit`,并按现有生产规则代理 `/api`。 -3. Nginx 修改后执行 `nginx -t`,通过后再 reload。 -4. 首次部署前确认 `192.168.10.15` 已安装 Java 17、systemd 可用,且网络可访问 SIT Nacos、MySQL、Redis 和 RabbitMQ。 - -## 已确认的 SIT 前置条件 - -- 数据库 `jayucloud_salon` 已完成初始化;部署工作流继续跳过数据库执行。 -- RabbitMQ 已创建/更新业务用户 `xiaowang`,已授权 `/` 和 `/jayucloud-salon-sit`;业务 vhost 使用 `/jayucloud-salon-sit`。 -- MinIO 使用 `192.168.10.14:9000`;七牛 Kodo 和阿里云 OSS 沿用生产凭据与连接参数,SIT 使用带 `sit` 后缀的 Bucket。 -- RabbitMQ 密码、对象存储密钥和 Nacos 凭据仅通过受控环境或 Gitea Secrets 注入,不写入本文档。 - -## 验证 - -- 推送 `sit` 后确认工作流完成 Core/Gateway 健康检查和前端文件发布。 -- 检查 `https://sit.yunail.art/`、`/health/check` 及前端静态资源均返回 200。 -- 检查前端 JavaScript 产物包含 SIT API 地址,且不包含 `https://yunail.art/api` 或 `https://yunail.art/admin/api`。 -- 检查 Nacos `jayucloud-salon` namespace 中服务注册状态和 SIT 配置读取。 diff --git a/docs/scripts/Salon初始化SQL历史脚本合并_20261010.md b/docs/scripts/Salon初始化SQL历史脚本合并_20261010.md deleted file mode 100644 index 2b4e988b..00000000 --- a/docs/scripts/Salon初始化SQL历史脚本合并_20261010.md +++ /dev/null @@ -1,34 +0,0 @@ -# Salon 初始化 SQL 历史脚本合并说明 - -## 原因 - -仅执行 `docs/scripts/sql/init/jayucloud-salon.sql` 的空库缺少 -`t_workbench_registration_application`,导致后台注册审核查询报表不存在。 -同时,目录中的短信供应商版本脚本也未完全进入空库基线。 - -## 合并范围 - -截至 2026-10-10,`docs/scripts/sql/` 下四个 Salon 版本脚本的最终状态已合入 -`docs/scripts/sql/init/jayucloud-salon.sql`: - -- `工作台注册审核_20260907.sql`:补入注册审核申请表、唯一索引和查询索引。 -- `短信供应商全局切换_20260906.sql`:补入 `SMS_PROVIDER=SPUG` 系统参数。 -- `短信模板编码映射调整_20260906.sql`:初始化种子已统一使用 `SPUG_SMS_VERIFY_1`。 -- `短信模板编码统一修复_20260915.sql`:六个短信场景初始化为启用、未删除、SPUG 发送方式。 - -两个短信模板脚本的最终状态在合并前已存在于初始化种子中,因此没有重复追加事务更新和结果查询。 -ArtList 初始化 SQL 未混入 Salon 专属表和参数。完成核对后,上述四个已合并的版本 SQL 已删除, -`docs/scripts/sql/` 只保留 Salon 与 ArtList 两个初始化入口。 - -## 使用方式 - -- 新空库:只需执行 `docs/scripts/sql/init/jayucloud-salon.sql`。 -- 已初始化数据库:不要重复执行完整初始化 SQL。需要补齐注册审核表时,应从初始化 SQL 中单独执行 - `t_workbench_registration_application` 的 `CREATE TABLE IF NOT EXISTS` 语句;不得对已有数据库重跑完整初始化文件。 - -## 验证 - -- 初始化 SQL 必须包含 `t_workbench_registration_application` 建表语句。 -- 初始化 SQL 必须包含 `SMS_PROVIDER` 参数种子。 -- 六个 Salon 短信验证码场景必须使用 `SPUG_SMS_VERIFY_1`、`SPUG` 且启用。 -- 已合入的重复历史 SQL 已删除;不连接或修改任何实际数据库环境。 diff --git a/docs/scripts/Salon小程序OpenID快捷登录说明_20261010.md b/docs/scripts/Salon小程序OpenID快捷登录说明_20261010.md deleted file mode 100644 index a8de4ced..00000000 --- a/docs/scripts/Salon小程序OpenID快捷登录说明_20261010.md +++ /dev/null @@ -1,40 +0,0 @@ -# Salon 小程序 OpenID 快捷登录说明 - -更新时间:2026-10-10 - -## 改造范围 - -- `JC-Salon-WeChat` 仅展示微信快捷登录,不再展示手机号、验证码和密码登录入口。 -- `JC-Salon-Core` 新增微信状态探测、快捷登录、注册票据及微信手机号绑定接口。 -- `docs/scripts/sql/init/jayucloud-salon.sql` 重新定义空库用户基线:账号和密码允许为空,手机号唯一且允许多行 `NULL`。 -- 未修改 ArtList,未生成迁移或清库脚本,未连接或操作任何实际数据库。 - -本次初始化 SQL 调整是经确认的空库模型重定义,属于对仓库“冻结初始化 SQL”规则的明确任务级例外;已有环境的数据处理由后续独立任务负责。 - -## 接口与状态 - -- `POST /user/wechat-mini/status`:只探测,不创建用户、不签发 Token。 -- `POST /user/wechat-mini/quick-login`:新 OpenID 创建待审核用户,已审核用户登录。 -- `POST /user/wechat-mini/confirm-login`:多门店用户选择门店后完成登录。 -- `POST /user/wechat-mini/bind-phone`:登录后使用微信手机号凭证完成绑定。 -- 注册票据有效期为 5 分钟,只能使用一次,并在服务端校验用户、AppID 与 OpenID 绑定关系。 - -探测状态包括 `NEW_USER`、`PENDING_REVIEW`、`REJECTED`、`READY`、`DISABLED`。只有 `SUCCESS` 登录结果会返回业务 Token。 - -## 小程序行为 - -- 每次启动先获取新的微信 code 探测状态;探测 code 不复用于登录。 -- 小程序以独立启动鉴权页作为首屏,避免已记住用户启动时短暂显示登录页或提前触发规划页业务请求。 -- 本机开启“记住登录”且状态为 `READY` 时,再获取新 code 自动登录并直接进入规划页;自动登录失败则回到登录页,且保留本机记住偏好以便重试。 -- 未勾选“记住登录”时点击快捷登录,会弹出“记住 / 不记住”二选一提示;选择后立即按对应策略登录,不需要再次点击登录按钮。 -- 登录后可在“账号设置”使用微信一键绑定或短信验证码绑定手机号。 -- 规划页未绑定手机号横幅可关闭到当天;主动退出会清除会话、记住登录偏好、当天横幅关闭状态和资料提示跳过状态,并回到登录页。 -- 昵称和头像缺失时使用 `chooseAvatar` 与 `input type="nickname"` 引导完善,可在本机跳过。 - -## 部署前检查 - -1. 确认微信小程序 AppID、AppSecret 配置正确,服务端可访问微信登录及手机号接口。 -2. 确认 Redis 可用,注册票据与多门店登录票据依赖 Redis 短期存储。 -3. 新建空库时执行更新后的 `jayucloud-salon.sql`;不得直接对已有环境执行该初始化文件。 -4. 网关与 Core 白名单已收紧为明确的探测、登录和确认登录路径;`/api/user/wechat-mini/bind-phone` 不在白名单中,必须携带有效登录会话。 -5. 仓库内 Salon 的 dev、SIT、prod Nacos `gateway.yaml` 已同步该白名单口径;发布配置前应复核目标命名空间,本文不执行任何配置发布。 diff --git a/docs/scripts/Salon生产发布共享目录配置说明_20260901.md b/docs/scripts/Salon生产发布共享目录配置说明_20260901.md deleted file mode 100644 index fe38107e..00000000 --- a/docs/scripts/Salon生产发布共享目录配置说明_20260901.md +++ /dev/null @@ -1,25 +0,0 @@ -# Salon 生产发布共享目录配置 - -Prepare 和 Deploy 工作流通过 Runner 宿主机共享目录传递发布包,不再跨运行读取 Gitea Artifact。 - -## Runner 配置 - -在 Runner 宿主机创建目录并设置为 Runner 用户可读写: - -```text -/opt/software/panel/apps/gitea/salon-release -``` - -在 `act_runner/config.yaml` 的 `container.options` 增加目录挂载: - -```yaml -- "--volume=/opt/software/panel/apps/gitea/salon-release:/salon-release:rw" -``` - -修改后重启 `jayucloud-runner`。Prepare 会将包写入 `/salon-release/`,Deploy 使用相同 `release_sha` 读取并校验 `manifest.json`。 - -## 验证 - -1. 在 Runner 任务容器中确认 `/salon-release` 可读写。 -2. 重新运行 Prepare,确认共享目录生成对应 SHA 子目录和 `manifest.json`。 -3. Deploy 输入同一 `release_sha`,确认“读取已审核发布包”步骤通过。 diff --git a/docs/scripts/三环境中间件配置分层整理_20261014.md b/docs/scripts/三环境中间件配置分层整理_20261014.md deleted file mode 100644 index a8a3bac9..00000000 --- a/docs/scripts/三环境中间件配置分层整理_20261014.md +++ /dev/null @@ -1,32 +0,0 @@ -# 三环境中间件配置分层整理 - -日期:2026-10-14 - -## 变更范围 - -- 整理 `dev`、`sit`、`prod` 三个环境的 `jayucloud-salon` 和 `jayucloud-artlist` Nacos 配置。 -- 不修改初始化 SQL,不修改微信端本地配置,不直接操作线上 Nacos。 - -## 配置分层 - -- `infra.yaml` 只保留地址、端口、数据库编号、vhost、对象存储 endpoint、bucket、region、开关和业务连接策略等非敏感参数。 -- `secret.yaml` 统一保存应用实际绑定的 Redis、RabbitMQ、MySQL、MinIO、七牛 Kodo、阿里云 OSS 账号密码和访问密钥。 -- `core.yaml` 保留对象存储 provider 顺序、备份策略和签名 URL 等业务策略,删除对象存储连接凭据及重复连接配置。 -- 删除未发现应用绑定关系的 `security.database`、`security.redis`、`security.rabbitmq`、`security.nacos` 重复节点。Nacos 启动认证继续由 `bootstrap.yaml` 的 `NACOS_*` 环境变量或默认值负责,不依赖业务 `secret.yaml`。 - -## 凭据来源与兼容性 - -- 已有 `secret.yaml` 中的 Redis、RabbitMQ、数据库凭据优先保留;SIT Salon Redis 使用此前已修正的 secret 值。 -- 对象存储凭据从当前生效配置迁入对应 `secret.yaml`,保持应用绑定路径不变:`minio.*`、`qiniu.kodo.*`、`aliyun.oss.*`。 -- 数据库同时保留 `spring.datasource.*` 与 `database.business.*` 两条现有绑定路径,但两者使用同一组 secret 凭据,避免合并覆盖不一致。 - -## 验证与发布 - -1. 使用 SnakeYAML 解析全部 18 份 YAML。 -2. 静态确认 `infra.yaml` 不含敏感字段,`core.yaml` 不含对象存储密钥,`secret.yaml` 含全部应用绑定的敏感路径。 -3. 只提交并推送 `dev`,通过受保护流程由 `dev` 合并到 `sit`,验证 SIT 后再晋级 `prod`。 -4. 发布后检查 Core/Gateway 健康接口、关键业务接口及 Redis、RabbitMQ、MySQL 认证日志。 - -## 回滚 - -发布前保留各环境 Nacos 配置快照和 Git 提交号。若启动或中间件连接异常,恢复上一提交对应配置并重启服务;不修改初始化 SQL。 diff --git a/docs/scripts/历史补单与服务中状态说明_20261013.md b/docs/scripts/历史补单与服务中状态说明_20261013.md deleted file mode 100644 index b1c50ba5..00000000 --- a/docs/scripts/历史补单与服务中状态说明_20261013.md +++ /dev/null @@ -1,5 +0,0 @@ -# 历史补单与服务中状态 - -历史补单使用订单来源 `HISTORICAL_BACKFILL`,状态 `4` 表示服务中。补单必须归属员工,可不填写客户和具体服务时间;没有具体时间时仅按 `service_date` 参与规划日期统计,不创建预约占用,也不执行排班冲突校验。 - -数据库字段和索引已融合到 `docs/scripts/sql/init/jayucloud-salon.sql`,初始化脚本可重复执行,不连接或清理已有业务数据。 diff --git a/docs/scripts/双端命名统一迁移说明_20261014.md b/docs/scripts/双端命名统一迁移说明_20261014.md deleted file mode 100644 index 667982bc..00000000 --- a/docs/scripts/双端命名统一迁移说明_20261014.md +++ /dev/null @@ -1,13 +0,0 @@ -# 双端命名统一迁移说明 - -本次将 ArtList 和 Salon 中遗留的历史品牌标识统一为 `jayucloud-artlist` 和 `jayucloud-salon`;迁移脚本中的旧值仅作为历史数据匹配条件保留。 - -- Nacos 配置、JWT issuer、消息来源、缓存/临时文件前缀、对象存储队列和前端存储键已按端侧更新。 -- Java 包和启动类已迁移到各自的 `com.xiaowang.jayucloud.` 包路径。 -- 历史来源标识、协议文案及表注释修正已合入对应端侧初始化 SQL;Salon 员工审核提醒参数也已并入 Salon 初始化 SQL。 -- `docs/scripts/sql/` 当前只保留 ArtList 和 Salon 两个完整初始化入口,不再保留独立版本 SQL 文件。 -- 这些修正用于空库初始化;已部署数据库不能重跑完整初始化脚本,历史数据升级须另行制定并人工执行迁移方案。 -- 对象存储的 MinIO、七牛云和阿里云 OSS 配置均需要声明 `private-bucket`(适用时)及 `signed-url-expire-minutes`,与 Core 中各适配器的校验字段保持一致;三套 Salon Nacos 环境已补齐默认值 60 分钟。 -- JWT issuer、缓存键和小程序本地会话变化会使已有令牌/会话失效,用户需重新登录。 -- 各环境发布前,先创建端侧专属 RabbitMQ vhost 和对象存储 bucket,并从旧 bucket 迁移该端所需对象;仓库未连接或操作实际中间件。 -- 数据库名保持现行端侧标识:`jayucloud_artlist` 与 `jayucloud_salon`。 diff --git a/docs/scripts/双端独立部署配置说明20260825.md b/docs/scripts/双端独立部署配置说明20260825.md deleted file mode 100644 index 0caabec9..00000000 --- a/docs/scripts/双端独立部署配置说明20260825.md +++ /dev/null @@ -1,44 +0,0 @@ -# 设计师端与店务端独立部署配置说明 - -## 适用范围 - -本说明对应 2026-08-25 的双端隔离改造,当前只适配生产环境。设计师端和店务端先保留完整后端代码,分别构建、注册和连接独立资源。 - -## 端侧边界 - -| 端侧 | 后端目录 | 前端目录 | Nacos namespace | 数据库 | -| --- | --- | --- | --- | --- | -| 设计师端 | `JC-ArtList-Core`、`JC-ArtList-Gateway` | `JC-ArtList-Frontend`、`JC-ArtList-WeChat` | `jayucloud-artlist` | `jayucloud_artlist` | -| 店务端 | `JC-Salon-Core`、`JC-Salon-Gateway` | `JC-Salon-Frontend`、`JC-Salon-WeChat` | `jayucloud-salon` | `jayucloud_salon` | - -店务端可只启动 `JC-Salon-Core` 和 `JC-Salon-Gateway`,不依赖设计师端进程或数据库。 - -## Nacos 配置源 - -生产配置位于 `nacos/namespaces/prod//DEFAULT_GROUP/`,包含 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml` 和 `logging.yaml`。 - -配置发布使用 `.gitea/workflows/publish-nacos.yml`,通过 Gitea Secrets 注入 `NACOS_URLS`、`NACOS_USERNAME` 和 `NACOS_PASSWORD`。发布脚本先写入第一个 Nacos 节点,再从至少两个节点读取并按 SHA-256 校验配置内容。 - -## 生产中间件入口 - -- Nacos 客户端:`192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848`。 -- Nacos 元数据库:`192.168.10.200:3306/nacos`,不使用 ProxySQL `6033`。 -- 业务数据库:使用中心1 ProxySQL `192.168.10.200:6033`,设计师端连接 `jayucloud_artlist`,店务端连接 `jayucloud_salon`。 -- Redis:Sentinel master `mymaster`,节点列表来自《中间件服务器信息表.md》生产配置。 -- RabbitMQ:使用 `mq-prod.internal:5672`,账号、vhost 和密码通过 Gitea Secrets 或部署环境注入。 -- 对象存储:生产 bucket 统一使用 `jayucloud`,各供应商 Endpoint 和密钥通过私有配置注入。 - -## 数据库脚本 - -- `docs/scripts/sql/init/jayucloud-artlist.sql` -- `docs/scripts/sql/init/jayucloud-salon.sql` - -两份脚本均为完整可执行空库初始化脚本,分别包含端侧职责裁剪与排班规则;新建库仅执行目标端对应脚本。 - -## 发布前验证 - -1. 分别构建 `JC-ArtList-Core/JC-ArtList-Gateway/JC-ArtList-Frontend` 和 `JC-Salon-Core/JC-Salon-Gateway/JC-Salon-Frontend`。 -2. 只启动店务 Core/Gateway,确认服务注册为 `jc-salon-core` 和 `jc-salon-gateway`。 -3. 确认店务 datasource 指向 `jayucloud_salon`,设计师 datasource 指向 `jayucloud_artlist`。 -4. 发布 Nacos 配置后,从两个节点读取相同 Data ID 并校验摘要一致。 -5. 完成店务 Web、小程序登录、员工、客户、排班、规划、预约、订单和设置冒烟验证后,再进行后端裁剪。 diff --git a/docs/scripts/后端Nacos启动引导环境变量修复_20261012.md b/docs/scripts/后端Nacos启动引导环境变量修复_20261012.md deleted file mode 100644 index 946ddf46..00000000 --- a/docs/scripts/后端Nacos启动引导环境变量修复_20261012.md +++ /dev/null @@ -1,56 +0,0 @@ -# 后端 Nacos 启动引导环境变量修复 - -更新时间:2026-10-12 - -## 问题 - -四个后端模块曾把 DEV Nacos 地址和认证信息固定写入 `bootstrap.yaml`。同一构建产物发布到 SIT 后,服务器的 `NACOS_*` 环境变量无法覆盖固定值,Salon Core 因而连接 DEV Nacos、读取 DEV 中间件配置并监听 `8081`,与 SIT 健康检查端口 `181` 不一致。 - -Gitea 的 `NACOS_SIT_URLS` 还保留了旧地址,导致 SIT Nacos 发布工作流连接不可达节点。 - -## 调整 - -以下模块恢复 Nacos 启动引导环境变量: - -- `JC-Salon-Core` -- `JC-Salon-Gateway` -- `JC-ArtList-Core` -- `JC-ArtList-Gateway` - -每个模块使用: - -- `NACOS_SERVER_ADDR` -- `NACOS_NAMESPACE` -- `NACOS_GROUP` -- `NACOS_USERNAME` -- `NACOS_PASSWORD` - -环境变量未设置时使用 DEV 默认值,保证本地开发兼容。服务名、独有 Data ID 和共享 Data ID 清单仍固定在各模块中。 - -## SIT 配置 - -SIT 参数以 `E:/code/doc/中间件服务器信息表-sit.md` 为来源: - -- Nacos:`192.168.10.10:8848` -- Salon namespace:`jayucloud-salon` -- ArtList namespace:`jayucloud-artlist` -- Group:`DEFAULT_GROUP` - -当前已确认的 SIT 应用服务器为 `192.168.10.15`: - -- Salon Core 使用 `SERVER_PORT=181` -- Salon Gateway 使用 `SERVER_PORT=180` - -服务器原有 Nacos认证值继续保留,不在本文档中记录私有密码。当前没有已确认的 ArtList SIT 应用服务器,因此不向未知主机写入配置。 - -## 配置边界 - -只有连接 Nacos 所必需的五个参数通过 `NACOS_*` 环境变量注入。`SERVER_PORT` 由应用服务器控制。MySQL、Redis、RabbitMQ、MinIO、其他对象存储、MessageHub、微信及业务参数继续由对应环境的 Nacos配置提供。 - -## 验证 - -1. 解析四个 `bootstrap.yaml` 并检查五个环境变量占位符。 -2. 构建四个后端模块。 -3. 更新 Gitea `NACOS_SIT_URLS` 后运行 SIT Nacos发布与回读校验。 -4. 发布 Salon SIT 后确认 Core/Gateway 分别监听 `181`/`180`。 -5. 确认服务注册到 `192.168.10.10:8848`,运行日志中不再出现 DEV Nacos或 DEV RabbitMQ。 diff --git a/docs/scripts/后端配置统一由Nacos明文管理_20261010.md b/docs/scripts/后端配置统一由Nacos明文管理_20261010.md deleted file mode 100644 index 72a6d367..00000000 --- a/docs/scripts/后端配置统一由Nacos明文管理_20261010.md +++ /dev/null @@ -1,63 +0,0 @@ -# 后端配置统一由 Nacos 明文管理说明 - -更新时间:2026-10-10 - -## 调整范围 - -本次覆盖以下后端模块与仓库 Nacos 配置源: - -- `JC-Salon-Core` -- `JC-Salon-Gateway` -- `JC-ArtList-Core` -- `JC-ArtList-Gateway` -- `nacos/namespaces/dev` -- `nacos/namespaces/sit` -- `nacos/namespaces/prod` - -前端和微信小程序不在本次范围内。本次未连接、修改或发布任何实际 Nacos 环境。 - -## 配置归属 - -四个后端模块连接 Nacos 所必需的地址、命名空间、分组、用户名和密码由 `bootstrap.yaml` 中的 `NACOS_*` 环境变量占位符读取,并保留 DEV 值作为本地默认值。服务名和 Data ID 仍固定写在各模块 `bootstrap.yaml` 中。 - -数据库、Redis、RabbitMQ、对象存储、MessageHub、微信小程序及其他业务参数在仓库的 Nacos 配置源中明文管理。这些业务参数原有的 `${ENV}` 与 `${ENV:default}` 占位符已展开,不再接受操作系统环境变量覆盖;仅连接 Nacos 所需的五个启动引导参数保留环境变量入口。 - -ArtList Core、ArtList Gateway 和 Salon Gateway 原有 `application.yaml` 业务兜底已移除,仅保留配置归属说明。服务无法读取 Nacos 时应直接启动失败,不再回退到仓库内另一套运行参数。 - -Gateway 的 `${remaining}` 是 `RewritePath` 路由替换表达式,不属于环境变量,继续保留。 - -## 环境值处理 - -- dev、SIT、prod 保留各自的数据库地址、Redis 地址、RabbitMQ 地址、对象存储地址、数据库名、桶名和命名空间差异。 -- SIT/prod 原本缺失的用户名、密码和存储密钥按任务确认复制 dev 明文值。 -- Salon dev、SIT、prod 已写入微信小程序 AppID `wxb6d77f7c07020d51`。 -- 微信 AppSecret 当前未提供,三个环境均明确配置为空字符串。发布前必须填入真实 AppSecret,否则 OpenID 登录会返回“微信小程序登录未配置 appId/appSecret”。 -- ArtList 未发现经确认的独立微信凭据,因此未伪造或复用 Salon 微信配置。 - -## 风险 - -仓库与 Git 历史会直接保存数据库、缓存、消息队列和对象存储等明文凭据。任何拥有仓库读取权限的人均可读取这些值;凭据轮换也必须通过仓库修改和 Nacos 发布完成。 - -同一构建产物部署到 SIT 或生产时,必须在 systemd 环境文件中显式设置 `NACOS_SERVER_ADDR`、`NACOS_NAMESPACE`、`NACOS_GROUP`、`NACOS_USERNAME` 和 `NACOS_PASSWORD`。未设置时会连接 DEV 默认值,因此发布前必须检查服务器环境文件。 - -## 发布步骤 - -1. 发布前补齐 Salon 微信 AppSecret,并复核每个环境的连接地址和明文凭据。 -2. 使用现有 Nacos 发布流程选择目标环境,不得跨环境混发。 -3. 先发布共享的 `infra.yaml`、`secret.yaml`,再发布 `core.yaml`、`gateway.yaml` 和 `logging.yaml`。 -4. 发布后重启对应 Core/Gateway,验证数据库、Redis、RabbitMQ、对象存储和微信接口。 -5. 本说明只描述仓库配置,不代表配置已经发布。 - -## 验证 - -- 扫描四个后端 `bootstrap.yaml`,确认只保留五个 `NACOS_*` 启动引导占位符及 Gateway `${remaining}` 路由表达式。 -- 解析全部 YAML 配置。 -- 编译四个后端 Maven 模块,并运行 Core 模块测试。 -- 确认最终 Git 差异不包含前端、小程序及用户已有工作区修改。 - -本次仓库验证结果: - -- SnakeYAML 成功解析 37 个后端与 Nacos YAML 文件。 -- Salon Core 测试通过(3 个测试,0 失败),Salon Gateway 与 ArtList Gateway 编译通过。 -- ArtList Core 被既有 Java 源码中的历史包名导入阻断:`UserServiceImpl` 与 `UserController` 仍引用不存在的 `com.xiaowang.jayucloud.artlist...` DTO 包。本次没有修改 Java 源码,该失败与配置调整无关,需另行修复后才能完成 ArtList Core 全量编译。 -- GitNexus 工具在当前会话不可用,提交前使用配置引用扫描、YAML 解析、Git 变更检查和 Maven 验证替代。 diff --git a/docs/scripts/开发环境Nacos配置发布说明_20260826.md b/docs/scripts/开发环境Nacos配置发布说明_20260826.md deleted file mode 100644 index 2603f818..00000000 --- a/docs/scripts/开发环境Nacos配置发布说明_20260826.md +++ /dev/null @@ -1,42 +0,0 @@ -# 开发环境 Nacos 配置发布说明 - -更新时间:2026-08-26 - -## 配置目录与命名空间 - -开发配置位于 `nacos/namespaces/dev/`,包含两个 namespace: - -- `jayucloud-artlist`:设计师端 -- `jayucloud-salon`:店务端 - -每个 namespace 的 `DEFAULT_GROUP` 下固定发布 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml` 和 `logging.yaml` 五个 Data ID。 - -## Dev 中间件 - -| 中间件 | 地址 | -| --- | --- | -| Nacos | `192.168.5.15:8848` | -| MySQL | `192.168.5.15:3306` | -| Redis | `192.168.5.15:6379` | -| RabbitMQ | `192.168.5.15:5672` | -| MinIO | `http://192.168.5.15:9000` | - -设计师端使用数据库 `jayucloud_artlist`,店务端使用数据库 `jayucloud_salon`。MinIO、七牛云和阿里云 OSS 的默认 Bucket 均为 `jayucloud-dev`。店务端 Dev 配置已登记开发中间件默认参数,部署环境变量仍可覆盖。 - -## Gitea Secrets - -工作流需要配置以下 Dev Secrets: - -- `NACOS_DEV_URLS`:`http://192.168.5.15:8848/nacos` -- `NACOS_DEV_USERNAME`:Dev Nacos 发布账号 -- `NACOS_DEV_PASSWORD`:Dev Nacos 发布账号密码 - -账号密码不得写入仓库、YAML、工作流日志或说明文档。 - -## 发布与校验 - -在 Gitea Actions 手工运行 `.gitea/workflows/publish-nacos.yml`,将 `environment` 选择为 `dev`。脚本只读取 `nacos/namespaces/dev/`,写入第一个 Dev Nacos 地址,并从该单节点回读每个 Data ID,按 SHA-256 摘要校验内容一致后才标记成功。 - -发布日志只显示环境、namespace、group 和 dataId,不输出配置正文、密码或 token。未配置 `NACOS_DEV_*` 时,脚本会在发起网络请求前明确失败。 - -本说明只覆盖 Dev 配置准备与发布流程,不执行生产 Nacos 发布。 diff --git a/docs/scripts/开发环境Nacos默认地址配置说明_20260623.md b/docs/scripts/开发环境Nacos默认地址配置说明_20260623.md deleted file mode 100644 index d8a146a8..00000000 --- a/docs/scripts/开发环境Nacos默认地址配置说明_20260623.md +++ /dev/null @@ -1,21 +0,0 @@ -# 开发环境Nacos默认地址配置说明 - -> 历史说明:后端环境变量覆盖入口已于 2026-10-10 移除。当前配置方式见 `后端配置统一由Nacos明文管理_20261010.md`。 - -## 当前配置 - -- `JC-ArtList-Core/src/main/resources/bootstrap.yaml` 和 `JC-ArtList-Gateway/src/main/resources/bootstrap.yaml` 保留 `NACOS_SERVER_ADDR`、`NACOS_NAMESPACE`、`NACOS_GROUP`、`NACOS_USERNAME`、`NACOS_PASSWORD` 环境变量覆盖方式。 -- 未设置环境变量时,默认连接开发环境 Nacos:`192.168.5.103:8848`。 -- 未设置环境变量时,默认命名空间为开发环境:`jayucloud-artlist`。 -- 默认分组为:`DEFAULT_GROUP`。 - -## 服务器信息依据 - -- `D:\doc\服务器信息.xlsx` 和 `D:\doc\prod-server-info-fd-db-switch-updated-20260623-145728.xlsx` 中记录:开发/测试使用单节点 `nacos04 192.168.5.103`。 -- 同表记录生产 Nacos 为三节点集群:`192.168.5.101:8848,192.168.5.102:8848,192.168.10.145:8848`。 - -## 部署要求 - -- 开发环境可以直接使用默认值。 -- 生产环境必须显式设置 `NACOS_SERVER_ADDR` 为生产三节点集群地址,并设置 `NACOS_NAMESPACE=jayucloud-artlist`。 -- 生产环境必须通过运行环境注入 Nacos 账号和密码,不依赖开发默认值。 diff --git a/docs/scripts/指尖管理师上线配置说明_20260622.md b/docs/scripts/指尖管理师上线配置说明_20260622.md deleted file mode 100644 index 1ec7f8ab..00000000 --- a/docs/scripts/指尖管理师上线配置说明_20260622.md +++ /dev/null @@ -1,32 +0,0 @@ -# 指尖管理师上线配置说明 - -## 生产配置约定 - -- 生产域名:`https://yunail.art`。 -- 指尖管理师小程序管理端 API:`https://yunail.art/api/admin`。 -- 网关对外管理端入口:`/api/admin/**`。 -- Core 内部管理端入口:`/admin/**`。 -- 生产数据库名:`jayucloud-artlist`,Linux MySQL 环境下必须保持大小写一致。 -- 生产 Nacos namespace:`jayucloud-artlist`。 - -## Nacos 必填配置 - -生产 namespace 下必须存在以下配置文件: - -- `core.yaml` -- `gateway.yaml` -- `infra.yaml` -- `secret.yaml` -- `logging.yaml` - -`infra.yaml` 至少需要确认 MySQL、Redis、RabbitMQ、MyBatis-Plus 相关配置。`secret.yaml` 至少需要确认 MySQL 密码、Redis 密码、RabbitMQ 密码、JWT 密钥、微信小程序配置、七牛 Kodo 密钥。对象存储使用七牛 Kodo 作为主存储时,必须填写 `QINIU_KODO_ACCESS_KEY`、`QINIU_KODO_SECRET_KEY`、`QINIU_KODO_BUCKET_NAME`、`QINIU_KODO_DOMAIN`、`QINIU_KODO_ZONE`。 - -如启用阿里云 OSS 作为备份存储,必须同时启用 `ALIYUN_OSS_ENABLED=true` 并填写 endpoint、region、bucket、access key。若暂不使用备份存储,发布前需要确认对象存储备份队列和定时补偿不会影响主链路。 - -## 发布前确认项 - -- 微信后台已配置 `https://yunail.art` 为合法请求域名。 -- 指尖管理师小程序与用户端小程序是否共用 appid 已经过产品/发布负责人确认。 -- Core 与 Gateway 的生产端口和健康检查地址已与 systemd、Nginx、部署脚本保持一致。 -- 上传大小限制已确认:当前 Servlet 单文件限制为 5MB,单请求限制为 10MB。 -- 初始化 SQL 仅用于空库首次部署;已有生产库必须使用版本变更 SQL,不允许直接执行初始化 SQL 覆盖升级。 diff --git a/docs/scripts/接回MinIO三副本对象存储配置说明_20260624.md b/docs/scripts/接回MinIO三副本对象存储配置说明_20260624.md deleted file mode 100644 index 61a1f868..00000000 --- a/docs/scripts/接回MinIO三副本对象存储配置说明_20260624.md +++ /dev/null @@ -1,140 +0,0 @@ -# 接回 MinIO 三副本对象存储配置说明 - -> 历史说明:后端对象存储环境变量覆盖入口已于 2026-10-10 移除,参数现由仓库 Nacos 配置源明文管理。当前方式见 `后端配置统一由Nacos明文管理_20261010.md`。 - -## 当前结论 - -- 开发 MinIO 服务健康检查已通过:`http://192.168.5.15:9000/minio/health/live` 返回 `200 OK`。 -- 开发 MinIO Console 可访问:`http://192.168.5.15:9001`。 -- `192.168.5.15` 的 `9090`、`80`、`443` 端口未作为 MinIO 服务端口开放。 -- 开发 Nacos 地址按服务器信息表确认为:`192.168.5.103:8848`。 -- 本地 `bootstrap.yaml` 只保留开发 Nacos 地址与命名空间默认值,不再保留 Nacos 用户名和密码默认值;启动时必须通过环境变量注入。 -- 已使用有写权限的 Nacos 账号在开发 Nacos 创建 `jayucloud-artlist` 命名空间,并发布 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml`、`logging.yaml` 五个配置。 -- 已只读核对 `jayucloud-artlist`:`core.yaml` 包含三 Provider 顺序,`infra.yaml` 包含 `http://192.168.5.15:9000` 和 `jayucloud-artlist` bucket,`secret.yaml` 未保留旧 `nailart` bucket、旧 MinIO endpoint 或 camelCase MinIO key。 - -## 代码配置约定 - -对象存储 Provider 标识固定为: - -- `MINIO` -- `QINIU_KODO` -- `ALIYUN_OSS` - -对象存储优先级固定为: - -```yaml -object-storage: - provider-order: - - MINIO - - QINIU_KODO - - ALIYUN_OSS - replica-required-providers: - - MINIO - - QINIU_KODO - - ALIYUN_OSS -``` - -旧字段 `primary-provider`、`backup-provider` 仅保留兼容展示和旧数据,不再作为三副本调度的唯一事实来源。 - -## Nacos 配置归属 - -`core.yaml` 放业务策略: - -```yaml -object-storage: - provider-order: - - MINIO - - QINIU_KODO - - ALIYUN_OSS - replica-required-providers: - - MINIO - - QINIU_KODO - - ALIYUN_OSS - primary-provider: MINIO - backup-provider: QINIU_KODO,ALIYUN_OSS - signed-url-expire-minutes: 60 - backup-queue-name: jayucloud-artlist.file.object-storage.backup.queue - backup-exchange-name: jayucloud-artlist.file.object-storage.backup.exchange - backup-routing-key: jayucloud-artlist.file.object-storage.backup - backup-retry-batch-limit: 500 - backup-retry-cron: "0 0 2 * * ?" -``` - -`infra.yaml` 放非敏感基础设施信息: - -```yaml -minio: - enabled: true - endpoint: http://192.168.5.15:9000 - bucket-name: jayucloud-artlist - private-bucket: true - signed-url-expire-minutes: 60 - -qiniu: - kodo: - bucket-name: jayucloud-artlist - domain: 需要按实际七牛域名填写 - zone: z2 - private-bucket: true - signed-url-expire-minutes: 60 - -aliyun: - oss: - enabled: true - endpoint: 需要按实际 OSS endpoint 填写 - region: 需要按实际 region 填写 - bucket-name: jayucloud-artlist - signed-url-expire-minutes: 60 -``` - -`secret.yaml` 放敏感信息: - -```yaml -minio: - access-key: 通过 Nacos 控制台填写 - secret-key: 通过 Nacos 控制台填写 - -qiniu: - kodo: - access-key: 通过 Nacos 控制台填写 - secret-key: 通过 Nacos 控制台填写 - -aliyun: - oss: - access-key-id: 通过 Nacos 控制台填写 - access-key-secret: 通过 Nacos 控制台填写 -``` - -`gateway.yaml`、`logging.yaml` 保持现有职责,不放对象存储密钥。 - -## 开发环境 Nacos 手工动作 - -1. 在 `192.168.5.103:8848` 创建命名空间 `jayucloud-artlist`。 -2. 从现有 `jayucloud-artlist` 命名空间复制 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml`、`logging.yaml`。 -3. 将开发环境 MySQL、Redis、RabbitMQ 保持为开发内网地址。 -4. 将 MinIO endpoint 改为 `http://192.168.5.15:9000`。 -5. 将 MinIO bucket 改为 `jayucloud-artlist`,不要复用旧 bucket。 -6. 发布后启动 Core/Gateway 验证服务注册到 `jayucloud-artlist`。 -7. 启动 Core/Gateway 并完成上传冒烟验证后,再停止使用或删除开发 Nacos 上旧的 `jayucloud-artlist` 命名空间配置。 - -## MinIO bucket 要求 - -- bucket 名称:`jayucloud-artlist` -- bucket 权限:建议私有。 -- 必须确认 Core 服务使用的 MinIO access key 对该 bucket 具备上传、下载、删除和签名 URL 所需权限。 -- 本次不迁移旧 bucket 中的历史对象;历史文件会优先按已有七牛或阿里云副本读取,并由副本补偿任务尝试补齐 MinIO。 - -## 数据库变更 - -空库初始化时执行对应端侧初始化 SQL: - -MinIO 三副本对象存储所需表结构已经并入端侧初始化 SQL。店务端执行 `docs/scripts/sql/init/jayucloud-salon.sql`,设计师端执行 `docs/scripts/sql/init/jayucloud-artlist.sql`。 - -该脚本会新增 `t_object_storage_file_replica`,并为历史文件生成 `MINIO`、`QINIU_KODO`、`ALIYUN_OSS` 三类副本记录。已有成功副本不会被覆盖,缺失副本会进入待上传状态,由重试任务补齐。 - -## 回滚方式 - -1. 将 `object-storage.provider-order` 改回只包含当前可用 Provider。 -2. 将 `object-storage.replica-required-providers` 改回当前需要补齐的 Provider 集合。 -3. 如需停止 MinIO,设置 `minio.enabled=false`。 -4. 不删除 `t_object_storage_file_replica` 表;保留副本事实便于后续恢复和排查。 diff --git a/docs/scripts/环境发布与回退工作流说明_20261015.md b/docs/scripts/环境发布与回退工作流说明_20261015.md deleted file mode 100644 index ee5a18e4..00000000 --- a/docs/scripts/环境发布与回退工作流说明_20261015.md +++ /dev/null @@ -1,22 +0,0 @@ -# 环境发布与回退工作流 - -仓库现在按环境拆分为 11 个入口:分支晋级检查、dev/SIT/prod 的 Nacos 发布与回退、SIT 和 prod 的自动部署与上一成功版本回退。 - -Nacos 发布先保存目标中心的线上快照,再发布全部 YAML,并从每个目标地址回读 SHA-256。成功记录写入 Runner 宿主机 `/salon-release/records//`,配置快照写入 `/salon-release/nacos-snapshots//`,应用包写入 `/salon-release/packages//`。生产发布同时处理 `NACOS_PROD_*` 主中心和 `NACOS_DR_*` 灾备中心。 - -## Runner 持久目录 - -Gitea Actions 的 `jayucloud-runner` 在 `192.168.5.15` 上运行。必须将宿主机持久目录 `/opt/software/panel/apps/gitea/act_runner/salon-release` 绑定挂载到每个任务容器的 `/salon-release`,并在 Runner 的 `config.yaml` `container.options` 中配置: - -```yaml -container: - options: - - "--add-host=gitea:host-gateway" - - "--volume=/opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release" -``` - -该目录由 Docker 宿主机持久保存,权限应限制为 Runner 和任务容器所需的读写账号。修改 Runner 配置后重启 `jayucloud-runner`。缺少此挂载时,Nacos 发布、部署和回退分别运行在独立任务容器中,后续任务无法读取前序任务生成的发布记录、配置快照和应用包。 - -自动部署只接受与成功 Nacos 记录相同的提交,并校验完整配置摘要和发布包 manifest。应用回退读取按 release ID 保存的成功记录;数据库始终使用 `-SkipDatabaseInit`,不会自动 DROP、重建或恢复。 - -自动失败回退通过 Gitea Actions API 触发对应回退入口并传递快照 ID。回退入口自身失败不会再次触发回退,仅保留工作流日志和失败状态。Runner 服务账号应独占 `/salon-release` 的读写权限,并定期清理旧快照和旧包。 diff --git a/docs/scripts/生产Gitea流水线发布Nacos配置准备说明_20260826.md b/docs/scripts/生产Gitea流水线发布Nacos配置准备说明_20260826.md deleted file mode 100644 index fa1fe2d7..00000000 --- a/docs/scripts/生产Gitea流水线发布Nacos配置准备说明_20260826.md +++ /dev/null @@ -1,65 +0,0 @@ -# 生产 Gitea 流水线发布 Nacos 配置准备说明 - -更新时间:2026-08-26 - -## 已核对的服务器与仓库信息 - -| 对象 | 脱敏信息 | 用途/边界 | -| --- | --- | --- | -| 中心1 Nacos | `192.168.10.11:8848`、`192.168.10.12:8848`、`192.168.10.13:8848` | Nacos 2.5.3 三节点生产集群;当前唯一生产写入源 | -| 中心2 Nacos | `192.168.20.10:8848` | Nacos 2.5.3 standalone 灾备副本;由 `prod-both` 在中心1成功后更新 | -| Gitea | `http://wcy111.top:3000` | Git 仓库与 Actions 发布入口 | -| 当前项目仓库 | `xiaowang/JayuCloud.git` | 当前代码、Nacos 配置和 Gitea Actions 工作流所在仓库 | -| 另有配置仓库 | `xiaowang/nacos-config.git` | 服务器信息表中登记的独立测试配置仓库;当前项目流水线不直接使用 | - -中心1 Nacos 节点间还需要 `9848/9849/7848`,业务客户端至少访问各节点的 `8848/9848`。中心2当前使用内置 Derby,由 Gitea 在中心1发布成功后按同一 Git 提交写入。 - -## 当前项目的发布入口 - -当前工作区的 Git remote 是 `xiaowang/JayuCloud.git`。由于发布工作流和 Nacos 配置目录已经在本项目中,现阶段应在该仓库配置并执行 Actions。`xiaowang/nacos-config.git` 若要作为正式配置源,必须先明确迁移方案,并同步迁移 `nacos/`、`.gitea/workflows/publish-nacos.yml`、`.gitea/scripts/publish-nacos.mjs` 及相关审批和回滚记录;在迁移完成前不要混用两个仓库。 - -- 工作流:`.gitea/workflows/publish-nacos.yml` -- 发布脚本:`.gitea/scripts/publish-nacos.mjs` -- 配置目录:`nacos/namespaces///DEFAULT_GROUP/.yaml` -- 当前 namespace:`jayucloud-artlist`、`jayucloud-salon` -- 当前 Data ID:`core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml`、`logging.yaml` -- `prod-center1` 会向中心1第一个地址写入,并从至少两个中心1地址回读 SHA-256 摘要;`prod-center2` 向中心2写入并回读;`prod-both` 严格按中心1、中心2顺序执行。 - -## Gitea Secrets 准备 - -在仓库的 Actions Secrets 中配置以下 9 个值;值只从私有凭据清单取得,不写入仓库、工作流文件或日志: - -| Secret | 内容要求 | -| --- | --- | -| `NACOS_PROD_URLS` | `http://192.168.10.11:8848/nacos,http://192.168.10.12:8848/nacos,http://192.168.10.13:8848/nacos`(也可省略末尾 `/nacos`) | -| `NACOS_PROD_USERNAME` | 生产 Nacos 发布专用账号,不能使用共享管理员账号 | -| `NACOS_PROD_PASSWORD` | 上述账号密码 | -| `NACOS_DR_URLS` | `http://192.168.20.10:8848/nacos`(也可省略末尾 `/nacos`) | -| `NACOS_DR_USERNAME` | 中心2 Nacos 发布账号 | -| `NACOS_DR_PASSWORD` | 中心2 Nacos 发布账号密码 | -| `NACOS_SIT_URLS` | `http://192.168.10.103:8848/nacos`(也可省略末尾 `/nacos`) | -| `NACOS_SIT_USERNAME` | SIT Nacos 发布账号 | -| `NACOS_SIT_PASSWORD` | SIT Nacos 发布账号密码 | - -中心2使用独立的 `NACOS_DR_*` Secrets,不把 `192.168.20.10` 混入 `NACOS_PROD_URLS`。工作流目标选择如下:`sit` 仅发布 SIT,`prod-center1` 仅发布中心1,`prod-center2` 仅发布中心2,`prod-both` 先发布并校验中心1,再发布并校验中心2。 - -## 上线前准备清单 - -1. 在 Gitea 仓库确认 Actions 已启用,默认分支和 `.gitea/workflows/publish-nacos.yml` 可被识别。 -2. 配置上表 6 个 Secrets,并用无敏感内容的测试提交验证 Secrets 未出现在日志中。 -3. 校验两个生产 namespace 的 5 个 Data ID 均存在,YAML 可解析,且 `secret.yaml` 仅包含受控占位符或密钥引用。 -4. 从 Gitea Runner 网络分别检查中心1三个 Nacos 地址的 `8848`/`9848` 连通性;检查任一节点 readiness 返回 `OK`。 -5. 先手工发布 `sit`,确认脚本日志显示每个 Data ID 已发布并校验,再安排生产审批窗口。 -6. 生产发布选择 `prod-both`,发布前记录目标 Git 提交号、配置文件清单和审批单号。 - -## 发布后验收 - -- Gitea Actions 工作流成功,且每个 Data ID 均出现“已发布并校验”。 -- 中心1至少两个 Nacos 节点读取内容的 SHA-256 与 Git 文件一致。 -- 三个中心1 Nacos 节点 readiness 正常,服务注册和业务客户端配置读取正常。 -- 中心2发布在中心1全量校验成功后执行;中心2回读失败时整体工作流标红并报告配置漂移。 -- 记录发布提交号、执行时间、发布人、Data ID 清单和校验结果;不记录密码或 token。 - -## 回滚与后续工作 - -回滚通过 Gitea 回退到目标 Git 提交后重新手工执行 `prod-both`,禁止直接在任一 Nacos 控制台修改受 Git 管理的配置。中心2仍作为业务只读灾备副本,仅允许流水线发布账号写入。 diff --git a/docs/scripts/生产Salon Core与Gateway环境变量准备说明_20260827.md b/docs/scripts/生产Salon Core与Gateway环境变量准备说明_20260827.md deleted file mode 100644 index 81a02dd4..00000000 --- a/docs/scripts/生产Salon Core与Gateway环境变量准备说明_20260827.md +++ /dev/null @@ -1,108 +0,0 @@ -# 生产 Salon Core 与 Gateway 环境变量准备说明 - -> 历史说明:本方案已于 2026-10-10 停用,不得再生成或注入本文所述环境文件。当前配置方式见 `后端配置统一由Nacos明文管理_20261010.md`。 - -更新时间:2026-08-27 - -## 适用节点 - -| 角色 | 节点 | 地址 | 服务端口 | 服务名 | 环境文件建议 | -| --- | --- | --- | ---: | --- | --- | -| Core | core01-01 | `192.168.10.24` | `81` | `jc-salon-core` | `/etc/jc-salon/jc-salon-core.env` | -| Core | core01-02 | `192.168.10.25` | `81` | `jc-salon-core` | `/etc/jc-salon/jc-salon-core.env` | -| Core | core01-03 | `192.168.20.16` | `81` | `jc-salon-core` | `/etc/jc-salon/jc-salon-core.env` | -| Gateway | gateway01-01 | `192.168.10.26` | `80` | `jc-salon-gateway` | `/etc/jc-salon/jc-salon-gateway.env` | -| Gateway | gateway01-02 | `192.168.10.27` | `80` | `jc-salon-gateway` | `/etc/jc-salon/jc-salon-gateway.env` | -| Gateway | gateway01-03 | `192.168.20.18` | `80` | `jc-salon-gateway` | `/etc/jc-salon/jc-salon-gateway.env` | - -三台同角色节点使用相同环境变量。不要将节点本机 IP 写入应用连接变量;Nacos、数据库、Redis 和 RabbitMQ 使用生产统一入口。 - -## Gateway 环境文件 - -保存为 `/etc/jc-salon/jc-salon-gateway.env`,权限设为 `600 root:root`: - -```dotenv -NACOS_SERVER_ADDR=192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848 -NACOS_NAMESPACE=jayucloud-salon -NACOS_GROUP=DEFAULT_GROUP -NACOS_USERNAME=jayucloud -NACOS_PASSWORD=122503wcy.... -SERVER_PORT=80 -``` - -Gateway 的业务路由从 Nacos `jayucloud-salon / DEFAULT_GROUP / gateway.yaml` 读取,注册名为 `jc-salon-gateway`。不要在 Gateway 环境文件中加入业务数据库、Redis 或对象存储密钥。 - -## Core 环境文件 - -保存为 `/etc/jc-salon/jc-salon-core.env`,权限设为 `600 root:root`: - -```dotenv -NACOS_SERVER_ADDR=192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848 -NACOS_NAMESPACE=jayucloud-salon -NACOS_GROUP=DEFAULT_GROUP -NACOS_USERNAME=jayucloud -NACOS_PASSWORD=122503wcy.... -SERVER_PORT=81 - -BUSINESS_JDBC_URL=jdbc:mysql://192.168.10.200:6033/jayucloud_salon?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai -BUSINESS_DB_USERNAME=root -BUSINESS_DB_PASSWORD=122503wcy.... - -REDIS_SENTINEL_MASTER=mymaster -REDIS_SENTINEL_NODES=192.168.10.17:26379,192.168.10.18:26379,192.168.10.19:26379,192.168.20.13:26379,10.66.0.4:26379 -REDIS_USERNAME=xiaowang -REDIS_PASSWORD=122503wcy.... -REDIS_DATABASE=0 - -RABBITMQ_ADDRESSES=mq-prod.internal:5672 -RABBITMQ_VHOST=Jayucloud-Salon -RABBITMQ_USERNAME=xiaowang -RABBITMQ_PASSWORD=122503wcy.... - -OBJECT_STORAGE_PRIMARY_PROVIDER=MINIO -MINIO_ENABLED=true -MINIO_ENDPOINT=http://192.168.10.105:9000 -MINIO_BUCKET_NAME=jayucloud -MINIO_ACCESS_KEY=root -MINIO_SECRET_KEY=122503wcy.... -MINIO_PRIVATE_BUCKET=true -MINIO_SIGNED_URL_EXPIRE_MINUTES=60 - -QINIU_KODO_ACCESS_KEY=U_btHNrxj1X0UaHllVO8mq4p-8jB1Php-87vi2M7 -QINIU_KODO_SECRET_KEY=WIO_jEcir_2upUqoIzn5Hu5EWSb4-yB4sWeLFiXD -QINIU_KODO_BUCKET_NAME=jayucloud -QINIU_KODO_DOMAIN=https://img.yunail.art -QINIU_KODO_ZONE=z2 -QINIU_KODO_PRIVATE_BUCKET=true -QINIU_KODO_SIGNED_URL_EXPIRE_MINUTES=60 - -ALIYUN_OSS_ENABLED=true -ALIYUN_OSS_ENDPOINT=https://oss-cn-chengdu.aliyuncs.com -ALIYUN_OSS_REGION=cn-chengdu -ALIYUN_OSS_BUCKET_NAME=jayucloud -ALIYUN_OSS_ACCESS_KEY_ID=LTAI5t9divmxMWHiKhLSRdDd -ALIYUN_OSS_ACCESS_KEY_SECRET=U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q -ALIYUN_OSS_SIGNED_URL_EXPIRE_MINUTES=60 -``` - -Core 注册名为 `jc-salon-core`,通过环境变量 `SERVER_PORT=81` 监听 `81` 端口,与部署脚本健康检查一致。生产正常运行时 MinIO 使用中心1 `192.168.10.105:9000`;灾备接管时才切换到中心2 MinIO 地址,并同步确认桶和凭据。 - -## systemd 注入 - -对应服务单元的 `[Service]` 段加入: - -```ini -EnvironmentFile=/etc/jc-salon/jc-salon-core.env -``` - -Gateway 使用 `jc-salon-gateway.env`。写入后执行 `systemctl daemon-reload`,首次启动前确认环境文件存在、权限正确且没有尖括号占位符。不要把环境文件打包进 JAR、前端产物或 Git。 - -## 发布前检查 - -1. 两个环境文件分别部署到 3 台同角色节点,并核对 SHA-256 一致。 -2. 从每台节点确认可以访问三个 Nacos `8848` 和 `9848` 端口、Redis Sentinel `26379`、RabbitMQ `5672` 及业务数据库 `6033`。 -3. 先启动 Core,确认 `jc-salon-core` 在 `jayucloud-salon` 注册且 `http://127.0.0.1:81/health/check` 成功。 -4. 再启动 Gateway,确认 `jc-salon-gateway` 注册且 `http://127.0.0.1:80/health/check` 成功。 -5. 通过入口节点验证 Salon Web/API;失败时保留旧 JAR 和旧环境文件,不直接覆盖回滚材料。 - -生产 Nacos、数据库和服务器部署仍需按审批后的 Gitea 发布工作流执行;本说明只准备变量,不执行连接或发布。`SERVER_PORT` 是本机 Spring Boot 端口,不依赖 Nacos 中是否声明 `server.port`。 diff --git a/docs/scripts/生产Salon Gitea流水线配置说明_20260827.md b/docs/scripts/生产Salon Gitea流水线配置说明_20260827.md deleted file mode 100644 index 50387bf9..00000000 --- a/docs/scripts/生产Salon Gitea流水线配置说明_20260827.md +++ /dev/null @@ -1,36 +0,0 @@ -# Salon 生产 Gitea 流水线配置说明 - -## 工作流 - -- `.gitea/workflows/salon-prod-prepare.yml`:仅在 `sit` 来源的 PR 合并到 `prod` 后自动运行,构建后端、前端和 SQL 归档并上传 Artifact,不修改生产环境。 -- `.gitea/workflows/salon-prod-deploy.yml`:仅支持手工运行,填写准备工作流运行 ID 和合并提交 SHA 后,下载对应 Artifact 并执行生产发布。 -- 发布工作流通过 Gitea Actions Artifact 原生接口下载准备产物,不使用 GitHub 专用的 `actions/download-artifact` 跨运行接口;下载并校验成功后才发布生产 Nacos 配置。 -- 两个 Salon 工作流使用内网 Gitea API 直接拉取提交,不依赖 `actions/checkout` 的 GitHub 外部仓库;Runner 需能访问 `http://192.168.5.15:3000`。 - -## prod 分支保护 - -在 Gitea 仓库的 Branches/Protected branches 中为 `prod` 配置: - -- 禁止直接 push; -- 仅允许 Pull Request 合并; -- 合并来源分支限制为 `sit`; -- 至少一名审批人,并要求状态检查 `Salon 生产发布准备 / prepare` 成功。 - -## Runner - -Runner 标签为 `jayucloud`,当前使用固定任务镜像 `jayucloud/runner:node20-java17-maven-pwsh`,已预装 Node.js 20、JDK 17、Maven、npm、tar、PowerShell 7 和 OpenSSH client。发布工作流会在任务容器内安装 `sshpass`,人工发布阶段还必须能访问生产 Nacos、6 台 Salon 后端服务器和阿里云 NGINX 主机。 - -## Secrets - -仓库 Actions Secrets 需要配置: - -- `SALON_PROD_SSH_PASSWORD`:生产和 SIT 发布使用的 SSH 密码; -- `GITHUB_TOKEN`:用于下载准备工作流 Artifact(由 Gitea 自动提供)。 - -SSH 登录目标固定为生产后端节点和阿里云 NGINX;账号、端口和前端目录由工作流按服务器清单注入。密码只配置为 Gitea Secret,禁止写入工作流或提交记录。生产 Nacos 认证和应用启动所需运行时变量应通过受控的服务环境文件或 Gitea Secrets 注入,不能写入仓库。 - -## 发布边界 - -自动准备阶段不连接生产 SSH、不发布 Nacos、不重启服务、不执行 SQL。人工发布阶段跳过数据库初始化;SQL 仅作为 Artifact 附件,由 DBA 按版本化迁移规则人工执行并记录。 - -首次人工发布前,需在 6 台后端完成 `jc-salon-core`、`jc-salon-gateway` 服务单元及运行时环境文件初始化;人工发布工作流使用 `-RequireSystemd`,缺少服务单元会直接失败,不会退回后台进程模式。还需确认阿里云 NGINX 已使用 `/opt/jc-salon-frontend/current` 或等价目录作为 Salon 站点根目录。 diff --git a/docs/scripts/生产与测试环境Nacos配置说明_20260826.md b/docs/scripts/生产与测试环境Nacos配置说明_20260826.md deleted file mode 100644 index 939da85c..00000000 --- a/docs/scripts/生产与测试环境Nacos配置说明_20260826.md +++ /dev/null @@ -1,49 +0,0 @@ -# 生产与测试环境 Nacos 配置说明 - -> 当前说明:数据库、Redis、RabbitMQ、对象存储和业务参数由 Nacos 管理;连接 Nacos 所需的五个启动引导参数继续由运行环境注入。 - -## 配置目录 - -Nacos 配置源按环境、命名空间和 Group 分离: - -```text -nacos/namespaces///DEFAULT_GROUP/.yaml -``` - -当前支持 `prod` 与 `sit` 环境,且每个环境均包含 `jayucloud-artlist`、`jayucloud-salon` 两个 namespace。每个 namespace 必须包含 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml` 和 `logging.yaml`。 - -## 环境差异 - -| 项目 | PROD | SIT | -| --- | --- | --- | -| Nacos | 三节点生产集群 | `192.168.10.10:8848` | -| MySQL | 生产 ProxySQL 入口 | `192.168.10.11:3306` | -| Redis | Sentinel `mymaster` | `192.168.10.12:6379` 单机 | -| RabbitMQ | `mq-prod.internal:5672` | `192.168.10.13:5672` | -| MinIO | `192.168.10.105:9000` | `192.168.10.14:9000` | -| 对象存储 Bucket | `jayucloud` | `jayucloud-sit` | - -SIT 的设计师库为 `jayucloud_artlist`,店务库为 `jayucloud_salon`。三个对象存储 Provider 在 SIT 均使用 `jayucloud-sit` Bucket;其他 Provider 参数沿用生产值。 - -## 应用启动变量 - -Core 和 Gateway 必须显式设置 `NACOS_SERVER_ADDR`、`NACOS_NAMESPACE`、`NACOS_GROUP`、`NACOS_USERNAME`、`NACOS_PASSWORD`。SIT 的 `NACOS_SERVER_ADDR` 固定为 `192.168.10.10:8848`;生产使用三个生产 Nacos 节点地址。两个端侧分别使用 `jayucloud-artlist` 与 `jayucloud-salon` namespace,Group 均为 `DEFAULT_GROUP`。 - -## Gitea Actions 发布 - -工作流 `.gitea/workflows/publish-nacos.yml` 必须手工选择发布目标:`dev`、`sit`、`prod-center1`、`prod-center2` 或 `prod-both`。脚本只读取所选环境目录;`dev` 使用单节点回读校验,`prod-both` 先发布并校验中心1,再发布并校验中心2。 - -Gitea 仓库 Secrets 必须配置: - -- `NACOS_PROD_URLS`、`NACOS_PROD_USERNAME`、`NACOS_PROD_PASSWORD` -- `NACOS_DR_URLS`、`NACOS_DR_USERNAME`、`NACOS_DR_PASSWORD` -- `NACOS_SIT_URLS`、`NACOS_SIT_USERNAME`、`NACOS_SIT_PASSWORD` -- `NACOS_DEV_URLS`、`NACOS_DEV_USERNAME`、`NACOS_DEV_PASSWORD` - -SIT 使用一个 Nacos 地址并在该节点回读校验;中心1至少提供两个地址并在两个节点回读校验;中心2提供一个灾备地址并单节点回读校验。Secrets 不得出现在 YAML、Git 提交、工作流日志或说明文档中。 - -## 发布前后检查 - -发布前检查所选环境的两个 namespace 均存在五个 Data ID,且 YAML 语法有效。确认 SIT RabbitMQ 已创建业务 vhost 与最小权限账号,并通过 `RABBITMQ_VHOST`、`RABBITMQ_USERNAME`、`RABBITMQ_PASSWORD` 注入。 - -发布后确认日志中每个 Data ID 都显示已发布并校验;随后启动对应 Core/Gateway,确认服务注册到所选 Nacos 环境并完成数据库、Redis、RabbitMQ 和 MinIO 连通性检查。 diff --git a/docs/scripts/生产对象存储与中间件配置调整说明_20260825.md b/docs/scripts/生产对象存储与中间件配置调整说明_20260825.md deleted file mode 100644 index 16ee4dc4..00000000 --- a/docs/scripts/生产对象存储与中间件配置调整说明_20260825.md +++ /dev/null @@ -1,26 +0,0 @@ -# 生产对象存储与中间件配置调整说明 2026-08-25 - -## 变更范围 - -- 更新两个生产 namespace 的 `core.yaml` 与 `infra.yaml`。 -- 补齐 MinIO、七牛云 Kodo、阿里云 OSS 的非敏感默认连接参数。 - -## 生产对象存储 - -- MinIO 默认主入口为 `http://192.168.10.105:9000`,中心2 `http://192.168.20.15:9000` 仅用于灾备接管,不配置为客户端多地址。 -- 七牛云 Kodo 使用私有空间 `jayucloud`、华南区域 `z2` 和 `https://img.yunail.art`。 -- 阿里云 OSS 使用私有桶 `jayucloud`、成都区域 `cn-chengdu` 和 `https://oss-cn-chengdu.aliyuncs.com`。 -- AccessKey、SecretKey 和其他敏感凭据继续仅由环境变量或 Gitea Secrets 注入,不写入 Git。 - -## 其他中间件核对 - -- 业务 MySQL 保持中心1 ProxySQL 入口 `192.168.10.200:6033`。 -- Redis 保持 `mymaster` 和五个 Sentinel 节点。 -- RabbitMQ 保持 `mq-prod.internal:5672`。 -- Nacos 元数据库仍应仅使用 `192.168.10.200:3306/nacos`,不使用 ProxySQL。 - -## 发布与验证 - -- 本次只更新 Git 管理的生产 Nacos 配置源,未向生产 Nacos 发布。 -- 发布后需从至少两个 Nacos 节点读取 `core.yaml` 与 `infra.yaml`,确认两个 namespace 的摘要一致。 -- 发布前验证生产节点可访问中心1 MinIO `9000`、Redis Sentinel、RabbitMQ 和业务数据库入口。 diff --git a/docs/scripts/管理师小程序本地接口地址配置说明_20260623.md b/docs/scripts/管理师小程序本地接口地址配置说明_20260623.md deleted file mode 100644 index 01b4d901..00000000 --- a/docs/scripts/管理师小程序本地接口地址配置说明_20260623.md +++ /dev/null @@ -1,10 +0,0 @@ -# 管理师小程序本地接口地址配置说明 - -管理师小程序的接口域名由 `JC-Salon-WeChat/utils/config.js` 统一生成。 - -- 微信开发者工具运行时,`develop` 环境默认使用 `local`,接口地址为 `http://127.0.0.1:80/api`,管理端接口地址为 `http://127.0.0.1:80/api/admin`。 -- 真机开发版默认使用 `http://wcy111.top:18888`,避免真机把 `127.0.0.1` 识别为手机本机地址。 -- 体验版和正式版默认使用 `https://yunail.art`。 -- 如需本地临时切换到 tunnel 或远程开发地址,可复制 `JC-Salon-WeChat/utils/config.local.example.js` 为 `JC-Salon-WeChat/utils/config.local.js`,再调整 `developTarget` 或 `domains`。 -- 已登录的非安全请求默认启用请求签名,`config.local.js` 可通过 `enableRequestSigning: false` 临时关闭本地覆盖,但不要提交关闭签名的配置。 -- `config.local.js` 属于个人本地覆盖配置,已加入 `.gitignore`,不要提交到仓库。 diff --git a/docs/scripts/统一JayuCloud数据库名配置说明_20260617.md b/docs/scripts/统一JayuCloud数据库名配置说明_20260617.md deleted file mode 100644 index de63d422..00000000 --- a/docs/scripts/统一JayuCloud数据库名配置说明_20260617.md +++ /dev/null @@ -1,19 +0,0 @@ -# 统一数据库名为 jayucloud-artlist 配置说明 - -## 变更内容 - -- 后端默认 JDBC 地址统一指向 `jayucloud-artlist`。 -- 初始化 SQL 的数据库创建语句和 `USE` 语句统一使用 `jayucloud-artlist`。 -- 测试说明文档中的数据库名前缀同步为 `jayucloud-artlist`。 - -## 配置要求 - -- Nacos 或本地 `spring.datasource.url` 必须指向 `jdbc:mysql://:/jayucloud-artlist`。 -- Core 与 Gateway 默认 Nacos 命名空间为 `jayucloud-artlist`,如需连接其他环境必须显式设置 `NACOS_NAMESPACE`。 -- MySQL 中必须存在目标端数据库:店务端为 `jayucloud_salon`,设计师端为 `jayucloud_artlist`;首次部署执行对应端侧初始化 SQL。 -- 开发、测试和上线空库分别执行 `docs/scripts/sql/init/jayucloud-salon.sql` 或 `docs/scripts/sql/init/jayucloud-artlist.sql`;已部署生产库如需调整库名,需要单独制定生产迁移方案。 - -## 注意事项 - -- 本次变更不迁移旧库数据。 -- 如旧环境存在历史数据库,需先确认数据不再使用后再手工清理。 diff --git a/docs/scripts/运行与发布配置总说明.md b/docs/scripts/运行与发布配置总说明.md new file mode 100644 index 00000000..58a3678c --- /dev/null +++ b/docs/scripts/运行与发布配置总说明.md @@ -0,0 +1,88 @@ +# JayuCloud 运行与发布配置总说明 + +更新时间:2026-10-16 + +本文是 `docs/scripts/` 下运行、配置、发布和回退规则的唯一说明入口。可执行脚本和初始化 SQL 保持独立文件,不在本文中重复粘贴。 + +## 1. 仓库资产边界 + +- `sql/init/jayucloud-artlist.sql`:ArtList 空库初始化入口。 +- `sql/init/jayucloud-salon.sql`:Salon 空库初始化入口,已包含历史版本脚本中的表、索引和种子数据。 +- `deploy-jayucloud-artlist-production.ps1`:ArtList 生产部署脚本。 +- `deploy-jayucloud-salon-production.ps1`:Salon 生产部署脚本。 +- `package-release.ps1`:发布包构建与归档脚本。 +- `nacos/namespaces///DEFAULT_GROUP/`:Nacos 配置源,每个端侧包含 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml`、`logging.yaml`。 + +代码、配置、脚本和 SQL 当前以 `0.0.1` 为基线。后续 SQL 默认使用版本文件;只有明确要求重整空库基线时才合入 `sql/init/`。 + +## 2. 端侧和环境 + +| 端侧 | 后端 | 前端/小程序 | Nacos namespace | 数据库 | +| --- | --- | --- | --- | --- | +| ArtList | `JC-ArtList-Core`、`JC-ArtList-Gateway` | `JC-ArtList-Frontend`、`JC-ArtList-WeChat` | `jayucloud-artlist` | `jayucloud_artlist` | +| Salon | `JC-Salon-Core`、`JC-Salon-Gateway` | `JC-Salon-Frontend`、`JC-Salon-WeChat` | `jayucloud-salon` | `jayucloud_salon` | + +环境目录为 `dev`、`sit`、`prod`。每个端侧的五个 Data ID 必须完整存在,配置按环境隔离,不跨环境复用凭据。 + +## 3. Nacos 配置分层 + +- `infra.yaml`:地址、端口、数据库、Redis、RabbitMQ、对象存储 endpoint/bucket/开关等基础设施参数。 +- `secret.yaml`:数据库、Redis、RabbitMQ、MinIO、七牛、阿里云 OSS、JWT、微信和 MessageHub 等敏感值。仓库当前按项目约定明文维护,发布权限必须受控。 +- `core.yaml`:Core 端口、缓存、慢请求、对象存储 Provider 顺序与备份策略、MessageHub 业务参数。 +- `gateway.yaml`:Gateway 端口、路由、白名单和网关参数。 +- `logging.yaml`:公共日志级别。 + +对象存储统一使用 `object-storage.signed-url-expire-minutes`。MinIO、七牛和 OSS 的连接配置只保留各自必要字段;私有桶按环境配置 `private-bucket: true`。三套 Salon 环境默认签名有效期为 60 分钟。 + +后端启动时只需要 Nacos 启动引导参数:`NACOS_SERVER_ADDR`、`NACOS_NAMESPACE`、`NACOS_GROUP`、`NACOS_USERNAME`、`NACOS_PASSWORD`。业务数据库、Redis、RabbitMQ 和对象存储参数由 Nacos 提供,不再通过应用环境变量覆盖。 + +## 4. 小程序接口地址 + +`JC-Salon-WeChat/utils/config.js` 根据 `wx.getAccountInfoSync().miniProgram.envVersion` 选择地址: + +- 开发工具 `develop`:默认 `http://127.0.0.1:80/api`。 +- 真机开发:不能访问手机自身的 `127.0.0.1`,使用 `config.local.js` 切换到局域网地址、tunnel 或远程开发地址。 +- 体验版 `trial`:`https://sit.yunail.art/api`。 +- 正式版 `release`:`https://yunail.art/api`。 + +个人覆盖配置从 `JC-Salon-WeChat/utils/config.local.example.js` 复制为未提交的 `config.local.js`,不要将其加入版本库。 + +## 5. 发布与回退 + +环境晋级链路固定为: + +```text +dev -> sit -> prod +``` + +`sit` 只接受 `dev` 来源的 Pull Request,`prod` 只接受 `sit` 来源的 Pull Request;两个环境禁止直接推送和强制推送。生产发布必须使用准备包和明确的合并提交 SHA。 + +Nacos 发布流程应先保存目标环境快照,再发布全部 YAML,并从目标地址回读配置摘要校验。发布记录、Nacos 快照和应用包保存在 Runner 的 `/salon-release` 持久目录中。Runner 宿主机目录建议挂载为: + +```text +/opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release +``` + +缺少该挂载时,Prepare、Deploy 和 Rollback 任务之间无法共享发布记录、配置快照和应用包。 + +SIT 和生产部署前确认 Java 17、systemd、Nacos、数据库、Redis、RabbitMQ、MinIO 和 Nginx 可达;SQL 只归档,不由发布工作流自动执行。回退必须使用上一成功版本的应用包和对应配置快照。 + +## 6. MessageHub 与对象存储 + +MessageHub 的地址、交换机、路由和来源系统放在对应环境 `core.yaml`,访问 Token 放在 `secret.yaml`。Salon SIT Token 当前由维护人员填入 Nacos 后再发布,空 Token 配置不得晋级。 + +对象存储发布前先确认端侧专属 bucket 和 RabbitMQ vhost 已创建。生产 MinIO 主入口、七牛 Kodo、阿里云 OSS 的实际地址和 bucket 以目标环境 Nacos 文件为准,灾备地址只在接管时切换。 + +## 7. Salon 小程序业务约定 + +- OpenID 快捷登录接口、注册审核、手机号绑定和登录状态机见 Salon Core 代码及初始化 SQL。 +- 历史补单使用订单来源 `HISTORICAL_BACKFILL`;状态 `4` 为“服务中”。补单必须归属员工,可不填写客户和具体服务时间,不创建预约占用。 +- 初始化 SQL 已包含注册审核表、短信供应商种子、员工审核提醒参数及补单相关字段;已部署数据库不得直接重跑完整初始化脚本。 + +## 8. 操作前检查 + +1. 确认目标分支和环境,检查 Nacos namespace、Data ID、Group 是否正确。 +2. 确认凭据位于目标环境 `secret.yaml`,不要把生产凭据写入脚本或工作流日志。 +3. 发布前校验全部 YAML、SQL 和脚本路径,确认目标服务器和持久目录可用。 +4. 发布后检查 Core、Gateway、前端和小程序请求地址,记录配置摘要、版本 SHA 和健康检查结果。 +5. 发生故障时先保存日志和配置快照,再按上一成功版本回退,不直接修改线上数据库或删除业务数据。 diff --git a/docs/运维配置与集成说明.md b/docs/运维配置与集成说明.md index 1c8fd885..b649c919 100644 --- a/docs/运维配置与集成说明.md +++ b/docs/运维配置与集成说明.md @@ -1,6 +1,6 @@ # 运维配置与集成说明 -> 已于 2026-10-10 停用后端环境变量注入方案。当前以 `docs/scripts/后端配置统一由Nacos明文管理_20261010.md` 为准;本文中的环境变量表仅保留为历史记录,不得继续作为部署依据。 +> 已于 2026-10-10 停用后端环境变量注入方案。当前以 `docs/scripts/运行与发布配置总说明.md` 为准;本文中的环境变量表仅保留为历史记录,不得继续作为部署依据。 ## 双端生产隔离 @@ -13,9 +13,9 @@ 服务注册名为 `jc-artlist-core`、`jc-artlist-gateway`、`jc-salon-core`、`jc-salon-gateway`。设计师 Web/小程序不再包含管理入口;店务 Web 仅保留管理工作流。 -Nacos 配置源位于 `nacos/namespaces/dev/`、`nacos/namespaces/sit/` 与 `nacos/namespaces/prod/`,发布流程为 `.gitea/workflows/publish-nacos.yml`。推送到 `dev` 或 `sit` 分支会自动发布对应环境;生产环境仍须通过工作流手工选择发布目标。配置与凭据不跨环境复用。生产 Nacos 元数据库使用 `192.168.10.200:3306/nacos`,生产业务数据库使用 `192.168.10.200:6033` 对应业务库;SIT 业务数据库使用 `192.168.10.102:3306`;Dev 中间件统一使用 `192.168.5.15`。Redis、RabbitMQ 和对象存储的连接信息通过环境变量或 Gitea Secrets 注入,不在仓库提交敏感值。详细规则见 `docs/scripts/生产与测试环境Nacos配置说明_20260826.md` 和 `docs/scripts/开发环境Nacos配置发布说明_20260826.md`。 +Nacos 配置源位于 `nacos/namespaces/dev/`、`nacos/namespaces/sit/` 与 `nacos/namespaces/prod/`,发布流程为 `.gitea/workflows/publish-nacos.yml`。推送到 `dev` 或 `sit` 分支会自动发布对应环境;生产环境仍须通过工作流手工选择发布目标。配置与凭据不跨环境复用。详细规则见 `docs/scripts/运行与发布配置总说明.md`。 -生产对象存储默认使用中心1 MinIO `http://192.168.10.105:9000`,中心2 `http://192.168.20.15:9000` 仅在灾备接管时切换。七牛云 Kodo 使用私有空间 `jayucloud`、`z2` 和 `https://img.yunail.art`;阿里云 OSS 使用私有桶 `jayucloud`、`cn-chengdu` 和 `https://oss-cn-chengdu.aliyuncs.com`。详细发布与验证要求见 `docs/scripts/生产对象存储与中间件配置调整说明_20260825.md`。 +生产对象存储默认使用中心1 MinIO,灾备地址仅在接管时切换。七牛云 Kodo 和阿里云 OSS 的地址、区域与 bucket 以目标环境 Nacos 配置为准,详细发布与验证要求见 `docs/scripts/运行与发布配置总说明.md`。 两套数据库空库脚本位于 `docs/scripts/sql/init/`:店务端执行 `jayucloud-salon.sql`,设计师端执行 `jayucloud-artlist.sql`。两个脚本已包含各自端侧职责边界和排班规则;生产执行前须先核对目标库、账号和备份状态。 diff --git a/docs/项目功能概览.md b/docs/项目功能概览.md index beb1dda7..2c957301 100644 --- a/docs/项目功能概览.md +++ b/docs/项目功能概览.md @@ -32,5 +32,5 @@ jayucloud-artlist 指尖设计师是一个面向美甲门店经营的全链路 - `JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/`:后端 Core 业务模块目录。 - `JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/`:后端 Core 公共 DTO、VO 和基类目录。 - `docs/scripts/sql/init/`:店务端 `jayucloud-salon.sql` 与设计师端 `jayucloud-artlist.sql` 的空库初始化脚本。 -- `docs/scripts/0.0.1版本基线与后续迭代规则_20260628.md`:脚本、配置、SQL 后续版本迭代规则。 +- `docs/scripts/运行与发布配置总说明.md`:脚本、配置、SQL、环境发布与回退规则。 - `artifacts/maven/`:Maven 打包产物指定输出目录。 From 3d18a1972b76f12f127cdfcfe56460aae965bc57 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Fri, 16 Oct 2026 16:25:03 +0800 Subject: [PATCH 002/165] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E8=BE=93=E5=85=A5=E4=B8=8E=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E4=BA=A4=E4=BA=92=E8=AE=BE=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...026-10-16-预约客户输入与选择交互-design.md | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md diff --git a/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md new file mode 100644 index 00000000..efc815c7 --- /dev/null +++ b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md @@ -0,0 +1,52 @@ +# 预约客户输入与选择交互设计 + +## 目标 + +优化 Salon 小程序新增预约页面的客户录入体验:客户姓名直接输入,已有客户通过按钮选择;未选择已有客户时,在提交阶段按统一唯一性规则检查客户,并在需要时引导创建客户。 + +## 唯一性规则 + +- 客户姓名和手机号都填写时,以“姓名 + 手机号”作为唯一组合。 +- 手机号为空时,以客户姓名作为唯一键。 +- 后端创建客户和预约关联前必须再次校验,前端检查仅用于改善交互,不能替代后端校验。 +- 已存在同一唯一键的客户不得重复创建。 + +## 页面交互 + +### 主表单 + +客户字段改为横向布局:左侧为客户姓名输入框,右侧为“选择已有客户”按钮。手机号作为同一客户信息的可选输入项保留在客户区域内。输入姓名或手机号时清除 `customerUserId`,防止修改文本后仍绑定旧客户。 + +点击“选择已有客户”打开现有底部选择页,支持按姓名或手机号搜索;选择后回填客户 ID、姓名和手机号并关闭选择页。 + +### 提交前检查 + +未选择已有客户且填写客户姓名时,提交预约前调用客户查询接口,使用姓名和手机号作为查询条件: + +1. 找到唯一匹配客户:弹窗询问“已找到匹配客户,是否使用该客户”,按钮为“使用已有客户”和“继续新建”。选择使用则回填客户 ID 后继续提交;继续新建则进入创建确认。 +2. 未找到匹配客户:弹窗询问“系统中没有该客户,是否新建客户”,按钮为“确认”和“不新建”。确认后调用客户创建接口,成功后使用返回 ID 提交预约;不新建则取消本次提交。 +3. 后端返回唯一性冲突:提示客户已存在并要求重新选择或修改信息,不重复创建。 + +手机号为空时不要求手机号格式校验;填写手机号时仍校验中国大陆手机号格式。客户姓名仍为预约必填字段。 + +## 后端接口与模型 + +- 扩展 `GET /manager/customers` 的姓名、手机号筛选能力,保证查询条件能够表达姓名加手机号的组合。 +- 调整 `POST /manager/customers`:手机号改为可选;无手机号时不生成手机号账号,使用系统生成的不可登录账号或现有客户创建约定;有手机号时保留现有账号兼容逻辑。 +- 创建前在事务内按唯一性规则查询并拒绝重复,返回明确业务错误。 +- 不修改预约提交协议,预约仍使用 `customerUserId`、`customerName` 和 `phone` 字段。 +- 保留已有客户列表、详情和其他端客户管理能力;后端规则对所有入口生效。 + +## 状态与错误处理 + +- 查询或创建失败时保持用户输入,不关闭页面,提示可重试。 +- 创建成功但预约提交失败时保留返回的客户 ID 和表单内容,避免重复创建;再次提交优先使用已创建客户。 +- 选择已有客户、手动输入、弹窗关闭均不清除未提交的姓名和手机号,除非用户明确选择其他客户。 + +## 兼容与测试 + +- 复用 `entity-selector-sheet`,不新增客户选择组件。 +- 覆盖已有客户选择、姓名输入清除绑定、姓名+手机号命中、仅姓名命中、未命中后确认创建、取消创建、手机号为空和重复创建冲突场景。 +- 后端测试覆盖有手机号组合唯一、无手机号姓名唯一、并发重复创建和旧客户数据兼容。 +- 不修改 ArtList、Nacos 或数据库初始化基线;如现有表约束无法表达规则,仅新增中文版本 SQL 变更脚本。 + From 4a7bd9008876f52c5d71bf456a25bd02b063f993 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Fri, 16 Oct 2026 17:33:58 +0800 Subject: [PATCH 003/165] =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E8=BE=93=E5=85=A5=E4=B8=8E=E5=94=AF=E4=B8=80?= =?UTF-8?q?=E6=80=A7=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/AdminManagerController.java | 23 ++- .../manager/dto/ManagerCustomerCreateDTO.java | 3 - .../service/impl/PlanningServiceImpl.java | 39 ++--- .../modules/user/service/UserService.java | 5 + .../user/service/impl/UserServiceImpl.java | 90 +++++++++++- JC-Salon-WeChat/api/customers.js | 7 + .../appointment-form/entity-selector.test.js | 29 +++- .../pages/appointment-form/index.js | 138 ++++++++++++------ .../pages/appointment-form/index.wxml | 43 +----- .../pages/appointment-form/index.wxss | 96 ++++++------ ...026-10-16-预约客户输入与选择交互-design.md | 2 +- docs/项目变更记录.md | 7 + 12 files changed, 318 insertions(+), 164 deletions(-) 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..308f420a 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 @@ -141,6 +141,16 @@ 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/{id}") @RequirePermission("user:view") public Result customer(HttpServletRequest request, @PathVariable Long id) { @@ -157,18 +167,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.getPhone(), shopId)); } @GetMapping("/employees") 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..43fd0742 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,5 @@ 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-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..d7a04df9 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 @@ -23,6 +23,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.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.planning.service.PlanningService; @@ -71,7 +72,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 +80,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; @@ -780,34 +781,26 @@ public class PlanningServiceImpl implements PlanningService { 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())) { + 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 = firstNonBlank(dto.getCustomerName(), dto.getPhone()); + if (!hasText(customerName)) { + 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; + String phone = trimToNull(dto.getPhone()); + List matches = + userService.findCustomerMatches(customerName, phone, shopId); + if (matches.size() > 1) { + throw new RuntimeException("存在多个匹配客户,请先选择已有客户"); } - 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 (!matches.isEmpty()) { + return userMapper.selectById(matches.get(0).getId()); + } + Long customerId = userService.createManagerCustomer(customerName, phone, shopId); + return userMapper.selectById(customerId); } private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) { 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..62eab615 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 @@ -34,6 +34,11 @@ public interface UserService extends IService { */ Long createUser(UserDTO userDTO); + Long createManagerCustomer(String nickname, String phone, Long shopId); + + List findCustomerMatches(String nickname, String phone, 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. 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..f703d3ee 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 @@ -69,6 +69,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; @@ -356,6 +357,10 @@ public class UserServiceImpl extends ServiceImpl implements @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserDTO userDTO) { + return createUserInternal(userDTO, false); + } + + private Long createUserInternal(UserDTO userDTO, boolean allowMissingCustomerPhone) { String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); // 检查账号是否已存在 UserDO existingUser = userMapper.selectOne( @@ -374,8 +379,12 @@ 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 = validateUserPhone(userDTO.getPhone(), null, + !(allowMissingCustomerPhone && Integer.valueOf(0).equals(userType))); + if (Integer.valueOf(0).equals(userType)) { + ensureCustomerUnique(userDTO.getNickname(), validatedPhone); + } String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); @@ -461,6 +470,68 @@ public class UserServiceImpl extends ServiceImpl implements return userDO.getId(); } + @Override + @Transactional(rollbackFor = Exception.class) + public Long createManagerCustomer(String nickname, 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(); + ensureCustomerUnique(nickname, normalizedPhone); + normalizedPhone = validateUserPhone(normalizedPhone, null, false); + UserDTO customer = new UserDTO(); + customer.setNickname(nickname.trim()); + customer.setPhone(normalizedPhone); + customer.setContactPhone(normalizedPhone); + customer.setAccount(normalizedPhone == null + ? "customer" + UUID.randomUUID().toString().replace("-", "") + : normalizedPhone); + customer.setType(0); + customer.setShopId(shopId); + customer.setShopIds(List.of(shopId)); + customer.setLevel(VIP_LEVEL_NORMAL); + customer.setVipId(0L); + return createUserInternal(customer, true); + } + + @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); + if (StringUtils.hasText(phone)) { + String normalizedPhone = phone.trim(); + wrapper.and(query -> query.eq(UserDO::getPhone, normalizedPhone) + .or().eq(UserDO::getContactPhone, 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().map(user -> { + UserVO customer = new UserVO(); + customer.setId(user.getId()); + customer.setNickname(user.getNickname()); + customer.setAccount(user.getAccount()); + customer.setPhone(user.getPhone()); + customer.setContactPhone(user.getContactPhone()); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + return customer; + }).collect(Collectors.toList()); + } + /** * 分配默认权限 * @param userId 用户ID @@ -3047,6 +3118,23 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("手机号已被使用"); } } + + private void ensureCustomerUnique(String nickname, String phone) { + 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); + if (StringUtils.hasText(phone)) { + wrapper.and(query -> query.eq(UserDO::getPhone, phone) + .or().eq(UserDO::getContactPhone, phone)); + } + if (userMapper.selectCount(wrapper) > 0) { + throw new RuntimeException("客户已存在,请选择已有客户"); + } + } /** * 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-WeChat/api/customers.js b/JC-Salon-WeChat/api/customers.js index d6a2b36b..8d4c25cd 100644 --- a/JC-Salon-WeChat/api/customers.js +++ b/JC-Salon-WeChat/api/customers.js @@ -14,6 +14,13 @@ module.exports = { }) }, + matchIdentity(nickname, phone) { + return request({ + url: '/manager/customers/matches', + params: { nickname, phone } + }) + }, + create(data) { return request({ url: '/manager/customers', diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index 128b531b..0eba88f5 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -7,13 +7,17 @@ global.wx = { setStorageSync: () => {}, removeStorageSync: () => {}, showToast: () => {}, + showModal: options => options.success({ confirm: modalConfirm }), navigateTo: () => {} } global.getApp = () => ({ globalData: { userInfo: { type: 2, id: 1, shopId: 2 } } }) +let modalConfirm = true + let definition global.Page = value => { definition = value } require('./index') +const customersApi = require('../../api/customers') function createPage() { return { @@ -39,11 +43,30 @@ async function run() { assert.strictEqual(page.data.customerSheetVisible, false) page.data.form.customerUserId = 18 - page.data.manualCustomerForm = { name: '新客户', phone: '13900139000' } - page.useManualCustomer() + page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '13900139000') + assert.strictEqual(page.data.form.phone, '') + + customersApi.matchIdentity = async () => [] + customersApi.create = async payload => { + assert.strictEqual(payload.nickname, '新客户') + assert.strictEqual(payload.phone, undefined) + return '42' + } + assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) + assert.strictEqual(page.data.form.customerUserId, '42') + + page.data.form.customerUserId = '' + page.data.form.customerName = '小周' + page.data.form.phone = '13800138000' + customersApi.matchIdentity = async (name, phone) => { + assert.strictEqual(name, '小周') + assert.strictEqual(phone, '13800138000') + return [{ id: '18', nickname: '小周', phone: '13800138000' }] + } + assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) + assert.strictEqual(page.data.form.customerUserId, '18') page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }] page.onArtistSearch({ detail: { value: '李' } }) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 2a47ba0f..68b7923d 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -295,8 +295,6 @@ Page({ customerKeyword: '', customerLoading: false, customerError: '', - manualCustomerVisible: false, - manualCustomerForm: { name: '', phone: '' }, products: [], filteredProducts: [], artists: [], @@ -434,6 +432,20 @@ Page({ } }, + onCustomerInput(event) { + const field = event.currentTarget.dataset.field + const patch = { + [`form.${field}`]: event.detail.value, + 'form.customerUserId': '' + } + if (field === 'customerName' && this.data.form.customerUserId) { + patch['form.phone'] = '' + } + this.setData({ + ...patch + }) + }, + openCustomerSheet() { this.setData({ customerSheetVisible: true }) this.searchCustomers(this.data.customerKeyword) @@ -491,45 +503,6 @@ Page({ }) }, - openManualCustomer() { - this.setData({ - customerSheetVisible: false, - manualCustomerVisible: true, - manualCustomerForm: { - name: this.data.form.customerName || '', - phone: this.data.form.phone || '' - } - }) - }, - - closeManualCustomer() { - this.setData({ manualCustomerVisible: false }) - }, - - onManualCustomerInput(event) { - this.setData({ [`manualCustomerForm.${event.currentTarget.dataset.field}`]: event.detail.value }) - }, - - useManualCustomer() { - const name = String(this.data.manualCustomerForm.name || '').trim() - const phone = String(this.data.manualCustomerForm.phone || '').trim() - if (!name) { - wx.showToast({ title: '请输入客户姓名', icon: 'none' }) - return - } - if (!/^1[3-9]\d{9}$/.test(phone)) { - wx.showToast({ title: '请输入正确手机号', icon: 'none' }) - return - } - this.setData({ - 'form.customerUserId': '', - 'form.customerName': name, - 'form.phone': phone, - manualCustomerVisible: false, - customerKeyword: '' - }) - }, - onUnload() { if (this._customerTimer) { clearTimeout(this._customerTimer) @@ -949,7 +922,83 @@ Page({ } }, + async ensureCustomerBeforeSubmit() { + const name = String(this.data.form.customerName || '').trim() + const phone = String(this.data.form.phone || '').trim() + if (!name) { + wx.showToast({ title: '请输入客户姓名', icon: 'none' }) + return false + } + if (phone && !/^1[3-9]\d{9}$/.test(phone)) { + wx.showToast({ title: '请输入正确手机号', icon: 'none' }) + return false + } + if (this.data.form.customerUserId) { + return true + } + + this.setData({ loading: true }) + try { + const matches = await customersApi.matchIdentity(name, phone || undefined) + if (matches.length > 1) { + this.setData({ + customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem), + customerKeyword: name, + customerSheetVisible: true + }) + return false + } + if (matches.length > 0) { + const customer = normalizeCustomer(matches[0]) + const choice = await new Promise(resolve => { + wx.showModal({ + title: '客户已存在', + content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`, + cancelText: '取消', + confirmText: '使用已有', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!choice.confirm) { + return false + } + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone + }) + return true + } + + const createChoice = await new Promise(resolve => { + wx.showModal({ + title: '新建客户', + content: '系统中没有匹配客户,是否新建到客户档案?', + cancelText: '不新建', + confirmText: '确认', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!createChoice.confirm) { + return false + } + const customerId = await customersApi.create({ nickname: name, phone: phone || undefined }) + this.setData({ 'form.customerUserId': customerId }) + return true + } catch (error) { + wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) + return false + } finally { + this.setData({ loading: false }) + } + }, + async submit() { + if (this.data.loading) { + return + } if (!this.data.canCreateAppointment) { wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return @@ -957,11 +1006,11 @@ Page({ const form = this.data.form const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || !form.phone || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { + if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } - if (!/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { + if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return } @@ -987,6 +1036,9 @@ Page({ }) if (!result.confirm) return } + if (!(await this.ensureCustomerBeforeSubmit())) { + return + } this.setData({ loading: true }) try { const payload = { diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index b72a8f68..3ecd6fec 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,15 +1,13 @@ - - 客户 - - - {{form.customerName || '请选择客户'}} - {{form.phone || '搜索已有客户或手动录入'}} - - 已有 - › + + 客户姓名 + + + + + 已关联系统客户 预约日期 @@ -76,12 +74,10 @@ selected-id="{{form.customerUserId}}" loading="{{customerLoading}}" error-text="{{customerError}}" - empty-text="暂无匹配客户,可手动录入" - action-text="手动录入客户" + empty-text="暂无匹配客户" bind:search="onCustomerSearch" bind:select="selectCustomer" bind:retry="retryCustomerSearch" - bind:action="openManualCustomer" bind:close="closeCustomerSheet" /> @@ -103,29 +99,6 @@ bind:close="closeArtistSheet" /> - - - - - 手动录入客户 - 录入后将直接带回本次预约 - - × - - - - 客户姓名 - - - - 手机号 - - - - - - - diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxss b/JC-Salon-WeChat/pages/appointment-form/index.wxss index 8cb157d3..ed1ef6a0 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxss @@ -4,6 +4,7 @@ } .customer-field { + display: block; align-items: stretch; padding: 18rpx 0; } @@ -13,6 +14,58 @@ align-items: center; } +.customer-entry { + display: flex; + align-items: center; + gap: 14rpx; + width: 100%; +} + +.customer-name-input { + min-width: 0; + flex: 1; + height: 78rpx; + padding: 0 18rpx; + border: 1rpx solid #e7e0d7; + border-radius: 18rpx; + background: #f8f4ee; + color: #29241f; + font-size: 27rpx; +} + +.customer-select-btn { + flex: 0 0 auto; + min-width: 176rpx; + height: 78rpx; + margin: 0; + padding: 0 18rpx; + border: 1rpx solid #d7b38e; + border-radius: 18rpx; + background: #fff7ed; + color: #9f5f2d; + font-size: 23rpx; + line-height: 78rpx; +} + +.customer-phone-input { + width: 100%; + height: 66rpx; + margin-top: 14rpx; + padding: 0 18rpx; + border: 1rpx solid #e7e0d7; + border-radius: 16rpx; + background: #fff; + color: #29241f; + font-size: 25rpx; +} + +.customer-selected-tip { + display: block; + margin-top: 10rpx; + color: #55786d; + font-size: 21rpx; +} + .reference-card, .reference-value { display: flex; @@ -215,49 +268,6 @@ background: rgba(18, 15, 12, 0.48); } -.manual-customer-sheet { - display: flex; - width: 100%; - height: 88vh; - max-height: 88vh; - flex-direction: column; - padding: 28rpx 28rpx calc(28rpx + env(safe-area-inset-bottom)); - border-radius: 34rpx 34rpx 0 0; - background: #fffaf4; - box-shadow: 0 -18rpx 40rpx rgba(41, 31, 23, 0.16); -} - -.manual-customer-form { - flex: 1; - padding-top: 12rpx; -} - -.manual-customer-field { - margin-bottom: 20rpx; - padding: 20rpx 22rpx; - border: 1rpx solid #e7e0d7; - border-radius: 20rpx; - background: #fff; -} - -.manual-customer-field text { - display: block; - margin-bottom: 10rpx; - color: #625c55; - font-size: 24rpx; - font-weight: 800; -} - -.manual-customer-field input { - height: 64rpx; - color: #29241f; - font-size: 28rpx; -} - -.manual-customer-submit { - flex: 0 0 auto; -} - .time-modal { width: 100%; max-height: 82vh; diff --git a/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md index efc815c7..97aaa790 100644 --- a/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md +++ b/docs/superpowers/specs/2026-10-16-预约客户输入与选择交互-design.md @@ -31,7 +31,7 @@ ## 后端接口与模型 -- 扩展 `GET /manager/customers` 的姓名、手机号筛选能力,保证查询条件能够表达姓名加手机号的组合。 +- 新增 `GET /manager/customers/matches`,按姓名及可选手机号返回当前店铺的精确匹配客户;原 `GET /manager/customers` 列表接口保持不变。 - 调整 `POST /manager/customers`:手机号改为可选;无手机号时不生成手机号账号,使用系统生成的不可登录账号或现有客户创建约定;有手机号时保留现有账号兼容逻辑。 - 创建前在事务内按唯一性规则查询并拒绝重复,返回明确业务错误。 - 不修改预约提交协议,预约仍使用 `customerUserId`、`customerName` 和 `phone` 字段。 diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index a4a1c9d5..3ad56ad1 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -1,5 +1,12 @@ # 项目变更记录 +## 2026-10-16 Salon 预约客户输入与选择优化 + +- 新增预约客户字段改为“客户姓名输入框 + 选择已有客户”按钮,手机号改为可选输入,输入文本时自动解除旧客户绑定。 +- 提交前按“姓名 + 手机号”或“仅姓名”规则查询客户;已存在时引导使用已有客户,未存在时提供确认新建和不新建选择。 +- 后端新增客户匹配接口,客户创建支持无手机号并在事务内执行唯一性校验,预约接口同步支持无手机号客户解析。 +- 更新预约页选择测试和 Core 预约测试夹具;GitNexus 当前无可调用接口,使用静态引用、JavaScript 检查和 Maven 测试替代影响分析。 + ## 2026-10-16 Gitea 工作流 YAML 兼容性修复 - 问题:Gitea Actions 页面只显示工作流文件名并标记无效,推送后没有执行。 From c952a913e8788c3d398f87cf9b97d120d25fb8f4 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Tue, 20 Oct 2026 13:29:55 +0800 Subject: [PATCH 004/165] =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E8=A1=A8=E5=8D=95=E5=B9=B6=E6=94=AF=E6=8C=81=E6=95=A3=E5=AE=A2?= =?UTF-8?q?=E9=A2=84=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/PlanningAppointmentCreateDTO.java | 2 + .../service/impl/PlanningServiceImpl.java | 52 +- .../service/impl/PlanningServiceImplTest.java | 348 ++++++++++++ .../components/entity-selector-sheet/index.js | 11 + .../entity-selector-sheet/index.wxml | 13 +- .../entity-selector-sheet/index.wxss | 60 ++ .../product-selector-sheet/index.js | 1 + .../product-selector-sheet/index.wxml | 2 +- .../appointment-form/entity-selector.test.js | 11 +- .../pages/appointment-form/index.js | 529 +++++++++++++----- .../pages/appointment-form/index.wxml | 165 ++---- .../pages/appointment-form/index.wxss | 368 +++++++++++- .../appointment-form/modal-scroll.test.js | 4 +- .../appointment-form/product-selector.test.js | 15 +- .../pages/appointment-form/unassigned.test.js | 26 + .../2026-10-20-salon预约表单与客户身份设计.md | 35 ++ docs/项目变更记录.md | 9 + 17 files changed, 1376 insertions(+), 275 deletions(-) create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java create mode 100644 docs/superpowers/specs/2026-10-20-salon预约表单与客户身份设计.md 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..ba3d50f1 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 @@ -16,6 +16,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/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index d7a04df9..65bf2bd0 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 @@ -44,6 +44,7 @@ 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; @@ -183,11 +184,18 @@ public class PlanningServiceImpl implements PlanningService { ensureWithinBusinessHours(shopId, startTime, endTime); 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); @@ -208,7 +216,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); @@ -295,7 +303,8 @@ 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 @@ -516,7 +525,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()); @@ -531,7 +540,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)) @@ -731,12 +740,19 @@ public class PlanningServiceImpl implements PlanningService { private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { String title = trimToNull(dto.getManualProductTitle()); + String imageFileIds = trimToNull(dto.getManualProductImageFileIds()); if (!hasText(title)) { - throw new RuntimeException("请选择预约作品或填写手动作品名称"); + title = firstNonBlank(dto.getCustomerName(), hasText(imageFileIds) ? "散客款式" : null); } - BigDecimal price = dto.getManualProductPrice(); - if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { - throw new RuntimeException("手动作品价格不能小于0"); + if (!hasText(title) && !hasText(imageFileIds)) { + throw new RuntimeException("请填写美甲款式名称或上传款式图片"); + } + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null) { + throw new RuntimeException("成交金额不能为空"); + } + if (price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); } int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); ProductDO product = new ProductDO(); @@ -746,7 +762,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); @@ -786,11 +802,17 @@ public class PlanningServiceImpl implements PlanningService { } return customer; } - String customerName = firstNonBlank(dto.getCustomerName(), dto.getPhone()); - if (!hasText(customerName)) { - throw new RuntimeException("客户姓名不能为空"); - } + String customerName = trimToNull(dto.getCustomerName()); String phone = trimToNull(dto.getPhone()); + if (!hasText(customerName) && hasText(phone)) { + throw new RuntimeException("填写手机号时请同时填写客户姓名"); + } + if (Boolean.FALSE.equals(dto.getCreateCustomerRecord())) { + return null; + } + if (!hasText(customerName)) { + return null; + } List matches = userService.findCustomerMatches(customerName, phone, shopId); if (matches.size() > 1) { 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..599b10c4 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -0,0 +1,348 @@ +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.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.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; +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.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 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.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 AppointmentCapacityService appointmentCapacityService; + @Mock private OrderService orderService; + @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + private PlanningServiceImpl service; + + @BeforeEach + void setUp() { + service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, + artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, + productMapper, shopMapper, appointmentCapacityService, orderService, snowflakeIdGenerator); + } + + @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 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("2026-10-13"); + 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("2026-10-22"); + 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 createsWalkInAppointmentWithoutCustomerUsingWalkInStyleTitle() { + 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.setManualProductImageFileIds("file-43"); + dto.setAmount(java.math.BigDecimal.valueOf(88)); + dto.setAppointmentDate("2026-10-22"); + 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"); + 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()); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result = + service.getAppointment(operator, 64L); + + assertNull(result.getCustomerId()); + assertEquals("散客预约", result.getCustomerName()); + assertEquals("13800138000", result.getCustomerPhone()); + 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.findCustomerMatches("小周", "13800138000", 21L)).thenReturn(java.util.List.of()); + when(userService.createManagerCustomer("小周", "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("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + verify(userService).createManagerCustomer("小周", "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; + } +} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.js b/JC-Salon-WeChat/components/entity-selector-sheet/index.js index 45eecd27..943ae555 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.js @@ -10,6 +10,9 @@ Component({ errorText: { type: String, value: '' }, emptyText: { type: String, value: '暂无可选内容' }, actionText: { type: String, value: '' }, + showViewSwitch: { type: Boolean, value: false }, + viewMode: { type: String, value: 'list' }, + sortLabel: { type: String, value: '' }, showSearch: { type: Boolean, value: true } }, @@ -36,6 +39,14 @@ Component({ action() { this.triggerEvent('action') + }, + + changeView(event) { + this.triggerEvent('changeview', { mode: event.currentTarget.dataset.mode }) + }, + + sort() { + this.triggerEvent('sort') } } }) diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml index 051750ac..cdba0c65 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml @@ -10,6 +10,14 @@ + + + + + + + + @@ -20,12 +28,13 @@ {{emptyText}} - - + + {{item.title}} + {{item.rightText}} {{item.badge}} {{item.subtitle}} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss index d20b4840..9917c0fa 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss @@ -125,6 +125,35 @@ transform: rotate(45deg); } +.selector-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12rpx; + padding: 0 28rpx 16rpx; +} + +.selector-view-switch { + display: flex; + flex: 1; + gap: 8rpx; +} + +.selector-view-switch button, +.selector-sort { + height: 58rpx; + padding: 0 18rpx; + border-radius: 16rpx; + background: #f1f5f3; + color: #687a72; + font-size: 22rpx; + line-height: 58rpx; +} + +.selector-view-switch button { flex: 1; } +.selector-view-switch button.active { background: #dff1e9; color: #247b63; font-weight: 800; } +.selector-sort { flex: 0 0 auto; color: #476259; } + .selector-search { height: 78rpx; flex: 1; @@ -157,6 +186,28 @@ .selector-item:active { transform: scale(0.99); } .selector-item.selected { border-color: #8eafa3; background: #f0f6f3; } +.selector-list.card-view { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12rpx; +} + +.selector-item.card-view { + position: relative; + display: block; + min-height: 190rpx; + margin: 0; + padding: 18rpx; +} + +.selector-item.card-view .selector-avatar { width: 66rpx; height: 66rpx; margin-bottom: 12rpx; } +.selector-item.card-view .selector-copy { margin-left: 0; } +.selector-item.card-view .selector-title-row { align-items: flex-start; } +.selector-item.card-view .selector-item-title { white-space: normal; } +.selector-item.card-view .selector-subtitle, +.selector-item.card-view .selector-meta { display: block; margin-top: 8rpx; } +.selector-item.card-view .selector-check { position: absolute; right: 18rpx; bottom: 16rpx; } + .selector-avatar { width: 76rpx; height: 76rpx; @@ -180,6 +231,8 @@ } .selector-item-title { + min-width: 0; + flex: 1; overflow: hidden; color: #2b2621; font-size: 28rpx; @@ -188,6 +241,13 @@ white-space: nowrap; } +.selector-right-text { + flex: 0 0 auto; + color: #756e66; + font-size: 23rpx; + font-weight: 600; +} + .selector-badge { flex: 0 0 auto; padding: 5rpx 12rpx; diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.js b/JC-Salon-WeChat/components/product-selector-sheet/index.js index 9983ecd1..c9e9d6e3 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.js @@ -13,6 +13,7 @@ Component({ manualForm: { type: Object, value: {} }, manualMoreExpanded: { type: Boolean, value: false }, showManualExtra: { type: Boolean, value: true }, + showManualAction: { type: Boolean, value: true }, manualImageUrl: { type: String, value: '' }, manualImageUploading: { type: Boolean, value: false } }, diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml index d877e401..5c2a40a1 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml @@ -17,7 +17,7 @@ - + diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index 0eba88f5..f503979e 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -46,16 +46,13 @@ async function run() { page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '') + assert.strictEqual(page.data.form.phone, '13800138000') customersApi.matchIdentity = async () => [] - customersApi.create = async payload => { - assert.strictEqual(payload.nickname, '新客户') - assert.strictEqual(payload.phone, undefined) - return '42' - } + customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) - assert.strictEqual(page.data.form.customerUserId, '42') + assert.strictEqual(page.data.form.customerUserId, '') + assert.strictEqual(page.data.form.createCustomerRecord, true) page.data.form.customerUserId = '' page.data.form.customerName = '小周' diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 68b7923d..a53209fc 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -192,6 +192,113 @@ function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } +function buildTimeValues(durationMinutes) { + const values = [] + const open = dateUtil.minutesOfDay('10:00') + const close = dateUtil.minutesOfDay('22:00') + for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) { + values.push(dateUtil.timeFromMinutes(minute)) + } + return values +} + +function buildTimePickerSlots(calendar, form, durationMinutes) { + const schedules = calendar.schedules || [] + const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] + return buildTimeValues(durationMinutes).map(value => { + const startMinute = dateUtil.minutesOfDay(value) + const endMinute = startMinute + durationMinutes + const occupied = hasBusyConflict(startMinute, endMinute, busyRanges) + const scheduled = !form.artistId || schedules.some(schedule => + isScheduleCoveringTime(schedule, form, startMinute, endMinute) + ) + const status = occupied ? 'occupied' : scheduled ? 'available' : 'off-shift' + return { + value, + hour: Number(value.slice(0, 2)), + minute: Number(value.slice(3, 5)), + rangeText: buildTimeRangeLabel(startMinute, durationMinutes), + status, + statusText: status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : '' + } + }) +} + +function buildTimePickerGroups(slots) { + const groupMap = { + morning: { key: 'morning', title: '上午', times: [] }, + afternoon: { key: 'afternoon', title: '下午', times: [] }, + evening: { key: 'evening', title: '晚上', times: [] } + } + ;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot)) + return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) +} + +function buildTimeWheelState(slots, preferredTime) { + if (!slots || slots.length === 0) { + return { + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift' + } + } + const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00') + const firstAvailableSlot = slots.find(slot => slot.status === 'available') + const selectedSlot = preferredSlot && preferredSlot.status === 'available' + ? preferredSlot + : firstAvailableSlot || preferredSlot || slots[0] + const hours = Array.from(new Set(slots.map(slot => slot.hour))) + const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour)) + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute)) + return { + timePickerHours: hours.map(hour => ({ + value: hour, + label: String(hour).padStart(2, '0'), + disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available') + })), + timePickerMinutes: minutes, + timePickerValue: [selectedHourIndex, selectedMinuteIndex], + selectedTimeCandidate: selectedSlot.value, + timePickerCandidateStatus: selectedSlot.status + } +} + +function timeWheelStateForHour(slots, hour, selectedMinute) { + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute)) + return { timePickerMinutes: minutes, selectedMinuteIndex } +} + +function customerCreatedAt(customer) { + return customer.createTime || customer.createdAt || customer.addedAt || '' +} + +function formatCustomerCreatedAt(value) { + if (!value) return '添加时间未知' + return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}` +} + function parseProductTags(product) { if (Array.isArray(product.tagList) && product.tagList.length > 0) { return product.tagList @@ -245,7 +352,8 @@ function normalizeCustomer(customer) { name, phone, displayName: name || phone || '客户', - displayPhone: phone || '未填写手机号' + displayPhone: phone || '未填写手机号', + createdAt: customerCreatedAt(customer) } } @@ -253,8 +361,8 @@ function buildCustomerSelectorItem(customer) { return { ...customer, title: customer.displayName, - subtitle: customer.displayPhone, - badge: '已有客户' + subtitle: formatCustomerCreatedAt(customer.createdAt), + rightText: customer.displayPhone } } @@ -276,6 +384,7 @@ Page({ phone: '', appointmentDate: dateUtil.formatDate(new Date()), appointmentTime: '', + amount: '', productId: '', manualProductTitle: '', manualProductPrice: '', @@ -285,14 +394,18 @@ Page({ manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', - durationMinutes: '', + durationMinutes: '60', artistId: '', + createCustomerRecord: false, remark: '' }, - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, customerOptions: [], + customerDirectory: [], customerSheetVisible: false, customerKeyword: '', + customerViewMode: 'list', + customerNewestFirst: true, + customerSuggestions: [], customerLoading: false, customerError: '', products: [], @@ -306,8 +419,6 @@ Page({ selectedProductPriceText: '', selectedArtist: {}, productModalVisible: false, - productSelectorMode: 'list', - manualProductMoreExpanded: false, productKeyword: '', productError: '', loadingProducts: false, @@ -317,6 +428,14 @@ Page({ draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, + timePickerMode: 'wheel', + timePickerValue: [0, 0], + timePickerHours: [], + timePickerMinutes: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerCandidateStatus: 'off-shift', + selectedTimeCandidate: '', timeLoading: false, timeError: '', timeSelectTip: '请先选择美甲师并填写时长', @@ -330,16 +449,6 @@ Page({ const baseForm = draftForm || {} this.setData({ canCreateAppointment: creatable, - manualProductDraft: { - title: baseForm.manualProductTitle || '', - price: baseForm.manualProductPrice || '', - description: baseForm.manualProductDescription || '', - tags: baseForm.manualProductTags || '', - targetAudience: baseForm.manualProductTargetAudience || '', - precautions: baseForm.manualProductPrecautions || '', - imageFileIds: baseForm.manualProductImageFileIds || '', - imageUrl: baseForm.manualProductImageUrl || '' - }, form: { ...this.data.form, ...baseForm, @@ -375,10 +484,14 @@ Page({ await this.loadArtists() this.refreshProductCards() const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {} - this.setData({ + const selectedProductPatch = { selectedProduct, selectedProductPriceText: selectedProduct.priceText || '' - }) + } + if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) { + selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price) + } + this.setData(selectedProductPatch) await this.refreshAvailableTimes() this.checkAvailability() }, @@ -420,6 +533,47 @@ Page({ } }, + async loadCustomerDirectory() { + this.setData({ customerLoading: true }) + try { + const size = 100 + const rows = [] + let page = 1 + let total = Number.POSITIVE_INFINITY + while (rows.length < total) { + const result = await customersApi.list({ page, size }) + const currentRows = Array.isArray(result) ? result : (result.list || []) + rows.push(...currentRows) + if (!Array.isArray(result) && Number.isFinite(Number(result.total))) { + total = Number(result.total) + } else if (currentRows.length < size) { + total = rows.length + } + if (currentRows.length === 0) break + page += 1 + } + const directory = rows.map(normalizeCustomer) + this.setData({ + customerDirectory: directory, + customerOptions: this.sortCustomerOptions(directory), + customerError: '' + }) + this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone) + } catch (error) { + this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' }) + } finally { + this.setData({ customerLoading: false }) + } + }, + + sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) { + return (customers || []).slice().sort((left, right) => { + const leftDate = String(left.createdAt || '') + const rightDate = String(right.createdAt || '') + return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate) + }).map(buildCustomerSelectorItem) + }, + onInput(event) { const field = event.currentTarget.dataset.field const patch = { @@ -432,18 +586,81 @@ Page({ } }, + onStyleTitleInput(event) { + const patch = { 'form.manualProductTitle': event.detail.value } + if (this.data.form.productId) { + patch['form.productId'] = '' + patch.selectedProduct = {} + patch.selectedProductPriceText = '' + patch['form.manualProductImageFileIds'] = '' + patch['form.manualProductImageUrl'] = '' + } + this.setData(patch) + }, + onCustomerInput(event) { const field = event.currentTarget.dataset.field const patch = { [`form.${field}`]: event.detail.value, - 'form.customerUserId': '' - } - if (field === 'customerName' && this.data.form.customerUserId) { - patch['form.phone'] = '' + 'form.customerUserId': '', + 'form.createCustomerRecord': false } this.setData({ ...patch }) + const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName + const phone = field === 'phone' ? event.detail.value : this.data.form.phone + this.refreshCustomerSuggestions(customerName, phone) + }, + + refreshCustomerSuggestions(nameValue, phoneValue) { + const name = String(nameValue || '').trim().toLowerCase() + const phone = String(phoneValue || '').trim().toLowerCase() + if (!name && !phone) { + this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1 + clearTimeout(this._suggestionTimer) + this.setData({ customerSuggestions: [] }) + return + } + const suggestions = this.data.customerDirectory + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: suggestions }) + const requestSeq = (this._customerSuggestionSeq || 0) + 1 + this._customerSuggestionSeq = requestSeq + clearTimeout(this._suggestionTimer) + this._suggestionTimer = setTimeout(async () => { + try { + const result = await customersApi.list({ page: 1, size: 50, keyword: name || phone }) + if (requestSeq !== this._customerSuggestionSeq) return + const rows = Array.isArray(result) ? result : (result.list || []) + const remoteSuggestions = rows.map(normalizeCustomer) + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: remoteSuggestions }) + } catch (error) { + if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) { + this.setData({ customerSuggestions: [] }) + } + } + }, 240) + }, + + selectCustomerSuggestion(event) { + const index = Number(event.currentTarget.dataset.index) + const customer = this.data.customerSuggestions[index] + if (!customer) return + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false, + customerSuggestions: [], + customerSheetVisible: false, + customerKeyword: '' + }) }, openCustomerSheet() { @@ -467,22 +684,24 @@ Page({ return } const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() - this.setData({ customerLoading: true }) - try { - const data = await customersApi.list({ keyword, page: 1, size: 20 }) - const list = data.list || data || [] - this.setData({ - customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem), - customerError: '' - }) - } catch (error) { - this.setData({ - customerOptions: [], - customerError: error.message || '客户列表加载失败' - }) - } finally { - this.setData({ customerLoading: false }) - } + if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase()) + ) + this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' }) + }, + + changeCustomerView(event) { + this.setData({ customerViewMode: event.detail.mode || 'list' }) + }, + + toggleCustomerSort() { + const customerNewestFirst = !this.data.customerNewestFirst + const keyword = String(this.data.customerKeyword || '').trim().toLowerCase() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword) + ) + this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) }) }, retryCustomerSearch() { @@ -498,8 +717,10 @@ Page({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, 'form.phone': customer.phone, + 'form.createCustomerRecord': false, customerSheetVisible: false, - customerKeyword: '' + customerKeyword: '', + customerSuggestions: [] }) }, @@ -507,6 +728,9 @@ Page({ if (this._customerTimer) { clearTimeout(this._customerTimer) } + if (this._suggestionTimer) { + clearTimeout(this._suggestionTimer) + } }, async onDateChange(event) { @@ -555,29 +779,20 @@ Page({ openProductModal() { this.refreshProductCards() - this.setData({ productModalVisible: true, productSelectorMode: 'list' }) + this.setData({ productModalVisible: true }) }, closeProductModal() { - this.setData({ productModalVisible: false, productSelectorMode: 'list' }) + this.setData({ productModalVisible: false }) }, openManualProduct() { - this.setData({ productSelectorMode: 'manual', manualProductMoreExpanded: false }) - }, - - backToProductList() { - this.setData({ productSelectorMode: 'list' }) - this.refreshProductCards() - }, - - onManualProductInput(event) { - const field = event.detail.field - this.setData({ [`manualProductDraft.${field}`]: event.detail.value }) - }, - - toggleManualProductMore() { - this.setData({ manualProductMoreExpanded: !this.data.manualProductMoreExpanded }) + this.setData({ + productModalVisible: false, + selectedProduct: {}, + selectedProductPriceText: '', + 'form.productId': '' + }) }, stopTap() { @@ -597,16 +812,8 @@ Page({ this.setData({ selectedProduct, selectedProductPriceText: selectedProduct.priceText || '', - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, 'form.productId': selectedProduct.id, - 'form.manualProductTitle': '', - 'form.manualProductPrice': '', - 'form.manualProductDescription': '', - 'form.manualProductTags': '', - 'form.manualProductTargetAudience': '', - 'form.manualProductPrecautions': '', - 'form.manualProductImageFileIds': '', - 'form.manualProductImageUrl': '', + 'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price), 'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '') }) this.closeProductModal() @@ -614,33 +821,6 @@ Page({ this.checkAvailability() }, - useManualProduct() { - const draft = this.data.manualProductDraft - const title = String(draft.title || '').trim() - const priceText = String(draft.price === undefined ? '' : draft.price).trim() - const price = Number(priceText) - if (!title || !priceText || !Number.isFinite(price) || price < 0) { - wx.showToast({ title: '请填写手动预约作品名称和价格', icon: 'none' }) - return - } - this.setData({ - selectedProduct: {}, - selectedProductPriceText: `¥${price}`, - 'form.productId': '', - 'form.manualProductTitle': title, - 'form.manualProductPrice': String(price), - 'form.manualProductDescription': String(draft.description || '').trim(), - 'form.manualProductTags': String(draft.tags || '').trim(), - 'form.manualProductTargetAudience': String(draft.targetAudience || '').trim(), - 'form.manualProductPrecautions': String(draft.precautions || '').trim(), - 'form.manualProductImageFileIds': String(draft.imageFileIds || ''), - 'form.manualProductImageUrl': String(draft.imageUrl || '') - }) - this.closeProductModal() - this.refreshAvailableTimes() - this.checkAvailability() - }, - async chooseManualProductImage() { if (this.data.manualImageUploading) { return @@ -658,8 +838,11 @@ Page({ throw new Error('作品图片上传成功但未返回文件ID') } this.setData({ - 'manualProductDraft.imageFileIds': String(fileId), - 'manualProductDraft.imageUrl': fileUrl + 'form.productId': '', + selectedProduct: {}, + selectedProductPriceText: '', + 'form.manualProductImageFileIds': String(fileId), + 'form.manualProductImageUrl': fileUrl }) } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) @@ -670,8 +853,8 @@ Page({ removeManualProductImage() { this.setData({ - 'manualProductDraft.imageFileIds': '', - 'manualProductDraft.imageUrl': '' + 'form.manualProductImageFileIds': '', + 'form.manualProductImageUrl': '' }) }, @@ -781,6 +964,13 @@ Page({ if (!form.appointmentDate || !durationMinutes) { const patch = { availableTimeGroups: [], + timePickerGroups: [], + timePickerSlots: [], + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift', timeError: '', timeSelectTip: '请先填写预约日期和时长' } @@ -792,8 +982,12 @@ Page({ } if (!form.artistId) { const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes) + const timePickerSlots = buildTimePickerSlots({ schedules: [], appointments: [] }, form, durationMinutes) this.setData({ availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), timeError: '', timeLoading: false, timeSelectTip: '请选择预约时间,员工可稍后分配' @@ -816,8 +1010,12 @@ Page({ } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) const patch = { availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { @@ -845,7 +1043,7 @@ Page({ wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' }) return } - this.setData({ timeSheetVisible: true }) + this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' }) await this.refreshAvailableTimes() }, @@ -855,16 +1053,61 @@ Page({ selectAvailableTime(event) { const value = event.currentTarget.dataset.value - this.setData({ - 'form.appointmentTime': value, - timeSheetVisible: false - }) - this.checkAvailability() + const slot = this.data.timePickerSlots.find(item => item.value === value) + if (!slot || slot.status !== 'available') { + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status }) }, - async checkAvailability() { + onTimePickerModeChange(event) { + this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' }) + }, + + onTimePickerChange(event) { + const values = event.detail.value || [0, 0] + const hourItem = this.data.timePickerHours[values[0]] + if (!hourItem) return + const hour = Number(hourItem.value) + const minuteIndex = Number(values[1] || 0) + const minuteItem = this.data.timePickerMinutes[minuteIndex] + const minute = minuteItem ? Number(minuteItem.value) : 0 + const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute) + this.setData({ + timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex], + timePickerMinutes: nextMinutes.timePickerMinutes, + selectedTimeCandidate: candidate, + timePickerCandidateStatus: slot ? slot.status : 'off-shift' + }) + }, + + confirmTimeSelection() { + const candidate = this.data.selectedTimeCandidate + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + if (!slot || slot.status !== 'available') { + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.checkAvailability(candidate).then(availability => { + if (!availability.ok) { + wx.showToast({ + title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约', + icon: 'none' + }) + return + } + this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false }) + this.checkAvailability() + }) + }, + + async checkAvailability(candidateTime) { const form = this.data.form - if (!form.appointmentDate || !form.appointmentTime) { + const appointmentTime = candidateTime || form.appointmentTime + if (!form.appointmentDate || !appointmentTime) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } @@ -873,7 +1116,7 @@ Page({ this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } - const startMinute = dateUtil.minutesOfDay(form.appointmentTime) + const startMinute = dateUtil.minutesOfDay(appointmentTime) const endMinute = startMinute + durationMinutes if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) { const tip = '该时间超出营业时间 10:00-22:00' @@ -912,7 +1155,7 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { @@ -925,8 +1168,12 @@ Page({ async ensureCustomerBeforeSubmit() { const name = String(this.data.form.customerName || '').trim() const phone = String(this.data.form.phone || '').trim() + if (!name && !phone) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } if (!name) { - wx.showToast({ title: '请输入客户姓名', icon: 'none' }) + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) return false } if (phone && !/^1[3-9]\d{9}$/.test(phone)) { @@ -934,6 +1181,7 @@ Page({ return false } if (this.data.form.customerUserId) { + this.setData({ 'form.createCustomerRecord': false }) return true } @@ -941,6 +1189,20 @@ Page({ try { const matches = await customersApi.matchIdentity(name, phone || undefined) if (matches.length > 1) { + const choice = await new Promise(resolve => { + wx.showModal({ + title: '找到多个同名客户', + content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。', + cancelText: '不关联提交', + confirmText: '选择客户', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!choice.confirm) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } this.setData({ customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem), customerKeyword: name, @@ -954,20 +1216,22 @@ Page({ wx.showModal({ title: '客户已存在', content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`, - cancelText: '取消', + cancelText: '不关联提交', confirmText: '使用已有', success: resolve, fail: () => resolve({ confirm: false }) }) }) - if (!choice.confirm) { - return false + if (choice.confirm) { + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false + }) + } else { + this.setData({ 'form.createCustomerRecord': false }) } - this.setData({ - 'form.customerUserId': customer.id, - 'form.customerName': customer.name, - 'form.phone': customer.phone - }) return true } @@ -981,11 +1245,7 @@ Page({ fail: () => resolve({ confirm: false }) }) }) - if (!createChoice.confirm) { - return false - } - const customerId = await customersApi.create({ nickname: name, phone: phone || undefined }) - this.setData({ 'form.customerUserId': customerId }) + this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) }) return true } catch (error) { wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) @@ -1003,13 +1263,25 @@ Page({ wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } - const form = this.data.form - const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() + let form = this.data.form + const manualProductTitle = String(form.manualProductTitle || '').trim() + const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() + const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim()) + const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim() + const amount = Number(amountText) const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { + if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } + if (!Number.isFinite(amount) || amount < 0) { + wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' }) + return + } + if (form.phone && !String(form.customerName || '').trim()) { + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) + return + } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return @@ -1039,12 +1311,17 @@ Page({ if (!(await this.ensureCustomerBeforeSubmit())) { return } + form = this.data.form this.setData({ loading: true }) try { const payload = { ...form, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: form.artistId ? String(form.artistId) : undefined, + customerName: String(form.customerName || '').trim() || undefined, + phone: String(form.phone || '').trim() || undefined, + amount, + createCustomerRecord: Boolean(form.createCustomerRecord), durationMinutes, clientRequestId: buildClientRequestId('manager-appointment') } @@ -1054,8 +1331,8 @@ Page({ payload.manualProductPrice = undefined } else { payload.productId = undefined - payload.manualProductTitle = String(form.manualProductTitle || '').trim() - payload.manualProductPrice = Number(form.manualProductPrice) + payload.manualProductTitle = manualProductTitle || undefined + payload.manualProductPrice = amount payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index 3ecd6fec..4420cff7 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,136 +1,67 @@ - - - - 客户姓名 - - - - - - 已关联系统客户 + + + + 美甲款式手动输入为主,也可快速选择已有款式 + - - 预约日期 - - {{form.appointmentDate}} - + + + {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · {{selectedProduct.durationText || '时长待定'}} + - - 预约作品 - + + + - - 预计时长 - - 分钟 + + + - - 员工(可稍后分配) - - {{selectedArtist.name || '暂不分配'}} - › - - - - 预约时间 - - - {{form.appointmentTime || timeSelectTip}} - {{form.appointmentDate}} · {{selectedArtist.name || '待分配'}} · {{form.durationMinutes}}分钟 - - › - - - - 备注 - 图 + 图 diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 5fcff649..b778560e 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -2065,6 +2065,10 @@ Page({ this.persistDraft(true) }, + onSelectedProductImageError() { + this.setData({ 'selectedProduct.coverImage': '' }) + }, + back() { wx.navigateBack() } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index f11e7683..afedb8a1 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -27,7 +27,7 @@ › - + ✦ {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · 本次 {{form.amount || '待填'}} 元 · {{form.durationMinutes || '60'}} 分钟 diff --git a/JC-Salon-WeChat/pages/backfill-order/index.js b/JC-Salon-WeChat/pages/backfill-order/index.js index 5fb06490..665c051d 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.js +++ b/JC-Salon-WeChat/pages/backfill-order/index.js @@ -121,6 +121,7 @@ Page({ async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ manualImageUploading: false }) } }, removeManualProductImage(event) { const index = Number(event.currentTarget.dataset.index); this.setData(imagePatch((this.data.form.manualProductImages || []).filter((item, itemIndex) => itemIndex !== index))) }, onManualProductImageError(event) { const index = Number(event.currentTarget.dataset.index); const images = this.data.form.manualProductImages || []; if (!images[index] || !images[index].fileUrl) return; const fallback = images.slice(); fallback[index] = { ...fallback[index], previewUrl: fallback[index].fileUrl }; this.setData(imagePatch(fallback)) }, + onSelectedProductImageError() { this.setData({ 'selectedProduct.coverImage': '' }) }, onInput(event) { const field = event.currentTarget.dataset.field; const value = event.detail.value; this.setData({ [`form.${field}`]: value, ...(field === 'amount' ? { 'manualProductDraft.price': value } : {}) }) }, onDateChange(event) { this.setData({ 'form.serviceDate': event.detail.value }) }, onTimeChange(event) { this.setData({ 'form.serviceTime': event.detail.value }) }, diff --git a/JC-Salon-WeChat/pages/backfill-order/index.wxml b/JC-Salon-WeChat/pages/backfill-order/index.wxml index 05080ead..4cf35371 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.wxml +++ b/JC-Salon-WeChat/pages/backfill-order/index.wxml @@ -25,7 +25,7 @@ › - + ✦ {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · 本次 {{form.amount || '待填'}} 元 · {{form.durationMinutes || '60'}} 分钟 diff --git a/JC-Salon-WeChat/pages/employee-create/index.js b/JC-Salon-WeChat/pages/employee-create/index.js index dba2f3a7..0a95d798 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.js +++ b/JC-Salon-WeChat/pages/employee-create/index.js @@ -56,10 +56,11 @@ Page({ if (!filePath) return this.setData({ avatarUploading: true }) const uploadResult = await uploadObjectFile(filePath) - const avatarUrl = uploadResult.fileUrl || uploadResult.primaryUrl || filePath + // 私有对象存储地址可能无法被小程序直接访问,上传完成后先用本地临时文件即时预览。 + const storedAvatar = uploadResult.fileUrl || uploadResult.primaryUrl || '' this.setData({ - 'form.avatar': avatarUrl, - 'form.avatarUrl': avatarUrl + 'form.avatar': storedAvatar, + 'form.avatarUrl': filePath }) } catch (error) { wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) @@ -72,6 +73,10 @@ Page({ this.setData({ 'form.avatar': '', 'form.avatarUrl': '' }) }, + onAvatarError() { + this.setData({ 'form.avatarUrl': '' }) + }, + stopTouchMove() { }, diff --git a/JC-Salon-WeChat/pages/employee-create/index.wxml b/JC-Salon-WeChat/pages/employee-create/index.wxml index ba8f37fb..5d1c7de6 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.wxml +++ b/JC-Salon-WeChat/pages/employee-create/index.wxml @@ -5,7 +5,7 @@ - + 美甲师头像 diff --git a/JC-Salon-WeChat/pages/employee-detail/index.js b/JC-Salon-WeChat/pages/employee-detail/index.js index 62831a66..aafcebdd 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.js +++ b/JC-Salon-WeChat/pages/employee-detail/index.js @@ -44,6 +44,10 @@ Page({ wx.navigateTo({ url: `${event.currentTarget.dataset.url}?id=${this.data.id}` }) }, + onAvatarError() { + this.setData({ 'employee.avatar': '' }) + }, + back() { wx.navigateBack() } diff --git a/JC-Salon-WeChat/pages/employee-detail/index.wxml b/JC-Salon-WeChat/pages/employee-detail/index.wxml index be9a8833..b4e82f9f 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.wxml +++ b/JC-Salon-WeChat/pages/employee-detail/index.wxml @@ -5,7 +5,8 @@ - {{employee.shortName}} + + {{employee.shortName}} {{employee.name}} 美甲师色 diff --git a/JC-Salon-WeChat/pages/employee-detail/index.wxss b/JC-Salon-WeChat/pages/employee-detail/index.wxss index 2212bace..6ed875b3 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.wxss +++ b/JC-Salon-WeChat/pages/employee-detail/index.wxss @@ -26,6 +26,12 @@ color: #fff; font-size: 34rpx; font-weight: 900; + overflow: hidden; +} + +.image-avatar image { + width: 100%; + height: 100%; } .employee-name { diff --git a/JC-Salon-WeChat/pages/employees/index.js b/JC-Salon-WeChat/pages/employees/index.js index ac3ec785..2136f665 100644 --- a/JC-Salon-WeChat/pages/employees/index.js +++ b/JC-Salon-WeChat/pages/employees/index.js @@ -291,6 +291,18 @@ Page({ } }, + onEmployeeAvatarError(event) { + const index = Number(event.currentTarget.dataset.index) + if (!Number.isInteger(index) || !this.data.employees[index]) return + this.setData({ [`employees[${index}].avatar`]: '' }) + }, + + onReviewAvatarError(event) { + const index = Number(event.currentTarget.dataset.index) + if (!Number.isInteger(index) || !this.data.reviewApplications[index]) return + this.setData({ [`reviewApplications[${index}].applicantAvatar`]: '' }) + }, + openDetail(event) { wx.navigateTo({ url: `/pages/employee-detail/index?id=${event.currentTarget.dataset.id}` }) }, diff --git a/JC-Salon-WeChat/pages/employees/index.wxml b/JC-Salon-WeChat/pages/employees/index.wxml index a62372c8..30caa0f9 100644 --- a/JC-Salon-WeChat/pages/employees/index.wxml +++ b/JC-Salon-WeChat/pages/employees/index.wxml @@ -20,7 +20,7 @@ 暂无待审核美甲师申请 - + {{item.applicantDisplayName}} 已预关联美甲师 @@ -45,7 +45,7 @@ - + {{item.shortName}} diff --git a/JC-Salon-WeChat/pages/planning/index.js b/JC-Salon-WeChat/pages/planning/index.js index 2161f3ad..8a23f9c4 100644 --- a/JC-Salon-WeChat/pages/planning/index.js +++ b/JC-Salon-WeChat/pages/planning/index.js @@ -331,6 +331,10 @@ Page({ this.loadCalendar() }, + onProfileAvatarError() { + this.setData({ 'profileForm.avatar': '' }) + }, + selectWeekDate(event) { const appointmentDate = dateUtil.formatDate(event.currentTarget.dataset.date) const target = toLocalDate(appointmentDate) diff --git a/JC-Salon-WeChat/pages/planning/index.wxml b/JC-Salon-WeChat/pages/planning/index.wxml index 3c9c03fb..0dde0bb6 100644 --- a/JC-Salon-WeChat/pages/planning/index.wxml +++ b/JC-Salon-WeChat/pages/planning/index.wxml @@ -44,7 +44,7 @@ 完善你的工作名片头像和昵称会用于门店协作展示,可暂时跳过。 diff --git a/JC-Salon-WeChat/pages/profile-edit/index.js b/JC-Salon-WeChat/pages/profile-edit/index.js index 976999dd..5e6f0138 100644 --- a/JC-Salon-WeChat/pages/profile-edit/index.js +++ b/JC-Salon-WeChat/pages/profile-edit/index.js @@ -139,6 +139,10 @@ Page({ } }, + onAvatarImageError() { + this.setData({ 'form.avatar': '' }) + }, + async chooseWechatAvatar(event) { if (this.data.loading || this.data.avatarUploading || this.data.saving) return try { diff --git a/JC-Salon-WeChat/pages/profile-edit/index.wxml b/JC-Salon-WeChat/pages/profile-edit/index.wxml index 9313a9aa..487202de 100644 --- a/JC-Salon-WeChat/pages/profile-edit/index.wxml +++ b/JC-Salon-WeChat/pages/profile-edit/index.wxml @@ -3,7 +3,7 @@ - + {{avatarText}} {{avatarUploading ? '上传中' : '点击更换'}} diff --git a/JC-Salon-WeChat/pages/profile/index.js b/JC-Salon-WeChat/pages/profile/index.js index 89de49de..25f793b7 100644 --- a/JC-Salon-WeChat/pages/profile/index.js +++ b/JC-Salon-WeChat/pages/profile/index.js @@ -90,6 +90,10 @@ Page({ wx.navigateTo({ url: event.currentTarget.dataset.url }) }, + onProfileAvatarError() { + this.setData({ 'profileCard.avatar': '' }) + }, + async loadProfile() { try { const profile = await profileCache.getProfile() diff --git a/JC-Salon-WeChat/pages/profile/index.wxml b/JC-Salon-WeChat/pages/profile/index.wxml index 589376b8..e1ef8abf 100644 --- a/JC-Salon-WeChat/pages/profile/index.wxml +++ b/JC-Salon-WeChat/pages/profile/index.wxml @@ -2,7 +2,7 @@ diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index d6a5e8b6..8582cd82 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -1,5 +1,14 @@ # 项目变更记录 +## 2026-11-01 Salon 对象存储头像与文件展示修复 + +- 修复 DEV/SIT 使用 MinIO 时,数据库中的内网或公共 MinIO 地址无法解析对象名,导致头像、作品和其他文件不能生成可访问签名地址的问题;统一支持 MinIO 内网端点、MinIO 公共端点、七牛域名和 OSS 引用。 +- 已识别的私有对象存储地址在签名失败时不再原样返回,避免小程序拿到不可访问或不应公开的内网地址;外部默认头像仍保持兼容。 +- 日程员工列表、注册审核候选美甲师统一使用可访问头像地址;审核采用申请头像时保存规范化存储地址,避免把临时/内网 URL 写入员工资料。 +- 小程序新增美甲师上传后优先使用本地临时文件预览;员工列表、员工详情、审核关联选择器、作品选择器、预约/补录款式图片和个人资料头像增加加载失败回退。 +- 新增 `JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java`,覆盖 MinIO 内外网 URL、七牛、OSS 解析及签名失败不泄露私有地址;该测试目录受仓库 `test/` 忽略规则影响,提交时需显式纳入。 +- Core 对象存储、日程、注册关联相关测试 29 项通过;小程序相关测试及 JavaScript 语法检查通过。 + ## 2026-10-30 Salon 安全接入配置服务启动循环修复 - 安全接入配置服务不再依赖 `AdminScopeHelper` / `UserServiceImpl`,改为在服务边界校验调用方必须为平台管理员 `type = 4`,保留配置读取和写入的管理员门禁。 From 203dac2370a1980739c555ae4f29dbfbe9ddf255 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Sun, 1 Nov 2026 14:43:04 +0800 Subject: [PATCH 066/165] =?UTF-8?q?=E6=8F=90=E4=BA=A4Salon=E6=97=A7?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=B8=85=E7=90=86=E4=B8=8E=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=9F=BA=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../salon/core/config/JwtProperties.java | 11 +- .../admin/AdminCampaignController.java | 52 - .../admin/AdminCouponController.java | 182 - .../controller/front/CouponController.java | 190 - .../controller/front/GrowthController.java | 25 - .../front/ProductLikeController.java | 65 - .../front/VipBenefitController.java | 99 - .../controller/front/VipInfoController.java | 99 - .../front/VipRechargePlanController.java | 113 - .../controller/front/WishlistController.java | 100 - .../controller/front/CartController.java | 116 - .../admin/AdminPaymentController.java | 62 - .../front/BalanceChangeDetailController.java | 99 - .../controller/front/BalanceController.java | 99 - .../controller/admin/AdminUserController.java | 104 - .../user/controller/front/UserController.java | 31 - .../src/main/resources/bootstrap.yaml | 8 +- JC-Salon-Frontend/src/App.vue | 43 +- JC-Salon-Frontend/src/api/cart.ts | 79 - JC-Salon-Frontend/src/api/coupon.ts | 221 -- JC-Salon-Frontend/src/api/index.ts | 3 - JC-Salon-Frontend/src/api/productLike.ts | 51 - JC-Salon-Frontend/src/api/wishlist.ts | 123 - .../src/components/BottomNav.vue | 45 +- JC-Salon-Frontend/src/utils/cart-state.ts | 41 - JC-Salon-Frontend/src/utils/recovery.test.ts | 5 +- JC-Salon-Frontend/src/utils/recovery.ts | 3 +- .../src/utils/system-message-action.ts | 14 - JC-Salon-Frontend/src/views/CartView.vue | 3267 ----------------- JC-Salon-Frontend/src/views/CouponView.vue | 446 --- JC-Salon-Frontend/src/views/HomeView.vue | 1601 -------- JC-Salon-Frontend/src/views/OrderView.vue | 2631 ------------- .../src/views/ProductDetailView.vue | 1935 ---------- .../src/views/ProductListView.vue | 1053 ------ JC-Salon-Frontend/src/views/ProfileView.vue | 1436 -------- .../src/views/ShopDetailView.vue | 1916 ---------- JC-Salon-Frontend/src/views/VipCenterView.vue | 755 ---- JC-Salon-Frontend/src/views/WishlistView.vue | 520 --- .../src/views/admin/CampaignsView.vue | 312 -- .../src/views/admin/CouponsView.vue | 987 ----- .../src/views/admin/UsersView.vue | 180 - .../src/views/admin/VipRechargePlansView.vue | 189 - .../salon/gateway/config/CorsConfig.java | 14 +- .../salon/gateway/config/CorsProperties.java | 15 + .../salon/gateway/config/JwtProperties.java | 11 +- .../src/main/resources/bootstrap.yaml | 8 +- .../DEFAULT_GROUP/gateway.yaml | 36 +- .../DEFAULT_GROUP/gateway.yaml | 33 +- .../DEFAULT_GROUP/gateway.yaml | 33 +- 49 files changed, 73 insertions(+), 19388 deletions(-) delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java delete mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java delete mode 100644 JC-Salon-Frontend/src/api/cart.ts delete mode 100644 JC-Salon-Frontend/src/api/coupon.ts delete mode 100644 JC-Salon-Frontend/src/api/productLike.ts delete mode 100644 JC-Salon-Frontend/src/api/wishlist.ts delete mode 100644 JC-Salon-Frontend/src/utils/cart-state.ts delete mode 100644 JC-Salon-Frontend/src/views/CartView.vue delete mode 100644 JC-Salon-Frontend/src/views/CouponView.vue delete mode 100644 JC-Salon-Frontend/src/views/HomeView.vue delete mode 100644 JC-Salon-Frontend/src/views/OrderView.vue delete mode 100644 JC-Salon-Frontend/src/views/ProductDetailView.vue delete mode 100644 JC-Salon-Frontend/src/views/ProductListView.vue delete mode 100644 JC-Salon-Frontend/src/views/ProfileView.vue delete mode 100644 JC-Salon-Frontend/src/views/ShopDetailView.vue delete mode 100644 JC-Salon-Frontend/src/views/VipCenterView.vue delete mode 100644 JC-Salon-Frontend/src/views/WishlistView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/CampaignsView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/CouponsView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/VipRechargePlansView.vue create mode 100644 JC-Salon-Gateway/src/main/java/com/xiaowang/jayucloud/salon/gateway/config/CorsProperties.java 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/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/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/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/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 b7d6eb3d..975cb151 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,14 +10,11 @@ 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.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; @@ -77,10 +74,6 @@ 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. */ @@ -229,30 +222,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查询用户 * diff --git a/JC-Salon-Core/src/main/resources/bootstrap.yaml b/JC-Salon-Core/src/main/resources/bootstrap.yaml index e9039e7d..4666dccc 100644 --- a/JC-Salon-Core/src/main/resources/bootstrap.yaml +++ b/JC-Salon-Core/src/main/resources/bootstrap.yaml @@ -18,8 +18,8 @@ spring: # 是否将当前服务注册到 Nacos。 register-enabled: true # Nacos 认证信息可由运行环境覆盖。 - username: ${NACOS_USERNAME:jayucloud} - password: ${NACOS_PASSWORD:122503wcy....} + username: ${NACOS_USERNAME:} + password: ${NACOS_PASSWORD:} config: # Nacos 配置中心与服务发现使用同一运行环境参数。 server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} @@ -34,8 +34,8 @@ spring: # 是否启用配置中心。 enabled: true # Nacos 认证信息可由运行环境覆盖。 - username: ${NACOS_USERNAME:jayucloud} - password: ${NACOS_PASSWORD:122503wcy....} + username: ${NACOS_USERNAME:} + password: ${NACOS_PASSWORD:} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml diff --git a/JC-Salon-Frontend/src/App.vue b/JC-Salon-Frontend/src/App.vue index f444f52c..6f75b9db 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,15 @@ 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/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..f4f0731a 100644 --- a/JC-Salon-Frontend/src/api/index.ts +++ b/JC-Salon-Frontend/src/api/index.ts @@ -5,7 +5,6 @@ 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' @@ -393,6 +392,4 @@ export const fileApi = { } } -export { wishlistApi } - export default api 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/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 @@ 作品集 - - - - +
@@ -420,7 +420,7 @@ @@ -1034,16 +1028,22 @@ watch(activeSection, () => { .settings-tab.is-active::after { content: ''; position: absolute; left: 0; right: 0; bottom: -11px; height: 2px; border-radius: 2px; background: var(--theme-primary); } .settings-health { display: inline-flex; align-items: center; gap: 7px; color: var(--admin-mobile-muted); font-size: 12px; white-space: nowrap; } .settings-health i { width: 7px; height: 7px; border-radius: 50%; background: var(--theme-primary); } -.settings-body { display: grid; grid-template-columns: 194px minmax(0, 1fr); gap: 18px; align-items: start; } -.settings-subnav { position: sticky; top: 16px; display: flex; flex-direction: column; gap: 2px; padding: 8px; border: 1px solid var(--admin-mobile-border); border-radius: 12px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); } -.settings-subnav__label { padding: 6px 8px 8px; color: var(--admin-mobile-muted); font-size: 10px; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; } -.settings-subnav__item { display: flex; width: 100%; align-items: center; justify-content: space-between; gap: 8px; min-height: 34px; padding: 7px 9px; border: 0; border-radius: 7px; background: none; color: var(--admin-mobile-muted); font: inherit; font-size: 12px; text-align: left; cursor: pointer; } -.settings-subnav__item:hover { background: color-mix(in srgb, var(--theme-primary) 6%, transparent); color: var(--theme-primary-action); } -.settings-subnav__item.is-active { background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 700; } +.settings-body { display: block; } +.settings-subnav { display: flex; max-width: 100%; align-items: center; gap: 6px; margin-bottom: 12px; padding: 7px; overflow-x: auto; border: 1px solid var(--admin-mobile-border); border-radius: 10px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); scrollbar-width: none; } +.settings-subnav::-webkit-scrollbar { display: none; } +.settings-subnav__label { display: none; } +.settings-subnav__item { display: flex; flex: none; width: auto; align-items: center; justify-content: space-between; gap: 6px; min-height: 30px; padding: 5px 11px; border: 1px solid transparent; border-radius: 999px; background: color-mix(in srgb, var(--theme-primary) 4%, transparent); color: var(--admin-mobile-muted); font: inherit; font-size: 12px; text-align: left; white-space: nowrap; cursor: pointer; } +.settings-subnav__item:hover { border-color: color-mix(in srgb, var(--theme-primary) 35%, var(--admin-mobile-border)); background: color-mix(in srgb, var(--theme-primary) 7%, transparent); color: var(--theme-primary-action); } +.settings-subnav__item.is-active { border-color: color-mix(in srgb, var(--theme-primary) 35%, var(--admin-mobile-border)); background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 700; } .settings-subnav__item em { flex: none; min-width: 18px; height: 18px; padding: 0 5px; border: 1px solid var(--admin-mobile-border); border-radius: 9px; background: var(--theme-card-bg); color: var(--admin-mobile-muted); font-size: 10px; font-style: normal; line-height: 16px; text-align: center; } .settings-content { min-width: 0; } .settings-groups { display: flex; flex-direction: column; gap: 14px; } .settings-group { min-width: 0; scroll-margin-top: 16px; border: 1px solid var(--admin-mobile-border); border-radius: 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); box-shadow: 0 1px 2px rgba(23, 33, 31, .03); } +.settings-group.is-located { animation: settings-locate 1.5s ease-out; } +@keyframes settings-locate { + 0% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--theme-primary) 42%, transparent); border-color: color-mix(in srgb, var(--theme-primary) 55%, var(--admin-mobile-border)); } + 100% { box-shadow: 0 1px 2px rgba(23, 33, 31, .03); } +} .settings-group__head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; padding: 15px 18px 12px; border-bottom: 1px solid var(--admin-mobile-border); } .settings-group__head-main { min-width: 0; } .settings-group__title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } @@ -1152,13 +1152,6 @@ watch(activeSection, () => { .field-grid.cols-3 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .field--wide { grid-column: auto; } } -@media (max-width: 1180px) { - .settings-body { grid-template-columns: 1fr; gap: 12px; } - .settings-subnav { position: static; flex-direction: row; align-items: center; gap: 4px; padding: 7px; overflow-x: auto; scrollbar-width: none; } - .settings-subnav::-webkit-scrollbar { display: none; } - .settings-subnav__label { display: none; } - .settings-subnav__item { width: auto; flex: none; min-height: 30px; padding: 5px 10px; white-space: nowrap; } -} @media (max-width: 960px) { .field-grid.cols-2, .field-grid.cols-3 { grid-template-columns: 1fr; } .field__desc { min-height: 0; } From e6ecca7d4739c9f8200baa03e13be4c9f880fdc4 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 20:08:45 +0800 Subject: [PATCH 103/165] =?UTF-8?q?=E5=BA=97=E9=95=BF=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E6=89=8B=E6=9C=BA=E5=8F=B7=E6=94=B9=E4=B8=BA=E4=BB=85=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E6=97=B6=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 编辑弹窗保留脱敏手机号展示,聚焦时清空并提示留空不修改;未修改或仍为脱敏值时不再提交 phone/contactPhone,避免脱敏串写库。 --- .../src/views/admin/UsersView.vue | 46 +++++++++++++++---- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/JC-Salon-Frontend/src/views/admin/UsersView.vue b/JC-Salon-Frontend/src/views/admin/UsersView.vue index 7a949b6c..2ceba4c2 100644 --- a/JC-Salon-Frontend/src/views/admin/UsersView.vue +++ b/JC-Salon-Frontend/src/views/admin/UsersView.vue @@ -214,10 +214,11 @@ @@ -625,6 +626,22 @@ const formState = reactive({ /** wechatQrUploading tracks QR upload state in the user modal. */ const wechatQrUploading = ref(false) +/** originalPhone keeps the phone value loaded from the backend so edits can be detected. */ +const originalPhone = ref('') + +/** phonePlaceholder explains that an existing masked phone is kept unless a new number is typed. */ +const phonePlaceholder = computed(() => + isEdit.value && originalPhone.value ? '已设置手机号,留空表示不修改' : '请输入手机号' +) + +/** phoneChanged is true only when the user typed a real, different phone number during editing. */ +const phoneChanged = computed(() => { + if (!isEdit.value) return true + const current = formState.phone.trim() + if (!current || isMaskedSensitiveValue(current)) return false + return current !== originalPhone.value.trim() +}) + /** handleAccountInput is a local helper used by this page script. */ const handleAccountInput = () => { const normalized = sanitizeAccountInput(formState.account) @@ -642,6 +659,14 @@ const handlePhoneInput = () => { formState.contactPhone = formState.phone } +/** handlePhoneFocus clears the masked placeholder value so stars can never be submitted as a phone number. */ +const handlePhoneFocus = () => { + if (isMaskedSensitiveValue(formState.phone)) { + formState.phone = '' + formState.contactPhone = '' + } +} + /** beforeUploadWechatQr validates QR image files before upload. */ const beforeUploadWechatQr = (file: File) => { const isImage = file.type.startsWith('image/') @@ -754,7 +779,7 @@ const formRules = { phone: [ { validator: async (_rule: unknown, value: string) => { - if (isEdit.value && !value?.trim()) return Promise.resolve() + if (isEdit.value && (!value?.trim() || isMaskedSensitiveValue(value))) return Promise.resolve() await validatePhoneUniqueness(value) return Promise.resolve() }, @@ -1001,6 +1026,7 @@ const resetFilters = () => { /** resetFormState is a local helper used by this page script. */ const resetFormState = () => { + originalPhone.value = '' Object.assign(formState, { account: '', nickname: '', @@ -1093,11 +1119,13 @@ const showAddModal = () => { const showEditModal = (record: any) => { isEdit.value = true currentUser.value = record + const loadedPhone = String(record.phone || record.contactPhone || '').trim() + originalPhone.value = loadedPhone Object.assign(formState, { account: isMaskedSensitiveValue(record.account) ? '' : record.account, nickname: record.nickname, - phone: isMaskedSensitiveValue(record.phone || record.contactPhone) ? '' : (record.phone || record.contactPhone || ''), - contactPhone: isMaskedSensitiveValue(record.phone || record.contactPhone) ? '' : (record.phone || record.contactPhone || ''), + phone: loadedPhone, + contactPhone: loadedPhone, birthday: record.birthday || '', wechatId: record.wechatId || '', wechatQrCode: record.wechatQrCode || '', @@ -1107,10 +1135,6 @@ const showEditModal = (record: any) => { }) restoreDraft() if (isMaskedSensitiveValue(formState.account)) formState.account = '' - if (isMaskedSensitiveValue(formState.phone)) { - formState.phone = '' - formState.contactPhone = '' - } modalVisible.value = true } @@ -1147,8 +1171,10 @@ const handleModalOk = async () => { ...(formState.password.trim() ? { password: formState.password.trim() } : {}) } - if (isEdit.value && !formState.account.trim()) delete requestData.account - if (isEdit.value && !primaryPhone) { + if (isEdit.value && (!formState.account.trim() || isMaskedSensitiveValue(formState.account))) { + delete requestData.account + } + if (isEdit.value && (!phoneChanged.value || !primaryPhone || isMaskedSensitiveValue(primaryPhone))) { delete requestData.phone delete requestData.contactPhone } From 80d187d23c055b980bad16ea9abee323fafe326b Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 20:18:12 +0800 Subject: [PATCH 104/165] =?UTF-8?q?=E4=BF=AE=E8=AE=A2=E9=9A=90=E7=A7=81?= =?UTF-8?q?=E6=94=BF=E7=AD=96=E4=B8=8E=E7=94=A8=E6=88=B7=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E4=BB=A5=E5=AF=B9=E9=BD=90=E5=8A=A0=E5=AF=86=E5=AD=98=E5=82=A8?= =?UTF-8?q?=E4=B8=8E=E5=9C=BA=E6=99=AF=E5=8C=96=E8=84=B1=E6=95=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 Salon V17 协议版本 2026.11.04 - 新增 ArtList V4 协议版本 2026.11.04(V3 已被账号加密并行改造占用) - 同步更新 Salon 静态隐私政策与用户协议页面 - 补充加密密钥管理、HMAC 索引、按场景脱敏、第三方清单、留存期限与用户权利条款 --- ...策与用户协议加密脱敏条款修订_20261104.sql | 110 ++++++++++++++++++ ...策与用户协议加密脱敏条款修订_20261104.sql | 109 +++++++++++++++++ .../public/legal/privacy-policy.html | 52 ++++++--- .../public/legal/user-terms.html | 26 +++-- 4 files changed, 271 insertions(+), 26 deletions(-) create mode 100644 JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql create mode 100644 JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql 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-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-Frontend/public/legal/privacy-policy.html b/JC-Salon-Frontend/public/legal/privacy-policy.html index 73b53a31..6b87551c 100644 --- a/JC-Salon-Frontend/public/legal/privacy-policy.html +++ b/JC-Salon-Frontend/public/legal/privacy-policy.html @@ -11,29 +11,49 @@

甲屿手纪 Salon 隐私政策

-

版本:2026.10.21 更新日期:2026年10月21日

-

本政策适用于 Salon 门店工作台的店长与员工账号。实际上线前,运营方应核实主体、短信服务商、消息通道、对象存储及微信后台隐私指引,并据实更新本政策。

+

版本:2026.11.04 更新日期:2026年11月4日

+

本政策适用于 Salon 门店工作台的店长与员工账号。实际上线前,运营方应核实主体、短信服务商、消息通道、对象存储、地图服务及微信后台隐私指引,并据实更新本政策;文中标注【待法务/业务确认】的事项尚未形成最终结论。

一、处理的信息及用途

    -
  • 登录:在用户主动同意后,通过微信登录获取 OpenID,用于识别和关联账号。
  • +
  • 登录与账号:在用户主动同意后,通过微信登录获取 OpenID,用于识别和关联账号;手机号用于注册登录、验证码校验、账号找回、订单联系和售后处理,不用于营销。
  • +
  • 账号标识:账号用于身份识别、权限校验和操作归属记录。当账号本身为手机号时,该账号按手机号同等强度加密存储;其他账号标识仅用于身份识别,并通过不可逆索引支持查询匹配。
  • 可选资料:用户主动选择时处理昵称和头像;未提供时使用系统默认展示。
  • -
  • 手机号:用户主动选择绑定或更换时处理,用于账号找回和必要业务联系,不用于营销;不绑定不影响基础工作台使用。
  • 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品和订单信息,以履行门店服务管理。客户业务资料不构成客户的小程序登录账号。
  • -
  • 安全运行:服务端会处理请求所需的网络地址、登录会话和操作审计信息,不读取设备标识、IMEI、MAC、麦克风或用户定位。
  • +
  • 安全运行:服务端会处理请求所需的网络地址、登录会话和操作审计信息,不读取 IMEI、MAC、麦克风或持续定位;仅在用户主动地图选点时调用微信地图能力获取所选地点。
  • +
  • 内容审核:头像、作品、评论、店铺展示资料、公告和人工发布的消息在对外展示前进行内容安全审核。

二、用户主动触发的权限

仅在用户主动选择头像、作品图片等操作后调用选图能力;仅在用户主动绑定手机号时调用微信手机号能力或发送短信验证码。短信只用于验证绑定、变更或解绑,不用于营销。手机号绑定和解绑前会显示用途说明。

-

三、存储与保护

-

账号、客户和订单快照中的手机号采用 AES-GCM 加密保存,另以独立 HMAC 索引支持查重。普通页面、日志和导出对手机号脱敏;完整号码仅在业务需要且权限允许时展示。账号密钥由各环境配置管理,运营方需限制配置访问并保留审计。

-

四、第三方服务

-

服务依赖微信小程序登录与用户主动触发的微信能力;验证码由部署环境启用的短信服务商发送;通知由配置的消息通道处理;头像、作品等文件存储于部署环境配置的对象存储服务。运营方上线前应在微信后台列明实际服务商,并确认其处理范围和协议。

-

五、内容审核

-

头像、作品文字和图片、评论文字和图片、店铺展示资料、公告及人工发布的系统消息在面向用户或门店成员展示前进行内容安全审核。开发环境使用本地模拟服务;配置启用微信审核服务的环境会将必要的文字、微信 OpenID 和图片的短时授权地址提交给微信内容安全接口,图片审核结果通过加密回调更新。审核未通过、待复核、超时或服务故障时内容保持隔离,不会公开。

-

客户姓名和联系电话、预约及补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外内容审核。审核记录、任务状态和人工复核操作会按安全审计要求保存。

-

六、保留、注销和解绑

-

用户可在小程序“我的-账号设置”申请注销或解绑手机号。解绑通过当前号码验证码核验后立即清除手机号密文和索引。注销申请经管理员完成门店移交或归档后撤销会话,并在目标15个工作日内删除或匿名化 OpenID、昵称、头像、手机号等个人资料。必要订单、预约和经营记录在去除账号身份关联后按产品目标保留五年;该期限及范围由运营方上线前核实。

-

七、政策更新与联系

-

处理目的、数据类别或服务商发生重要变化时,我们会更新本政策并在需要时重新征求同意。用户可以在账号设置查看注销申请状态、撤回待处理申请并提交隐私相关请求;也可联系所属门店管理员。

+

三、加密存储与检索索引

+

手机号以及手机号形式的账号使用 AES-GCM 加密后落库,密文带版本标识,不以明文存入数据库。加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供;密钥访问受配置权限和审计约束。

+

为实现登录、去重和查询匹配,系统另以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引。该索引不能反推出手机号或账号原文,且不用于对外展示。数据导出、备份和迁移沿用同等加密要求;如发生密钥轮换,按版本标识兼容解密并逐步重加密。

+

四、按场景脱敏展示

+

常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。

+

脱敏规则由服务端统一执行,不依赖前端隐藏;客户端不得缓存、截屏传播或在无权限场景转述完整号码。客户本人资料页、员工账号资料页默认展示脱敏号码;修改绑定手机号时通过短信验证码核验,不以页面明文号码作为身份凭证。

+

五、第三方共享

+

我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的:

+
    +
  • 微信:微信登录、手机号授权、地图选点和内容安全审核(图片与文本)。
  • +
  • 短信服务商:通过部署环境配置的短信通道发送验证码、绑定/解绑通知和必要的业务通知。
  • +
  • 消息通道:通过 MessageHub 等已配置通道发送站内或订阅消息。
  • +
  • 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。
  • +
  • 地图服务:仅在用户主动地图选点时,由微信内置地图能力(腾讯位置服务)处理所选位置。
  • +
+

我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。

+

六、保存期限与删除

+

解绑手机号:通过当前号码验证码核验后,立即清除手机号密文及 phone_hash 索引。账号注销:可在小程序“我的-账号设置”提交申请,处理前可撤回;管理员完成门店移交或归档后撤销会话,并在目标 15 个工作日内删除或匿名化 OpenID、昵称、头像和手机号等个人资料。

+

订单、预约和经营记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。安全审计日志按安全审计要求保存,具体期限【待法务/业务确认】。法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。

+

七、你的权利

+

你可以在个人资料页查询和更正昵称、头像等资料,在账号设置中更换手机号、申请注销或解绑,并可撤回待处理的授权;撤回后不影响撤回前已进行的处理。你也可以请求删除非业务必需的资料。

+

隐私相关请求可联系所属门店管理员,或通过运营方公布的客服渠道提交;具体客服渠道【待业务/法务确认】。我们将在收到请求后按适用法律规定的期限响应;对于无法核验身份的请求,可能要求补充验证。

+

八、未成年人保护

+

本服务主要面向门店经营人员。不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;我们不会在明知未取得监护人同意的情况下处理其个人信息。如发现误收集,将停止处理并删除。

+

九、安全措施与安全事件响应

+

我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向用户和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。

+

十、跨境传输

+

目前我们不涉及向境外提供个人信息。如未来因业务需要发生跨境传输,我们将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。

+

十一、政策更新与联系

+

处理目的、数据类别或服务商发生重要变化时,我们会更新本政策并在需要时重新征求同意。用户可以在账号设置查看当前版本、注销申请状态、撤回待处理申请并提交隐私相关请求;也可联系所属门店管理员。

本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。

diff --git a/JC-Salon-Frontend/public/legal/user-terms.html b/JC-Salon-Frontend/public/legal/user-terms.html index e265071b..c3b8ebe2 100644 --- a/JC-Salon-Frontend/public/legal/user-terms.html +++ b/JC-Salon-Frontend/public/legal/user-terms.html @@ -11,21 +11,27 @@

甲屿手纪 Salon 用户协议

-

版本:2026.10.21 更新日期:2026年10月21日

+

版本:2026.11.04 更新日期:2026年11月4日

本服务面向经门店授权的店长和员工,提供门店日程、预约、客户业务资料和经营记录管理。预约金额是业务记录,不表示本平台已收款;当前不提供充值、订阅或平台虚拟权益购买。

-

一、接受协议

-

使用前请阅读本协议及《隐私政策》。登录时须主动选择同意;未同意时不会交换微信登录凭证,也不能继续使用。协议更新后需重新确认。

+

一、协议接受与版本

+

使用前请阅读本协议及《隐私政策》。登录时须主动选择同意;未同意时不会交换微信登录凭证,也不能继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议更新后需重新确认。

二、账号与使用权限

-

微信 OpenID 用于关联工作台账号。账号仅供本人使用,不得转借。昵称和头像可选;手机号可选绑定,不绑定不影响基础功能。离职或不再获授权时,门店管理员可以调整账号权限。

+

微信 OpenID 用于关联工作台账号。账号仅供本人使用,不得转借、出租或共享。昵称和头像可选;手机号可选绑定,不绑定不影响基础功能。离职或不再获授权时,门店管理员可以调整或停用账号权限。

+

手机号及手机号形式的账号按《隐私政策》所述采用加密存储和不可逆索引;常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。使用者不得擅自收集、导出或向无关第三方提供完整号码。

三、业务资料与内容

-

使用者仅可录入履行门店业务所需且有权处理的客户、预约、作品和员工资料,并应确保上传文字和图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。用户可随时更正自己提交的非业务资料。

+

使用者仅可录入履行门店业务所需且有权处理的客户、预约、作品、员工和经营资料,并应确保上传文字和图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。用户可随时更正自己提交的非业务资料。

头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核。开发环境使用本地模拟服务进行验证;正式环境启用微信内容安全服务后,文字和图片会按审核平台要求处理,未通过、待复核或服务异常的内容不会公开。

+

客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外内容审核,但仍受门店权限和保密要求约束。

四、业务记录与金额

-

订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值或订阅交易。不得将工作台用于未经授权的资金收取或虚拟权益交易。

-

五、账号注销

-

用户可在小程序“我的-账号设置”提交注销申请并在处理前撤回。管理员完成必要的门店移交或归档后撤销会话并清理或匿名化个人账号资料。目标处理期限为15个工作日,具体取决于门店交接;必要的订单、预约和经营记录将去除身份关联后按产品目标保留五年。

-

六、服务调整与联系

-

平台会在合理范围内维护服务,并在功能或数据处理方式发生重要变化时更新说明。隐私相关申请可从账号设置发起;其他问题请联系所属门店管理员。

+

订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值或订阅交易。不得将工作台用于未经授权的资金收取、代收或虚拟权益交易。

+

五、账号注销与数据处理

+

用户可在小程序“我的-账号设置”提交注销申请并在处理前撤回。管理员完成必要的门店移交或归档后撤销会话并清理或匿名化个人账号资料。目标处理期限为15个工作日,具体取决于门店交接。

+

解绑手机号经当前号码验证码核验后立即生效,系统清除手机号密文和检索索引。必要的订单、预约和经营记录将去除身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。

+

六、未成年人

+

不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务。门店不得要求未成年人独立提交与其年龄不相适应的个人信息。

+

七、服务调整、责任与联系

+

平台会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。因使用者违反本协议、法律法规或侵害他人权益造成的损失,由使用者依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,平台将在合理范围内协助恢复。

+

隐私相关申请可从账号设置发起或联系所属门店管理员;其他问题请联系门店管理员或运营方公布的客服渠道【待业务确认】。

本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。

From bbe1473b70453d8ad06a9e655c0b73368b78e495 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 21:34:15 +0800 Subject: [PATCH 105/165] =?UTF-8?q?Salon=20=E4=B8=A4=E4=B8=AA=E9=9D=99?= =?UTF-8?q?=E6=80=81=E5=8D=8F=E8=AE=AE=E9=A1=B5=E6=94=B9=E4=B8=BA=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E6=97=B6=E8=AF=BB=E5=8F=96=E5=90=8E=E5=8F=B0=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E5=8F=91=E5=B8=83=E5=8D=8F=E8=AE=AE=EF=BC=8C=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E5=86=85=E7=BD=AE=E6=AD=A3=E6=96=87=E5=BF=AB=E7=85=A7?= =?UTF-8?q?=E5=85=9C=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../public/legal/privacy-policy.html | 292 +++++++++++++++--- .../public/legal/user-terms.html | 248 +++++++++++++-- 2 files changed, 470 insertions(+), 70 deletions(-) diff --git a/JC-Salon-Frontend/public/legal/privacy-policy.html b/JC-Salon-Frontend/public/legal/privacy-policy.html index 6b87551c..6786b6c2 100644 --- a/JC-Salon-Frontend/public/legal/privacy-policy.html +++ b/JC-Salon-Frontend/public/legal/privacy-policy.html @@ -4,56 +4,256 @@ + 甲屿手纪 Salon 隐私政策 -

甲屿手纪 Salon 隐私政策

-

版本:2026.11.04 更新日期:2026年11月4日

-

本政策适用于 Salon 门店工作台的店长与员工账号。实际上线前,运营方应核实主体、短信服务商、消息通道、对象存储、地图服务及微信后台隐私指引,并据实更新本政策;文中标注【待法务/业务确认】的事项尚未形成最终结论。

-

一、处理的信息及用途

-
    -
  • 登录与账号:在用户主动同意后,通过微信登录获取 OpenID,用于识别和关联账号;手机号用于注册登录、验证码校验、账号找回、订单联系和售后处理,不用于营销。
  • -
  • 账号标识:账号用于身份识别、权限校验和操作归属记录。当账号本身为手机号时,该账号按手机号同等强度加密存储;其他账号标识仅用于身份识别,并通过不可逆索引支持查询匹配。
  • -
  • 可选资料:用户主动选择时处理昵称和头像;未提供时使用系统默认展示。
  • -
  • 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品和订单信息,以履行门店服务管理。客户业务资料不构成客户的小程序登录账号。
  • -
  • 安全运行:服务端会处理请求所需的网络地址、登录会话和操作审计信息,不读取 IMEI、MAC、麦克风或持续定位;仅在用户主动地图选点时调用微信地图能力获取所选地点。
  • -
  • 内容审核:头像、作品、评论、店铺展示资料、公告和人工发布的消息在对外展示前进行内容安全审核。
  • -
-

二、用户主动触发的权限

-

仅在用户主动选择头像、作品图片等操作后调用选图能力;仅在用户主动绑定手机号时调用微信手机号能力或发送短信验证码。短信只用于验证绑定、变更或解绑,不用于营销。手机号绑定和解绑前会显示用途说明。

-

三、加密存储与检索索引

-

手机号以及手机号形式的账号使用 AES-GCM 加密后落库,密文带版本标识,不以明文存入数据库。加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供;密钥访问受配置权限和审计约束。

-

为实现登录、去重和查询匹配,系统另以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引。该索引不能反推出手机号或账号原文,且不用于对外展示。数据导出、备份和迁移沿用同等加密要求;如发生密钥轮换,按版本标识兼容解密并逐步重加密。

-

四、按场景脱敏展示

-

常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。

-

脱敏规则由服务端统一执行,不依赖前端隐藏;客户端不得缓存、截屏传播或在无权限场景转述完整号码。客户本人资料页、员工账号资料页默认展示脱敏号码;修改绑定手机号时通过短信验证码核验,不以页面明文号码作为身份凭证。

-

五、第三方共享

-

我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的:

-
    -
  • 微信:微信登录、手机号授权、地图选点和内容安全审核(图片与文本)。
  • -
  • 短信服务商:通过部署环境配置的短信通道发送验证码、绑定/解绑通知和必要的业务通知。
  • -
  • 消息通道:通过 MessageHub 等已配置通道发送站内或订阅消息。
  • -
  • 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。
  • -
  • 地图服务:仅在用户主动地图选点时,由微信内置地图能力(腾讯位置服务)处理所选位置。
  • -
-

我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。

-

六、保存期限与删除

-

解绑手机号:通过当前号码验证码核验后,立即清除手机号密文及 phone_hash 索引。账号注销:可在小程序“我的-账号设置”提交申请,处理前可撤回;管理员完成门店移交或归档后撤销会话,并在目标 15 个工作日内删除或匿名化 OpenID、昵称、头像和手机号等个人资料。

-

订单、预约和经营记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。安全审计日志按安全审计要求保存,具体期限【待法务/业务确认】。法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。

-

七、你的权利

-

你可以在个人资料页查询和更正昵称、头像等资料,在账号设置中更换手机号、申请注销或解绑,并可撤回待处理的授权;撤回后不影响撤回前已进行的处理。你也可以请求删除非业务必需的资料。

-

隐私相关请求可联系所属门店管理员,或通过运营方公布的客服渠道提交;具体客服渠道【待业务/法务确认】。我们将在收到请求后按适用法律规定的期限响应;对于无法核验身份的请求,可能要求补充验证。

-

八、未成年人保护

-

本服务主要面向门店经营人员。不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;我们不会在明知未取得监护人同意的情况下处理其个人信息。如发现误收集,将停止处理并删除。

-

九、安全措施与安全事件响应

-

我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向用户和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。

-

十、跨境传输

-

目前我们不涉及向境外提供个人信息。如未来因业务需要发生跨境传输,我们将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。

-

十一、政策更新与联系

-

处理目的、数据类别或服务商发生重要变化时,我们会更新本政策并在需要时重新征求同意。用户可以在账号设置查看当前版本、注销申请状态、撤回待处理申请并提交隐私相关请求;也可联系所属门店管理员。

-

本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。

+
+

甲屿手纪 Salon 隐私政策

+ + + + +
+ + diff --git a/JC-Salon-Frontend/public/legal/user-terms.html b/JC-Salon-Frontend/public/legal/user-terms.html index c3b8ebe2..366c7318 100644 --- a/JC-Salon-Frontend/public/legal/user-terms.html +++ b/JC-Salon-Frontend/public/legal/user-terms.html @@ -4,34 +4,234 @@ + 甲屿手纪 Salon 用户协议 -

甲屿手纪 Salon 用户协议

-

版本:2026.11.04 更新日期:2026年11月4日

-

本服务面向经门店授权的店长和员工,提供门店日程、预约、客户业务资料和经营记录管理。预约金额是业务记录,不表示本平台已收款;当前不提供充值、订阅或平台虚拟权益购买。

-

一、协议接受与版本

-

使用前请阅读本协议及《隐私政策》。登录时须主动选择同意;未同意时不会交换微信登录凭证,也不能继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议更新后需重新确认。

-

二、账号与使用权限

-

微信 OpenID 用于关联工作台账号。账号仅供本人使用,不得转借、出租或共享。昵称和头像可选;手机号可选绑定,不绑定不影响基础功能。离职或不再获授权时,门店管理员可以调整或停用账号权限。

-

手机号及手机号形式的账号按《隐私政策》所述采用加密存储和不可逆索引;常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。使用者不得擅自收集、导出或向无关第三方提供完整号码。

-

三、业务资料与内容

-

使用者仅可录入履行门店业务所需且有权处理的客户、预约、作品、员工和经营资料,并应确保上传文字和图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。用户可随时更正自己提交的非业务资料。

-

头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核。开发环境使用本地模拟服务进行验证;正式环境启用微信内容安全服务后,文字和图片会按审核平台要求处理,未通过、待复核或服务异常的内容不会公开。

-

客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外内容审核,但仍受门店权限和保密要求约束。

-

四、业务记录与金额

-

订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值或订阅交易。不得将工作台用于未经授权的资金收取、代收或虚拟权益交易。

-

五、账号注销与数据处理

-

用户可在小程序“我的-账号设置”提交注销申请并在处理前撤回。管理员完成必要的门店移交或归档后撤销会话并清理或匿名化个人账号资料。目标处理期限为15个工作日,具体取决于门店交接。

-

解绑手机号经当前号码验证码核验后立即生效,系统清除手机号密文和检索索引。必要的订单、预约和经营记录将去除身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。

-

六、未成年人

-

不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务。门店不得要求未成年人独立提交与其年龄不相适应的个人信息。

-

七、服务调整、责任与联系

-

平台会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。因使用者违反本协议、法律法规或侵害他人权益造成的损失,由使用者依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,平台将在合理范围内协助恢复。

-

隐私相关申请可从账号设置发起或联系所属门店管理员;其他问题请联系门店管理员或运营方公布的客服渠道【待业务确认】。

-

本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。

+
+

甲屿手纪 Salon 用户协议

+ + + + +
+ + From 05493923e45a218066c1c44484d85b6ba137da4f Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 22:02:51 +0800 Subject: [PATCH 106/165] =?UTF-8?q?Salon=20=E4=BE=A7=E5=85=A8=E5=9C=BA?= =?UTF-8?q?=E6=99=AF=E8=84=B1=E6=95=8F=E4=B8=8E=E6=8B=A8=E5=8F=B7=E5=8D=95?= =?UTF-8?q?=E6=AC=A1=E5=8F=96=E5=8F=B7=E6=94=B9=E9=80=A0=EF=BC=9A=E6=94=B6?= =?UTF-8?q?=E6=8E=89=E9=A2=84=E7=BA=A6=E9=80=89=E6=8B=A9=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=9A=84=E5=AE=8C=E6=95=B4=E6=89=8B=E6=9C=BA=E5=8F=B7=E5=87=BA?= =?UTF-8?q?=E5=8F=A3=EF=BC=8C=E6=96=B0=E5=A2=9E=E6=8C=89=E9=97=A8=E5=BA=97?= =?UTF-8?q?=E4=B8=8E=E8=AE=A2=E5=8D=95=E4=B8=8A=E4=B8=8B=E6=96=87=E6=8E=88?= =?UTF-8?q?=E6=9D=83=E7=9A=84=E6=8B=A8=E5=8F=B7=E5=8F=96=E5=8F=B7=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E5=8F=8A=E9=9A=90=E7=A7=81=E5=8F=B7=E5=8D=A0=E4=BD=8D?= =?UTF-8?q?=E6=B8=A0=E9=81=93=EF=BC=8C=E5=89=8D=E7=AB=AF=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E8=84=B1=E6=95=8F=E5=B1=95=E7=A4=BA=E5=8A=A0=E5=91=BC=E5=8F=AB?= =?UTF-8?q?=E5=8F=96=E5=8F=B7=EF=BC=8C=E5=B9=B6=E5=90=8C=E6=AD=A5=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=8D=8F=E8=AE=AE=E6=9D=A1=E6=AC=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/config/RateLimitProperties.java | 2 + .../admin/AdminManagerController.java | 15 ++ .../vo/AppointmentCustomerOptionVO.java | 3 + .../service/impl/PlanningServiceImpl.java | 8 +- .../planning/vo/PlanningAppointmentVO.java | 3 + .../privacy/config/DialProperties.java | 17 +++ .../core/modules/privacy/dial/DialMode.java | 14 ++ .../core/modules/privacy/dial/DialTarget.java | 29 ++++ .../privacy/dial/DialTargetProvider.java | 20 +++ .../dial/DirectDialTargetProvider.java | 54 +++++++ .../PlaceholderPrivacyNumberProvider.java | 28 ++++ .../privacy/service/CustomerDialService.java | 14 ++ .../service/impl/CustomerDialServiceImpl.java | 94 ++++++++++++ .../modules/privacy/vo/CustomerDialVO.java | 19 +++ .../support/SecurityAuditActions.java | 1 + .../user/service/impl/UserServiceImpl.java | 8 +- .../security/RequestThrottleService.java | 8 + ...与用户协议全场景脱敏条款修订_20261104.sql | 51 +++++++ .../service/impl/PlanningServiceImplTest.java | 8 +- .../impl/CustomerDialServiceImplTest.java | 138 ++++++++++++++++++ .../impl/UserServiceCustomerMatchingTest.java | 12 +- JC-Salon-Frontend/src/api/user.ts | 17 +++ .../src/views/ArtistOrderView.vue | 28 ++++ JC-Salon-WeChat/api/customers.js | 12 ++ .../pages/appointment-detail/index.js | 23 +++ .../pages/appointment-detail/index.wxml | 11 +- .../pages/appointment-detail/index.wxss | 18 +++ .../appointment-form/entity-selector.test.js | 9 +- .../pages/appointment-form/index.js | 41 ++++-- JC-Salon-WeChat/pages/backfill-order/index.js | 2 +- .../jayucloud-salon/DEFAULT_GROUP/core.yaml | 6 + .../jayucloud-salon/DEFAULT_GROUP/core.yaml | 6 + .../jayucloud-salon/DEFAULT_GROUP/core.yaml | 6 + 33 files changed, 697 insertions(+), 28 deletions(-) create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java create mode 100644 JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java 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/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 81194408..1703a4a2 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 @@ -33,6 +33,8 @@ 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; @@ -49,6 +51,7 @@ 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; @@ -65,6 +68,7 @@ public class AdminManagerController { private final ProductService productService; private final ShopService shopService; private final AdminScopeHelper adminScopeHelper; + private final CustomerDialService customerDialService; @GetMapping("/planning/calendar") @RequirePermission("schedule:view") @@ -179,6 +183,17 @@ public class AdminManagerController { 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 Long orderId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + response.setHeader("Cache-Control", "no-store"); + return Result.success(customerDialService.dial(currentUser, customerId, orderId, request)); + } + @GetMapping("/customers/{id}") @RequirePermission("user:view") public Result customer(HttpServletRequest request, @PathVariable Long id) { 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 index 3831ab2f..2bf1f36b 100644 --- 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 @@ -11,7 +11,10 @@ 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/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index 7a77525e..d5120bdd 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 @@ -37,6 +37,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu 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; @@ -103,6 +104,7 @@ public class PlanningServiceImpl implements PlanningService { private final WechatSubscribeMessageService wechatSubscribeMessageService; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final PhoneCrypto phoneCrypto; @Override public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) { @@ -621,7 +623,11 @@ 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() 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 edd3899a..b7f2ebdd 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 @@ -11,7 +11,10 @@ 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 Long artistId; 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/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..0b1fd44d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java @@ -0,0 +1,54 @@ +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 { + + 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(422, "该客户未登记可拨打的手机号"); + } + return new DialTarget(DialMode.DIRECT, plainPhone.trim(), 0); + } + + private String resolvePlainPhone(UserDO customer, OrderDO order) { + 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; + } + } + } + if (order != null && StringUtils.hasText(order.getCustomerPhoneSnapshot())) { + return phoneCrypto.decrypt(order.getCustomerPhoneSnapshot()); + } + 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/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..bd2db693 --- /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 orderId, HttpServletRequest request); +} 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..abf0ec56 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java @@ -0,0 +1,94 @@ +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.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 RequestThrottleService requestThrottleService; + private final SecurityAuditSupport securityAuditSupport; + private final DialProperties dialProperties; + private final List providers; + + @Override + public CustomerDialVO dial(UserDO currentUser, Long customerId, Long orderId, HttpServletRequest request) { + adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号"); + Long currentShopId = currentUser.getShopId(); + requestThrottleService.checkCustomerDial(request, currentUser.getId()); + + UserDO customer = userService.getById(customerId); + if (customer == null || Objects.equals(1, customer.getIsDelete()) || !Objects.equals(0, customer.getType())) { + throw new BusinessException(404, "客户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, customerId, "无权拨打其他店铺客户"); + + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Objects.equals(1, order.getIsDelete()) || !Objects.equals(customerId, order.getUserId())) { + throw new BusinessException(403, "该客户与订单不匹配,或无权拨打"); + } + if (!Objects.equals(currentShopId, order.getShopId())) { + throw new BusinessException(403, "无权拨打其他店铺订单客户"); + } + + DialTargetProvider provider = resolveProvider(); + String reason = "customerId=" + customerId + ";orderId=" + orderId + ";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; + } + } + + 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/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/security/support/SecurityAuditActions.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java index a581544f..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 @@ -108,6 +108,7 @@ public final class SecurityAuditActions { 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/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index 158af818..ec8e200e 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 @@ -629,7 +629,9 @@ public class UserServiceImpl extends ServiceImpl implements AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO(); customer.setId(user.getId()); customer.setName(user.getNickname()); - customer.setPhone(resolveCustomerPhone(user)); + 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; @@ -658,7 +660,9 @@ public class UserServiceImpl extends ServiceImpl implements AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO(); option.setId(user.getId()); option.setName(user.getNickname()); - option.setPhone(resolveCustomerPhone(user)); + 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; 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 59c2c8d1..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 @@ -90,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. 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/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 index 46273f97..1c1c1121 100644 --- 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 @@ -29,6 +29,7 @@ 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; @@ -69,6 +70,7 @@ class PlanningServiceImplTest { @Mock private WechatSubscribeMessageService wechatSubscribeMessageService; @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private PhoneCrypto phoneCrypto; private PlanningServiceImpl service; @@ -77,7 +79,7 @@ class PlanningServiceImplTest { service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, productMapper, shopMapper, shopBusinessExpiryService, shopBusinessScheduleService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator, - objectStorageUrlSupport); + objectStorageUrlSupport, phoneCrypto); ShopBusinessHoursDayVO defaultOpenDay = new ShopBusinessHoursDayVO(); defaultOpenDay.setOpen(true); defaultOpenDay.setStartTime("10:00"); @@ -514,13 +516,15 @@ class PlanningServiceImplTest { 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("13800138000", result.getCustomerPhone()); + assertEquals("138****8000", result.getCustomerPhone()); + assertEquals(Boolean.TRUE, result.getCustomerPhoneAvailable()); assertEquals("门店临时闭店", result.getCancelReason()); verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull()); } 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..a3e11b63 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java @@ -0,0 +1,138 @@ +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.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.mockito.ArgumentMatchers.any; +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 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, + 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, 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 rejectsOrderOfAnotherShop() { + order.setShopId(2L); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, 10L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void rejectsOrderThatDoesNotBelongToCustomer() { + order.setUserId(101L); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, 10L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void privacyNumberProviderReportsNotConfiguredWithoutFallingBackToRealNumber() { + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, + 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, 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/user/service/impl/UserServiceCustomerMatchingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java index f32bae0f..35d9b893 100644 --- 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 @@ -75,7 +75,7 @@ class UserServiceCustomerMatchingTest { } @Test - void appointmentIdentityLookupReturnsOnlyExactTupleAndFullPhone() { + void appointmentIdentityLookupReturnsOnlyExactTupleAndMaskedPhone() { UserDO existing = new UserDO(); existing.setId(92L); existing.setNickname("周女士"); @@ -85,6 +85,7 @@ class UserServiceCustomerMatchingTest { 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); @@ -92,12 +93,13 @@ class UserServiceCustomerMatchingTest { userService.findCustomerIdentityMatches("周女士", "wx-another", "13800138000", null); assertEquals(1, matches.size()); - assertEquals("13800138000", matches.get(0).getPhone()); + assertEquals("138****8000", matches.get(0).getPhone()); + assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable()); assertTrue(wrongWechat.isEmpty()); } @Test - void appointmentIdentityLookupFallsBackToLegacyContactPhone() { + void appointmentIdentityLookupFallsBackToLegacyContactPhoneWithMaskedPhone() { UserDO existing = new UserDO(); existing.setId(93L); existing.setNickname("周女士"); @@ -107,11 +109,13 @@ class UserServiceCustomerMatchingTest { 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("13800138000", matches.get(0).getPhone()); + assertEquals("138****8000", matches.get(0).getPhone()); + assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable()); } } diff --git a/JC-Salon-Frontend/src/api/user.ts b/JC-Salon-Frontend/src/api/user.ts index 53072cd9..0bc9418e 100644 --- a/JC-Salon-Frontend/src/api/user.ts +++ b/JC-Salon-Frontend/src/api/user.ts @@ -261,11 +261,28 @@ 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 (customerId: IdType, orderId: IdType): Promise => { + return await api.post(`/manager/customers/${customerId}/dial`, null, { + params: { orderId } + }) as unknown as CustomerDialResult + }, getUserInfo: async (): Promise => { return await api.get('/user/info') as unknown as UserVO }, diff --git a/JC-Salon-Frontend/src/views/ArtistOrderView.vue b/JC-Salon-Frontend/src/views/ArtistOrderView.vue index 557989ef..c990f035 100644 --- a/JC-Salon-Frontend/src/views/ArtistOrderView.vue +++ b/JC-Salon-Frontend/src/views/ArtistOrderView.vue @@ -67,6 +67,13 @@
预约用户:{{ order.customerNickname || '用户' }} 联系电话:{{ order.customerPhoneMasked }} + 呼叫
@@ -215,6 +222,7 @@ const route = useRoute() * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const orders = ref([]) +const dialingOrderId = ref(null) /** * Purpose: orderRefs supports ArtistOrderView.vue by holding or executing the order refs 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. @@ -659,6 +667,26 @@ const confirmQuote = async () => { } } +/** 按订单上下文单次取号后发起拨号,号码不落库、不缓存。 */ +const dialCustomer = async (order: any) => { + if (!order?.userId || !order?.id) { + message.warning('缺少订单上下文,无法取号') + return + } + dialingOrderId.value = order.id + try { + const result = await userApi.dialCustomer(order.userId, order.id) + if (!result?.dialNumber) { + throw new Error('未获取到可拨打号码') + } + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '取号失败') + } finally { + dialingOrderId.value = null + } +} + /** completeOrder is a local helper used by this page script. */ const completeOrder = (orderId: IdType) => { Modal.confirm({ diff --git a/JC-Salon-WeChat/api/customers.js b/JC-Salon-WeChat/api/customers.js index c76e2c53..1eff37c0 100644 --- a/JC-Salon-WeChat/api/customers.js +++ b/JC-Salon-WeChat/api/customers.js @@ -46,6 +46,18 @@ module.exports = { }) }, + /** + * 后台按预约/订单上下文单次取号,号码不入库、不缓存。 + */ + dialCustomer(customerId, orderId) { + return request({ + url: `/manager/customers/${customerId}/dial`, + method: 'POST', + data: {}, + params: { orderId } + }) + }, + create(data) { return request({ url: '/manager/customers', diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index c49e37eb..8bf5f75f 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -1,4 +1,5 @@ const planningApi = require('../../api/planning') +const customersApi = require('../../api/customers') const { markPlanningRefresh } = require('../../utils/planning-refresh') function displayValue(value, fallback) { @@ -24,6 +25,7 @@ Page({ showComplete: false, showCancel: false, updating: false, + dialing: false, loadError: '' }, @@ -130,6 +132,27 @@ Page({ }) }, + async dialCustomer() { + const appointment = this.data.appointment || {} + if (this.data.dialing) return + if (!appointment.customerPhoneAvailable || !appointment.customerId || !appointment.orderId) { + wx.showToast({ title: '该客户暂无可拨打的手机号', icon: 'none' }) + return + } + this.setData({ dialing: true }) + try { + const result = await customersApi.dialCustomer(appointment.customerId, appointment.orderId) + if (!result || !result.dialNumber) { + throw new Error('未获取到可拨打号码') + } + wx.makePhoneCall({ phoneNumber: result.dialNumber }) + } catch (error) { + wx.showToast({ title: error.message || '取号失败', icon: 'none' }) + } finally { + this.setData({ dialing: false }) + } + }, + goTransfer() { if (!this.data.showTransfer) return wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` }) diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxml b/JC-Salon-WeChat/pages/appointment-detail/index.wxml index 97af5b86..aa8bdacb 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxml @@ -10,7 +10,16 @@ {{avatarText}} {{appointment.customerNameText}} - {{appointment.customerPhoneText}} + + {{appointment.customerPhoneText}} + + {{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}} diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxss b/JC-Salon-WeChat/pages/appointment-detail/index.wxss index 54a5b15e..2df450ce 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxss @@ -67,6 +67,24 @@ font-size: 24rpx; } +.phone-row { + display: flex; + align-items: center; + gap: 12rpx; +} + +.call-btn { + flex-shrink: 0; + margin: 0; + padding: 0 18rpx; + border-radius: 999rpx; + background: #edf6ef; + color: #247b63; + font-size: 22rpx; + font-weight: 800; + line-height: 44rpx; +} + .status-tag { flex-shrink: 0; padding: 8rpx 14rpx; diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index a09e6503..4aa8b0a4 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -36,17 +36,17 @@ function createPage() { async function run() { const page = createPage() - page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '13800138000' } } }) + page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '138****8000' } } }) assert.strictEqual(page.data.form.customerUserId, 18) assert.strictEqual(page.data.form.customerName, '小周') - assert.strictEqual(page.data.form.phone, '13800138000') + assert.strictEqual(page.data.form.phone, '') assert.strictEqual(page.data.customerSheetVisible, false) page.data.form.customerUserId = 18 page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '13800138000') + assert.strictEqual(page.data.form.phone, '') customersApi.matchIdentityForAppointment = async () => [] customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } @@ -61,10 +61,11 @@ async function run() { assert.strictEqual(name, '小周') assert.strictEqual(wechatId, undefined) assert.strictEqual(phone, '13800138000') - return [{ id: '18', name: '小周', phone: '13800138000' }] + return [{ id: '18', name: '小周', phone: '138****8000' }] } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) assert.strictEqual(page.data.form.customerUserId, '18') + assert.strictEqual(page.data.form.phone, '13800138000') page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }] page.onArtistSearch({ detail: { value: '李' } }) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 1709fc88..ae28ef55 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -520,6 +520,7 @@ function normalizeCustomer(customer) { id: customer.id, name, phone, + phoneAvailable: customer.phoneAvailable === true || (Boolean(phone) && !String(phone).includes('*')), displayName: name || phone || '客户', displayPhone: phone || '未填写手机号', createdAt: customerCreatedAt(customer) @@ -952,7 +953,7 @@ Page({ if (requestSeq !== this._customerSuggestionSeq) return const rows = Array.isArray(result) ? result : (result.list || []) const remoteSuggestions = rows.map(normalizeCustomer) - .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .filter(customer => !name || customer.name.toLowerCase().includes(name)) .slice(0, 3) .map(buildCustomerSelectorItem) this.setData({ customerSuggestions: remoteSuggestions }) @@ -971,7 +972,8 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone || '', + // 后端仅返回脱敏号码,不回填到表单,避免把脱敏值当真实号码提交 + 'form.phone': '', 'form.createCustomerRecord': false, customerSuggestions: [], customerSheetVisible: false, @@ -1000,11 +1002,25 @@ Page({ return } const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() + if (keyword) { + // 号码已全场景脱敏,按手机号检索必须交给后端精确匹配 + try { + const result = await customersApi.listForAppointment({ page: 1, size: 100, keyword }) + const rows = Array.isArray(result) ? result : (result.list || []) + this.setData({ + customerOptions: this.sortCustomerOptions(rows.map(normalizeCustomer)), + customerError: '' + }) + } catch (error) { + this.setData({ customerOptions: [], customerError: error.message || '客户加载失败' }) + } + return + } if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory() - const matches = this.data.customerDirectory.filter(customer => - !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase()) - ) - this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' }) + this.setData({ + customerOptions: this.sortCustomerOptions(this.data.customerDirectory), + customerError: '' + }) }, changeCustomerView(event) { @@ -1013,11 +1029,10 @@ Page({ toggleCustomerSort() { const customerNewestFirst = !this.data.customerNewestFirst - const keyword = String(this.data.customerKeyword || '').trim().toLowerCase() - const matches = this.data.customerDirectory.filter(customer => - !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword) - ) - this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) }) + this.setData({ + customerNewestFirst, + customerOptions: this.sortCustomerOptions(this.data.customerOptions, customerNewestFirst) + }) }, retryCustomerSearch() { @@ -1032,7 +1047,8 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone || '', + // 选择已有客户时不回填脱敏号码,手机号仅在用户主动修改时提交 + 'form.phone': '', 'form.createCustomerRecord': false, customerSheetVisible: false, customerKeyword: '', @@ -1925,7 +1941,6 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone, 'form.createCustomerRecord': false }) } else { diff --git a/JC-Salon-WeChat/pages/backfill-order/index.js b/JC-Salon-WeChat/pages/backfill-order/index.js index 665c051d..2ad1fe72 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.js +++ b/JC-Salon-WeChat/pages/backfill-order/index.js @@ -114,7 +114,7 @@ Page({ searchCustomers(event) { const keyword = String(event.detail.value || '').toLowerCase(); this.setData({ customerKeyword: keyword, customerOptions: this.data.allCustomerOptions.filter(item => !keyword || `${item.name} ${item.phone}`.toLowerCase().includes(keyword)) }) }, selectProduct(event) { const item = event.detail.item || {}; const duration = String(item.serviceDurationMinutes || String(item.approximateDuration || '').replace(/[^0-9]/g, '') || '60'); this.setData({ 'form.productId': item.id, 'form.manualProductTitle': '', 'form.amount': item.price == null ? this.data.form.amount : String(item.price), 'form.durationMinutes': duration, selectedProduct: item, selectedProductTitle: item.title, selectedProductPriceText: item.priceText || '价格待定', manualProductDraft: { title: '', price: '', durationMinutes: duration, description: '' }, productSelectorVisible: false, manualProductSheetVisible: false }) }, selectArtist(event) { const item = event.detail.item; this.setData({ 'form.artistId': item.id, selectedArtistName: item.title, artistSelectorVisible: false }) }, - selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': item.phone || '', customerSelectorVisible: false }) }, + selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': '', customerSelectorVisible: false }) }, useWalkIn() { this.setData({ 'form.customerUserId': '', 'form.customerName': '', 'form.wechatId': '', 'form.phone': '', customerSelectorVisible: false }) }, onCustomerInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value, 'form.customerUserId': '' }) }, useManualProduct() { const title = String(this.data.manualProductDraft.title || '').trim(); const priceText = String(this.data.manualProductDraft.price || this.data.form.amount || '').trim(); const price = Number(priceText); const images = this.data.form.manualProductImages || []; if (this.data.form.productId) { if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } this.setData({ 'form.amount': priceText, 'form.durationMinutes': String(this.data.manualProductDraft.durationMinutes || '60'), manualProductSheetVisible: false }); return } if (!title && !images.length) { wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' }); return } if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } const duration = String(this.data.manualProductDraft.durationMinutes || '60'); this.setData({ 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductDescription': this.data.manualProductDraft.description || '', 'form.manualProductPrice': priceText, 'form.amount': priceText, 'form.durationMinutes': duration, 'manualProductDraft.price': priceText, selectedProduct: {}, selectedProductTitle: title, selectedProductPriceText: `¥${price}`, productSelectorVisible: false, manualProductSheetVisible: false }) }, diff --git a/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml index 5f789af5..fa31fa5e 100644 --- a/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -51,6 +51,9 @@ jayucloud-salon: brand: message-template-name: JayuCloud-Salon manager-register-shop-description: 甲屿店务注册店铺 + dial: + # direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码) + provider: direct privacy: content-moderation: # 仅 DEV 允许在后台设置中使用本地模拟审核;SIT/PROD 继续失败关闭。 @@ -87,6 +90,9 @@ jayucloud-salon: order-create: limit: 10 window-seconds: 60 + customer-dial: + limit: 10 + window-seconds: 60 cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml index deb8140e..1fb6193b 100644 --- a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -50,6 +50,9 @@ jayucloud-salon: brand: message-template-name: JayuCloud-Salon manager-register-shop-description: 甲屿店务注册店铺 + dial: + # direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码) + provider: direct privacy: content-moderation: # 微信审核平台接入前失败关闭,内容进入隔离/人工复核,不自动放行。 @@ -87,6 +90,9 @@ jayucloud-salon: order-create: limit: 10 window-seconds: 60 + customer-dial: + limit: 10 + window-seconds: 60 cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml index 43316412..7db07310 100644 --- a/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -50,6 +50,9 @@ jayucloud-salon: brand: message-template-name: JayuCloud-Salon manager-register-shop-description: 甲屿店务注册店铺 + dial: + # direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码) + provider: direct privacy: content-moderation: # 仅 DEV 允许模拟审核;SIT 必须在后台配置微信审核并保持失败关闭。 @@ -86,6 +89,9 @@ jayucloud-salon: order-create: limit: 10 window-seconds: 60 + customer-dial: + limit: 10 + window-seconds: 60 cache: local-max-size: 2048 product-detail: From 99fa38f110844b0c355629404640ff9d669f4cf3 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 22:04:14 +0800 Subject: [PATCH 107/165] =?UTF-8?q?feat(artlist):=20=E5=85=A8=E5=9C=BA?= =?UTF-8?q?=E6=99=AF=E8=84=B1=E6=95=8F=E4=B8=8E=E5=8D=95=E6=AC=A1=E6=8B=A8?= =?UTF-8?q?=E5=8F=B7=E5=8F=96=E5=8F=B7=EF=BC=8C=E8=A1=A5=E9=BD=90=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E5=8A=A0=E5=AF=86=E4=B8=8E=E5=8D=8F=E8=AE=AE=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 手机号/账号全场景一律脱敏:SensitiveFieldPolicy 删除完整值分支与 ADMIN_EDIT,SELF_PROFILE 同样脱敏;convertToVO 全调用点统一脱敏 - 联系信息接口不再返回号码:toContact 置空 phone 并给出 phoneAvailable,补齐 ensureUserCanSeeShop 真实可见范围校验 - 新增 POST /contact-info/dial,按 scene(SHOP_MANAGER/ORDER_ARTIST/PRODUCT_ARTIST/PLATFORM) 一次一取;DialTargetProvider 抽象直连/隐私号,未配置隐私号返回 9001 且不回退真实号;/contact-info/** 按用户限流并记录审计 - 验证码与换绑手机号改为服务端按当前登录用户取号,客户端 phone/oldPhone 参数兼容忽略;前端与小程序同步去掉回传 - 消息发布人昵称兜底改为脱敏账号,避免 account 明文写入 publisher_name - 新增 V5 账号加密与账号哈希、V6 协议文本改为全场景脱敏与单次拨号取号 --- .../artlist/core/config/DialProperties.java | 19 ++ .../core/config/MyMetaObjectHandler.java | 6 + .../core/config/RateLimitProperties.java | 10 + .../service/impl/CommentServiceImpl.java | 5 +- .../service/impl/AnnouncementServiceImpl.java | 8 +- .../impl/SystemMessageServiceImpl.java | 6 +- .../order/service/impl/OrderServiceImpl.java | 3 +- .../impl/SecurityAuditLogServiceImpl.java | 5 +- .../front/ContactInfoController.java | 71 ++++++- .../core/modules/shop/dto/DialRequestDTO.java | 25 +++ .../shop/service/ContactDialService.java | 15 ++ .../service/impl/ContactDialServiceImpl.java | 200 ++++++++++++++++++ .../service/impl/ContactInfoServiceImpl.java | 35 ++- .../modules/shop/support/dial/DialScene.java | 41 ++++ .../shop/support/dial/DialTargetProvider.java | 19 ++ .../dial/DirectDialTargetProvider.java | 30 +++ .../PlaceholderPrivacyNumberProvider.java | 27 +++ .../core/modules/shop/vo/DialResponseVO.java | 25 +++ .../user/controller/front/UserController.java | 48 ++++- .../core/modules/user/entity/UserDO.java | 11 +- .../modules/user/service/UserService.java | 5 + .../user/service/impl/UserServiceImpl.java | 103 +++++---- .../privacy/AccountHashBackfillRunner.java | 52 +++++ .../privacy/AccountPhoneTypeHandler.java | 35 +++ .../core/support/privacy/PhoneCrypto.java | 23 +- .../support/privacy/SensitiveFieldPolicy.java | 51 +++++ .../security/OperationGuardService.java | 4 +- .../security/RequestThrottleService.java | 16 ++ .../V5__账号加密与账号哈希_20261104.sql | 118 +++++++++++ ...改为全场景脱敏与单次拨号取号_20261104.sql | 119 +++++++++++ .../front/ContactDialControllerTest.java | 92 ++++++++ .../service/impl/ContactDialServiceTest.java | 131 ++++++++++++ .../core/support/privacy/PhoneCryptoTest.java | 20 ++ .../privacy/SensitiveFieldPolicyTest.java | 55 +++++ JC-ArtList-Frontend/src/api/user.ts | 23 +- .../src/views/AccountSettingsView.vue | 2 +- JC-ArtList-Frontend/src/views/HelpView.vue | 18 +- .../src/views/OrderDetailView.vue | 19 +- .../src/views/PasswordSettingsView.vue | 2 +- JC-ArtList-Frontend/src/views/ProfileView.vue | 14 +- .../src/views/ShopDetailView.vue | 28 ++- JC-ArtList-WeChat/api/user.js | 12 ++ JC-ArtList-WeChat/pages/help/index.js | 12 ++ JC-ArtList-WeChat/pages/help/index.wxml | 4 +- JC-ArtList-WeChat/pages/order-detail/index.js | 15 ++ .../pages/order-detail/index.wxml | 4 +- JC-ArtList-WeChat/pages/settings/index.js | 18 +- JC-ArtList-WeChat/pages/shop-detail/index.js | 21 +- .../pages/shop-detail/index.wxml | 2 +- .../jayucloud-artlist/DEFAULT_GROUP/core.yaml | 8 + .../jayucloud-artlist/DEFAULT_GROUP/core.yaml | 8 + .../jayucloud-artlist/DEFAULT_GROUP/core.yaml | 8 + 52 files changed, 1515 insertions(+), 136 deletions(-) create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java create mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java create mode 100644 JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql create mode 100644 JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql create mode 100644 JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java create mode 100644 JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java create mode 100644 JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java 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/MyMetaObjectHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java index 45f4bea2..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 @@ -47,6 +47,12 @@ public class MyMetaObjectHandler implements MetaObjectHandler { * 注意: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) { 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/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/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 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 0e50f9cc..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,12 +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.PhoneCrypto; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -41,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. */ @@ -49,7 +55,6 @@ public class ContactInfoServiceImpl implements ContactInfoService { * Variable `objectStorageUrlSupport`: converts stored QR image URLs into frontend-safe signed URLs. */ private final ObjectStorageUrlSupport objectStorageUrlSupport; - private final PhoneCrypto phoneCrypto; @Override /** @@ -162,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, "店铺不存在或不可见"); } } @@ -204,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(phoneCrypto.mask(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 ebc2b9ec..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 @@ -140,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. @@ -361,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 ? "账号可用" : "账号已被注册"; @@ -379,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") ); @@ -552,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") ); @@ -599,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. @@ -609,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 168f7e99..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,7 @@ 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 @@ -45,11 +46,17 @@ 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("account_hash") + private String accountHash; + /** * 手机号(AES-GCM 密文,落库列 phone_cipher;实体中保持明文,便于业务使用) */ 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 e1e596f3..996ac58f 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,6 +6,7 @@ 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.*; @@ -49,6 +50,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrl 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; @@ -371,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) { @@ -536,7 +538,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) { @@ -655,21 +657,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, null) - .set(UserDO::getPhoneHash, null) - .set(UserDO::getContactPhoneHash, null) - .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 @@ -687,7 +702,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); } /** @@ -701,7 +716,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()); } @@ -722,7 +737,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()); } @@ -739,7 +754,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()); } @@ -753,7 +768,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())) { @@ -765,7 +780,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); } /** @@ -774,7 +789,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); @@ -795,9 +810,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(maskPhone(userDO.getPhone())); - userVO.setContactPhone(maskPhone(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())); @@ -873,7 +888,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") ); @@ -978,7 +993,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") ); @@ -1026,7 +1041,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)) ); /** @@ -1243,7 +1258,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)) ); /** @@ -1452,7 +1467,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) { @@ -1545,7 +1560,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") ); @@ -1901,8 +1916,10 @@ public class UserServiceImpl extends ServiceImpl implements // 不再过滤普通用户,由前端根据用户角色进行过滤 if (StringUtils.hasText(keyword)) { String keywordPhoneHash = phoneCrypto.isMobilePhone(keyword) ? phoneCrypto.index(keyword) : null; + String keywordAccountHash = phoneCrypto.index(keyword); wrapper.and(w -> { - w.like(UserDO::getAccount, keyword).or().like(UserDO::getNickname, keyword); + // 账号落库为密文,不能模糊检索,统一走 account_hash 精确匹配 + w.eq(UserDO::getAccountHash, keywordAccountHash).or().like(UserDO::getNickname, keyword); // 手机号只做精确匹配:密文不可模糊检索,统一走 phone_hash if (keywordPhoneHash != null) { w.or().eq(UserDO::getPhoneHash, keywordPhoneHash) @@ -1960,7 +1977,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); @@ -2220,7 +2237,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(); @@ -2240,14 +2257,6 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("当前账号未绑定手机号"); } - if (!Objects.equals(phoneCrypto.index(userDO.getPhone()), phoneCrypto.index(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`. @@ -2272,6 +2281,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`. @@ -2489,7 +2511,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); } /** 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 index 9f402853..3d28e1be 100644 --- 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 @@ -84,6 +84,20 @@ public class PhoneCrypto { } } + /** + * 账号加密: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); } @@ -98,13 +112,6 @@ public class PhoneCrypto { return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain; } - /** - * 非手机号内容原样返回,手机号返回脱敏值;用于审计日志等既有账号字段。 - */ - public String maskIfMobile(String value) { - return isMobilePhone(value) ? mask(value) : value; - } - public String index(String value) { if (!StringUtils.hasText(value)) return null; try { @@ -113,7 +120,7 @@ public class PhoneCrypto { byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(digest); } catch (GeneralSecurityException exception) { - throw new IllegalStateException("手机号索引生成失败", exception); + throw new IllegalStateException("敏感字段索引生成失败", exception); } } 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 6a4b6c26..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 @@ -191,8 +191,8 @@ public class OperationGuardService { readBodyField(request, key) ); if (StringUtils.hasText(value)) { - // 手机号不落 Redis 键:统一替换为哈希 - return "phone".equals(key) ? phoneCrypto.index(value) : 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/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 index 4f7a8948..51221fda 100644 --- 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 @@ -65,4 +65,24 @@ class PhoneCryptoTest { 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/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 5531b08e..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) @@ -130,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 @@ -334,7 +349,9 @@ onMounted(loadOrder)

联系信息

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

-

电话:{{ contact.phone }}

+

+ 拨打美甲师电话 +

微信:{{ contact.wechatId }}

{{ contact.platformContactText }}

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..8f2277d2 100644 --- a/JC-ArtList-Frontend/src/views/ProfileView.vue +++ b/JC-ArtList-Frontend/src/views/ProfileView.vue @@ -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 || '' @@ -742,15 +746,17 @@ const handleSaveProfile = async () => { 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-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/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/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/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml index 075434e6..ee068974 100644 --- a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -66,6 +66,14 @@ jayucloud-artlist: order-create: limit: 10 window-seconds: 60 + contact-info-read: + limit: 30 + window-seconds: 60 + contact-dial: + limit: 10 + window-seconds: 60 + dial: + provider: direct cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml index 63ba85fa..a7e24c06 100644 --- a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -66,6 +66,14 @@ jayucloud-artlist: order-create: limit: 10 window-seconds: 60 + contact-info-read: + limit: 30 + window-seconds: 60 + contact-dial: + limit: 10 + window-seconds: 60 + dial: + provider: direct cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml index 944cd2bd..15c130fd 100644 --- a/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -66,6 +66,14 @@ jayucloud-artlist: order-create: limit: 10 window-seconds: 60 + contact-info-read: + limit: 30 + window-seconds: 60 + contact-dial: + limit: 10 + window-seconds: 60 + dial: + provider: direct cache: local-max-size: 2048 product-detail: From 90b07bf33eea49c6537b069bd291479e9564736a Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 23:24:05 +0800 Subject: [PATCH 108/165] =?UTF-8?q?feat:=20=E5=BE=AE=E4=BF=A1=E5=AE=A1?= =?UTF-8?q?=E6=A0=B8=E5=9B=9E=E8=B0=83=E6=94=AF=E6=8C=81=E8=B7=A8=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E8=BD=AC=E5=8F=91=E4=B8=8E=E8=A1=A5=E5=81=BF=E9=87=8D?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/config/SalonDeployProperties.java | 24 ++ ...atContentModerationCallbackController.java | 144 +++++++- .../WechatContentModerationProvider.java | 12 +- .../ContentModerationForwardService.java | 46 +++ .../ContentModerationForwardServiceImpl.java | 341 ++++++++++++++++++ .../support/ModerationForwardHttpClient.java | 35 ++ ...dminSecureIntegrationConfigController.java | 28 ++ .../dto/SecureIntegrationConfigDTO.java | 7 + .../entity/ModerationCallbackForwardDO.java | 46 +++ .../ModerationCallbackForwardMapper.java | 9 + .../secure/ModerationForwardConfig.java | 30 ++ .../SecureIntegrationConfigService.java | 5 + .../SecureIntegrationConfigServiceImpl.java | 141 ++++++++ .../system/vo/ModerationForwardRecordVO.java | 18 + .../system/vo/SecureIntegrationConfigVO.java | 6 + .../V20__微信审核回调跨环境转发_20261104.sql | 16 + ...ntentModerationCallbackControllerTest.java | 232 ++++++++++-- ...ntentModerationForwardServiceImplTest.java | 172 +++++++++ ...ecureIntegrationConfigServiceImplTest.java | 6 +- .../impl/IntegrationProbeServiceImplTest.java | 13 +- JC-Salon-Frontend/src/api/admin.ts | 23 +- .../src/views/admin/SystemSettingsView.vue | 165 +++++++++ .../jayucloud-salon/DEFAULT_GROUP/core.yaml | 3 + .../jayucloud-salon/DEFAULT_GROUP/core.yaml | 3 + .../jayucloud-salon/DEFAULT_GROUP/core.yaml | 3 + 25 files changed, 1479 insertions(+), 49 deletions(-) create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java create mode 100644 JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java 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/modules/privacy/controller/front/WechatContentModerationCallbackController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java index fa0e972b..6aac43d2 100644 --- 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 @@ -2,30 +2,46 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +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.ModerationForwardConfig; 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 FORWARD_BY_HEADER = "X-Moderation-Forward-By"; + private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop"; + 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") @@ -54,12 +70,23 @@ public class WechatContentModerationCallbackController { MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE }) - public String callback(@RequestParam("timestamp") String timestamp, - @RequestParam("nonce") String nonce, + 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, - @org.springframework.web.bind.annotation.RequestBody String body) throws Exception { + @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) 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; @@ -90,12 +117,119 @@ public class WechatContentModerationCallbackController { extra = firstText(root, "extra", "Extra"); } if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识"); - if (!integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) { - contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); + if (claimLocally(taskId, suggest, reason, extra)) { + return "success"; + } + + String taskEnv = normalizeEnv(decodeTaskEnv(extra)); + String localEnv = deployProperties.getEnv(); + String forwardPayload = buildForwardPayload(taskId, suggest, reason, extra); + if (!StringUtils.hasText(taskEnv)) { + contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "回调 extra 缺少部署环境标识"); + log.warn("微信审核回调无法认领:extra 缺少环境标识,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + taskId, localEnv, null); + return "success"; + } + if (taskEnv.equals(localEnv)) { + contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "本环境未匹配到审核任务"); + log.warn("微信审核回调无法认领:本环境未匹配任务,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + taskId, localEnv, taskEnv); + return "success"; + } + ModerationForwardConfig forwardConfig = contentModerationForwardService.runtimeConfig(); + if (!StringUtils.hasText(forwardConfig.targetFor(taskEnv))) { + contentModerationForwardService.recordTargetMissing(taskId, localEnv, taskEnv, extra, forwardPayload); + log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + taskId, localEnv, taskEnv); + return "success"; + } + contentModerationForwardService.enqueue(taskId, localEnv, taskEnv, extra, forwardPayload); + return "success"; + } + + /** + * 处理转发进来的回调:只允许一跳,验签通过后仅在本地处理,不再二次转发。 + */ + private String handleForwardedCallback(String forwardBy, String forwardHop, String timestamp, + String nonce, String signature, String body) { + if (!contentModerationForwardService.verifySignature(timestamp, nonce, signature, body)) { + throw new IllegalArgumentException("跨环境转发签名校验失败"); + } + String taskId; + String suggest; + String reason; + String extra; + try { + JsonNode root = objectMapper.readTree(body == null ? "" : body); + taskId = firstText(root, "trace_id", "traceId", "task_id"); + suggest = firstText(root, "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = "review"; + reason = firstText(root, "reason", "errmsg"); + if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调"; + extra = firstText(root, "extra", "Extra"); + } catch (Exception exception) { + throw new IllegalArgumentException("跨环境转发报文无法解析"); + } + if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("跨环境转发报文缺少任务标识"); + + String hopText = forwardHop == null ? "1" : forwardHop.trim(); + int hop; + try { + hop = Integer.parseInt(hopText); + } catch (NumberFormatException exception) { + hop = 2; + } + String localEnv = deployProperties.getEnv(); + String sourceEnv = normalizeEnv(forwardBy); + if (hop > 1 || (StringUtils.hasText(sourceEnv) && sourceEnv.equals(localEnv))) { + contentModerationForwardService.recordUnclaimed(taskId, extra, body, + "检测到转发环路或超过一跳,已丢弃"); + log.warn("微信审核回调转发被丢弃:环路或超过一跳,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + taskId, sourceEnv, localEnv, hop); + return "success"; + } + log.info("收到跨环境转发的微信审核回调,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + taskId, sourceEnv, localEnv, hop); + if (!claimLocally(taskId, suggest, reason, extra)) { + contentModerationForwardService.recordUnclaimed(taskId, extra, body, "转发目标环境仍未匹配到审核任务"); + log.warn("跨环境转发的微信审核回调未匹配到本地任务,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + taskId, sourceEnv, localEnv, hop); } return "success"; } + private boolean claimLocally(String taskId, String suggest, String reason, String extra) { + if (integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) { + return true; + } + return contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); + } + + private String buildForwardPayload(String taskId, String suggest, String reason, String extra) { + ObjectNode payload = objectMapper.createObjectNode(); + payload.put("trace_id", taskId); + payload.put("suggest", suggest); + payload.put("reason", reason); + if (StringUtils.hasText(extra)) payload.put("extra", extra); + return payload.toString(); + } + + private String decodeTaskEnv(String extra) { + if (!StringUtils.hasText(extra)) return null; + try { + JsonNode payload = objectMapper.readTree(extra); + return firstText(payload, "env"); + } catch (Exception ignored) { + return null; + } + } + + 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 decodeSourceEnvVersion(String extra) { if (!StringUtils.hasText(extra)) return null; try { 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 index fed6376b..929a101a 100644 --- 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 @@ -2,6 +2,7 @@ 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.config.SalonDeployProperties; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; import org.springframework.beans.factory.annotation.Qualifier; @@ -26,16 +27,19 @@ public class WechatContentModerationProvider implements ContentModerationProvide private final ObjectMapper objectMapper; private final WechatMiniClientService wechatMiniClientService; private final ContentModerationProperties properties; + private final SalonDeployProperties deployProperties; public WechatContentModerationProvider( @Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate, ObjectMapper objectMapper, WechatMiniClientService wechatMiniClientService, - ContentModerationProperties properties) { + ContentModerationProperties properties, + SalonDeployProperties deployProperties) { this.restTemplate = restTemplate; this.objectMapper = objectMapper; this.wechatMiniClientService = wechatMiniClientService; this.properties = properties; + this.deployProperties = deployProperties; } @Override @@ -67,6 +71,7 @@ public class WechatContentModerationProvider implements ContentModerationProvide public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) { Map extra = new LinkedHashMap<>(); + extra.put("env", deployProperties.getEnv()); extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion)); extra.put("probeId", probeId); try { @@ -103,8 +108,11 @@ public class WechatContentModerationProvider implements ContentModerationProvide if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) { envVersion = "UNKNOWN"; } + Map extra = new LinkedHashMap<>(); + extra.put("env", deployProperties.getEnv()); + extra.put("envVersion", envVersion); try { - return objectMapper.writeValueAsString(Map.of("envVersion", envVersion)); + return objectMapper.writeValueAsString(extra); } catch (java.io.IOException exception) { throw new IllegalStateException("无法编码微信审核来源版本", exception); } 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..65d8527a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java @@ -0,0 +1,46 @@ +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); + + /** + * 记录无法认领的回调(extra 缺失或指向本环境但本地没有任务),不自动重试。 + */ + void recordUnclaimed(String traceId, String extraJson, String payload, String note); + + /** + * 记录目标环境未配置的回调,不自动重试,配置补齐后可由补偿任务重放。 + */ + void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload); + + /** + * 落库为 PENDING 并异步转发,确保微信回调在 5 秒内拿到 success。 + */ + void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload); + + /** + * 重放到期的 RETRY 记录,最多 5 次,指数退避。 + */ + int retryPending(); + + /** + * 转发配置补齐后,把对应目标环境下的 TARGET_MISSING 记录重新排队。 + */ + int requeueConfiguredTargets(); + + /** + * 校验转发请求的 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/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..f7076718 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java @@ -0,0 +1,341 @@ +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.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient; +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.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +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.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_SUCCESS = "SUCCESS"; + private static final String STATUS_RETRY = "RETRY"; + private static final String STATUS_FAILED = "FAILED"; + private static final String STATUS_NO_ENV = "NO_ENV"; + private static final String STATUS_TARGET_MISSING = "TARGET_MISSING"; + + private static final int MAX_RETRY = 5; + private static final long SIGNATURE_WINDOW_SECONDS = 300; + private static final long NONCE_TTL_SECONDS = 600; + private static final String NONCE_KEY_PREFIX = "salon:content-moderation:forward:nonce:"; + 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 AtomicInteger THREAD_INDEX = new AtomicInteger(1); + private static final ExecutorService FORWARD_EXECUTOR = Executors.newFixedThreadPool(2, new ThreadFactory() { + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "moderation-forward-" + 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; + + @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 void recordUnclaimed(String traceId, String extraJson, String payload, String note) { + if (!StringUtils.hasText(traceId)) { + log.warn("微信审核回调无法认领且缺少任务标识,note={}", note); + return; + } + log.warn("微信审核回调无法认领,traceId={}, sourceEnv={}, targetEnv={}, hop=0, note={}", + traceId, deployProperties.getEnv(), null, note); + ModerationCallbackForwardDO row = build(traceId, deployProperties.getEnv(), null, extraJson, payload, STATUS_NO_ENV, note); + saveQuietly(row); + } + + @Override + public void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) { + log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + traceId, sourceEnv, targetEnv); + ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload, + STATUS_TARGET_MISSING, "目标环境未配置转发地址"); + saveQuietly(row); + } + + @Override + public void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) { + ModerationCallbackForwardDO existing = findByTrace(traceId); + if (existing != null) { + log.info("微信审核回调转发已存在记录,traceId={}, sourceEnv={}, targetEnv={}, status={}", + traceId, sourceEnv, targetEnv, existing.getStatus()); + return; + } + ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload, STATUS_PENDING, null); + if (!saveQuietly(row)) return; + log.info("微信审核回调进入跨环境转发,traceId={}, sourceEnv={}, targetEnv={}, hop=1", + traceId, sourceEnv, targetEnv); + FORWARD_EXECUTOR.execute(() -> dispatchById(row.getId())); + } + + @Override + @Scheduled(fixedDelay = 60000) + public int retryPending() { + List rows = forwardMapper.selectList(new LambdaQueryWrapper() + .eq(ModerationCallbackForwardDO::getStatus, STATUS_RETRY) + .lt(ModerationCallbackForwardDO::getRetryCount, MAX_RETRY) + .orderByAsc(ModerationCallbackForwardDO::getId) + .last("LIMIT 50")); + LocalDateTime now = LocalDateTime.now(); + int attempted = 0; + for (ModerationCallbackForwardDO row : rows) { + if (!backoffElapsed(row, now)) continue; + attempted++; + dispatchById(row.getId()); + } + return attempted; + } + + @Override + public int requeueConfiguredTargets() { + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready() || config.getTargets() == null || config.getTargets().isEmpty()) return 0; + List configuredEnvs = config.getTargets().entrySet().stream() + .filter(entry -> StringUtils.hasText(entry.getValue())) + .map(Map.Entry::getKey) + .toList(); + if (configuredEnvs.isEmpty()) return 0; + return forwardMapper.update(null, new UpdateWrapper() + .eq("status", STATUS_TARGET_MISSING) + .in("target_env", configuredEnvs) + .set("status", STATUS_RETRY) + .set("retry_count", 0) + .set("last_error", null) + .set("updated_at", LocalDateTime.now())); + } + + @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)); + } + + private void dispatchById(Long id) { + ModerationCallbackForwardDO row = forwardMapper.selectById(id); + if (row == null || STATUS_SUCCESS.equals(row.getStatus())) return; + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready()) { + markFailed(row, "跨环境转发未启用或共享密钥缺失", false); + return; + } + String target = config.targetFor(row.getTargetEnv()); + if (!StringUtils.hasText(target)) { + row.setStatus(STATUS_TARGET_MISSING); + row.setLastError("目标环境未配置转发地址"); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.warn("微信审核回调转发目标缺失,traceId={}, sourceEnv={}, targetEnv={}, hop=1", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv()); + return; + } + try { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String nonce = UUID.randomUUID().toString().replace("-", ""); + String signature = sign(config.getSecret(), timestamp, nonce, row.getPayload() == null ? "" : row.getPayload()); + Map headers = new java.util.HashMap<>(); + headers.put(FORWARD_BY_HEADER, deployProperties.getEnv()); + headers.put(FORWARD_HOP_HEADER, "1"); + headers.put("X-Timestamp", timestamp); + headers.put("X-Nonce", nonce); + headers.put("X-Signature", signature); + boolean accepted = forwardHttpClient.post(target, row.getPayload(), headers); + if (accepted) { + row.setStatus(STATUS_SUCCESS); + row.setLastError(null); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.info("微信审核回调跨环境转发成功,traceId={}, sourceEnv={}, targetEnv={}, hop=1", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv()); + } else { + markRetry(row, "目标环境返回异常状态"); + } + } catch (RuntimeException exception) { + markRetry(row, "目标环境不可达或请求失败"); + } + } + + private void markRetry(ModerationCallbackForwardDO row, String error) { + int retries = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1; + row.setRetryCount(retries); + row.setLastError(clip(error, 500)); + row.setStatus(retries >= MAX_RETRY ? STATUS_FAILED : STATUS_RETRY); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, retryCount={}, status={}", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv(), retries, row.getStatus()); + } + + private void markFailed(ModerationCallbackForwardDO row, String error, boolean retry) { + if (retry) { + markRetry(row, error); + return; + } + row.setStatus(STATUS_FAILED); + row.setLastError(clip(error, 500)); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, status=FAILED", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv()); + } + + private boolean backoffElapsed(ModerationCallbackForwardDO row, LocalDateTime now) { + if (row.getUpdatedAt() == null) return true; + long minutes = 1L << Math.min(Math.max(row.getRetryCount() == null ? 0 : row.getRetryCount(), 0), 5); + return !row.getUpdatedAt().plusMinutes(minutes).isAfter(now); + } + + 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 build(String traceId, String sourceEnv, String targetEnv, + String extraJson, String payload, String status, String error) { + LocalDateTime now = LocalDateTime.now(); + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setTraceId(clip(traceId, 128)); + row.setSourceEnv(clip(sourceEnv, 16)); + row.setTargetEnv(StringUtils.hasText(targetEnv) ? clip(targetEnv, 16) : null); + row.setExtraJson(clip(extraJson, 256)); + row.setPayload(payload); + row.setStatus(status); + row.setRetryCount(0); + row.setLastError(clip(error, 500)); + row.setCreatedAt(now); + row.setUpdatedAt(now); + return row; + } + + private boolean saveQuietly(ModerationCallbackForwardDO row) { + try { + forwardMapper.insert(row); + return true; + } catch (DuplicateKeyException exception) { + log.info("微信审核回调转发记录已存在,traceId={}", row.getTraceId()); + return false; + } + } + + private ModerationCallbackForwardDO findByTrace(String traceId) { + if (!StringUtils.hasText(traceId)) return null; + return forwardMapper.selectOne(new LambdaQueryWrapper() + .eq(ModerationCallbackForwardDO::getTraceId, traceId) + .last("LIMIT 1")); + } + + 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.setCreatedAt(row.getCreatedAt()); + vo.setUpdatedAt(row.getUpdatedAt()); + return vo; + } + + 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); + } + + @PreDestroy + public void shutdown() { + FORWARD_EXECUTOR.shutdownNow(); + } +} 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..6bd9dfd1 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java @@ -0,0 +1,35 @@ +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.Map; + +/** + * 跨环境审核回调转发客户端,固定 3 秒超时,失败以异常抛出由上层登记重试。 + */ +@Component +public class ModerationForwardHttpClient { + + private final RestTemplate restTemplate; + + public ModerationForwardHttpClient() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(3000); + factory.setReadTimeout(3000); + this.restTemplate = new RestTemplate(factory); + } + + public boolean post(String url, String body, Map headers) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + headers.forEach(httpHeaders::set); + ResponseEntity response = restTemplate.postForEntity(url, new HttpEntity<>(body, httpHeaders), String.class); + return response.getStatusCode().is2xxSuccessful(); + } +} 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 index f40efc2f..21c851fc 100644 --- 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 @@ -6,6 +6,7 @@ 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; @@ -31,6 +32,7 @@ import java.util.List; public class AdminSecureIntegrationConfigController { private final SecureIntegrationConfigService secureIntegrationConfigService; private final IntegrationProbeService integrationProbeService; + private final ContentModerationForwardService contentModerationForwardService; private final AdminScopeHelper adminScopeHelper; private final SecurityAuditSupport securityAuditSupport; @@ -40,6 +42,7 @@ public class AdminSecureIntegrationConfigController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); config.setProbeResults(integrationProbeService.listLatest(currentUser)); + config.setModerationForwardRecent(contentModerationForwardService.listRecent(10)); return Result.success(config); } @@ -82,6 +85,31 @@ public class AdminSecureIntegrationConfigController { } } + @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); + int requeued = contentModerationForwardService.requeueConfiguredTargets(); + if (requeued > 0) { + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "section=CONTENT_MODERATION_FORWARD,requeued=" + requeued); + } else { + 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) { 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 index 23c58956..4b162450 100644 --- 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 @@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.system.dto; import lombok.Data; +import java.util.Map; + @Data public class SecureIntegrationConfigDTO { private String mapProvider; @@ -19,4 +21,9 @@ public class SecureIntegrationConfigDTO { private String moderationEncodingAesKey; private Boolean clearModerationCallbackToken; private Boolean clearModerationEncodingAesKey; + + private Boolean moderationForwardEnabled; + private Map moderationForwardTargets; + private String moderationForwardSecret; + private Boolean clearModerationForwardSecret; } 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..5fb504a3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java @@ -0,0 +1,46 @@ +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; +} 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/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..47ecd003 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.springframework.util.StringUtils; + +import java.util.Collections; +import java.util.Map; + +@Data +@AllArgsConstructor +public class ModerationForwardConfig { + private boolean enabled; + private Map targets; + private String secret; + + public static ModerationForwardConfig disabled() { + return new ModerationForwardConfig(false, Collections.emptyMap(), ""); + } + + 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); + } +} 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 index 1fd7f59f..d574f5eb 100644 --- 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 @@ -1,6 +1,7 @@ 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; @@ -14,6 +15,10 @@ public interface SecureIntegrationConfigService { void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + ModerationForwardConfig getModerationForwardConfig(); + Map getMapRuntimeConfig(UserDO currentUser); ModerationRuntimeConfig getModerationRuntimeConfig(); 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 index a1930a6b..8d8af40f 100644 --- 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 @@ -1,6 +1,9 @@ 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; @@ -8,12 +11,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegration 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; @@ -22,10 +27,12 @@ import java.net.URI; import java.net.URISyntaxException; 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 { @@ -40,6 +47,7 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf private final SecureConfigEncryptionService encryptionService; private final ContentModerationProperties moderationProperties; private final WechatMiniProperties wechatMiniProperties; + private final ObjectMapper objectMapper; @Override @Transactional @@ -80,6 +88,12 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId()) ? wechatMiniProperties.getAppId() : ""); result.setMockProviderAllowed(isMockAllowed()); + + ModerationForwardConfig forwardConfig = getModerationForwardConfig(); + result.setModerationForwardEnabled(forwardConfig.isEnabled()); + result.setModerationForwardTargets(forwardConfig.getTargets()); + result.setModerationForwardSecretConfigured(StringUtils.hasText(forwardConfig.getSecret())); + result.setUpdatedAt(latestUpdateTime()); return result; } @@ -163,6 +177,77 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf 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 仅允许内网主机"); + } + } + + 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("启用跨环境回调转发时至少需要配置一个目标环境地址"); + } + } + + Map payload = new LinkedHashMap<>(); + payload.put("enabled", enabled); + payload.put("targets", targets); + payload.put("secret", secret); + try { + writeValue(MODERATION, "FORWARD_JSON", 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_JSON", ""); + 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("")); + } + }); + } + return new ModerationForwardConfig(enabled, targets, node.path("secret").asText("")); + } catch (JsonProcessingException exception) { + log.warn("跨环境转发配置解析失败,按未启用处理"); + return ModerationForwardConfig.disabled(); + } + } + @Override @Transactional public Map getMapRuntimeConfig(UserDO currentUser) { @@ -362,6 +447,62 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf } } + 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; + } + + /** + * 只允许指向内容审核回调路径: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"); } 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..227be6bf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java @@ -0,0 +1,18 @@ +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; + 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 index d8c3d72d..2500683c 100644 --- 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 @@ -4,6 +4,7 @@ import lombok.Data; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; @Data public class SecureIntegrationConfigVO { @@ -24,6 +25,11 @@ public class SecureIntegrationConfigVO { private String wechatMiniAppId; private Boolean mockProviderAllowed; + private Boolean moderationForwardEnabled; + private Map moderationForwardTargets; + private Boolean moderationForwardSecretConfigured; + private List moderationForwardRecent; + private Boolean encryptionKeyConfigured; private LocalDateTime updatedAt; /** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */ 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/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 index 6b91d189..7e34bb01 100644 --- 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 @@ -1,45 +1,51 @@ 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.ModerationForwardConfig; 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 org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.junit.jupiter.api.Test; + +import java.util.Map; 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.mock; +import static org.mockito.Mockito.never; +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; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; 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/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); - WechatMiniProperties wechatProperties = new WechatMiniProperties(); - wechatProperties.setAppId("mini-app-id"); + 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 = new WechatContentModerationCallbackController( - secureConfig, - wechatProperties, - crypto, - mock(ContentModerationService.class), - mock(IntegrationProbeService.class), - new ObjectMapper()); + 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"); @@ -52,31 +58,31 @@ class WechatContentModerationCallbackControllerTest { void plaintextHandshakeStillUsesPlainSignature() { SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); when(secureConfig.getModerationCallbackConfig()).thenReturn( - new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); + 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 = new WechatContentModerationCallbackController( - secureConfig, - new WechatMiniProperties(), - crypto, - mock(ContentModerationService.class), - mock(IntegrationProbeService.class), - new ObjectMapper()); + WechatMiniProperties wechatProperties = new WechatMiniProperties(); + wechatProperties.setAppId("mini-app-id"); + 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 acceptsJsonEnvelopeForAesEncryptedCallback() throws Exception { + void localHitDoesNotForward() throws Exception { SecureIntegrationConfigService secureConfig = readyWechatConfig(); WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); ContentModerationService moderationService = mock(ContentModerationService.class); - when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")) - .thenReturn(true); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true); when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")) - .thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}"); - MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build(); + .thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"envVersion\\\":\\\"trial\\\"}\"}"); + when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), forwardService)).build(); mvc.perform(post("/integration/wechat/content-moderation/callback") .param("timestamp", "1000") @@ -90,6 +96,8 @@ class WechatContentModerationCallbackControllerTest { verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature"); verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial"); + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + verify(forwardService, never()).recordUnclaimed(anyString(), any(), any(), anyString()); } @Test @@ -99,14 +107,15 @@ class WechatContentModerationCallbackControllerTest { ContentModerationService moderationService = mock(ContentModerationService.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{"envVersion":"release"}"; + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true); + String decodedXml = "task-xmlreview{"env":"prod","envVersion":"release"}"; when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml); when(crypto.value(decodedXml, "trace_id")).thenReturn("task-xml"); when(crypto.value(decodedXml, "suggest")).thenReturn("review"); - when(crypto.value(decodedXml, "extra")).thenReturn("{\"envVersion\":\"release\"}"); - MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build(); + when(crypto.value(decodedXml, "extra")).thenReturn("{\"env\":\"prod\",\"envVersion\":\"release\"}"); + when(moderationService.handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), mock(ContentModerationForwardService.class))).build(); mvc.perform(post("/integration/wechat/content-moderation/callback") .param("timestamp", "1000") @@ -122,19 +131,170 @@ class WechatContentModerationCallbackControllerTest { verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release"); } + @Test + void probeHitSkipsModerationAndForwarding() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + IntegrationProbeService probeService = mock(IntegrationProbeService.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true); + when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")) + .thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"probeId\\\":\\\"probe-1\\\"}\"}"); + when(probeService.handleImageCallback("probe-1", "review", "probe-1")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, + mock(ContentModerationService.class), probeService, 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")); + + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + } + + @Test + void otherEnvironmentCallbackIsEnqueuedAndReturnsSuccessImmediately() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationService moderationService = mock(ContentModerationService.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-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}"); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false); + when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH))); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + 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")); + + verify(forwardService).enqueue(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString()); + } + + @Test + void missingTargetReturnsSuccessAndRecordsTargetMissing() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationService moderationService = mock(ContentModerationService.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-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}"); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false); + when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of())); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + 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")); + + verify(forwardService).recordTargetMissing(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString()); + } + + @Test + void extraWithoutEnvIsRecordedAsNoEnvAndNotForwarded() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationService moderationService = mock(ContentModerationService.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-unknown\",\"suggest\":\"review\",\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}"); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false); + when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH))); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + 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")); + + verify(forwardService).recordUnclaimed(eq("task-unknown"), anyString(), anyString(), anyString()); + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + } + + @Test + void secondHopOrSelfForwardIsDroppedAndRecorded() throws Exception { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + 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", "sit") + .header("X-Moderation-Forward-Hop", "2") + .header("X-Timestamp", "1000") + .header("X-Nonce", "forward-nonce") + .header("X-Signature", "forward-signature") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"trace_id\":\"loop-task\",\"suggest\":\"review\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService).recordUnclaimed(eq("loop-task"), any(), anyString(), anyString()); + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + } + + @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\"}")); + } + + private ModerationForwardConfig forwardConfig(Map targets) { + return new ModerationForwardConfig(true, targets, "forward-secret-key-01"); + } + private SecureIntegrationConfigService readyWechatConfig() { SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); when(secureConfig.getModerationCallbackConfig()).thenReturn( - new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); + 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) { + ContentModerationService moderationService, + IntegrationProbeService probeService, + ContentModerationForwardService forwardService) { WechatMiniProperties wechatProperties = new WechatMiniProperties(); wechatProperties.setAppId("mini-app-id"); - return new WechatContentModerationCallbackController( - secureConfig, wechatProperties, crypto, moderationService, mock(IntegrationProbeService.class), new ObjectMapper()); + 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/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..4e0a40a1 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java @@ -0,0 +1,172 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient; +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.SecureIntegrationConfigService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ContentModerationForwardServiceImplTest { + private static final String SECRET = "forward-secret-key-01"; + private static final String TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback"; + + private ModerationCallbackForwardMapper forwardMapper; + private SecureIntegrationConfigService secureConfig; + private ModerationForwardHttpClient httpClient; + private RedisTemplate redisTemplate; + private ValueOperations valueOperations; + private ContentModerationForwardServiceImpl service; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + forwardMapper = mock(ModerationCallbackForwardMapper.class); + secureConfig = mock(SecureIntegrationConfigService.class); + httpClient = mock(ModerationForwardHttpClient.class); + redisTemplate = mock(RedisTemplate.class); + valueOperations = mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(true); + when(secureConfig.getModerationForwardConfig()) + .thenReturn(new ModerationForwardConfig(true, Map.of("prod", TARGET), SECRET)); + SalonDeployProperties deployProperties = new SalonDeployProperties(); + deployProperties.setEnv("sit"); + service = new ContentModerationForwardServiceImpl(forwardMapper, secureConfig, deployProperties, + redisTemplate, httpClient); + } + + @Test + void acceptsValidHmacSignature() throws Exception { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String nonce = "nonce-valid"; + String body = "{\"trace_id\":\"task-1\"}"; + String signature = sign(SECRET, timestamp, nonce, body); + + assertTrue(service.verifySignature(timestamp, nonce, signature, body)); + } + + @Test + void rejectsInvalidHmacSignature() { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + + assertFalse(service.verifySignature(timestamp, "nonce-bad", "deadbeef", "{\"trace_id\":\"task-1\"}")); + } + + @Test + void rejectsExpiredTimestamp() { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600); + + assertFalse(service.verifySignature(timestamp, "nonce-expired", "deadbeef", "{}")); + } + + @Test + void retryPendingMarksSuccessWhenTargetAccepts() { + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setId(11L); + row.setTraceId("task-retry"); + row.setSourceEnv("sit"); + row.setTargetEnv("prod"); + row.setStatus("RETRY"); + row.setRetryCount(1); + row.setUpdatedAt(LocalDateTime.now().minusMinutes(5)); + row.setPayload("{\"trace_id\":\"task-retry\"}"); + when(forwardMapper.selectList(any())).thenReturn(List.of(row)); + when(forwardMapper.selectById(11L)).thenReturn(row); + when(httpClient.post(anyString(), anyString(), any())).thenReturn(true); + + int attempted = service.retryPending(); + + assertEquals(1, attempted); + assertEquals("SUCCESS", row.getStatus()); + verify(forwardMapper).updateById(row); + } + + @Test + void retryFailureIncrementsCountAndKeepsRetry() { + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setId(12L); + row.setTraceId("task-fail"); + row.setSourceEnv("sit"); + row.setTargetEnv("prod"); + row.setStatus("RETRY"); + row.setRetryCount(0); + row.setUpdatedAt(null); + row.setPayload("{\"trace_id\":\"task-fail\"}"); + when(forwardMapper.selectList(any())).thenReturn(List.of(row)); + when(forwardMapper.selectById(12L)).thenReturn(row); + when(httpClient.post(anyString(), anyString(), any())).thenThrow(new IllegalStateException("timeout")); + + service.retryPending(); + + assertEquals("RETRY", row.getStatus()); + assertEquals(1, row.getRetryCount()); + assertEquals("目标环境不可达或请求失败", row.getLastError()); + } + + @Test + void targetMissingIsRecordedWithoutRetryQueue() { + service.recordTargetMissing("task-missing", "sit", "prod", "{\"env\":\"prod\"}", "{}"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class); + verify(forwardMapper).insert(captor.capture()); + ModerationCallbackForwardDO saved = captor.getValue(); + assertEquals("TARGET_MISSING", saved.getStatus()); + assertEquals("prod", saved.getTargetEnv()); + assertEquals(0, saved.getRetryCount()); + } + + @Test + void missingExtraIsRecordedAsNoEnv() { + service.recordUnclaimed("task-noenv", "{\"envVersion\":\"trial\"}", "{}", "回调 extra 缺少部署环境标识"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class); + verify(forwardMapper).insert(captor.capture()); + assertEquals("NO_ENV", captor.getValue().getStatus()); + assertEquals("sit", captor.getValue().getSourceEnv()); + } + + @Test + void requeueMovesTargetMissingToRetryForConfiguredTargets() { + when(forwardMapper.update(any(), any())).thenReturn(2); + + int requeued = service.requeueConfiguredTargets(); + + assertEquals(2, requeued); + verify(forwardMapper).update(org.mockito.ArgumentMatchers.isNull(), any()); + } + + private String sign(String secret, String timestamp, String nonce, String body) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + StringBuilder bodyHash = new StringBuilder(); + for (byte item : digest.digest(body.getBytes(StandardCharsets.UTF_8))) bodyHash.append(String.format("%02x", item)); + String canonical = timestamp + "\n" + nonce + "\n" + bodyHash; + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + StringBuilder result = new StringBuilder(); + for (byte item : mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))) result.append(String.format("%02x", item)); + return result.toString(); + } +} 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 index 2c0b7300..9fb0e17d 100644 --- 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 @@ -116,7 +116,7 @@ class SecureIntegrationConfigServiceImplTest { currentUser.setType(2); SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), - new ContentModerationProperties(), configuredWechat()); + new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper()); assertThrows(RuntimeException.class, () -> service.getMapRuntimeConfig(currentUser)); verify(mapper, never()).selectOne(any()); @@ -131,7 +131,7 @@ class SecureIntegrationConfigServiceImplTest { UserDO currentUser = adminUser(); SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), - new ContentModerationProperties(), configuredWechat()); + new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper()); assertEquals("false", service.getMapRuntimeConfig(currentUser).get("enabled")); verify(mapper, org.mockito.Mockito.atLeastOnce()).selectOne(any()); @@ -142,7 +142,7 @@ class SecureIntegrationConfigServiceImplTest { ContentModerationProperties moderationProperties, WechatMiniProperties wechatProperties) { return new SecureIntegrationConfigServiceImpl(mapper, mock(SystemParameterConfigMapper.class), encryption, - moderationProperties, wechatProperties); + moderationProperties, wechatProperties, new com.fasterxml.jackson.databind.ObjectMapper()); } private UserDO adminUser() { 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 index 0cdf5079..faaefecf 100644 --- 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 @@ -132,7 +132,8 @@ class IntegrationProbeServiceImplTest { .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()); + new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(), + deployProperties()); provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial"); @@ -149,7 +150,8 @@ class IntegrationProbeServiceImplTest { .thenReturn("{\"errcode\":47001}"); WechatContentModerationProvider provider = new WechatContentModerationProvider( restTemplate, new ObjectMapper(), wechatClient, - new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); + new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(), + deployProperties()); var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial"); @@ -157,6 +159,13 @@ class IntegrationProbeServiceImplTest { assertEquals("微信审核请求参数格式无效,请核对接口字段", result.reason()); } + private com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties deployProperties() { + com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties properties = + new com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties(); + properties.setEnv("sit"); + return properties; + } + private UserDO admin() { UserDO user = new UserDO(); user.setId(1L); diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 76b23ebe..f73b6e67 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -1594,11 +1594,27 @@ export interface SecureIntegrationConfigVO { wechatMiniAppConfigured: boolean wechatMiniAppId: string mockProviderAllowed: boolean + moderationForwardEnabled?: boolean + moderationForwardTargets?: Record + moderationForwardSecretConfigured?: boolean + moderationForwardRecent?: ModerationForwardRecordVO[] encryptionKeyConfigured: boolean updatedAt?: string probeResults?: IntegrationProbeResultVO[] } +export interface ModerationForwardRecordVO { + id: IdType + traceId: string + sourceEnv?: string + targetEnv?: string + status: 'PENDING' | 'SUCCESS' | 'RETRY' | 'FAILED' | 'NO_ENV' | 'TARGET_MISSING' | string + retryCount?: number + lastError?: string + createdAt?: string + updatedAt?: string +} + export interface IntegrationProbeCheckVO { name: string status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' @@ -1640,6 +1656,10 @@ export interface SecureIntegrationConfigUpdate { moderationEncodingAesKey?: string clearModerationCallbackToken?: boolean clearModerationEncodingAesKey?: boolean + moderationForwardEnabled?: boolean + moderationForwardTargets?: Record + moderationForwardSecret?: string + clearModerationForwardSecret?: boolean } /** @@ -1664,7 +1684,8 @@ export const adminSecureIntegrationConfigApi = { 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 + 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 { diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index d205d878..16eeafa5 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -306,6 +306,61 @@ 回调资料仍不完整,暂时不能进行微信 URL 验证。 安全接入加密主密钥尚未配置,Token 与 AESKey 不会保存。
+ +
+
+
+ 跨环境回调转发 + CROSS ENV +

微信只向一个环境推送异步图片审核结果;命中不到本地任务时,按回调 extra 中的部署环境标识转发到真正创建任务的环境。默认关闭。

+
+ 保存转发设置 +
+
+
+
启用跨环境转发
+

关闭时未命中本地任务的回调只记录不转发。

+
+
+ {{ moderationForwardEnabled ? '已启用' : '未启用' }} +
+
+
+
共享密钥
+

16-128 位,仅用于服务端 HMAC-SHA256 转发验签,不写日志;各环境需配置相同密钥。

+
+ + {{ clearModerationForwardSecret ? '撤销清除' : '清除' }} +
+
+ {{ clearModerationForwardSecret ? '保存后清除' : secureStatus?.moderationForwardSecretConfigured ? '已配置' : '待配置' }} +
+
+
+
{{ env.label }}回调地址
+

必须精确指向 /api/integration/wechat/content-moderation/callback;HTTP 仅允许内网主机。

+
+ +
+
+
+
+
+ 最近转发结果 + NO_ENV / TARGET_MISSING 不自动重试,补齐配置或人工处理后可重放。 +
+
暂无转发记录
+
    +
  • + {{ forwardStatusLabel(item.status) }} + {{ item.sourceEnv || '-' }} → {{ item.targetEnv || '-' }} + {{ item.traceId }} + {{ formatProbeTime(item.createdAt) }} + {{ item.lastError }} +
  • +
+
+
@@ -473,6 +528,16 @@ const moderationProvider = ref<'DISABLED' | 'MOCK' | 'WECHAT'>('DISABLED') const moderationCallbackUrl = ref('') const moderationSecrets = reactive({ callbackToken: '', encodingAesKey: '' }) const clearModerationSecrets = reactive({ callbackToken: false, encodingAesKey: false }) +const moderationForwardEnabled = ref(false) +const moderationForwardTargets = reactive>({ dev: '', sit: '', prod: '' }) +const moderationForwardSecret = ref('') +const clearModerationForwardSecret = ref(false) +const savingModerationForward = ref(false) +const forwardEnvTargets = [ + { key: 'dev' as const, label: 'DEV' }, + { key: 'sit' as const, label: 'SIT' }, + { key: 'prod' as const, label: 'PROD' } +] const smsProviderOptions = [ { label: 'Spug 短信', value: 'SPUG' }, { label: '阿里云短信认证服务', value: 'ALIYUN_SMS_VERIFY' } @@ -630,6 +695,12 @@ const load = async () => { mapEnabled.value = Boolean(secureConfig.mapEnabled) moderationProvider.value = secureConfig.moderationProvider || 'DISABLED' moderationCallbackUrl.value = secureConfig.moderationCallbackUrl || defaultCallbackUrl() + moderationForwardEnabled.value = Boolean(secureConfig.moderationForwardEnabled) + moderationForwardTargets.dev = secureConfig.moderationForwardTargets?.dev || '' + moderationForwardTargets.sit = secureConfig.moderationForwardTargets?.sit || '' + moderationForwardTargets.prod = secureConfig.moderationForwardTargets?.prod || '' + moderationForwardSecret.value = '' + clearModerationForwardSecret.value = false mapSecrets.tencentWeb = '' mapSecrets.amapWeb = '' mapSecrets.amapMini = '' @@ -955,6 +1026,46 @@ const saveModerationConfig = async () => { } } +const forwardStatusLabel = (status?: string) => ({ + PENDING: '待转发', SUCCESS: '已转发', RETRY: '待重试', FAILED: '失败', + NO_ENV: '无法认领', TARGET_MISSING: '目标未配置' +} as Record)[status || ''] || '未知' + +const saveModerationForwardConfig = async () => { + if (moderationForwardSecret.value && !/^[A-Za-z0-9+/=_\-]{16,128}$/.test(moderationForwardSecret.value)) { + message.warning('共享密钥需要为 16-128 位字母、数字或常用符号') + return + } + if (moderationForwardEnabled.value) { + const hasSecret = moderationForwardSecret.value.trim() + || (secureStatus.value?.moderationForwardSecretConfigured && !clearModerationForwardSecret.value) + if (!hasSecret) { + message.warning('启用跨环境转发前,请填写共享密钥') + return + } + if (!Object.values(moderationForwardTargets).some(value => value.trim())) { + message.warning('启用跨环境转发前,至少填写一个目标环境地址') + return + } + } + savingModerationForward.value = true + try { + secureStatus.value = await adminSecureIntegrationConfigApi.saveModerationForwardConfig({ + moderationForwardEnabled: moderationForwardEnabled.value, + moderationForwardTargets: { ...moderationForwardTargets }, + moderationForwardSecret: moderationForwardSecret.value, + clearModerationForwardSecret: clearModerationForwardSecret.value + }) + moderationForwardSecret.value = '' + clearModerationForwardSecret.value = false + message.success('跨环境转发设置已保存') + } catch (error) { + message.error(error instanceof Error ? error.message : '跨环境转发设置保存失败') + } finally { + savingModerationForward.value = false + } +} + const toggleMapSecretClear = (key: MapKey) => { clearMapSecrets[key] = !clearMapSecrets[key] } const toggleModerationSecretClear = (key: 'callbackToken' | 'encodingAesKey') => { clearModerationSecrets[key] = !clearModerationSecrets[key] } @@ -1174,5 +1285,59 @@ onMounted(() => { .svc__desc { white-space: normal; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; } .field__save { margin-left: 0; } } +.settings-subsection { + margin-top: 18px; + padding-top: 16px; + border-top: 1px dashed var(--border-color, #e5e7eb); +} +.settings-subsection__head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; +} +.settings-subsection__head strong { font-size: 14px; } +.settings-subsection__head .tag { margin-left: 8px; } +.settings-subsection__head p { margin: 4px 0 0; } +.forward-recent { margin-top: 14px; } +.forward-recent__head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 10px; + margin-bottom: 8px; +} +.forward-recent__list { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} +.forward-recent__list li { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 7px 10px; + border: 1px solid var(--border-color, #e5e7eb); + border-radius: 8px; + font-size: 12px; +} +.forward-recent__trace { + flex: 1 1 180px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; +} +.forward-recent__time { color: var(--text-color-secondary, #6b7280); } +.forward-recent__error { color: var(--danger-color, #c0392b); } +@media (max-width: 760px) { + .settings-subsection__head { flex-direction: column; align-items: stretch; } +} diff --git a/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml index fa31fa5e..b6fb9761 100644 --- a/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -38,6 +38,9 @@ mybatis: map-underscore-to-camel-case: true jayucloud-salon: + deploy: + # 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败 + env: dev wechat: mini: app-id: wxb6d77f7c07020d51 diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml index 1fb6193b..994885d0 100644 --- a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -37,6 +37,9 @@ mybatis: map-underscore-to-camel-case: true jayucloud-salon: + deploy: + # 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败 + env: prod wechat: mini: app-id: wxb6d77f7c07020d51 diff --git a/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml index 7db07310..1a2e2db1 100644 --- a/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -37,6 +37,9 @@ mybatis: map-underscore-to-camel-case: true jayucloud-salon: + deploy: + # 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败 + env: sit wechat: mini: app-id: wxb6d77f7c07020d51 From 114a8a423ca4bafde3e6695a8fa93ed5dfab17ba Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 23:26:14 +0800 Subject: [PATCH 109/165] =?UTF-8?q?fix:=20=E8=B7=A8=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E8=BD=AC=E5=8F=91=E9=85=8D=E7=BD=AE=E9=A1=B9=E6=8C=89=20CONTEN?= =?UTF-8?q?T=5FMODERATION=5FFORWARD=20=E5=91=BD=E5=90=8D=E8=90=BD=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/SecureIntegrationConfigServiceImpl.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 index 8d8af40f..bb17b8bd 100644 --- 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 @@ -38,6 +38,7 @@ import java.util.Map; 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"; @@ -218,7 +219,7 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf payload.put("targets", targets); payload.put("secret", secret); try { - writeValue(MODERATION, "FORWARD_JSON", objectMapper.writeValueAsString(payload), true, currentUser.getId()); + writeValue(MODERATION_FORWARD, "CONFIG", objectMapper.writeValueAsString(payload), true, currentUser.getId()); } catch (JsonProcessingException exception) { throw new IllegalStateException("无法保存跨环境转发配置", exception); } @@ -227,7 +228,7 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf @Override public ModerationForwardConfig getModerationForwardConfig() { if (!encryptionService.isConfigured()) return ModerationForwardConfig.disabled(); - String json = readValue(MODERATION, "FORWARD_JSON", ""); + String json = readValue(MODERATION_FORWARD, "CONFIG", ""); if (!StringUtils.hasText(json)) return ModerationForwardConfig.disabled(); try { JsonNode node = objectMapper.readTree(json); From 88589e25753a248c71166d5bca9d97e22f034c9a Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 23:38:42 +0800 Subject: [PATCH 110/165] =?UTF-8?q?feat(salon):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=95=A3=E5=AE=A2=E9=A2=84=E7=BA=A6=E6=8B=A8=E5=8F=B7=E5=B9=B6?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E5=8D=8F=E8=AE=AE=E6=96=B0=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=BC=BA=E5=88=B6=E9=87=8D=E6=96=B0=E5=90=8C=E6=84=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../salon/core/config/WebMvcConfig.java | 2 + .../admin/AdminManagerController.java | 17 ++- .../dial/DirectDialTargetProvider.java | 19 ++- .../privacy/service/CustomerDialService.java | 2 +- .../service/impl/CustomerDialServiceImpl.java | 69 ++++++++-- .../front/LegalAgreementController.java | 22 +++ .../system/service/LegalAgreementService.java | 5 + .../impl/LegalAgreementServiceImpl.java | 54 ++++++++ .../modules/system/vo/AgreementPendingVO.java | 25 ++++ ..._隐私政策与用户协议新版本发布_20261104.sql | 30 ++++ .../impl/CustomerDialServiceImplTest.java | 103 ++++++++++++-- .../impl/LegalAgreementServiceImplTest.java | 130 ++++++++++++++++++ JC-Salon-Frontend/src/api/auth.ts | 15 ++ JC-Salon-Frontend/src/api/index.ts | 21 ++- JC-Salon-Frontend/src/api/user.ts | 10 +- JC-Salon-Frontend/src/utils/agreement-gate.ts | 11 ++ .../src/views/ArtistOrderView.vue | 11 +- .../src/views/admin/AdminLayout.vue | 74 ++++++++++ JC-Salon-WeChat/api/customers.js | 13 +- .../pages/appointment-detail/index.js | 8 +- .../pages/appointment-detail/index.test.js | 3 + .../pages/appointment-detail/index.wxml | 2 +- 22 files changed, 602 insertions(+), 44 deletions(-) create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java create mode 100644 JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java create mode 100644 JC-Salon-Frontend/src/utils/agreement-gate.ts 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 64d4bb98..623b0e2e 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 @@ -55,8 +55,10 @@ public class WebMvcConfig implements WebMvcConfigurer { "/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/**", 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 1703a4a2..422210bf 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 @@ -188,10 +188,23 @@ public class AdminManagerController { public Result dialCustomer(HttpServletRequest request, HttpServletResponse response, @PathVariable Long customerId, - @RequestParam Long orderId) { + @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, orderId, request)); + 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}") 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 index 0b1fd44d..56e57e9b 100644 --- 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 @@ -15,6 +15,10 @@ import org.springframework.util.StringUtils; @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 @@ -26,12 +30,22 @@ public class DirectDialTargetProvider implements DialTargetProvider { public DialTarget resolve(UserDO customer, OrderDO order) { String plainPhone = resolvePlainPhone(customer, order); if (!StringUtils.hasText(plainPhone) || plainPhone.contains("*")) { - throw new BusinessException(422, "该客户未登记可拨打的手机号"); + 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()); @@ -46,9 +60,6 @@ public class DirectDialTargetProvider implements DialTargetProvider { } } } - if (order != null && StringUtils.hasText(order.getCustomerPhoneSnapshot())) { - return phoneCrypto.decrypt(order.getCustomerPhoneSnapshot()); - } return null; } } 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 index bd2db693..16a840cb 100644 --- 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 @@ -10,5 +10,5 @@ import javax.servlet.http.HttpServletRequest; */ public interface CustomerDialService { - CustomerDialVO dial(UserDO currentUser, Long customerId, Long orderId, HttpServletRequest request); + 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/CustomerDialServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java index abf0ec56..f70423a6 100644 --- 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 @@ -2,6 +2,8 @@ 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; @@ -34,33 +36,56 @@ public class CustomerDialServiceImpl implements CustomerDialService { 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 orderId, HttpServletRequest request) { + 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()); - UserDO customer = userService.getById(customerId); - if (customer == null || Objects.equals(1, customer.getIsDelete()) || !Objects.equals(0, customer.getType())) { - throw new BusinessException(404, "客户不存在"); + if (customerId == null && appointmentId == null && orderId == null) { + throw new BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)"); } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, customerId, "无权拨打其他店铺客户"); - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Objects.equals(1, order.getIsDelete()) || !Objects.equals(customerId, order.getUserId())) { - throw new BusinessException(403, "该客户与订单不匹配,或无权拨打"); + 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 (!Objects.equals(currentShopId, order.getShopId())) { - throw new BusinessException(403, "无权拨打其他店铺订单客户"); + 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=" + customerId + ";orderId=" + orderId + ";provider=" + provider.providerKey(); + 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"); @@ -80,6 +105,28 @@ public class CustomerDialServiceImpl implements CustomerDialService { } } + /** + * 解析目标客户:优先使用显式 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() 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..9452992a 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 @@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementSe 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; @@ -68,6 +69,27 @@ 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); + 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/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/impl/LegalAgreementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java index dff0a9ed..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. 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/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/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 index a3e11b63..d9c89eb0 100644 --- 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 @@ -2,6 +2,8 @@ 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; @@ -26,7 +28,7 @@ import java.util.List; 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.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; @@ -38,6 +40,7 @@ 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; @@ -54,7 +57,7 @@ class CustomerDialServiceImplTest { List providers = List.of( new DirectDialTargetProvider(phoneCrypto), new PlaceholderPrivacyNumberProvider()); - service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, orderItemMapper, requestThrottleService, securityAuditSupport, properties, providers); currentUser = new UserDO(); @@ -81,7 +84,7 @@ class CustomerDialServiceImplTest { when(userService.getById(100L)).thenReturn(customer); when(orderMapper.selectById(10L)).thenReturn(order); - CustomerDialVO result = service.dial(currentUser, 100L, 10L, request); + CustomerDialVO result = service.dial(currentUser, 100L, null, 10L, request); assertEquals(DialMode.DIRECT, result.getMode()); assertEquals("13800138000", result.getDialNumber()); @@ -90,13 +93,94 @@ class CustomerDialServiceImplTest { } @Test - void rejectsOrderOfAnotherShop() { - order.setShopId(2L); + 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, 100L, 10L, request)); + () -> 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()); } @@ -104,18 +188,17 @@ class CustomerDialServiceImplTest { @Test void rejectsOrderThatDoesNotBelongToCustomer() { order.setUserId(101L); - when(userService.getById(100L)).thenReturn(customer); when(orderMapper.selectById(10L)).thenReturn(order); BusinessException error = assertThrows(BusinessException.class, - () -> service.dial(currentUser, 100L, 10L, request)); + () -> service.dial(currentUser, 100L, null, 10L, request)); assertEquals(403, error.getCode()); } @Test void privacyNumberProviderReportsNotConfiguredWithoutFallingBackToRealNumber() { - service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, orderItemMapper, requestThrottleService, securityAuditSupport, privacyProperties(), List.of( new DirectDialTargetProvider(phoneCrypto), new PlaceholderPrivacyNumberProvider())); @@ -124,7 +207,7 @@ class CustomerDialServiceImplTest { when(orderMapper.selectById(10L)).thenReturn(order); BusinessException error = assertThrows(BusinessException.class, - () -> service.dial(currentUser, 100L, 10L, request)); + () -> service.dial(currentUser, 100L, null, 10L, request)); assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, error.getCode()); verify(securityAuditSupport).fail(eq(request), anyString(), anyString()); 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-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/index.ts b/JC-Salon-Frontend/src/api/index.ts index f4f0731a..45f093da 100644 --- a/JC-Salon-Frontend/src/api/index.ts +++ b/JC-Salon-Frontend/src/api/index.ts @@ -11,6 +11,7 @@ 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 { isAgreementPending } from '../utils/agreement-gate' import { getApiResponseMessage, isPermissionErrorMessage, @@ -77,6 +78,18 @@ 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'] + /** * 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. @@ -238,7 +251,11 @@ 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/') + if (isAgreementPending() && !AGREEMENT_GATE_ALLOWLIST.some(path => config.url?.includes(path))) { + return Promise.reject(new Error('请先阅读并同意最新版用户协议与隐私政策')) + } + + const isAdminRequest = isAdminScopedUrl(config.url) let token = isAdminRequest ? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) @@ -286,7 +303,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) diff --git a/JC-Salon-Frontend/src/api/user.ts b/JC-Salon-Frontend/src/api/user.ts index 0bc9418e..b8e70888 100644 --- a/JC-Salon-Frontend/src/api/user.ts +++ b/JC-Salon-Frontend/src/api/user.ts @@ -278,9 +278,13 @@ export const userApi = { /** * 后台管理员按预约/订单上下文单次取号,号码不入库、不缓存。 */ - dialCustomer: async (customerId: IdType, orderId: IdType): Promise => { - return await api.post(`/manager/customers/${customerId}/dial`, null, { - params: { orderId } + 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 => { diff --git a/JC-Salon-Frontend/src/utils/agreement-gate.ts b/JC-Salon-Frontend/src/utils/agreement-gate.ts new file mode 100644 index 00000000..90a1f9df --- /dev/null +++ b/JC-Salon-Frontend/src/utils/agreement-gate.ts @@ -0,0 +1,11 @@ +/** + * 协议同意门禁状态:登录后检测到未同意的新版本时置位, + * 请求层据此拦截非协议类业务请求,避免用户绕过弹层继续操作。 + */ +let agreementPending = false + +export const setAgreementPending = (value: boolean) => { + agreementPending = value +} + +export const isAgreementPending = () => agreementPending diff --git a/JC-Salon-Frontend/src/views/ArtistOrderView.vue b/JC-Salon-Frontend/src/views/ArtistOrderView.vue index c990f035..f23465be 100644 --- a/JC-Salon-Frontend/src/views/ArtistOrderView.vue +++ b/JC-Salon-Frontend/src/views/ArtistOrderView.vue @@ -68,7 +68,7 @@ 预约用户:{{ order.customerNickname || '用户' }} 联系电话:{{ order.customerPhoneMasked }} { } } -/** 按订单上下文单次取号后发起拨号,号码不落库、不缓存。 */ +/** 按订单上下文单次取号后发起拨号,号码不落库、不缓存;散客无 userId 时仅用订单定位。 */ const dialCustomer = async (order: any) => { - if (!order?.userId || !order?.id) { + if (!order?.id) { message.warning('缺少订单上下文,无法取号') return } dialingOrderId.value = order.id try { - const result = await userApi.dialCustomer(order.userId, order.id) + const result = await userApi.dialCustomer({ + customerId: order.userId || undefined, + orderId: order.id + }) if (!result?.dialNumber) { throw new Error('未获取到可拨打号码') } diff --git a/JC-Salon-Frontend/src/views/admin/AdminLayout.vue b/JC-Salon-Frontend/src/views/admin/AdminLayout.vue index 000e6a46..544d7a36 100644 --- a/JC-Salon-Frontend/src/views/admin/AdminLayout.vue +++ b/JC-Salon-Frontend/src/views/admin/AdminLayout.vue @@ -70,6 +70,25 @@
+ + +
+

新版本{{ agreementVersionText ? `(${agreementVersionText})` : '' }}已发布,请阅读并同意后继续使用后台。

+ + 同意并继续 +
+
@@ -84,6 +103,8 @@ import { DEFAULT_AVATAR } from '@/constants' import { completeAdminLogout } from '@/utils/admin-logout' import { runWithGlobalLoading } from '@/utils/action-loading' import { useAdminViewport } from '@/composables/useAdminViewport' +import { legalAgreementApi, type AgreementPending } from '@/api/auth' +import { setAgreementPending } from '@/utils/agreement-gate' const router = useRouter() const route = useRoute() @@ -92,6 +113,9 @@ const collapsed = ref(false) const mobileDrawerOpen = ref(false) const selectedKeys = ref([route.path]) const userInfo = ref(null) +const agreementModalOpen = ref(false) +const agreementAccepting = ref(false) +const agreementVersionText = ref('') const iconMap: Record = { home: HomeOutlined, user: UserOutlined, shop: HomeOutlined, security: SafetyCertificateOutlined, tool: ToolOutlined, team: TeamOutlined, dashboard: HomeOutlined, gift: HomeOutlined, message: HomeOutlined, tag: HomeOutlined, shopping: HomeOutlined, calendar: HomeOutlined } const menuItems = adminNavigationItems.map(item => ({ key: item.path, label: item.label, icon: iconMap[item.iconKey] })) @@ -99,9 +123,43 @@ const handleMenuClick = ({ key }: { key: string | number }) => router.push(Strin const openMobileMenu = ({ key }: { key: string | number }) => { mobileDrawerOpen.value = false; router.push(String(key)) } const handleLogout = () => Modal.confirm({ title: '确认退出登录', content: '退出后需要重新登录后台。', okText: '确认', cancelText: '取消', onOk: async () => { await runWithGlobalLoading(() => completeAdminLogout(router)); message.success('已退出登录') } }) +const checkAgreementGate = async () => { + try { + const result = await legalAgreementApi.getPending() as unknown as AgreementPending + if (result?.pending) { + agreementVersionText.value = result.currentVersions?.USER_TERMS || '' + setAgreementPending(true) + agreementModalOpen.value = true + } else { + setAgreementPending(false) + } + } catch (error) { + // 查询失败不阻塞后台使用,协议接口仍由服务端登录态校验保护 + } +} + +const acceptAgreements = async () => { + if (agreementAccepting.value) return + agreementAccepting.value = true + try { + const result = await legalAgreementApi.accept('WEB') as unknown as AgreementPending + if (result?.pending === true) { + throw new Error('协议同意状态未更新,请稍后重试') + } + setAgreementPending(false) + agreementModalOpen.value = false + message.success('已同意最新版协议') + } catch (error: any) { + message.error(error?.message || '同意协议失败') + } finally { + agreementAccepting.value = false + } +} + watch(() => route.path, path => { selectedKeys.value = [path] }, { immediate: true }) onMounted(() => { try { userInfo.value = JSON.parse(localStorage.getItem('adminUserInfo') || 'null') } catch { userInfo.value = null } + checkAgreementGate() }) @@ -419,6 +477,22 @@ onMounted(() => { color: #fff; } +.agreement-gate { + display: grid; + gap: 14px; + color: #315650; + line-height: 1.7; +} + +.agreement-gate p { + margin: 0; +} + +.agreement-gate__links a { + color: var(--theme-primary-action); + font-weight: 700; +} + @media (max-width: 960px) { .header, .content { diff --git a/JC-Salon-WeChat/api/customers.js b/JC-Salon-WeChat/api/customers.js index 1eff37c0..a3cf3106 100644 --- a/JC-Salon-WeChat/api/customers.js +++ b/JC-Salon-WeChat/api/customers.js @@ -47,14 +47,19 @@ module.exports = { }, /** - * 后台按预约/订单上下文单次取号,号码不入库、不缓存。 + * 后台按预约/订单上下文单次取号,号码不入库、不缓存;散客可不传 customerId。 */ - dialCustomer(customerId, orderId) { + dialCustomer(params) { + const source = params || {} + const query = {} + if (source.customerId) query.customerId = source.customerId + if (source.appointmentId) query.appointmentId = source.appointmentId + if (source.orderId) query.orderId = source.orderId return request({ - url: `/manager/customers/${customerId}/dial`, + url: '/manager/customers/dial', method: 'POST', data: {}, - params: { orderId } + params: query }) }, diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index 8bf5f75f..04104d50 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -135,13 +135,17 @@ Page({ async dialCustomer() { const appointment = this.data.appointment || {} if (this.data.dialing) return - if (!appointment.customerPhoneAvailable || !appointment.customerId || !appointment.orderId) { + if (!appointment.customerPhoneAvailable || !appointment.orderId) { wx.showToast({ title: '该客户暂无可拨打的手机号', icon: 'none' }) return } this.setData({ dialing: true }) try { - const result = await customersApi.dialCustomer(appointment.customerId, appointment.orderId) + const result = await customersApi.dialCustomer({ + customerId: appointment.customerId, + appointmentId: appointment.orderItemId, + orderId: appointment.orderId + }) if (!result || !result.dialNumber) { throw new Error('未获取到可拨打号码') } diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.test.js b/JC-Salon-WeChat/pages/appointment-detail/index.test.js index 22edb2da..2b3be24d 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.test.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.test.js @@ -95,4 +95,7 @@ const styles = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8') ;['订单编号', '服务项目', '美甲师', '时长', '成交金额', '取消原因', 'remarkText', 'customerPhoneText'].forEach(text => assert(markup.includes(text))) assert.match(markup, /class="primary-btn transfer-action"/) assert.match(markup, /class="danger-btn"/) +assert.match(markup, /appointment\.customerPhoneAvailable && appointment\.orderId/) +assert.strictEqual(markup.includes('appointment.customerId && appointment.orderId'), false) assert.match(styles, /\.transfer-action\s*\{[^}]*box-shadow/) +assert.match(styles, /\.call-btn\s*\{/) diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxml b/JC-Salon-WeChat/pages/appointment-detail/index.wxml index aa8bdacb..285f2f7c 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxml @@ -13,7 +13,7 @@ {{appointment.customerPhoneText}}