Author SHA1 Message Date
xiaowang 74f8fa5f4e 修复回归安全问题并补充验证 2026-06-05 16:10:58 +08:00
3093 changed files with 129404 additions and 330554 deletions
BIN
View File
Binary file not shown.
-49
View File
@@ -1,49 +0,0 @@
---
name: jayu-api
description: JayuCloud 接口与权限规则:Gateway 路由前缀(/api、/api/admin、/internal)、白名单与 JWT 门禁、小程序与管理端基址差异、脱敏与授权取数出口、接口变更检查清单。用于新增/修改后端接口或前后端联调契约时;通用 API 设计方法用全局 $api-design
---
# JayuCloud 接口规则
本项目接口变更最常见的事故是**路由前缀与门禁错配**(管理接口暴露、小程序被误拦)。新增或修改接口必须按本技能核对。
## 路由与门禁基线
| 前缀 | 用途 | 门禁 |
|------|------|------|
| `/api/**` | 业务接口(小程序与前端业务路由) | Gateway JWT 初筛 + 白名单 |
| `/api/admin/**` | 管理端接口 | 管理员门禁(Core 按 URL 前缀判断) |
| `/internal/**` | 服务间内部接口 | 仅限内部调用,禁止暴露到公网路由 |
关键事实:
- Salon Core 的管理员门禁按 `/admin/**` URL 前缀判断:**小程序绝不能复用 `/api/admin` 基址**,否则店长/员工业务会被误拒;小程序用 `/api` 业务路由,需要时由 Core 提供非 `/admin` 路由别名。
- 给小程序提供别名时不得整控制器映射:只映射实际需要的端点(例如对象存储只映射上传端点,不映射列表/更新/删除)。
- 生产小程序请求走 `https://yunail.art/api/admin`(管理师小程序)与 `/api`(用户端);本地开发用 `utils/config.local.js`(不入 Git)。
- 匿名白名单:逐个端点枚举,禁止 `/wechat-mini/**` 这类宽泛前缀——后续新增认证端点会被静默暴露。白名单需同时核对服务拦截器与 Gateway 各份配置。
## 新增接口检查清单
1. 确定归属端与前缀(对照上表);拿不准时先看同域现有接口。
2. 认证与授权:匿名还是登录?管理端权限码?数据属主(门店作用域)校验写在 Service 层。
3. 请求/响应:统一 `Result<T>` 包装;参数校验注解;错误语义与现有错误码一致。
4. 隐私字段:默认脱敏返回;需要明文时走独立授权端点(一次一取,按门店/订单上下文授权),并记录审计。
5. 幂等与并发:写接口明确重复提交语义;金额/配额操作原子化。
6. 前端/小程序同步:`src/api/` 或 `api/` 封装、免登录路径、请求基址是否需要同步修改。
7. Gateway 白名单与路由是否需要同步(Nacos `gateway.yaml`)。
8. 涉及 SQL 时转 $jayu-database;涉及配置时转 $jayu-release。
## 联调约定
- 前端开发代理:`/admin/api` 与 `/api` → `VITE_DEV_PROXY_TARGET`(vite.config.ts)。
- 小程序:`utils/request.js` 统一封装;401 处理全局唯一,清会话要彻底(含 `wx.uploadFile` 路径)。
- 大数 ID:雪花 ID 传前端按字符串处理,避免 `JSON.parse` 精度丢失。
## 安全边界
- 不新增绕过门禁的「临时匿名接口」;确有需要必须逐个列出理由并提示安全评审。
- 不在接口返回中携带密钥、内部堆栈、完整隐私字段。
## 验收标准
- 清单 8 项逐一给出结论(含「不涉及」);前缀与门禁选择有依据;联调端同步修改已列出。
-59
View File
@@ -1,59 +0,0 @@
---
name: jayu-database
description: JayuCloud 数据库与迁移纪律:Flyway 版本文件规则(中文命名、已执行不可改、向前兼容补偿)、空库初始化基线、实体与迁移同步清单、MySQL 已知坑。用于新增/修改表结构、字段、索引或写 SQL 时;通用数据库设计方法用全局 $database-design
---
# JayuCloud 数据库纪律
本项目数据库变更是高危操作:DEV/SIT/PROD 由 Core 启动时 Flyway 自动执行,**没有人工补救窗口**。任何结构改动必须按本技能执行。
## 硬性规则(不可违反)
1. 结构变更只走 Flyway 版本文件:
- Salon:`JC-Salon-Core/src/main/resources/db/migration/V{n}__中文功能说明_YYYYMMDD.sql`
- ArtList:`JC-ArtList-Core/src/main/resources/db/migration/` 同规则
- 版本号取当前目录最大版本号 +1;文件名中文体现功能与日期;内容必须完整可执行。
2. 已在任一环境执行过的迁移文件**不得修改或删除**;撤销/修正必须新增向前兼容的补偿迁移。禁止 Flyway `clean`、自动 baseline、重跑初始化 SQL。
3. 空库初始化仅用 `docs/scripts/sql/init/jayucloud-salon.sql` / `jayucloud-artlist.sql`(0.0.1 基线);只有负责人明确要求重整基线时才把变更合并进初始化 SQL。
4. 生产已部署库升级不直接执行初始化 SQL,必须单独制定迁移方案。
5. Gitea 工作流不得直连数据库或绕过 Flyway;合并 SIT 前先在 DEV 验证迁移。
## 工作流程
### 1. 设计
- 先读现有表结构(初始化 SQL + 已有版本文件)与对应实体,遵循既有命名/主键/字符集约定。
- 字段类型注意:金额用 DECIMAL;时间遵循现有约定;枚举落库策略与现有一致。
- 索引从实际查询出发;唯一约束必须显式建唯一索引。
### 2. 实体与迁移同步清单(逐项核对)
- [ ] 实体类字段与 SQL 列一一对应(`@TableName`/`@TableField`)。
- [ ] 新 Mapper 包已加入 `MyBatisPlusConfig` 的 `@MapperScan` 清单(编译过≠启动过)。
- [ ] 自动填充逻辑合并进现有 `MetaObjectHandler`(只接受单例)。
- [ ] 所有插入入口都覆盖新字段(静态搜索该实体的全部保存入口)。
- [ ] 存量数据需要回填时,在同一版本文件或后续版本中写幂等回填。
- [ ] 历史迁移中不得夹带本次之外的变更。
### 3. 已知坑(写 SQL 前对照)
- 排序规则冲突:`utf8mb4_0900_ai_ci` 与旧列 `utf8mb4_unicode_ci` 混用会报 1267;跨 collation 比较显式 `CONVERT(... USING utf8mb4) COLLATE utf8mb4_unicode_ci`。
- MySQL 迁移失败不回滚已执行 DDL:可重试迁移要先检查字段/索引是否已存在(幂等)。
- `flyway repair` 只清失败历史记录,不回滚结构;独立调用 repair 必须显式设置完整 `locations`,否则可能误删历史。
- 整理/合并初始化 SQL 时检查脚本尾部 DROP 语句,别把运行必需表删掉。
- 雪花 ID:MyBatis-Plus `ASSIGN_ID` 在应用层分配,表定义可能仍是 `AUTO_INCREMENT`,判断主键策略要三处核对(注解/生成策略/SQL)。
- 无斜杠的 `test/` gitignore 规则会忽略任意层级的 test 目录,新增测试文件用 `git check-ignore -v` 确认。
### 4. 验证与交付
- 能在临时库执行就实际执行验证;不能执行时记录阻塞原因。
- 任务说明中写明:新增的版本文件路径、影响的表、是否需要回填、DEV 验证结果。
## 安全边界
- 不对任何真实环境数据库直接执行 DDL/DML;执行由 Core 启动的 Flyway 完成。
- 不在 SQL 中写入真实客户数据;种子数据只保留运行必需项(平台管理员 `xiaowang`、权限、协议、系统参数等)。
## 验收标准
- 版本文件命名与位置合规、可独立执行;实体与列一致;清单全部勾选;任务记录包含验证结论。
-54
View File
@@ -1,54 +0,0 @@
---
name: jayu-devflow
description: JayuCloud 开发与验证流程:各模块构建命令(Maven/npm/node 语法检查)、启动烟测要求、提交前检查(GitNexus detect_changes、中文提交)、常见陷阱清单。用于在本仓库写代码、构建、测试、提交时;TDD 方法论用全局 $test-driven-development,调试方法用 $systematic-debugging
---
# JayuCloud 开发流程
## 构建与验证命令(按改动范围选择)
| 改动范围 | 验证命令 | 说明 |
|----------|----------|------|
| Salon 后端 | `mvn -f JC-Salon-Core/pom.xml -DskipTests compile`(测试:`... test`) | 非聚合工程,必须 `-f` 指定模块;本机 Maven:`D:\software\apache-maven-3.9.12\bin\mvn.cmd` |
| ArtList 后端 | `mvn -f JC-ArtList-Core/pom.xml -DskipTests compile` | 同上 |
| Gateway | `mvn -f JC-Salon-Gateway/pom.xml -DskipTests compile`(ArtList 同理) | |
| 前端 | `JC-Salon-Frontend` / `JC-ArtList-Frontend` 下 `npm run build` | 开发 `npm run dev` |
| 小程序 | `node --check <改动文件>` 语法检查 | 有条件时微信开发者工具冒烟 |
| SQL | 临时库执行或记录阻塞原因 | 见 $jayu-database |
**升级规则**:涉及 Bean 装配、事务、拦截器、`@MapperScan`、自动填充的改动,编译通过后必须做一次 Core 启动烟测——编译通过不等于能启动。
## 开发节奏
1. 动手前:`git status` 确认工作区;有他人未提交改动时先按项目规则处理(中文回溯提交)。
2. 修改符号前:GitNexus impact 分析(AGENTS.md 文首规则);业务域不熟时先读 $jayu-domain。
3. 实施:遵循模块分层与命名约定;接口改动走 $jayu-api 清单;SQL 改动走 $jayu-database。
4. 验证:按上表执行对应命令;测试遵循红绿纪律,Mock 参数全字面量或全 matcher。
5. 提交前:GitNexus `detect_changes`(失败时记录原因,用 `git diff` + 测试结果兜底);只暂存本任务文件。
6. 提交:中文提交信息;任务记录写明新增/调整的版本化文件(SQL/配置说明)。
## 提交与分支纪律
- 每次任务完成后整理相关改动创建 git 提交,提交信息必须中文。
- 只暂存和提交本次任务涉及的文件,保留其他并行改动。
- 注意 `.gitignore` 陷阱:无斜杠的 `test/` 会忽略任意层级 test 目录,新增测试用 `git check-ignore -v` 确认,必要时 `git add -f`。
## 常见陷阱(改前对照,详见 references/pitfalls.md)
1. 编译过 ≠ 启动过(扫描清单、Bean 冲突在启动期暴露)。
2. 事务自调用失效;事务内远程调用不可回滚。
3. 多构造器时注入构造器要显式 `@Autowired`(Spring Boot 2.x)。
4. 共享基类字段(软删除等)并非所有实体都有,查询前先核对继承链。
5. 配置覆盖链:`secret.yaml`/环境变量可能覆盖 `infra.yaml` 与本地文件。
6. 旧 class 残留:移除组件后 clean 构建再验证。
7. 雪花 ID 传 JS 前端的精度问题(字符串传输)。
8. 小程序 401 清会话不彻底导致反复跳登录。
## 安全边界
- 不在本地验证中连接生产数据库/生产 Nacos;本地联调用 dev 环境或本机中间件。
- 验证失败如实报告,不以「应该没问题」代替证据(全局 $verification-before-completion 约束同样适用)。
## 验收标准
- 对应范围的验证命令已实际执行且输出通过;提交信息中文、范围干净;任务记录含版本化文件清单。
@@ -1,43 +0,0 @@
# JayuCloud 常见陷阱清单
来源:历史任务教训沉淀(全局 error-memory 与本项目复盘),仅保留与本项目技术栈相关的通用条目。
## Spring / MyBatis-Plus
- `MyBatisPlusConfig` 使用显式 `@MapperScan` 包清单:新增 `@Mapper` 模块包必须同步加入,否则编译通过但启动缺 Bean。
- MyBatis Mapper statement ID = namespace + 方法名(无参数类型):同一 Mapper 不能重载同名 SQL 方法,否则一条注解映射被忽略。
- MyBatis-Plus 自动填充只接受单个 `MetaObjectHandler`:新增填充逻辑合并进同一处理器;移除旧组件后 clean 构建,防止旧 class 被扫描。
- MyBatis lambda 查询共享基类字段(如 `isDelete`)前,确认具体实体继承链上确实有该字段。
- Spring Bean 多构造器时,注入构造器显式 `@Autowired`;用一次真实容器启动烟测确认。
- Mockito 验证不混用字面量与 `any()`,参数要么全字面量要么全 matcher。
- 事务:自调用不走代理;事务内不做远程调用/发消息等不可回滚操作。
## 配置与环境
- Nacos 配置写入成功后集群读回可能短暂落后:发布/回退都要做有限重试 + 内容摘要校验,失败要 fail closed。
- 排查配置问题不能只看单一文件:后加载的 `secret.yaml`、systemd `EnvironmentFile`、环境变量都可能覆盖。
- 本地 `application.yaml`/`bootstrap.yaml` 只放 Nacos 引导参数,运行配置改 Nacos 并同步 `nacos/` 仓库副本与说明文档。
## 前端 / 小程序
- 小程序不要复用 `/api/admin` 基址(管理门禁按前缀误拒业务);别名只映射需要的端点。
- 雪花 `Long` ID 经 `JSON.parse` 丢精度:前端回传按字符串保留,补回归测试。
- 上传到私有对象存储后不要直接拿响应 `fileUrl` 做预览:可能是私有桶/内网地址;先用本地临时路径预览,以服务端文件 ID 提交。
- 对象存储 URL 解析必须按环境配置处理 MinIO 内网端点、公共端点与 `oss://` 引用;签名失败不得把私有地址原样返回。
- 401 处理:清会话要覆盖 `wx.request` 与 `wx.uploadFile` 全部路径,防重状态保持到新登录成功,避免残留旧登录态反复跳登录。
- 提供 HTML demo 做参照时,实现前完整检查其 HTML/CSS/交互脚本再映射组件,不能只按截图复刻。
## 数据库 / 迁移
- 新增必需业务字段:静态搜索实体所有插入入口逐一补齐 + 幂等回填存量空值。
- 排序规则冲突(`utf8mb4_0900_ai_ci` vs `utf8mb4_unicode_ci`):跨 collation 比较显式 `CONVERT ... COLLATE`。
- MySQL 迁移失败不回滚已执行 DDL:可重试迁移先查字段/索引是否已存在。
- 独立调用 Flyway `repair` 必须显式完整 `locations`,执行后立即检查 `flyway_schema_history`。
- 整理初始化 SQL 时核对尾部 DROP 与实体表清单,防止误删运行必需表。
- 注册/申请类「取最新记录」查询:按创建时间排序后还要按雪花 ID 倒序,避免同秒提交取旧。
## 工具链
- 本机 `node`/`mvn` 可能不在 PATH:Node 在 `D:\software\nodejs`(PowerShell 用 `npm.cmd`/`npx.cmd`),Maven 在 `D:\software\apache-maven-3.9.12\bin\mvn.cmd`。
- GitNexus 特定版本在本机分析可能失败,优先用项目 `.gitnexus/run.cjs analyze --index-only` 或可用版本。
- GitNexus 对 Vue/Java 同名局部符号可能跨语言误关联:critical 风险提示先核对实际引用与构建结果再决策。
-42
View File
@@ -1,42 +0,0 @@
---
name: jayu-domain
description: JayuCloud 项目领域知识:Salon 店务与 ArtList 设计师两条产品线的模块地图、核心业务流程(预约/排班/订单/注册审核/协议/拨号/内容审核)、角色权限模型。用于理解或修改本项目业务功能前;通用需求分析方法用全局 $requirements-analysis
---
# JayuCloud 领域知识
JayuCloud 是双产品线仓库:**Salon(店务/指尖管理师)** 与 **ArtList(指尖设计师)**。修改业务代码前先读本技能与 [references/module-map.md](references/module-map.md),确认改动落在哪个业务域、影响哪些端。
## 产品线速览
| 产品线 | 服务对象 | 端 | 后端 |
|--------|----------|----|------|
| Salon | 美甲门店(平台管理员/店长/美甲师) | 管理端 Vue + 指尖管理师小程序 | JC-Salon-Core / JC-Salon-Gateway |
| ArtList | C 端用户 + 平台运营 | 用户端/管理端 Vue + 用户小程序 | JC-ArtList-Core / JC-ArtList-Gateway |
## 核心业务流程(改前必查上下游)
1. **预约与排班(Salon)**:门店每周营业排班 → 美甲师可约时段 → 客户预约(散客支持拨号联系)→ 订单履约。改动排班/预约时核对 `planning`、`order`、`shop` 三域。
2. **订单与收款**:下单 → 状态流转 → 收款(线上/线下收款登记)→ 完成。订单完成强制校验收款状态;补单创建即 PAID。
3. **注册与审核**:门店/美甲师注册申请 → 店长审核模式 → 门店经营有效期;驳回重申保留历史版本并新建申请。
4. **内容审核与协议**:对外内容审核(图片/作品)、协议版本管理、用户同意状态拦截(微信端 4510 流程)。
5. **隐私与拨号**:手机号/账号全链路加密存储(AES-GCM + hash 查询),所有接口默认脱敏返回;明文一次一取,走独立授权端点(按门店与订单上下文授权)。
6. **文件体系**:上传按 `MINIO → QINIU_KODO → ALIYUN_OSS` 优先级补副本,读取按配置的渠道优先级生成签名地址;历史数据可能存 MinIO 内网端点或 `oss://` 引用,统一 URL 工具按环境解析。
7. **ArtList 电商链路**:浏览 → 购物车 → 下单 → 评价/改派 → VIP/优惠券;订单镜像与 Salon 侧存在同步契约(事件/状态映射)。
## 角色与权限
- 角色:平台管理员(`xiaowang`)、店长、美甲师、普通用户 + 门店自定义角色。
- 权限码裁剪菜单与接口;数据属主校验(门店作用域)在 Service 层;管理端走 `/api/admin/**` 门禁。
- 新增权限/菜单种子后必须授权给平台管理员。
## 使用要求
- 修改业务功能前:先定位业务域(module-map)→ 按 AGENTS.md 要求做 GitNexus impact → 再动手。
- 涉及流程 1-7 的改动,完成后在任务说明中写明对上下游的影响。
- 本技能只提供项目知识,不替代开发流程技能($jayu-devflow)与数据库纪律($jayu-database)。
## 安全边界
- 不输出、不记录任何真实客户手机号/账号明文;示例一律用占位符。
- 隐私字段相关改动必须保持「默认脱敏、授权取明文」的基线,不得新开完整号码出口。
@@ -1,50 +0,0 @@
# JayuCloud 模块地图
> 依据 2026-11-05 源码目录核实;如有出入以源码为准。
## 后端业务域(Core `modules/`)
| 域 | Salon | ArtList | 职责 |
|----|:---:|:---:|------|
| auth | ✓ | ✓ | 登录、令牌、会话(微信登录/账号登录) |
| user | ✓ | ✓ | 用户资料、客户管理、隐私字段加密与脱敏出口 |
| shop | ✓ | ✓ | 门店/店铺、营业设置、有效期、主题 |
| artist | ✓ | ✓ | 美甲师/艺术家资料、注册申请关联 |
| product | ✓ | ✓ | 作品/服务项、分类标签、价格与时长 |
| order | ✓ | ✓ | 订单状态机、收款登记、完成校验 |
| payment | ✓ | ✓ | 支付/退款集成 |
| planning | ✓ | ✓ | 排班、预约占用、规划日历 |
| marketing | ✓ | ✓ | 优惠券、营销活动、VIP |
| message | ✓ | ✓ | 系统消息、订阅消息、跳转与弹窗 |
| content | ✓ | ✓ | 内容审核(图片/作品/对外文案) |
| file | ✓ | ✓ | 上传编排、对象存储三副本、签名地址 |
| integration | ✓ | ✓ | 第三方集成(微信审核回调、内容审核、短信等) |
| security | ✓ | ✓ | 审计日志、安全接入配置 |
| system | ✓ | ✓ | 系统参数、协议版本、诊断 |
| privacy | ✓ | — | 隐私政策、脱敏策略、拨号取号授权 |
| registration | ✓ | — | 门店/员工注册审核流 |
| manager | ✓ | — | 店长/管理端专属能力 |
| inventory | ✓ | — | 库存耗材 |
| analytics | ✓ | — | 经营分析、绩效统计 |
ArtList 已清理 inventory/manager/analytics/planning 实现等(保留订单容量校验所需依赖);新增 ArtList 功能前先确认该域仍存在。
## 端侧入口
| 端 | 页面/视图位置 | 请求封装 | 登录态 |
|----|--------------|----------|--------|
| JC-Salon-Frontend | `src/views/` | `src/api/*.ts` | Axios 拦截器 |
| JC-ArtList-Frontend | `src/views/` | `src/api/*.ts` | Axios 拦截器 |
| JC-Salon-WeChat | `pages/`(planning/customers/employees/appointment…) | `utils/request.js` | `utils/auth.js` |
| JC-ArtList-WeChat | `pages/`(home/products/cart/orders/vip-center…) | `utils/request.js` | `utils/auth.js` |
## 网关与公共件
- `JC-*-Gateway`:`filter/AuthGlobalFilter`(白名单 + JWT 初筛)、路由配置在 Nacos `gateway.yaml`。
- Core 公共:`common/`(`Result<T>`、DTO/VO 基类)、`config/`(MyBatis-Plus、加密组件、对象存储编排等)。
## 关键横切组件
- 手机号/账号加密:AES-GCM 加密组件 + `*_hash` 查询列;日志脱敏。
- 协议拦截:服务端拦截未同意最新协议用户,微信端 4510 原地同意后重试。
- 对象存储读取渠道优先级:配置项控制,历史数据多端点兼容解析。
-47
View File
@@ -1,47 +0,0 @@
---
name: jayu-release
description: JayuCloud 发布与配置管理:Nacos 配置分层(core/gateway/infra/secret/logging)、dev→sit→prod 晋级流程、Gitea 工作流边界、配置变更说明文档要求、发布回滚纪律。用于修改配置、发布环境、部署脚本或 Nacos 相关任务;线上故障排查用全局 $incident-troubleshooting
---
# JayuCloud 发布与配置管理
配置与发布是本项目的高风险动作:生产配置由 Nacos 管理、发布由 Gitea 工作流驱动、数据库迁移随应用启动自动执行。任何配置/发布改动按本技能执行。
## 配置体系
- 仓库副本:`nacos/namespaces/<environment>/<namespace>/DEFAULT_GROUP/`,environment ∈ dev/sit/prod,namespace ∈ `jayucloud-salon` / `jayucloud-artlist`。
- 每个命名空间五个 dataId:`core.yaml`(业务运行)、`gateway.yaml`(路由与网关)、`infra.yaml`(中间件地址/开关)、`secret.yaml`(敏感配置)、`logging.yaml`。
- 覆盖关系:后加载来源覆盖先加载来源;排查配置问题必须核对全部来源的最终生效值(含 systemd EnvironmentFile 与环境变量)。
- 仓库副本不得包含真实密钥;敏感值只存在于对应环境的 Nacos `secret.yaml`。
- dev 分支推送触发 Gitea 工作流自动发布 dev Nacos 配置(带失败自动回退);发布后有读回校验(SHA256 比对)。
## 发布流程(dev → sit → prod)
1. **先 DEV 验证**:迁移、配置、代码必须在 DEV 验证通过;迁移未过不得合并 SIT。
2. **SIT**:合并后由 SIT 部署流程发布;核对 Nacos 发布快照与读回校验结果。
3. **PROD**:走发布提交 + `自动部署prod环境` 工作流(构建发布包 → 部署脚本 → 记录部署,失败自动回退);生产发布前核对目标环境、备份状态与凭据注入方式,并取得确认。
4. 发布顺序契约:数据库迁移随 Core 启动由 Flyway 执行,变更设计必须向前兼容(先加后删),应用回退不会回滚数据库。
## 配置变更任务要求
1. 修改前先读取现有配置(Nacos 只读查询或仓库副本),备份原配置内容到任务记录。
2. 仓库 `nacos/` 副本与 Nacos 实际内容同步修改;dev 走分支推送自动发布,sit/prod 按既有发布流程。
3. **必须提供中文说明文档**:按「功能+日期」命名(如 `Salon××配置说明_20261105.md`),放在 `docs/scripts/`,写明变更内容、生效环境、验证方式、回退方式。
4. 涉及脚本/配置/SQL 的任务,先读 `docs/scripts/运行与发布配置总说明.md`。
5. 发布后验证:服务日志、Nacos 实例健康、读回校验结果。
## Gitea 工作流边界
- 工作流不得直连数据库、不得绕过 Flyway 执行 SQL。
- 不可绕过的分支保护检查必须由目标分支定义的工作流(`pull_request_target` 类)完成,且不得检出/执行来源分支代码。
- 修改工作流定义属于发布基础设施变更:先说明影响,单独提交。
## 安全边界
- 生产环境动作(发布、Nacos 生产写、生产 SQL)必须先取得明确确认;未授权只读。
- 不在仓库、日志、说明文档中写入密钥/口令/令牌;示例用占位符。
- 回滚优先使用工作流与发布脚本的既有回退机制;数据库问题用补偿迁移,不依赖 clean/baseline。
## 验收标准
- 配置变更有说明文档且命名合规;环境晋级顺序未跳级;发布后验证结果已记录;仓库副本与 Nacos 一致。
-110
View File
@@ -1,110 +0,0 @@
---
name: gitnexus-cli
description: "Use when the user needs to run GitNexus CLI commands like analyze/index a repo, check status, clean the index, generate a wiki, or list indexed repos. Examples: \"Index this repo\", \"Reanalyze the codebase\", \"Generate a wiki\""
---
# GitNexus CLI Commands
Commands below use `node .gitnexus/run.cjs <command>` — the project-local runner `gitnexus analyze` drops next to the index. It auto-selects an available runner at call time (global `gitnexus`, else `pnpm dlx`, else `bunx`, else `npx`), so no package-manager assumption and no global install is required — including on a bun-only machine, which has no npm, npx or pnpm at all.
> **Not analyzed yet, or `node .gitnexus/run.cjs` reports `Cannot find module`** (the gitignored runner is absent — e.g. a fresh clone or `git clean`)? (Re)generate it with `npx gitnexus analyze` from the project root, or `bunx gitnexus@latest analyze` on a bun-only machine. On **npm 11.x**, if `npx` crashes during install (`node.target is null`), install once with `npm i -g gitnexus` (then `gitnexus analyze`), or use `bunx gitnexus@latest analyze`, or `pnpm --allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx gitnexus@latest analyze`. See [#1939](https://github.com/abhigyanpatwari/GitNexus/issues/1939).
## Commands
### analyze — Build or refresh the index
```bash
node .gitnexus/run.cjs analyze
```
Run from the project root. This parses all source files, builds the knowledge graph, writes it to `.gitnexus/`, and generates CLAUDE.md / AGENTS.md context files.
| Flag | Effect |
| -------------- | ---------------------------------------------------------------- |
| `--watch` | Keep a Git repository index current with serialized refreshes |
| `--debounce <ms>` | Watch quiet period before refresh (default: 300 ms) |
| `--force` | Force full re-index even if up to date |
| `--embeddings` | Enable embedding generation for semantic search (off by default) |
| `--drop-embeddings` | Drop existing embeddings on rebuild. By default, an `analyze` without `--embeddings` preserves them. |
| `--pdg` | Build the program-dependence layers used by `explain` and `pdg_query` (taint, CDG, and REACHING_DEF). |
| `--spring-actuator <path>` | Import opt-in Spring Boot Actuator mappings, beans, conditions, configprops, and env snapshots. Forces a full rebuild; unsupported with `--watch`. |
| `--asyncapi-spec <path>` | Read opt-in AsyncAPI 3.x documents (directory or single file) and mint `Destination` nodes from their operations. 2.x is refused, not mapped. Unsupported with `--watch`. |
**When to run:** First time in a project, after major code changes, or when `gitnexus://repo/{name}/context` reports the index is stale. In Claude Code, a PostToolUse hook detects staleness after `git commit` and `git merge` and notifies the agent to run `analyze` — the hook does not run analyze itself, to avoid blocking the agent for up to 120s and risking KuzuDB corruption on timeout.
For Spring runtime enrichment, pass a JSON bundle, one endpoint JSON file, or a directory containing endpoint files. Route evidence is authoritative only when `runtimeConfirmed === true`; `runtimeSource` records provenance and may also accompany `handler-conflict`. Env/configprops values are never persisted.
## Index storage and retention
Default location is `<repo>/.gitnexus/`. Override with environment variables (also documented in README):
| Env | Effect |
| --- | ------ |
| `GITNEXUS_STORAGE_PATH` | One complete external index directory. Wins if both storage vars are set. |
| `GITNEXUS_STORAGE_ROOT` | Absolute root; GitNexus creates an isolated `<repo-basename>-<12-hex>/` slot per repository. |
| `GITNEXUS_CONTENT_RETENTION` | `full` (default) keeps file text; `symbol` keeps snippets; `none` keeps the graph only. |
`list_repos`, `gitnexus://repo/{name}/context`, and HTTP `GET /api/repos` / `GET /api/repo` expose `storagePath`, `contentRetention`, and `sourceAvailable`. HTTP `/api/file` and `/api/grep` return 410 unless retention is `full`. MCP `include_content` may still return symbol spans when retention is `symbol`.
Use `node .gitnexus/run.cjs analyze --watch` for a long-lived local Git repository. It performs an initial analysis, queues scanner-admitted file changes, and retries intact failed batches with bounded backoff. Watch refreshes update only the graph: they skip AGENTS.md / CLAUDE.md injection and standard skill installation, so run a one-shot `analyze` when those generated files need updating. Watch rejects one-shot or context-output flags including `--force`, embedding flags, `--skills`, `--default-branch`, `--skip-agents-md`, `--skip-skills`, `--no-stats`, `--self-commit`, `--index-only`, and `--skip-git`. It never pulls remotes. Scheduled remote clone/pull is a different command: `gitnexus auto-sync`. Bare `gitnexus watch` is reserved and does not start either job. Running MCP and `serve` processes periodically check for a published replacement and reopen it without a restart. MCP checks are throttled to once every five seconds, so a tool call before the next check can briefly use the previous index.
### status — Check index freshness
```bash
node .gitnexus/run.cjs status
```
Shows whether the current repo has a GitNexus index, when it was last updated, and symbol/relationship counts. Use this to check if re-indexing is needed.
### clean — Delete the index
```bash
node .gitnexus/run.cjs clean
```
Deletes the `.gitnexus/` directory and unregisters the repo from the global registry. Use before re-indexing if the index is corrupt or after removing GitNexus from a project.
| Flag | Effect |
| --------- | ------------------------------------------------- |
| `--force` | Skip confirmation prompt |
| `--all` | Clean all indexed repos, not just the current one |
### wiki — Generate documentation from the graph
```bash
node .gitnexus/run.cjs wiki
```
Generates repository documentation from the knowledge graph using an LLM. HTTP providers require an API key (saved to `~/.gitnexus/config.json` on first use). Local CLI providers (`--provider cursor|claude|codex|opencode|grok`) use your existing CLI login.
| Flag | Effect |
| ------------------- | ----------------------------------------- |
| `--force` | Force full regeneration, also required to re-generate an existing wiki in a different language |
| `--provider <name>` | LLM provider: minimax, openai, openrouter, azure, custom, cursor, claude, codex, opencode, or grok (default: minimax). Local CLIs (`cursor`, `claude`, `codex`, `opencode`, `grok`) use your existing CLI login and skip `--api-key`. |
| `--model <model>` | LLM model (default: MiniMax-M3) |
| `--base-url <url>` | LLM API base URL |
| `--api-key <key>` | LLM API key |
| `--concurrency <n>` | Parallel LLM calls (default: 3) |
| `--timeout <seconds>` | LLM request timeout in seconds (default: disabled) |
| `--retries <n>` | Max LLM retry attempts per request (default: 3) |
| `--lang <lang>` | Output language for generated documentation (e.g. english, chinese, spanish, japanese) |
| `--gist` | Publish wiki as a public GitHub Gist |
### list — Show all indexed repos
```bash
node .gitnexus/run.cjs list
```
Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information.
## After Indexing
1. **Read `gitnexus://repo/{name}/context`** to verify the index loaded
2. Use the other GitNexus skills (`exploring`, `debugging`, `impact-analysis`, `refactoring`) for your task
## Troubleshooting
- **"Not inside a git repository"**: Run from a directory inside a git repo
- **Index is stale after re-analyzing**: Wait for the next MCP tool call to reopen the published index; this normally takes no more than five seconds
- **Embeddings slow**: Omit `--embeddings` (it's off by default) or set `OPENAI_API_KEY` for faster API-based embedding
-131
View File
@@ -1,131 +0,0 @@
---
name: gitnexus-debugging
description: "Use when the user is debugging a bug, tracing an error, or asking why something fails. Examples: \"Why is X failing?\", \"Where does this error come from?\", \"Trace this bug\""
---
# Debugging with GitNexus
## When to Use
- "Why is this function failing?"
- "Trace where this error comes from"
- "Who calls this method?"
- "This endpoint returns 500"
- Investigating bugs, errors, or unexpected behavior
## Bind the repository first
A root cause traced in the wrong repository is a wrong root cause.
Call `list_repos {}` before the first tool call. With one indexed repository,
use the examples below as written. With more than one, pass `repo` on every
call: an omitted `repo` normally errors, but under an MCP policy with a
configured default it resolves to that default silently. If you cannot tell
which repository is meant, stop and ask. This matters most for `cypher`, whose
statement carries no in-band hint of which database it ran against.
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
`hasMore` is false before concluding a repository is absent.
A stale index describes the code from before your bug, so refresh before
trusting a trace, and state the repository and index freshness with the
diagnosis.
## Workflow
```
0. list_repos {} → Bind repo
1. query({search_query: "<error or symptom>"}) → Find related execution flows
2. context({name: "<suspect>"}) → See callers/callees/processes
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow
4. cypher({statement: "MATCH path..."}) → Custom traces if needed
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
## Checklist
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] Understand the symptom (error message, unexpected behavior)
- [ ] query for error text or related code
- [ ] Identify the suspect function from returned processes
- [ ] context to see callers and callees
- [ ] Trace execution flow via process resource if applicable
- [ ] cypher for custom call chain traces if needed
- [ ] Read source files to confirm root cause
- [ ] State the repository and index freshness with the diagnosis
```
## Debugging Patterns
| Symptom | GitNexus Approach |
| -------------------- | ---------------------------------------------------------- |
| Error message | `query` for error text → `context` on throw sites |
| Wrong return value | `context` on the function → trace callees for data flow |
| Intermittent failure | `context` → look for external calls, async deps |
| Performance issue | `context` → find symbols with many callers (hot paths) |
| Recent regression | `detect_changes` to see what your changes affect — pass `worktree` for a linked worktree |
| "How does A reach B?" | `trace` between the two symbols — shortest call chain in one call |
## Tools
**query** — find code related to error:
```
query({search_query: "payment validation error", repo: "my-app"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError, PaymentException
```
**context** — full context for a suspect:
```
context({name: "validatePayment", repo: "my-app"})
→ Incoming calls: processCheckout, webhookHandler
→ Outgoing calls: verifyCard, fetchRates (external API!)
→ Processes: CheckoutFlow (step 3/7)
```
**cypher** — custom call chain traces. Pass `repo` alongside the statement; the
Cypher text itself names no repository, so the result is unattributable without
it:
```cypher
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"})
RETURN [n IN nodes(path) | n.name] AS chain
```
**trace** — shortest call chain between two symbols ("how does A reach B?"), one call instead of chaining `context` hops:
```
trace({ from: "processCheckout", to: "fetchRates", repo: "my-app" })
→ status: ok, hopCount: 3
→ hops: processCheckout → validatePayment → verifyCard → fetchRates
→ edges: CALLS (1.0), CALLS (0.95), CALLS (1.0)
```
When no path exists, `trace` reports the furthest reachable node — exactly where the chain breaks (dynamic dispatch, reflection, or an external boundary).
## Example: "Payment endpoint returns 500 intermittently"
```
0. list_repos {}
→ total: 2 (my-app, billing-api) — bind my-app explicitly on every call
1. query({search_query: "payment error handling", repo: "my-app"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError
2. context({name: "validatePayment", repo: "my-app"})
→ Outgoing calls: verifyCard, fetchRates (external API!)
3. READ gitnexus://repo/my-app/process/CheckoutFlow
→ Step 3: validatePayment → calls fetchRates (external)
4. Root cause: fetchRates calls external API without proper timeout
Repository: my-app Index: current
```
With a single indexed repository, step 0 returns `total: 1` and the `repo`
argument drops out of every call above.
-100
View File
@@ -1,100 +0,0 @@
---
name: gitnexus-exploring
description: "Use when the user asks how code works, wants to understand architecture, trace execution flows, or explore unfamiliar parts of the codebase. Examples: \"How does X work?\", \"What calls this function?\", \"Show me the auth flow\""
---
# Exploring Codebases with GitNexus
## When to Use
- "How does authentication work?"
- "What's the project structure?"
- "Show me the main components"
- "Where is the database logic?"
- Understanding code you haven't seen before
## Bind the repository first
Step 1 discovers what is indexed; every call after it must say which of those
it means. With one indexed repository, use the examples below as written. With
more than one, pass `repo` on every call: an omitted `repo` normally errors,
but under an MCP policy with a configured default it resolves to that default
silently. If you cannot tell which repository is meant, stop and ask. Report
the bound repository and index freshness alongside your explanation.
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
`hasMore` is false before concluding a repository is absent.
## Workflow
```
1. list_repos {} or READ gitnexus://repos → Discover indexed repos
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
3. query({search_query: "<what you want to understand>"}) → Find related execution flows
4. context({name: "<symbol>"}) → Deep dive on specific symbol
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow
```
> If step 2 says "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
## Checklist
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] READ gitnexus://repo/{name}/context
- [ ] query for the concept you want to understand
- [ ] Review returned processes (execution flows)
- [ ] context on key symbols for callers/callees
- [ ] READ process resource for full execution traces
- [ ] Read source files for implementation details
- [ ] State the repository and index freshness with the explanation
```
## Resources
| Resource | What you get |
| --------------------------------------- | ------------------------------------------------------- |
| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) |
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores (~300 tokens) |
| `gitnexus://repo/{name}/cluster/{name}` | Area members with file paths (~500 tokens) |
| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) |
## Tools
**query** — find execution flows related to a concept:
```
query({search_query: "payment processing", repo: "my-app"})
→ Processes: CheckoutFlow, RefundFlow, WebhookHandler
→ Symbols grouped by flow with file locations
```
**context** — 360-degree view of a symbol:
```
context({name: "validateUser", repo: "my-app"})
→ Incoming calls: loginHandler, apiMiddleware
→ Outgoing calls: checkToken, getUserById
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3)
```
`repo` is required once more than one repository is indexed, and may be omitted
with a single one.
## Example: "How does payment processing work?"
```
1. list_repos {} → total: 1 (my-app) — bind it
READ gitnexus://repo/my-app/context → 918 symbols, 45 processes
2. query({search_query: "payment processing"})
→ CheckoutFlow: processPayment → validateCard → chargeStripe
→ RefundFlow: initiateRefund → calculateRefund → processRefund
3. context({name: "processPayment"})
→ Incoming: checkoutHandler, webhookHandler
→ Outgoing: validateCard, chargeStripe, saveTransaction
4. Read src/payments/processor.ts for implementation details
5. Answer, noting: Repository my-app, index current
```
Had step 1 returned two repositories, every call above would carry
`repo: "my-app"`.
-138
View File
@@ -1,138 +0,0 @@
---
name: gitnexus-guide
description: "Use when the user asks about GitNexus itself — available tools, how to query the knowledge graph, MCP resources, graph schema, or workflow reference. Examples: \"What GitNexus tools are available?\", \"How do I use GitNexus?\""
---
# GitNexus Guide
Quick reference for all GitNexus MCP tools, resources, and the knowledge graph schema.
## Always Start Here
For any task involving code understanding, debugging, impact analysis, or refactoring:
1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness
2. **Match your task to a skill below** and **read that skill file**
3. **Follow the skill's workflow and checklist**
> If step 1 warns the index is stale, run `node .gitnexus/run.cjs analyze` in the terminal first.
## Skills
| Task | Skill to read |
| -------------------------------------------- | ------------------- |
| Understand architecture / "How does X work?" | `gitnexus-exploring` |
| Blast radius / "What breaks if I change X?" | `gitnexus-impact-analysis` |
| Trace bugs / "Why is X failing?" | `gitnexus-debugging` |
| Rename / extract / split / refactor | `gitnexus-refactoring` |
| Tools, resources, schema reference | `gitnexus-guide` (this file) |
| Index, status, clean, wiki CLI commands | `gitnexus-cli` |
## Tools Reference
| Tool | What it gives you |
| ---------------- | ------------------------------------------------------------------------ |
| `query` | Process-grouped code intelligence — execution flows related to a concept |
| `context` | 360-degree symbol view — categorized refs, processes it participates in |
| `impact` | Symbol blast radius — what breaks at depth 1/2/3 with confidence |
| `trace` | Shortest path between two symbols — "how does A reach B?" in one call |
| `detect_changes` | Git-diff impact — what do your current changes affect |
| `rename` | Multi-file coordinated rename with confidence-tagged edits |
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) |
| `explain` | Persisted taint findings — source→sink data flows (needs `analyze --pdg`) |
| `pdg_query` | Control/data dependence — what gates X (CDG) / where Y flows (REACHING_DEF); needs `analyze --pdg` |
| `check` | Check graph invariants such as circular imports |
| `route_map` | API route map — which components/hooks fetch which endpoints, and the handler files that serve them |
| `shape_check` | Response-shape drift — keys each route returns vs keys its consumers access (flags MISMATCH) |
| `api_impact` | Pre-change report for an API route — consumers, middleware, shape mismatches, risk level |
| `tool_map` | MCP/RPC tool definitions and the files that handle them |
| `group_list` | List configured multi-repo groups, or one group's config |
| `group_sync` | Rebuild a group's Contract Registry (cross-repo HTTP contract links); run after `group.yaml` changes or member re-index |
| `list_repos` | Discover indexed repos (paginated — `limit`/`offset`) |
### Paginating `list_repos`
`list_repos` is paginated so a large registry is not truncated by MCP/LLM token limits. It takes optional `limit` (default **50**, max **200**) and `offset`, and returns:
```jsonc
{
"repositories": [
{ "name": "...", "path": "...", "indexedAt": "...", "lastCommit": "...", "stats": { } }
],
"pagination": {
"total": 437,
"limit": 50,
"offset": 0,
"returned": 50,
"hasMore": true,
"nextOffset": 50
}
}
```
To enumerate **every** repository, keep calling with `offset` set to `pagination.nextOffset` until `hasMore` is `false`:
```text
list_repos {} → repos 1–50, nextOffset 50, hasMore true
list_repos { offset: 50 } → repos 51–100, nextOffset 100, hasMore true
…
list_repos { offset: 400 } → repos 401–437, hasMore false (done)
```
Notes: `offset` ≥ `total` returns an empty page (with `total` still reported). Out-of-range or malformed `limit`/`offset` (non-integer, `limit` outside `[1, 200]`, `offset < 0`) are rejected with a clear error — `limit` above the max is rejected, not silently capped. The order is deterministic (lower-cased name, then path), so paging never skips or duplicates an entry while the registry is unchanged.
### Taint findings (`explain`)
`explain` returns taint findings recorded by `gitnexus analyze --pdg` — intra-procedural `TAINTED` edges plus cross-function `TAINT_PATH` hops where the interprocedural taint phase found a function-level source→sink chain. Each finding includes a sink category (command-injection, code-injection, path-traversal, sql-injection, xss), source/sink lines, and the ordered hop path with the variable carried on each hop.
- `explain {}` — enumerate all findings for the repo (bounded by `limit`, deterministic order)
- `explain { target: "src/vuln.ts" }` — findings in a file (suffix path match accepted)
- `explain { target: "runUserCommand" }` — findings in a function (resolved like `context`; ambiguous names return ranked candidates)
A repo indexed without `--pdg` returns a clear "no taint layer" note. Caveats: closure/callback, property/field, and implicit flows are not modeled, and interprocedural findings are function-level `TAINT_PATH` hops rather than statement-level path proof, so the absence of a finding is **not** proof of safety. `SANITIZES` (sanitizer-kill) edges are queryable via `cypher`.
### Control & data dependence (`pdg_query`)
`pdg_query` reads the control/data-dependence layers `gitnexus analyze --pdg` records (CDG + REACHING_DEF, basic-block granular) — the control/data analog of `explain`. It is **always anchored** (a `target` file path or symbol, resolved like `context`) and has two modes:
- `pdg_query { mode: "controls", target: "..." }` — CDG: "under what condition does X run?". Each edge is a controlling predicate block → dependent block with the branch sense (`'T'`/`'F'`) in `reason`; an edge into an early `return`/`throw` is flagged `guard: true` (guard-clause discovery — the sense depends on the predicate, so don't filter guards by a fixed label).
- `pdg_query { mode: "flows", target: "...", variable?: "..." }` — REACHING_DEF def→use edges within the function; pass `variable` to trace one binding.
A repo indexed without `--pdg` returns a "no PDG layer" note (or "status unknown" when the layer can't be confirmed). Intra-procedural only — cross-function flow is taint's domain (`explain`). The raw CDG/REACHING_DEF edges are also queryable via `cypher`. See the `gitnexus-pdg-query` skill for the full query surface.
### Shortest path between two symbols (`trace`)
`trace` answers "how does A reach B?" in one call — the shortest directed path over `CALLS` (plus `HAS_METHOD`, so a class-rooted trace descends into its methods) instead of chaining 3–8 `context`/`impact` hops by hand.
- `trace { from: "validateUser", to: "executeQuery" }` — shortest path between two symbols.
- Disambiguate common names with `from_uid`/`to_uid` (zero-ambiguity) or `from_file`/`to_file`; an ambiguous name returns ranked candidates.
- `maxDepth` (default 10, max 30) bounds the search; `includeTests` (default false) lets the traversal pass through test-file symbols.
Returns ordered `hops` (each `{ name, filePath, startLine }`) and an aligned `edges[]` of `{ relType, confidence }`, so call hops and containment (`HAS_METHOD`) hops stay distinguishable. When no path exists it reports the **furthest** reachable node (where the chain breaks) and sets `truncated: true` if a traversal cap was hit first. Every result carries a `status`: `ok` / `no_path` / `ambiguous` / `not_found` / `error`.
Cross-repo (experimental): pass `repo: "@groupName"` to trace across a group's member repos — the path may cross **one** `ContractLink` boundary (reported as a `CONTRACT_LINK` hop with the bridged contract in `crossings[]`). Omit `to` entirely to follow `from`'s outgoing HTTP call to whatever provider endpoint it lands on. Groups are configured via `group_list` / `group_sync`.
## Resources Reference
Lightweight reads (~100-500 tokens) for navigation:
| Resource | Content |
| ---------------------------------------------- | ----------------------------------------- |
| `gitnexus://repo/{name}/context` | Stats, staleness check |
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores |
| `gitnexus://repo/{name}/cluster/{clusterName}` | Area members |
| `gitnexus://repo/{name}/processes` | All execution flows |
| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace |
| `gitnexus://repo/{name}/schema` | Graph schema for Cypher |
## Graph Schema
**Nodes:** File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, Route, Tool, plus language-specific types (Struct, Enum, Trait, Impl, Namespace, Module, …) and BasicBlock (`--pdg` indexes only). The full node list lives in `gitnexus://repo/{name}/schema`.
**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, CONTAINS, MEMBER_OF, HAS_METHOD, HAS_PROPERTY, ACCESSES, METHOD_OVERRIDES, METHOD_IMPLEMENTS, STEP_IN_PROCESS, HANDLES_ROUTE, FETCHES, HANDLES_TOOL, ENTRY_POINT_OF, WRAPS, QUERIES, INJECTS, plus `--pdg`-only types (CFG, REACHING_DEF, TAINTED, SANITIZES, TAINT_PATH, CDG — zero rows on a default index).
Read `gitnexus://repo/{name}/schema` before writing Cypher — it is the authoritative schema for the indexed repo.
```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"})
RETURN caller.name, caller.filePath
```
@@ -1,167 +0,0 @@
---
name: gitnexus-impact-analysis
description: "Use when the user wants to know what will break if they change something, or needs safety analysis before editing code. Examples: \"Is it safe to change X?\", \"What depends on this?\", \"What will break?\""
---
# Impact Analysis with GitNexus
## When to Use
- "Is it safe to change this function?"
- "What will break if I modify X?"
- "Show me the blast radius"
- "Who uses this code?"
- Before making non-trivial code changes
- Before committing — to understand what your changes affect
## Bind the repository first
Impact analysis is the gate that authorizes an edit, so it must answer for the
repository you are about to edit.
Call `list_repos {}` before the first tool call. With one indexed repository,
use the examples below as written. With more than one, pass `repo` on every
call: an omitted `repo` normally errors, but under an MCP policy with a
configured default it resolves to that default silently. If you cannot tell
which repository is meant, stop and ask — every result below an ambiguous
identity inherits the ambiguity. `list_repos` is paginated, so page with
`offset: pagination.nextOffset` until `hasMore` is false before concluding a
repository is absent.
`detect_changes` takes `worktree` when your changes are in a linked worktree
the MCP server was not launched from. The server auto-detects a worktree only
when it was launched from inside one; otherwise `git diff` runs in the wrong
checkout and reports zero changed symbols — a false clean check that carries
none of the degradation flags described below. In the CLI fallbacks, `--repo .`
means the current checkout; pass the intended repository path instead when you
are not standing in it.
State the bound identity with your risk report:
```
Repository: <name> (<path>) Worktree: <path> Index: <commit>, <n> behind HEAD
```
## Workflow
```
0. list_repos {} → Bind repo (and worktree)
1. impact({target: "X", direction: "upstream"}) or `node .gitnexus/run.cjs impact "X" --direction upstream --repo .`
2. READ gitnexus://repo/{name}/processes → Check affected execution flows
3. detect_changes({scope: "all"}) or `node .gitnexus/run.cjs detect-changes --scope all --repo .`
4. Assess risk and report to user, echoing repo/worktree/index identity
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
> If `.gitnexus/run.cjs` is missing, replace `node .gitnexus/run.cjs` with `npx gitnexus` in the fallback commands.
## Checklist
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] impact({target, direction: "upstream"}) or CLI fallback to find dependents
- [ ] Review d=1 items first (these WILL BREAK)
- [ ] Check high-confidence (>0.8) dependencies
- [ ] READ processes to check affected execution flows
- [ ] detect_changes({scope: "all"}) or CLI fallback for pre-commit check
- [ ] Confirm the checkout you edited is the checkout that was diffed
- [ ] Assess risk level and report, stating repo/worktree/index identity
```
## Understanding Output
| Depth | Risk Level | Meaning |
| ----- | ---------------- | ------------------------ |
| d=1 | **WILL BREAK** | Direct callers/importers |
| d=2 | LIKELY AFFECTED | Indirect dependencies |
| d=3 | MAY NEED TESTING | Transitive effects |
## Risk Assessment
| Affected | Risk |
| ------------------------------ | -------- |
| <5 symbols, few processes | LOW |
| 5-15 symbols, 2-5 processes | MEDIUM |
| >15 symbols or many processes | HIGH |
| Critical path (auth, payments) | CRITICAL |
| **Zero callers found** | **UNKNOWN** |
`UNKNOWN` is not a low rung on this scale — it means the walk could not answer.
An empty caller set is equally consistent with "genuinely unused" and "the
callers are not resolvable by the index" (plain-object property access, dynamic
dispatch, cross-language calls), so few-callers ⇒ LOW does **not** apply. The
result carries a `riskNote` saying so. Confirm with a text search before
treating the symbol as safe to change or delete.
`risk` is the edit gate: warn on HIGH/CRITICAL and stop on UNKNOWN until the
uncertainty is resolved. Within single-repo mode, compare File and symbol
targets with local `riskSharedAxes` (direct/total only). Within group mode,
compare only group results: their `riskSharedAxes` overlays resolved
cross-repo crossings on that local value. Never use either field to waive the
edit gate. Check `riskScale.unusedAxes` before comparing kinds: MCP File walks
omit process/module axes, while web Graph-RAG expands File targets to in-file
symbols before enrichment.
## Tools
**impact** — the primary tool for symbol blast radius. If MCP is unavailable, use `node .gitnexus/run.cjs impact <symbol> --direction upstream --repo .` instead:
```
impact({
target: "validateUser",
repo: "my-app", // required once >1 repository is indexed
direction: "upstream",
minConfidence: 0.8,
maxDepth: 3
})
→ d=1 (WILL BREAK):
- loginHandler (src/auth/login.ts:42) [CALLS, 100%]
- apiMiddleware (src/api/middleware.ts:15) [CALLS, 100%]
→ d=2 (LIKELY AFFECTED):
- authRouter (src/routes/auth.ts:22) [CALLS, 95%]
```
**detect_changes** — git-diff based impact analysis. If MCP is unavailable, use `node .gitnexus/run.cjs detect-changes --scope all --repo .` instead:
```
detect_changes({scope: "all"})
→ Changed: 5 symbols in 3 files
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
→ Risk: MEDIUM
```
Add `repo` once more than one repository is indexed, and `worktree: "<abs
path>"` when your changes are in a linked worktree the server was not launched
from.
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
listing was capped) means the result is short of the truth, and reads like
`UNKNOWN` above: a zero there means unseen, not unaffected. Re-run it rather
than tick the pre-commit check.
A wrong-worktree zero carries neither flag and is shape-identical to a genuine
clean result, so confirm the checkout you edited is the one that was diffed
before treating an empty change set as a passed check.
## Example: "What breaks if I change validateUser?"
```
0. list_repos {}
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
1. impact({target: "validateUser", repo: "my-app", direction: "upstream"}) or `node .gitnexus/run.cjs impact "validateUser" --direction upstream --repo .`
→ d=1: loginHandler, apiMiddleware (WILL BREAK)
→ d=2: authRouter, sessionManager (LIKELY AFFECTED)
2. READ gitnexus://repo/my-app/processes
→ LoginFlow and TokenRefresh touch validateUser
3. Risk: 2 direct callers, 2 processes = MEDIUM
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
```
With a single indexed repository, step 0 returns `total: 1` and the `repo`
argument drops out of every call above.
@@ -1,164 +0,0 @@
---
name: gitnexus-refactoring
description: "Use when the user wants to rename, extract, split, move, or restructure code safely. Examples: \"Rename this function\", \"Extract this into a module\", \"Refactor this class\", \"Move this to a separate file\""
---
# Refactoring with GitNexus
## When to Use
- "Rename this function safely"
- "Extract this into a module"
- "Split this service"
- "Move this to a new file"
- Any task involving renaming, extracting, splitting, or restructuring code
## Bind the repository first
Refactoring writes to disk. `rename` with `dry_run: false` edits files in
whichever repository was resolved, so binding identity here is a safety gate,
not bookkeeping.
Call `list_repos {}` before the first tool call. With one indexed repository,
use the examples below as written. With more than one, pass `repo` on every
call: an omitted `repo` normally errors, but under an MCP policy with a
configured default it resolves to that default silently. If you cannot tell
which repository is meant, stop and ask. Never run `rename` with
`dry_run: false` until the preview in the same bound repository has been
reviewed — its returned `file_path` values show which checkout is about to be
written, so read them as a confirmation of identity.
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
`hasMore` is false before concluding a repository is absent.
`detect_changes` takes `worktree` when you are editing a linked worktree the
MCP server was not launched from; otherwise `git diff` runs in the wrong
checkout and reports nothing changed, which reads as a verified refactor.
## Workflow
```
0. list_repos {} → Bind repo (and worktree)
1. impact({target: "X", direction: "upstream"}) → Map all dependents
2. query({search_query: "X"}) → Find execution flows involving X
3. context({name: "X"}) → See all incoming/outgoing refs
4. Plan update order: interfaces → implementations → callers → tests
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
## Checklists
### Rename Symbol
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
- [ ] Confirm the previewed file paths are in the bound repository/worktree
- [ ] Review graph edits (high confidence) and text_search edits (review carefully)
- [ ] If satisfied: rename({..., dry_run: false}) — apply edits
- [ ] detect_changes() — verify only expected files changed
- [ ] Run tests for affected processes
```
### Extract Module
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] context({name: target}) — see all incoming/outgoing refs
- [ ] impact({target, direction: "upstream"}) — find all external callers
- [ ] Define new module interface
- [ ] Extract code, update imports
- [ ] detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
### Split Function/Service
```
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
- [ ] context({name: target}) — understand all callees
- [ ] Group callees by responsibility
- [ ] impact({target, direction: "upstream"}) — map callers to update
- [ ] Create new functions/services
- [ ] Update callers
- [ ] detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
## Tools
**rename** — automated multi-file rename:
```
rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
→ 12 edits across 8 files
→ 10 graph edits (high confidence), 2 text_search edits (review)
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}]
```
**impact** — map all dependents first:
```
impact({target: "validateUser", repo: "my-app", direction: "upstream"})
→ d=1: loginHandler, apiMiddleware, testUtils
→ Affected Processes: LoginFlow, TokenRefresh
```
**detect_changes** — verify your changes after refactoring:
```
detect_changes({scope: "all"})
→ Changed: 8 files, 12 symbols
→ Affected processes: LoginFlow, TokenRefresh
→ Risk: MEDIUM
```
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
listing was capped) means the result is short of the truth: a short or empty
list is not proof that only the expected files changed. Re-run it rather than
treat the refactor as verified.
A wrong-worktree zero carries neither flag and is indistinguishable from a
clean verification, so confirm the diffed checkout is the one you edited.
**cypher** — custom reference queries:
```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"})
RETURN caller.name, caller.filePath ORDER BY caller.filePath
```
## Risk Rules
| Risk Factor | Mitigation |
| ------------------- | ----------------------------------------- |
| Many callers (>5) | Use rename for automated updates |
| Cross-area refs | Use detect_changes after to verify scope |
| String/dynamic refs | query to find them |
| External/public API | Version and deprecate properly |
| Same name in another indexed repo | Bind `repo`; verify previewed paths before applying |
## Example: Rename `validateUser` to `authenticateUser`
```
0. list_repos {}
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
1. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
→ 12 edits: 10 graph (safe), 2 text_search (review)
→ Files: validator.ts, login.ts, middleware.ts, config.json...
2. Review text_search edits (config.json: dynamic reference!)
3. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: false})
→ Applied 12 edits across 8 files
4. detect_changes({scope: "all", repo: "my-app"})
→ Affected: LoginFlow, TokenRefresh
→ Risk: MEDIUM — run tests for these flows
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
```
With a single indexed repository, step 0 returns `total: 1` and the `repo`
argument drops out of every call above.
@@ -5,16 +5,14 @@ description: "Use when the user needs to run GitNexus CLI commands like analyze/
# GitNexus CLI Commands
Commands below use `node .gitnexus/run.cjs <command>` — the project-local runner `gitnexus analyze` drops next to the index. It auto-selects an available runner at call time (global `gitnexus`, else `pnpm dlx`, else `npx`), so no package-manager assumption and no global install is required.
> **Not analyzed yet, or `node .gitnexus/run.cjs` reports `Cannot find module`** (the gitignored runner is absent — e.g. a fresh clone or `git clean`)? (Re)generate it with `npx gitnexus analyze` from the project root. On **npm 11.x**, if `npx` crashes during install (`node.target is null`), install once with `npm i -g gitnexus` (then `gitnexus analyze`) or use `pnpm --allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx gitnexus@latest analyze`. See [#1939](https://github.com/abhigyanpatwari/GitNexus/issues/1939).
All commands work via `npx` — no global install required.
## Commands
### analyze — Build or refresh the index
```bash
node .gitnexus/run.cjs analyze
npx gitnexus analyze
```
Run from the project root. This parses all source files, builds the knowledge graph, writes it to `.gitnexus/`, and generates CLAUDE.md / AGENTS.md context files.
@@ -30,7 +28,7 @@ Run from the project root. This parses all source files, builds the knowledge gr
### status — Check index freshness
```bash
node .gitnexus/run.cjs status
npx gitnexus status
```
Shows whether the current repo has a GitNexus index, when it was last updated, and symbol/relationship counts. Use this to check if re-indexing is needed.
@@ -38,7 +36,7 @@ Shows whether the current repo has a GitNexus index, when it was last updated, a
### clean — Delete the index
```bash
node .gitnexus/run.cjs clean
npx gitnexus clean
```
Deletes the `.gitnexus/` directory and unregisters the repo from the global registry. Use before re-indexing if the index is corrupt or after removing GitNexus from a project.
@@ -51,7 +49,7 @@ Deletes the `.gitnexus/` directory and unregisters the repo from the global regi
### wiki — Generate documentation from the graph
```bash
node .gitnexus/run.cjs wiki
npx gitnexus wiki
```
Generates repository documentation from the knowledge graph using an LLM. Requires an API key (saved to `~/.gitnexus/config.json` on first use).
@@ -68,7 +66,7 @@ Generates repository documentation from the knowledge graph using an LLM. Requir
### list — Show all indexed repos
```bash
node .gitnexus/run.cjs list
npx gitnexus list
```
Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information.
@@ -16,23 +16,23 @@ description: "Use when the user is debugging a bug, tracing an error, or asking
## Workflow
```
1. query({query: "<error or symptom>"}) → Find related execution flows
2. context({name: "<suspect>"}) → See callers/callees/processes
1. gitnexus_query({query: "<error or symptom>"}) → Find related execution flows
2. gitnexus_context({name: "<suspect>"}) → See callers/callees/processes
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow
4. cypher({query: "MATCH path..."}) → Custom traces if needed
4. gitnexus_cypher({query: "MATCH path..."}) → Custom traces if needed
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
> If "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklist
```
- [ ] Understand the symptom (error message, unexpected behavior)
- [ ] query for error text or related code
- [ ] gitnexus_query for error text or related code
- [ ] Identify the suspect function from returned processes
- [ ] context to see callers and callees
- [ ] gitnexus_context to see callers and callees
- [ ] Trace execution flow via process resource if applicable
- [ ] cypher for custom call chain traces if needed
- [ ] gitnexus_cypher for custom call chain traces if needed
- [ ] Read source files to confirm root cause
```
@@ -40,7 +40,7 @@ description: "Use when the user is debugging a bug, tracing an error, or asking
| Symptom | GitNexus Approach |
| -------------------- | ---------------------------------------------------------- |
| Error message | `query` for error text → `context` on throw sites |
| Error message | `gitnexus_query` for error text → `context` on throw sites |
| Wrong return value | `context` on the function → trace callees for data flow |
| Intermittent failure | `context` → look for external calls, async deps |
| Performance issue | `context` → find symbols with many callers (hot paths) |
@@ -48,24 +48,24 @@ description: "Use when the user is debugging a bug, tracing an error, or asking
## Tools
**query** — find code related to error:
**gitnexus_query** — find code related to error:
```
query({query: "payment validation error"})
gitnexus_query({query: "payment validation error"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError, PaymentException
```
**context** — full context for a suspect:
**gitnexus_context** — full context for a suspect:
```
context({name: "validatePayment"})
gitnexus_context({name: "validatePayment"})
→ Incoming calls: processCheckout, webhookHandler
→ Outgoing calls: verifyCard, fetchRates (external API!)
→ Processes: CheckoutFlow (step 3/7)
```
**cypher** — custom call chain traces:
**gitnexus_cypher** — custom call chain traces:
```cypher
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"})
@@ -75,11 +75,11 @@ RETURN [n IN nodes(path) | n.name] AS chain
## Example: "Payment endpoint returns 500 intermittently"
```
1. query({query: "payment error handling"})
1. gitnexus_query({query: "payment error handling"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError
2. context({name: "validatePayment"})
2. gitnexus_context({name: "validatePayment"})
→ Outgoing calls: verifyCard, fetchRates (external API!)
3. READ gitnexus://repo/my-app/process/CheckoutFlow
@@ -18,20 +18,20 @@ description: "Use when the user asks how code works, wants to understand archite
```
1. READ gitnexus://repos → Discover indexed repos
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
3. query({query: "<what you want to understand>"}) → Find related execution flows
4. context({name: "<symbol>"}) → Deep dive on specific symbol
3. gitnexus_query({query: "<what you want to understand>"}) → Find related execution flows
4. gitnexus_context({name: "<symbol>"}) → Deep dive on specific symbol
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow
```
> If step 2 says "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklist
```
- [ ] READ gitnexus://repo/{name}/context
- [ ] query for the concept you want to understand
- [ ] gitnexus_query for the concept you want to understand
- [ ] Review returned processes (execution flows)
- [ ] context on key symbols for callers/callees
- [ ] gitnexus_context on key symbols for callers/callees
- [ ] READ process resource for full execution traces
- [ ] Read source files for implementation details
```
@@ -47,18 +47,18 @@ description: "Use when the user asks how code works, wants to understand archite
## Tools
**query** — find execution flows related to a concept:
**gitnexus_query** — find execution flows related to a concept:
```
query({query: "payment processing"})
gitnexus_query({query: "payment processing"})
→ Processes: CheckoutFlow, RefundFlow, WebhookHandler
→ Symbols grouped by flow with file locations
```
**context** — 360-degree view of a symbol:
**gitnexus_context** — 360-degree view of a symbol:
```
context({name: "validateUser"})
gitnexus_context({name: "validateUser"})
→ Incoming calls: loginHandler, apiMiddleware
→ Outgoing calls: checkToken, getUserById
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3)
@@ -68,10 +68,10 @@ context({name: "validateUser"})
```
1. READ gitnexus://repo/my-app/context → 918 symbols, 45 processes
2. query({query: "payment processing"})
2. gitnexus_query({query: "payment processing"})
→ CheckoutFlow: processPayment → validateCard → chargeStripe
→ RefundFlow: initiateRefund → calculateRefund → processRefund
3. context({name: "processPayment"})
3. gitnexus_context({name: "processPayment"})
→ Incoming: checkoutHandler, webhookHandler
→ Outgoing: validateCard, chargeStripe, saveTransaction
4. Read src/payments/processor.ts for implementation details
@@ -15,7 +15,7 @@ For any task involving code understanding, debugging, impact analysis, or refact
2. **Match your task to a skill below** and **read that skill file**
3. **Follow the skill's workflow and checklist**
> If step 1 warns the index is stale, run `node .gitnexus/run.cjs analyze` in the terminal first.
> If step 1 warns the index is stale, run `npx gitnexus analyze` in the terminal first.
## Skills
@@ -38,38 +38,7 @@ For any task involving code understanding, debugging, impact analysis, or refact
| `detect_changes` | Git-diff impact — what do your current changes affect |
| `rename` | Multi-file coordinated rename with confidence-tagged edits |
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) |
| `list_repos` | Discover indexed repos (paginated — `limit`/`offset`) |
### Paginating `list_repos`
`list_repos` is paginated so a large registry is not truncated by MCP/LLM token limits. It takes optional `limit` (default **50**, max **200**) and `offset`, and returns:
```jsonc
{
"repositories": [
{ "name": "...", "path": "...", "indexedAt": "...", "lastCommit": "...", "stats": { } }
],
"pagination": {
"total": 437,
"limit": 50,
"offset": 0,
"returned": 50,
"hasMore": true,
"nextOffset": 50
}
}
```
To enumerate **every** repository, keep calling with `offset` set to `pagination.nextOffset` until `hasMore` is `false`:
```text
list_repos {} → repos 1–50, nextOffset 50, hasMore true
list_repos { offset: 50 } → repos 51–100, nextOffset 100, hasMore true
…
list_repos { offset: 400 } → repos 401–437, hasMore false (done)
```
Notes: `offset` ≥ `total` returns an empty page (with `total` still reported). Out-of-range or malformed `limit`/`offset` (non-integer, `limit` outside `[1, 200]`, `offset < 0`) are rejected with a clear error — `limit` above the max is rejected, not silently capped. The order is deterministic (lower-cased name, then path), so paging never skips or duplicates an entry while the registry is unchanged.
| `list_repos` | Discover indexed repos |
## Resources Reference
@@ -17,22 +17,22 @@ description: "Use when the user wants to know what will break if they change som
## Workflow
```
1. impact({target: "X", direction: "upstream"}) → What depends on this
1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this
2. READ gitnexus://repo/{name}/processes → Check affected execution flows
3. detect_changes() → Map current git changes to affected flows
3. gitnexus_detect_changes() → Map current git changes to affected flows
4. Assess risk and report to user
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
> If "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklist
```
- [ ] impact({target, direction: "upstream"}) to find dependents
- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents
- [ ] Review d=1 items first (these WILL BREAK)
- [ ] Check high-confidence (>0.8) dependencies
- [ ] READ processes to check affected execution flows
- [ ] detect_changes() for pre-commit check
- [ ] gitnexus_detect_changes() for pre-commit check
- [ ] Assess risk level and report to user
```
@@ -55,10 +55,10 @@ description: "Use when the user wants to know what will break if they change som
## Tools
**impact** — the primary tool for symbol blast radius:
**gitnexus_impact** — the primary tool for symbol blast radius:
```
impact({
gitnexus_impact({
target: "validateUser",
direction: "upstream",
minConfidence: 0.8,
@@ -73,10 +73,10 @@ impact({
- authRouter (src/routes/auth.ts:22) [CALLS, 95%]
```
**detect_changes** — git-diff based impact analysis:
**gitnexus_detect_changes** — git-diff based impact analysis:
```
detect_changes({scope: "staged"})
gitnexus_detect_changes({scope: "staged"})
→ Changed: 5 symbols in 3 files
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
@@ -86,7 +86,7 @@ detect_changes({scope: "staged"})
## Example: "What breaks if I change validateUser?"
```
1. impact({target: "validateUser", direction: "upstream"})
1. gitnexus_impact({target: "validateUser", direction: "upstream"})
→ d=1: loginHandler, apiMiddleware (WILL BREAK)
→ d=2: authRouter, sessionManager (LIKELY AFFECTED)
@@ -16,78 +16,78 @@ description: "Use when the user wants to rename, extract, split, move, or restru
## Workflow
```
1. impact({target: "X", direction: "upstream"}) → Map all dependents
2. query({query: "X"}) → Find execution flows involving X
3. context({name: "X"}) → See all incoming/outgoing refs
1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents
2. gitnexus_query({query: "X"}) → Find execution flows involving X
3. gitnexus_context({name: "X"}) → See all incoming/outgoing refs
4. Plan update order: interfaces → implementations → callers → tests
```
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
> If "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklists
### Rename Symbol
```
- [ ] rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
- [ ] gitnexus_rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
- [ ] Review graph edits (high confidence) and ast_search edits (review carefully)
- [ ] If satisfied: rename({..., dry_run: false}) — apply edits
- [ ] detect_changes() — verify only expected files changed
- [ ] If satisfied: gitnexus_rename({..., dry_run: false}) — apply edits
- [ ] gitnexus_detect_changes() — verify only expected files changed
- [ ] Run tests for affected processes
```
### Extract Module
```
- [ ] context({name: target}) — see all incoming/outgoing refs
- [ ] impact({target, direction: "upstream"}) — find all external callers
- [ ] gitnexus_context({name: target}) — see all incoming/outgoing refs
- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers
- [ ] Define new module interface
- [ ] Extract code, update imports
- [ ] detect_changes() — verify affected scope
- [ ] gitnexus_detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
### Split Function/Service
```
- [ ] context({name: target}) — understand all callees
- [ ] gitnexus_context({name: target}) — understand all callees
- [ ] Group callees by responsibility
- [ ] impact({target, direction: "upstream"}) — map callers to update
- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update
- [ ] Create new functions/services
- [ ] Update callers
- [ ] detect_changes() — verify affected scope
- [ ] gitnexus_detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
## Tools
**rename** — automated multi-file rename:
**gitnexus_rename** — automated multi-file rename:
```
rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true})
gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true})
→ 12 edits across 8 files
→ 10 graph edits (high confidence), 2 ast_search edits (review)
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}]
```
**impact** — map all dependents first:
**gitnexus_impact** — map all dependents first:
```
impact({target: "validateUser", direction: "upstream"})
gitnexus_impact({target: "validateUser", direction: "upstream"})
→ d=1: loginHandler, apiMiddleware, testUtils
→ Affected Processes: LoginFlow, TokenRefresh
```
**detect_changes** — verify your changes after refactoring:
**gitnexus_detect_changes** — verify your changes after refactoring:
```
detect_changes({scope: "all"})
gitnexus_detect_changes({scope: "all"})
→ Changed: 8 files, 12 symbols
→ Affected processes: LoginFlow, TokenRefresh
→ Risk: MEDIUM
```
**cypher** — custom reference queries:
**gitnexus_cypher** — custom reference queries:
```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"})
@@ -98,24 +98,24 @@ RETURN caller.name, caller.filePath ORDER BY caller.filePath
| Risk Factor | Mitigation |
| ------------------- | ----------------------------------------- |
| Many callers (>5) | Use rename for automated updates |
| Many callers (>5) | Use gitnexus_rename for automated updates |
| Cross-area refs | Use detect_changes after to verify scope |
| String/dynamic refs | query to find them |
| String/dynamic refs | gitnexus_query to find them |
| External/public API | Version and deprecate properly |
## Example: Rename `validateUser` to `authenticateUser`
```
1. rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true})
1. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true})
→ 12 edits: 10 graph (safe), 2 ast_search (review)
→ Files: validator.ts, login.ts, middleware.ts, config.json...
2. Review ast_search edits (config.json: dynamic reference!)
3. rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false})
3. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false})
→ Applied 12 edits across 8 files
4. detect_changes({scope: "all"})
4. gitnexus_detect_changes({scope: "all"})
→ Affected: LoginFlow, TokenRefresh
→ Risk: MEDIUM — run tests for these flows
```
-18
View File
@@ -1,18 +0,0 @@
import { createHash } from 'node:crypto';
import { access, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, latestSuccess, recordsRoot, snapshotRoot } from './release-store.mjs';
const environment = envName(process.env.RELEASE_ENVIRONMENT);
const commitSha = process.env.RELEASE_SHA;
const record = await latestSuccess(environment, 'nacos');
if (!commitSha || record.commitSha !== commitSha || record.status !== 'success') throw new Error(`没有提交 ${commitSha} 对应的成功 Nacos 发布`);
if (!record.activeSnapshotId || !record.snapshotId || !Array.isArray(record.files) || record.files.length === 0 || record.files.some((file) => !file.sha256 || !file.dataId || !file.namespace)) throw new Error('Nacos 发布记录不完整');
const destinations = environment === 'prod' ? ['prod-center1', 'prod-center2'] : [environment];
for (const destination of destinations) for (const file of record.files) {
const path = join(snapshotRoot(environment, record.activeSnapshotId), destination, file.namespace, 'DEFAULT_GROUP', file.dataId);
const content = await readFile(path, 'utf8');
if (createHash('sha256').update(content, 'utf8').digest('hex') !== file.sha256) throw new Error(`Nacos 发布快照摘要不匹配:${destination}/${file.namespace}/${file.dataId}`);
}
await access(join(recordsRoot(environment), 'latest-success-nacos.json'));
console.log(JSON.stringify(record));
-20
View File
@@ -1,20 +0,0 @@
const workflow = process.argv[2];
const ref = process.argv[3] || process.env.GITHUB_REF_NAME;
if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs <workflow.yml> <ref>');
const token = process.env.GITHUB_TOKEN;
if (!token) throw new Error('缺少 GITHUB_TOKEN');
const server = process.env.GITHUB_SERVER_URL || 'http://wcsrv.top:3000';
const repository = process.env.GITHUB_REPOSITORY || 'xiaowang/JayuCloud';
const inputs = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('DISPATCH_INPUT_')).map(([key, value]) => [key.slice('DISPATCH_INPUT_'.length).toLowerCase(), value]));
if (process.env.AUTO_ROLLBACK === 'true') inputs.auto_rollback = 'true';
const isNacosRollback = /^(回退dev环境nacos配置|回退sit环境nacos配置|回退prod环境nacos配置)\.yml$/.test(workflow);
if (isNacosRollback && !inputs.snapshot_id && process.env.RELEASE_STORE_ROOT && (process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT)) {
try { inputs.snapshot_id = JSON.parse(await (await import('node:fs/promises')).readFile(`${process.env.RELEASE_STORE_ROOT}/records/${process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT}/pending-nacos.json`, 'utf8')).snapshotId; } catch {}
}
if (isNacosRollback && process.env.AUTO_ROLLBACK === 'true' && !inputs.snapshot_id) {
console.log('没有待处理的 Nacos 发布快照,无需触发 Nacos 回退');
process.exit(0);
}
const response = await fetch(`${server}/api/v1/repos/${repository}/actions/workflows/${workflow}/dispatches`, { method: 'POST', headers: { Authorization: `token ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ ref, inputs }) });
if (!response.ok && response.status !== 204) throw new Error(`触发 ${workflow} 失败:HTTP ${response.status} ${await response.text()}`);
console.log(`已触发 ${workflow} @ ${ref}`);
-25
View File
@@ -1,25 +0,0 @@
import { createHash } from 'node:crypto';
export async function verifyConfigReadback(url, expectedContent, expectExists, options = {}) {
const request = options.request || fetch;
const attempts = options.attempts || 3;
const delayMs = options.delayMs ?? 1000;
const expectedHash = expectExists ? sha256(expectedContent) : null;
for (let attempt = 0; attempt < attempts; attempt += 1) {
const response = await request(url);
const actual = await response.text();
const matches = expectExists
? response.ok && sha256(actual) === expectedHash
: response.status === 404;
if (matches) return true;
if (attempt + 1 < attempts && delayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
return false;
}
function sha256(value) {
return createHash('sha256').update(value ?? '', 'utf8').digest('hex');
}
-45
View File
@@ -1,45 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { verifyConfigReadback } from './nacos-readback.mjs';
test('retries a stale read until the restored config is visible', async () => {
const responses = [
new Response('old config', { status: 200 }),
new Response('restored config', { status: 200 })
];
let calls = 0;
const verified = await verifyConfigReadback('http://nacos/config', 'restored config', true, {
request: async () => responses[calls++],
attempts: 3,
delayMs: 0
});
assert.equal(verified, true);
assert.equal(calls, 2);
});
test('fails closed when the config does not match after bounded retries', async () => {
let calls = 0;
const verified = await verifyConfigReadback('http://nacos/config', 'restored config', true, {
request: async () => {
calls += 1;
return new Response('different config', { status: 200 });
},
attempts: 3,
delayMs: 0
});
assert.equal(verified, false);
assert.equal(calls, 3);
});
test('confirms deletion only after the config is absent', async () => {
const verified = await verifyConfigReadback('http://nacos/config', null, false, {
request: async () => new Response(null, { status: 404 }),
attempts: 1,
delayMs: 0
});
assert.equal(verified, true);
});
-79
View File
@@ -1,79 +0,0 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, readdir, rm } from 'node:fs/promises';
import { join, relative, sep } from 'node:path';
import { atomicWrite, envName, listYamlFiles, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP';
const root = process.cwd();
const configRoot = join(root, 'nacos', 'namespaces', environment);
const files = await listYamlFiles(configRoot);
if (!files.length) throw new Error(`没有可发布的 ${environment} YAML 配置`);
const destinations = (environment === 'prod' ? [['NACOS_PROD', 'prod-center1', 2], ['NACOS_DR', 'prod-center2', 1]] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment, 1]]).map(([prefix, id, nodes]) => {
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
if (urls.length < nodes) throw new Error(`${prefix} Nacos 地址不足`);
return { prefix, id, urls, token: null, nodes };
});
for (const destination of destinations) destination.token = await login(destination.urls[0], required(`${destination.prefix}_USERNAME`), required(`${destination.prefix}_PASSWORD`));
const groupName = group;
const runId = process.env.GITHUB_RUN_ID || 'manual';
const commitSha = process.env.GITHUB_SHA || 'unknown';
const recordRoot = recordsRoot(environment);
const snapshotId = `${new Date().toISOString().replaceAll(/[:.]/g, '-')}-${runId}`;
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${runId}`;
const snapshot = snapshotRoot(environment, snapshotId);
const activeSnapshotId = `active-${releaseId}`;
const activeSnapshot = snapshotRoot(environment, activeSnapshotId);
await mkdir(snapshot, { recursive: true });
await mkdir(activeSnapshot, { recursive: true });
const entries = [];
for (const file of files) {
const { namespace, dataId } = info(file);
const content = await readFile(file, 'utf8');
const entry = { namespace, dataId, sha256: sha256(content), previousSha256: {}, previousExists: {} };
entries.push(entry);
for (const destination of destinations) {
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`);
if (!response.ok && response.status !== 404) throw new Error(`读取当前 Nacos 配置失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
const oldContent = await response.text();
entry.previousExists[destination.id] = response.status !== 404;
entry.previousSha256[destination.id] = sha256(oldContent);
await atomicWrite(join(snapshot, destination.id, namespace, groupName, dataId), oldContent);
await atomicWrite(join(activeSnapshot, destination.id, namespace, groupName, dataId), content);
}
}
await writeJson(join(recordRoot, 'pending-nacos.json'), { environment, snapshotId, activeSnapshotId, commitSha, runId, releaseId, files: entries, createdAt: new Date().toISOString() });
try {
for (const file of files) {
const { namespace, dataId } = info(file);
const content = await readFile(file, 'utf8');
for (const destination of destinations) {
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(destination.token)}`, { method: 'POST', body: new URLSearchParams({ dataId, group: groupName, tenant: namespace, type: 'yaml', content }) });
const result = await response.text();
if (!response.ok || result.trim() !== 'true') throw new Error(`发布失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
await verify(destination, namespace, dataId, content);
}
}
const previous = await optionalJson(join(recordRoot, 'latest-success-nacos.json'));
const record = { environment, status: 'success', commitSha, runId, releaseId, snapshotId, activeSnapshotId, previousReleaseId: previous?.releaseId || null, files: entries, publishedAt: new Date().toISOString() };
await writeJson(join(recordRoot, 'latest-success-nacos.json'), record);
await writeJson(join(recordRoot, 'nacos', `${releaseId}.json`), record);
await rm(join(recordRoot, 'pending-nacos.json'), { force: true });
console.log(`已发布并校验 ${environment} Nacos,回退快照 ${snapshotId}`);
} catch (error) {
console.error(error.message);
console.error(`AUTO_ROLLBACK_SNAPSHOT_ID=${snapshotId}`);
throw error;
}
function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; }
function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); }
function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
function info(file) {
const parts = relative(configRoot, file).split(sep);
if (parts.length !== 3 || parts[1] !== group || !parts[0] || !parts[2]) throw new Error(`配置路径无效,必须为 namespace/${group}/dataId:${file}`);
return { namespace: parts[0], dataId: parts[2] };
}
async function optionalJson(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; }
async function verify(destination, namespace, dataId, expected) { const expectedHash = sha256(expected); for (const base of destination.urls) { let status = 0; let content = ''; for (let attempt = 0; attempt < 3; attempt += 1) { const response = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`); status = response.status; content = await response.text(); if (status === 200 && sha256(content) === expectedHash) break; await new Promise((resolve) => setTimeout(resolve, 1000)); } if (status !== 200 || sha256(content) !== expectedHash) throw new Error(`Nacos 校验失败:${destination.prefix}/${base}/${namespace}/${dataId}`); } }
-37
View File
@@ -1,37 +0,0 @@
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, latestSuccess, recordsRoot, writeJson } from './release-store.mjs';
const environment = envName(process.env.RELEASE_ENVIRONMENT);
const commitSha = process.env.RELEASE_SHA;
const nacos = await latestSuccess(environment, 'nacos');
const packageDir = process.env.PACKAGE_DIRECTORY;
if (!commitSha || nacos.commitSha !== commitSha || !packageDir) throw new Error('部署记录参数不完整');
if (nacos.status !== 'success' || !nacos.files?.length || !nacos.activeSnapshotId) throw new Error('Nacos 发布已回退或发布记录不完整');
const manifestPath = await findFile(packageDir, 'manifest.json');
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
const artifactPaths = {};
for (const [name, fileName] of Object.entries({ core: 'JC-Salon-Core.jar', gateway: 'JC-Salon-Gateway.jar', frontend: 'jc-salon-frontend-dist.tar.gz' })) {
const artifactPath = await findFile(packageDir, fileName);
const sha256 = createHash('sha256').update(await readFile(artifactPath)).digest('hex');
const expected = manifest.artifacts?.find((item) => item.Path?.endsWith(fileName))?.Sha256?.toLowerCase();
if (!expected || expected !== sha256) throw new Error(`发布包摘要不匹配:${fileName}`);
artifactPaths[name] = { path: artifactPath, sha256 };
}
const previous = await optional(join(recordsRoot(environment), 'latest-success-deploy.json'));
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${process.env.GITHUB_RUN_ID || 'manual'}`;
const record = { environment, status: 'success', commitSha, releaseId, nacosReleaseId: nacos.releaseId, snapshotId: nacos.snapshotId, activeSnapshotId: nacos.activeSnapshotId, packageDir, manifestPath, artifacts: artifactPaths, previousReleaseId: previous?.releaseId || null, runId: process.env.GITHUB_RUN_ID || 'manual', deployedAt: new Date().toISOString() };
await writeJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`), record);
await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), record);
console.log(JSON.stringify(record));
async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function findFile(root, name) {
for (const entry of await readdir(root, { withFileTypes: true })) {
const path = join(root, entry.name);
if (entry.isDirectory()) { const nested = await optionalFind(path, name); if (nested) return nested; }
else if (entry.name === name) return path;
}
throw new Error(`发布包缺少 ${name}`);
}
async function optionalFind(root, name) { try { return await findFile(root, name); } catch { return null; } }
-10
View File
@@ -1,10 +0,0 @@
import { join } from 'node:path';
import { envName, recordsRoot, readJson, writeJson } from './release-store.mjs';
const environment = envName(process.env.RELEASE_ENVIRONMENT);
const releaseId = process.env.ROLLBACK_RELEASE_ID;
if (!releaseId) throw new Error('缺少 ROLLBACK_RELEASE_ID');
const record = await readJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`));
if (record.status !== 'success' || !record.packageDir || !record.activeSnapshotId) throw new Error('目标回退版本记录不完整');
await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), { ...record, restoredAt: new Date().toISOString() });
console.log(`已将 ${environment} 成功版本指针更新到 ${releaseId}`);
-62
View File
@@ -1,62 +0,0 @@
import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
export const storeRoot = process.env.RELEASE_STORE_ROOT || '/salon-release';
export function envName(value = process.env.NACOS_ENVIRONMENT) {
if (!['dev', 'sit', 'prod'].includes(value)) throw new Error(`不支持的环境:${value}`);
return value;
}
export function environmentRoot(environment = envName()) {
return join(storeRoot, environment);
}
export function snapshotRoot(environment = envName(), snapshotId) {
return join(storeRoot, 'nacos-snapshots', environment, snapshotId);
}
export function recordsRoot(environment = envName()) {
return join(storeRoot, 'records', environment);
}
export async function atomicWrite(path, content) {
await mkdir(dirname(path), { recursive: true });
const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
await writeFile(temp, content, 'utf8');
await rename(temp, path);
}
export async function readJson(path) {
return JSON.parse(await readFile(path, 'utf8'));
}
export async function writeJson(path, value) {
await atomicWrite(path, `${JSON.stringify(value, null, 2)}\n`);
}
export async function latestSuccess(environment = envName(), kind = 'nacos') {
const path = join(recordsRoot(environment), `latest-success-${kind}.json`);
return readJson(path);
}
export async function releaseRecord(environment, kind, releaseId) {
return readJson(join(recordsRoot(environment), kind, `${releaseId}.json`));
}
export async function listYamlFiles(root) {
const result = [];
for (const entry of await readdir(root, { withFileTypes: true })) {
const path = join(root, entry.name);
if (entry.isDirectory()) result.push(...await listYamlFiles(path));
else if (entry.isFile() && entry.name.endsWith('.yaml')) result.push(path);
}
return result.sort();
}
export function safeRelative(root, path) {
const value = resolve(path);
const base = resolve(root);
if (!value.startsWith(`${base}/`) && !value.startsWith(`${base}\\`)) throw new Error(`路径越界:${path}`);
return value.slice(base.length + 1).replaceAll('\\', '/');
}
-67
View File
@@ -1,67 +0,0 @@
import { createHash } from 'node:crypto';
import { readFile, readdir, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
import { verifyConfigReadback } from './nacos-readback.mjs';
const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP';
const destinations = environment === 'prod' ? [['NACOS_PROD', 'prod-center1'], ['NACOS_DR', 'prod-center2']] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment]];
const targets = [];
for (const [prefix, id] of destinations) {
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
if (!urls.length) throw new Error(`${prefix}_URLS 为空`);
targets.push({ prefix, id, urls, token: await login(urls[0], required(`${prefix}_USERNAME`), required(`${prefix}_PASSWORD`)) });
}
const root = recordsRoot(environment);
const pending = await optional(join(root, 'pending-nacos.json'));
const latest = await optional(join(root, 'latest-success-nacos.json'));
let selected = process.env.NACOS_RELEASE_ID
? await optional(join(root, 'nacos', `${process.env.NACOS_RELEASE_ID}.json`))
: null;
if (process.env.NACOS_RELEASE_ID && !selected) throw new Error(`找不到 Nacos 发布记录:${process.env.NACOS_RELEASE_ID}`);
if (!process.env.NACOS_SNAPSHOT_ID && !pending && !selected && latest?.previousReleaseId) selected = await optional(join(root, 'nacos', `${latest.previousReleaseId}.json`));
const snapshotId = process.env.NACOS_SNAPSHOT_ID || (selected ? selected.activeSnapshotId : pending?.snapshotId || latest?.snapshotId);
if (!snapshotId) throw new Error(`没有 ${environment} Nacos 回退快照`);
if (!selected && !pending) selected = await findSnapshotRecord(join(root, 'nacos'), snapshotId);
const snapshot = snapshotRoot(environment, snapshotId);
const entries = selected?.files || pending?.files || latest?.files || [];
const selectedIsActive = selected?.activeSnapshotId === snapshotId;
if (!entries.length) throw new Error('回退记录缺少配置清单');
for (const target of targets) {
for (const entry of entries) {
for (const base of target.urls) {
const exists = selectedIsActive || entry.previousExists?.[target.id] !== false;
const path = join(snapshot, target.id, entry.namespace, group, entry.dataId);
const content = exists ? await readFile(path, 'utf8') : '';
const expectedHash = selectedIsActive ? entry.sha256 : entry.previousSha256?.[target.id];
if (exists && (!expectedHash || sha256(content) !== expectedHash)) throw new Error(`回退快照摘要不匹配:${target.id}/${entry.namespace}/${entry.dataId}`);
const query = new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token });
const response = exists
? await fetch(`${base}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(target.token)}`, { method: 'POST', body: new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, type: 'yaml', content }) })
: await fetch(`${base}/nacos/v1/cs/configs?${query}`, { method: 'DELETE' });
if (!response.ok || (exists && (await response.text()).trim() !== 'true')) throw new Error(`回退失败:${target.id}/${entry.namespace}/${entry.dataId}`);
const checkUrl = `${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`;
if (!(await verifyConfigReadback(checkUrl, content, exists))) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`);
}
}
}
await writeJson(join(root, 'last-rollback.json'), { environment, snapshotId, source: process.env.AUTO_ROLLBACK === 'true' ? 'automatic' : 'manual', rollbackAt: new Date().toISOString() });
if (selectedIsActive && selected) await writeJson(join(root, 'latest-success-nacos.json'), selected);
await rm(join(root, 'pending-nacos.json'), { force: true });
console.log(`已回退 ${environment} Nacos:${snapshotId}`);
function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; }
function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); }
function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function findSnapshotRecord(directory, id) {
try {
for (const file of await readdir(directory)) {
if (!file.endsWith('.json')) continue;
const record = await optional(join(directory, file));
if (record?.snapshotId === id || record?.activeSnapshotId === id) return record;
}
} catch {}
return null;
}
async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; }
@@ -1,87 +0,0 @@
name: 生产环境回退上一个版本
"on":
workflow_dispatch:
inputs:
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release
NACOS_ENVIRONMENT: prod
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 读取上一成功版本
shell: bash
run: |
set -euo pipefail
current=/salon-release/records/prod/latest-success-deploy.json
test -f "$current"
node - <<'NODE' >> "$GITHUB_ENV"
const fs = require('fs');
const latest = JSON.parse(fs.readFileSync('/salon-release/records/prod/latest-success-deploy.json'));
const id = process.env.AUTO_ROLLBACK === 'true' ? latest.releaseId : latest.previousReleaseId;
if (!id) throw new Error('没有可回退的 PROD 成功版本');
const target = JSON.parse(fs.readFileSync(`/salon-release/records/prod/deploy/${id}.json`));
console.log(`PACKAGE_DIRECTORY=${target.packageDir}`);
console.log(`ROLLBACK_SNAPSHOT_ID=${target.activeSnapshotId}`);
console.log(`ROLLBACK_RELEASE_ID=${target.releaseId}`);
console.log(`NACOS_RELEASE_ID=${target.nacosReleaseId}`);
NODE
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 写入 PROD 目标清单
shell: bash
run: |
mkdir -p "$RUNNER_TEMP/salon-prod"
printf '[{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Environment":"prod"},{"Name":"salon-web","Host":"%s","Port":%s,"User":"%s","Environment":"prod"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-prod/servers.json"
- name: 恢复 PROD Nacos
shell: bash
env:
NACOS_SNAPSHOT_ID: ${{ env.ROLLBACK_SNAPSHOT_ID }}
NACOS_RELEASE_ID: ${{ env.NACOS_RELEASE_ID }}
AUTO_ROLLBACK: 'true'
NACOS_ROLLBACK_INVALIDATE: 'true'
run: node .gitea/scripts/rollback-nacos.mjs
- name: 恢复 PROD 应用
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-prod/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core -GatewayRemoteAppDir /opt/jc-salon-gateway -CorePattern '^core01-' -GatewayPattern '^gateway01-' -CoreServiceName jc-salon-core -GatewayServiceName jc-salon-gateway -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://salon.yunail.art
- name: 记录回退后的成功版本
shell: bash
run: node .gitea/scripts/record-rollback.mjs
@@ -1,78 +0,0 @@
name: 测试环境回退上一个版本
"on":
workflow_dispatch:
inputs:
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release
NACOS_ENVIRONMENT: sit
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://wcsrv.top:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 读取最近成功版本
shell: bash
run: |
set -euo pipefail
test -f /salon-release/records/sit/latest-success-deploy.json
node - <<'NODE' >> "$GITHUB_ENV"
const fs = require('fs');
const latest = JSON.parse(fs.readFileSync('/salon-release/records/sit/latest-success-deploy.json'));
const id = process.env.AUTO_ROLLBACK === 'true' ? latest.releaseId : latest.previousReleaseId;
if (!id) throw new Error('没有可回退的 SIT 成功版本');
const target = JSON.parse(fs.readFileSync(`/salon-release/records/sit/deploy/${id}.json`));
console.log(`PACKAGE_DIRECTORY=${target.packageDir}`);
console.log(`ROLLBACK_SNAPSHOT_ID=${target.activeSnapshotId}`);
console.log(`ROLLBACK_RELEASE_ID=${target.releaseId}`);
console.log(`NACOS_RELEASE_ID=${target.nacosReleaseId}`);
NODE
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 恢复 SIT Nacos
shell: bash
env:
NACOS_SNAPSHOT_ID: ${{ env.ROLLBACK_SNAPSHOT_ID }}
NACOS_RELEASE_ID: ${{ env.NACOS_RELEASE_ID }}
AUTO_ROLLBACK: 'true'
NACOS_ROLLBACK_INVALIDATE: 'true'
run: node .gitea/scripts/rollback-nacos.mjs
- name: 执行 SIT 应用回退
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.salon.yunail.art
- name: 记录回退后的成功版本
shell: bash
run: node .gitea/scripts/record-rollback.mjs
@@ -1,46 +0,0 @@
name: 回退开发环境 Nacos 配置
"on":
workflow_dispatch:
inputs:
snapshot_id:
description: 可选快照 ID,留空使用待回退快照
required: false
type: string
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-dev
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
NACOS_ENVIRONMENT: dev
RELEASE_STORE_ROOT: /salon-release
NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }}
NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }}
NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }}
NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://wcsrv.top:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 恢复并校验 Nacos
shell: bash
run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs
@@ -1,57 +0,0 @@
name: 回退生产环境 Nacos 配置
"on":
workflow_dispatch:
inputs:
snapshot_id:
description: 可选快照 ID,留空使用待回退快照
required: false
type: string
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
NACOS_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release
NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
GITHUB_SERVER_URL: http://wcsrv.top:3000
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://wcsrv.top:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 恢复并校验 Nacos
shell: bash
run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs
- name: 触发 PROD 应用恢复
if: inputs.auto_rollback == true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs prod环境回退上一个版本.yml refs/heads/prod
@@ -1,54 +0,0 @@
name: 回退测试环境 Nacos 配置
"on":
workflow_dispatch:
inputs:
snapshot_id:
description: 可选快照 ID,留空使用待回退快照
required: false
type: string
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
NACOS_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release
NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
GITHUB_SERVER_URL: http://wcsrv.top:3000
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://wcsrv.top:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 恢复并校验 Nacos
shell: bash
run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs
- name: 触发 SIT 应用恢复
if: inputs.auto_rollback == true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs sit环境回退上一个版本.yml refs/heads/sit
@@ -1,43 +0,0 @@
name: 环境分支晋级检查
on:
pull_request_target:
branches:
- sit
- prod
jobs:
validate-source:
name: environment-promotion-source
runs-on: jayucloud
steps:
- name: 校验环境分支晋级链路
shell: bash
env:
TARGET_BRANCH: ${{ gitea.base_ref }}
SOURCE_BRANCH: ${{ gitea.head_ref }}
SOURCE_REPOSITORY: ${{ gitea.event.pull_request.head.repo.full_name }}
TARGET_REPOSITORY: ${{ gitea.repository }}
run: |
set -euo pipefail
test -n "$TARGET_BRANCH"
test -n "$SOURCE_BRANCH"
test -n "$SOURCE_REPOSITORY"
test -n "$TARGET_REPOSITORY"
if [[ "$SOURCE_REPOSITORY" != "$TARGET_REPOSITORY" ]]; then
echo "拒绝跨仓库环境晋级:$SOURCE_REPOSITORY -> $TARGET_REPOSITORY"
exit 1
fi
case "$TARGET_BRANCH:$SOURCE_BRANCH" in
sit:dev|prod:sit)
echo "允许环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH"
;;
*)
echo "拒绝环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH"
echo "允许链路仅为 dev -> sit -> prod"
exit 1
;;
esac
@@ -1,44 +0,0 @@
name: 自动发布开发环境 Nacos 配置
"on":
push:
branches: [dev]
concurrency:
group: release-dev
cancel-in-progress: false
jobs:
publish:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
NACOS_ENVIRONMENT: dev
RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: dev
NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }}
NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }}
NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }}
steps:
- name: 检出提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 发布并校验 Nacos
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=dev node .gitea/scripts/dispatch-workflow.mjs rollback-dev-nacos.yml refs/heads/dev || true' ERR
node .gitea/scripts/publish-nacos.mjs
@@ -1,52 +0,0 @@
name: 自动发布生产环境 Nacos
"on":
push:
branches: [prod]
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
publish:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
NACOS_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: prod
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
steps:
- name: 检出提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 发布并校验 Nacos
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=prod node .gitea/scripts/dispatch-workflow.mjs 回退prod环境nacos配置.yml refs/heads/prod || true' ERR
node .gitea/scripts/publish-nacos.mjs
- name: 触发生产部署
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DISPATCH_INPUT_RELEASE_SHA: ${{ github.sha }}
run: node .gitea/scripts/dispatch-workflow.mjs 自动部署prod环境.yml refs/heads/prod
@@ -1,49 +0,0 @@
name: 自动发布测试环境 Nacos 配置
"on":
push:
branches: [sit]
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
publish:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
NACOS_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: sit
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
steps:
- name: 检出提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 发布并校验 Nacos
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=sit node .gitea/scripts/dispatch-workflow.mjs 回退sit环境nacos配置.yml refs/heads/sit || true' ERR
node .gitea/scripts/publish-nacos.mjs
- name: 触发 SIT 部署
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DISPATCH_INPUT_RELEASE_SHA: ${{ github.sha }}
run: node .gitea/scripts/dispatch-workflow.mjs 自动部署sit环境.yml refs/heads/sit
@@ -1,85 +0,0 @@
name: 自动部署生产环境
"on":
workflow_dispatch:
inputs:
release_sha:
description: 已成功发布 PROD Nacos 的提交 SHA
required: true
type: string
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
deploy:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: prod
RELEASE_SHA: ${{ inputs.release_sha || github.sha }}
RELEASE_STORE_ROOT: /salon-release
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
steps:
- name: 检出发布提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$RELEASE_SHA"
git checkout --detach "$RELEASE_SHA"
- name: 校验 PROD Nacos 发布记录
shell: bash
run: node .gitea/scripts/assert-nacos-release.mjs
- name: 构建并校验含 Flyway 迁移的 PROD 发布包
shell: pwsh
env:
VITE_API_BASE_URL: https://salon.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://salon.yunail.art/admin/api
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit
- name: 保存发布包
shell: bash
run: |
set -euo pipefail
package_dir="/salon-release/packages/prod/${RELEASE_SHA}-${GITHUB_RUN_ID}"
mkdir -p "$package_dir"
cp -a artifacts/release/. "$package_dir/"
echo "PACKAGE_DIRECTORY=$package_dir" >> "$GITHUB_ENV"
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 写入 PROD 目标清单
shell: bash
run: |
mkdir -p "$RUNNER_TEMP/salon-prod"
printf '[{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Environment":"prod"},{"Name":"salon-web","Host":"%s","Port":%s,"User":"%s","Environment":"prod"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-prod/servers.json"
- name: 执行 PROD 部署
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-prod/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core -GatewayRemoteAppDir /opt/jc-salon-gateway -CorePattern '^core01-' -GatewayPattern '^gateway01-' -CoreServiceName jc-salon-core -GatewayServiceName jc-salon-gateway -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://salon.yunail.art
- name: 记录成功部署
shell: bash
run: node .gitea/scripts/record-deploy.mjs
- name: 部署失败自动回退
if: failure()
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs prod环境回退上一个版本.yml refs/heads/prod
@@ -1,82 +0,0 @@
name: 自动部署测试环境
"on":
workflow_dispatch:
inputs:
release_sha:
description: 已成功发布 SIT Nacos 的提交 SHA
required: true
type: string
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
deploy:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://wcsrv.top:3000
RELEASE_ENVIRONMENT: sit
RELEASE_SHA: ${{ inputs.release_sha || github.sha }}
RELEASE_STORE_ROOT: /salon-release
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
steps:
- name: 检出发布提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$RELEASE_SHA"
git checkout --detach "$RELEASE_SHA"
- name: 校验 SIT Nacos 发布记录
shell: bash
run: node .gitea/scripts/assert-nacos-release.mjs
- name: 构建并校验含 Flyway 迁移的 SIT 发布包
shell: pwsh
env:
VITE_API_BASE_URL: https://sit.salon.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://sit.salon.yunail.art/admin/api
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit
- name: 持久化已校验发布包
shell: bash
run: |
set -euo pipefail
package_dir="/salon-release/packages/sit/${RELEASE_SHA}-${GITHUB_RUN_ID}"
mkdir -p "$package_dir"
cp -a artifacts/release/. "$package_dir/"
echo "PACKAGE_DIRECTORY=$package_dir" >> "$GITHUB_ENV"
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 写入 SIT 目标清单
shell: bash
run: |
mkdir -p "$RUNNER_TEMP/salon-sit"
printf '[{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},{"Name":"salon-web-sit","Host":"%s","Port":%s,"User":"%s","Purpose":"Salon SIT NGINX","Environment":"sit"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-sit/servers.json"
- name: 执行 SIT 部署
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.salon.yunail.art
- name: 记录成功部署
shell: bash
run: node .gitea/scripts/record-deploy.mjs
- name: 部署失败自动回退
if: failure()
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs sit环境回退上一个版本.yml refs/heads/sit
+3 -20
View File
@@ -5,13 +5,6 @@
# Log file
*.log
# Full-regression database backups may contain development user data.
artifacts/full-regression/*backup*.sql
# Local agent skill mirrors stay ignored; project skills under .agents/skills/ are versioned.
.agents/*
!.agents/skills/
# BlueJ files
*.ctxt
@@ -41,10 +34,8 @@ docs/_book
# TODO: where does this rule come from?
test/
!FD-Core/src/test/
!FD-Core/src/test/**
!FD-Gateway/src/test/
!FD-Gateway/src/test/**
!YumiNail-Core/src/test/
!YumiNail-Core/src/test/**
# ---> Python
# Byte-compiled / optimized / DLL files
@@ -269,17 +260,10 @@ jspm_packages/
# Mini program local overrides
WeChatProgram/utils/config.local.js
JayuCloudArtList-Admin-Program/utils/config.local.js
FM-Wechat-Fronted/utils/config.local.js
# 本地敏感服务器信息
docx/服务器信息.xlsx
docx/生产服务器信息.xlsx
YumiNail-Admin-Program/utils/config.local.js
# Local release/test artifacts
release-packages/
/.codex-tmp/
/tmp/
artifacts/full-acceptance-*/
artifacts/release/
.codex-run/
@@ -404,4 +388,3 @@ m2repo/
/docs/product/
WeChatProgram/project.private.config.json
/.idea/
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Annotation profile for YumiNail-Core" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="D:/apache-maven-3.9.9/repository/nailart/org/projectlombok/lombok/1.18.32/lombok-1.18.32.jar" />
</processorPath>
<module name="YumiNail-Core" />
</profile>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="YumiNail-Gateway" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="YumiNail-Core" options="-parameters" />
<module name="YumiNail-Gateway" options="-parameters" />
</option>
</component>
</project>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/YumiNail-Core/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/YumiNail-Gateway/src/main/java" charset="UTF-8" />
</component>
</project>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://maven.aliyun.com/repository/public" />
</remote-repository>
</component>
</project>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/YumiNail-Core/pom.xml" />
<option value="$PROJECT_DIR$/YumiNail-Gateway/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/xiaowang.iml" filepath="$PROJECT_DIR$/.idea/xiaowang.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
@@ -1,49 +0,0 @@
# Ardot 图标补齐剩余步骤
## Context
用户反馈 Ardot 文件 `https://ardot.tencent.com/file/744106780552731` 中已复刻的 35 个页面(Web 11 页、小程序 24 页)图标缺失,要求用本地 MCP(`mcp_ardot_*`)补齐真实图标,不重建页面、不改页面名、不动布局文案、不删页面、不改仓库、不提交 Git。
已完成部分:
- 品牌 logo 4 页:`3:3`(`7:18`)、`3:8`(`10:40`)、`3:9`(`10:15`)、`35:4`(`35:17`),已用 `upload_images` 应用 `assets/images/app-icon.png` 并删除原文字占位。
- tabBar 4 页:`35:1`(`36:625/630/635/640`)、`35:2`(`38:81/86/91/96`)、`35:11`(`55:117/122/127/132`)、`35:9`(`48:118/123/128/133`),已用 `assets/tabbar/*.png` 替换内层 SVG 容器。
剩余问题:两个页面的缺省头像仍是字母/文字占位,需要替换为 `assets/images/default-user-avatar.png`。
## 执行步骤(均在本地 MCP,只读仓库)
### 1. 定位头像容器(只读)
- 对页面 `3:12`(salon-小程序端-个人信息)用 `batch_read` 搜索 `^管$`,已得 TEXT `15:21`(21×25,x=0,y=2)。再读取其父节点,确认 50×50 或等效头像框 id。
- 对页面 `35:3`(salon-小程序端-新增美甲师)用 `batch_read` 读取整页树(已有 JSONL:`C:\Users\21616\AppData\Local\Temp\.ardot\reads\batch_read-35_3-3987-20261105_175025311.jsonl`),定位 50×50 头像框 id。
### 2. 替换为真实头像
- `upload_images` 将 `e:\code\JayuCloud\JC-Salon-WeChat\assets\images\default-user-avatar.png` 应用到上述两个头像框。
- `batch_edit` 删除字母/文字子节点(`3:12` 的 `15:21`,以及 `35:3` 中对应占位文字),保持外框尺寸、圆角与位置不变。
### 3. Web 端图标核对(只读 + 汇报,不新增页面)
- 用 `batch_read` 抽查 `3:1`(登录)、`3:2`(首页)、`3:7` 等页面的 VECTOR 节点,确认侧栏菜单、header 刷新/审核/待处理、列表操作图标已导入并渲染(记录尺寸与描边)。
- 源码侧 `JC-Salon-Frontend/src/assets` 仅 `vue.svg`,图标全部来自 `@ant-design/icons-vue`;侧栏与登录页品牌标记源码本身是文字「S」,无图片使用 → 在汇报中标注「源码无图片使用,保持近似」。
- 整理「还原 / 近似 / 缺失」三类清单。
### 4. 最终复核
- `fetch_editor_state` 确认 pageList 仍为 35 页(`3:20` 不恢复,`0:1` 不恢复)。
- 抽查补图标页面节点(`3:3`、`3:8`、`3:9`、`35:4`、`35:1`、`35:2`、`35:9`、`35:11`、`3:12`、`35:3`),确认 fills 为 IMAGE。
### 5. 汇报
- 以「图标补齐已完成」开头,给出:
- 小程序端:品牌 logo、tabBar、缺省头像的还原清单与节点 id;
- Web 端:已存在的 Ant Design Vue 图标(近似还原)清单、源码无图片的说明;
- 仍有缺失:上传失败或工具不支持(SVG 不能 `register_assets`,必要时内联)的条目与原因。
## 验证方式
- `batch_read` 返回节点 `fills` 含 `type: "IMAGE"`;
- `fetch_editor_state` 页面数量与名称未变;
- 截图抽查 `capture_screenshot` 对应 pageId 的局部区域(可选)。
## 约束
- 只增补图标节点,不重建页面、不改页面名、不动布局文案;
- 不改仓库文件、不提交 Git、不导出;
- 上传失败贴原始错误并跳过,继续其余页面。
```
@@ -1,161 +0,0 @@
# Ardot 设计稿批次 5 收尾与批次 6 执行计划
## Summary
针对 Ardot 文件 `https://ardot.tencent.com/file/744106780552731`(当前 35 页)继续完成已确认的 8 项优化中剩余部分:
- **批次 5 收尾**:验证 `salon-小程序端-我的`(35:9)本批改动;为 `salon-小程序端-关于系统`(3:3)补「用户协议 / 隐私政策」入口与「版本更新日志」。
- **批次 6**:新增 4 个注册相关页面(`补充资料(店长)`、`补充资料(店员)`、`申请状态(店长)`、`申请状态(店员)`)。
- 全部完成后按用户要求以「任务完成」开头,按「改了什么 / 依据 / 与源码不一致处 / 推断项 / 新增页面 ID 与命名 / 截图验证结论」汇报。
约束:不重建已有页面、不改页面名、不删页;只改内容或新增页面;不改仓库文件、不提交 Git、不导出。
## Current State Analysis
### 已核实(只读读取结果)
**35:9 我的页(48:1)** — 编辑已执行,待截图验证:
- `48:28` 96×23 r11.5,内含 `69:277` 选中胶囊 42×19 #247B63、`69:278`「店长」11px Bold 白、`69:279`「美甲师」11px Regular #71807A;旧「管理端」节点 `48:29` 已删。
- 菜单卡 `48:70/48:113` 高 250,`48:73` 内 5 行 × 49:`48:74` 个人信息 → `48:80` 店铺信息 → `48:86` 账号安全 → `48:92` 订单数据 → `48:110` 关于系统(文案已按顺序改写,文案字体为 Sarasa Bold)。
- 退出登录 `48:114` 357×44 r10 #FBE9E7(r0.984,g0.914,b0.906),y=538;`48:115` 14px Sarasa Semi Bold #B3261E(r0.702,g0.149,b0.118),x=152、y=12。
**3:3 关于系统(7:1)** — 尚未修改:
- `7:1` 390×844,底色 #F5F7F4;`7:2` vertical gap 0 → `7:3` 状态栏 44、`7:8` 导航头 44(返回 18×18 @x16、标题「关于系统」17px SemiBold)、`7:16` 内容区 vertical gap 10 / padding-top 42。
- `7:16` 子节点:`7:17` 品牌卡 366×175(`7:18` logo 58×58 imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`、`7:20`「甲屿手纪」20px Black、`7:22` 描述 12.5px #908865);`7:24` 信息卡 366×112 r12 白底。
- `7:24` → `7:25` vertical,padding 1/1/13/15;行 `7:26`「版本 / 0.0.1」340×43、`7:29`「定位 / 日程 / 客户 / 美甲师 / 我的」340×43;行内 padding 6/6/12/12,标签 14.5px #17211F、值 14.5px #71807A。
**35:4 注册页(40:1)** — 仅含第 1 步「选择工作身份」,第 2/3 步无画板,作为批次 6 的复用样式源:
- 页面 390×844 #F5F7F4;`40:15` 内容层为 `layout:"none"`,子节点全部 ABSOLUTE 定位。
- 品牌头 `40:16`:360.8×47.1 @(15,19),logo 45.8×45.8 r13.5 @(6.5,0.65) 同 imageHash,brand 文案列 156 宽。
- 进度条 `40:24`:360.8×40 @(15,84),三步 40×40 @x0/160/321,圆点 21.8×21.8 r10.9(激活 #247B63 / 未激活 #E0E9E2),连线 108×1 #DCE6DE @y12。
- 卡片 `40:42`:360.8×283.6 @(15,137),r12.5,填充 #FBFDFB(0.984,0.992,0.984),描边 #E7ECE9,标题 17.7px ExtraBold,描述 12px #879792,角色项 58.2 高 r8.3 #F5F7F4 描边 #E7ECE9。
- 主按钮 `40:70`:329.6×43.7 r7.3 #247B63 @(16,221),文字 14.6px Bold 白。
- 页脚注 `40:72`:11px #9AA9A0,居中 x=44。
### 源码依据(只读)
- `JC-Salon-WeChat/pages/register/index.wxml`:
- 进度条三步:选择身份 / 补充资料 / 申请状态。
- 第 2 步店长:`店铺名称*`、`店铺地址(选填)+ 地图选点` + 提示「地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。」;副标题「提交后由平台管理员审核」。
- 第 2 步店员:`选择店铺*`(picker,占位「请选择要加入的店铺」)、`昵称*`(提示「可从微信昵称中选择,也可以手动填写,最多20个字。」)、`头像*`(默认头像 + 「点击选择微信头像」)、notice「审核通过前不会获得门店业务权限」;副标题「提交后由对应店长审核,昵称和头像为必填资料」。
- 第 2 步底部:主按钮「提交审核」+ 文字链「返回上一步」。
- 第 3 步:结果图标(…/✓/!)、标题(申请已提交 / 申请已通过 / 申请未通过)、描述、`当前状态:待审核`、详情行(申请门店、申请身份、[申请昵称]、[申请编号]、提交时间)、主按钮「返回登录」(驳回态为「返回登录并重新申请」)。
- `JC-Salon-WeChat/pages/profile/index.js`:`menus` 顺序为用户协议/隐私政策在第 5/6 位,并入「关于系统」后需在 3:3 提供入口。
- `JC-Salon-WeChat/pages/about/index.wxml`:仅「版本 / 定位」两行,无协议入口、无更新日志 —— 3:3 的两处补充均属「按用户要求新增」,需在汇报中标注与源码不一致。
## Proposed Changes
### 批次 5-A:35:9 我的页截图验证(不改内容)
1. `capture_screenshot(nodeIds:["48:1"])`,核对:
- 身份切换 chip 显示「店长(选中)/ 美甲师」,无溢出、无换行;
- 菜单五项顺序为 个人信息 → 店铺信息 → 账号安全 → 订单数据 → 关于系统,行高一致无重叠;
- 退出登录为低饱和红底按钮,文字居中。
2. `capture_layout({parentId:"48:1", problemsOnly:true})` 复核裁剪/重叠。
3. 如发现渲染问题,仅做最小修正(改宽度/坐标/字号),不改结构。
### 批次 5-B:3:3 关于系统补协议入口与版本更新日志(`batch_edit` 于 `7:1`)
1. 信息卡扩容:
- `U("7:24",{"height":200})`
- `U("7:25",{"height":200})`
2. 新增两行入口(父节点 `7:25`,行样式对齐 `7:26`):
- `I("7:25",{ FRAME 名称「用户协议」340×43, layout:"none" })` → 子项:`TEXT`「用户协议」14.5px #17211F @(6,12);`TEXT`「›」22.9px #B0A79A @(320,10)
- `I("7:25",{ FRAME 名称「隐私政策」340×43, layout:"none" })` → 同上,文字「隐私政策」
3. 新增「版本更新日志」卡片(父节点 `7:16`,插入在 `7:24` 之后,顺序即视觉顺序):
- 卡片 `366×190` r12 白底 `layout:"none"`
- 标题「版本更新日志」15px Bold #17211F @(16,16)
- 条目块(横向:版本胶囊 + 日期,随后三行说明,均 11.5px):
- 版本胶囊 `58×22` r11 #E5F4ED,「0.0.1」11px Bold #247B63 居中;日期「2026-11-05」11.5px #71807A @x=82,y≈4
- 说明行 1「新增补充资料与申请状态设计稿(店长 / 店员)」@y=52
- 说明行 2「我的页支持店长 / 美甲师身份切换」@y=74
- 说明行 3「用户协议与隐私政策入口并入关于系统」@y=96
- 底部说明「后续版本更新将在此处按时间倒序展示」11px #9AA9A0 @y=140
4. 校验内容总高:42 + 175 + 10 + 200 + 10 + 190 = 627 < 800(扣除状态栏与导航头后可用 756),无溢出。
### 批次 6:新增 4 个注册相关页面
**通用构造**(每页一张 390×844 画板,页面底色 #F5F7F4,`layout:"none"` + 子节点 ABSOLUTE):
- 状态栏 44:`9:41`(13px SemiBold #17211F @x28 垂直居中)、`●●●` 与 `▮`(13px SemiBold,#17211F,gap 5,右侧 @x≈332)。
- 品牌头(复用 35:4 `40:16` 几何):logo 45.8×45.8 r13.5 @(21.5,20.3) imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`;右侧文案列 @(77.2,19):主标题「Salon」20px Black #17211F,副标题「用微信身份申请门店工作权限」11.380px #879792。
- 进度条 @(15,84):三步圆点 21.8×21.8 r10.9;未激活 #E0E9E2、已激活 #247B63;完成步数字「✓」7.6px Bold 白,当前步白字「2」或「3」,未开始步 #6B7B74;步名 10px #6B7B74 / 当前步 #247B63 Bold(「选择身份」「补充资料」「申请状态」);连线 108×1 #DCE6DE @y12 @x46 与 @x207。
- 卡片 @(15,137):360.8 宽,r12.5,#FBFDFB 填充 + #E7ECE9 1px 描边。
**1) `salon-小程序端-补充资料(店长)`**
- 进度:第 1 步完成、第 2 步激活、第 3 步未开始。
- 卡片高 352:
- 标题「补充资料」17.7px ExtraBold @(16,19);副标题「提交后由平台管理员审核」12px #879792 @(16,48)
- 字段 1:标签「* 店铺名称」(`*` 6.9px #C0392B + 文案 14px #17211F)@(16,84);输入框 329.6×44 r8 #F5F7F4 描边 #E7ECE9 @(16,106),占位「请输入店铺名称」12px #9AA9A0 @(12,12)
- 字段 2:标签「店铺地址 选填」(「选填」10px #9AA9A0)@(16,166);输入框 238×44 @(16,188) 占位「可手动填写门店地址」;按钮 83.6×44 r8 #E5F4ED @(262,188),文字「地图选点」11.5px Bold #247B63
- 提示「地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。」11px #9AA9A0,宽 329.6 @(16,240),两行
- 主按钮 329.6×43.7 r7.3 #247B63 @(16,278),文字「提交审核」14.6px Bold 白
- 文字链「返回上一步」11.5px #71807A @(y=330) 居中
- 页脚注 11px #9AA9A0 居中:「OpenID 仅用于识别你的微信身份,不会在页面中展示。」
**2) `salon-小程序端-补充资料(店员)`**
- 进度同 1)。
- 卡片高 430:
- 标题「补充资料」@(16,19);副标题「提交后由对应店长审核,昵称和头像为必填资料」@(16,48)
- 字段 1「* 选择店铺」@(16,84);选择行 329.6×44 r8 @(16,106),占位「请选择要加入的店铺」12px #9AA9A0,右箭头「›」22.9px #B0A79A @x≈318
- 字段 2「* 昵称」@(16,166);输入框 329.6×44 @(16,188),占位「点击输入框选择或填写微信昵称」;提示「可从微信昵称中选择,也可以手动填写,最多20个字。」11px #9AA9A0 @(16,240)
- 字段 3「* 头像」@(16,266);头像行 @(16,288):圆形 56×56 r28 默认头像(复用 imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`,若该图为品牌图则改用首字占位「微」#E5F4ED/#247B63),右侧文字「点击选择微信头像」12px #71807A;提示「请选择头像,头像会先上传并完成资料登记,提交时只引用已上传的文件。」11px @(16,350)
- 提示条 329.6×34 r8 #FDF3E7(0.992,0.953,0.906),文字「审核通过前不会获得门店业务权限」11.5px #A9743B @(16,382)
- 主按钮「提交审核」@(16,428)——卡片高需同步扩为 500,避免按钮与文字链越界
- 文字链「返回上一步」11.5px #71807A @y=484 居中
- 页脚注同 1)。
> 说明:头像占位若不使用品牌图,需在汇报中标注为「推断的默认头像占位」。
**3) `salon-小程序端-申请状态(店长)`**
- 进度:第 1、2 步完成、第 3 步激活。
- 卡片高 396:
- 结果图标 72×72 r36 #E5F4ED @(144.4,24),内「…」20px Bold #247B63 居中
- 标题「申请已提交」17.7px ExtraBold 居中 @y=112
- 描述「申请由平台管理员处理,通过后即可使用快捷登录。」12px #879792 居中,宽 300 @(30,144),两行
- 状态行「当前状态:待审核」12.5px #17211F @(16,186),「待审核」#D59A52 Bold
- 详情区 @(16,212):三行 40 高(申请门店「甲屿手纪·望京店」/ 申请身份「店长」/ 提交时间「2026-11-05 14:32」),行内左侧 11.5px #71807A、右侧 11.5px #17211F 右对齐 @x≈250;每行底部 1px #EDEDED
- 主按钮「返回登录」329.6×43.7 @(16,336)
- 页脚注「申请进度会随审核结果更新,可在登录页重新进入查看。」11px #9AA9A0 居中 @y=392(卡片外)
**4) `salon-小程序端-申请状态(店员)`**
- 进度同 3)。
- 卡片高 436:
- 结果图标、标题、描述同 3),描述为「申请由门店店长处理,通过后即可使用快捷登录。」
- 详情四行(申请门店「甲屿手纪·望京店」/ 申请身份「店员」/ 申请昵称「小雨」/ 提交时间「2026-11-05 14:32」),y 起点 212,每行 40
- 主按钮「返回登录」@(16,376)
- 页脚注同 3) @y=432
**页面创建与定位步骤(每页)**:
1. `create_new_page({name:"salon-小程序端-补充资料(店长)"})` 等 4 次,按序创建。
2. `locate_available_space` 取该页可用区(page 级插入前必须调用)。
3. `batch_edit` 在该页插入 390×844 顶层画板,`layout:"none"`,`I(pageId,{...})` 逐节点构建(每批 ≤ 60 行,操作行换行分隔,不用分号)。
4. 数字/中文混排节点显式设置 `fontName:{family:"Sarasa Gothic SC", style:"Semi Bold"}`,避免缺字回退。
## Assumptions & Decisions
| # | 决策 | 理由 |
|---|---|---|
| A1 | 4 个注册页各自独立成页,不复用 35:4 页面 | 用户明确要求「新增页面 ID 与命名」,且命名按「补充资料(店长)」等给出 |
| A2 | 新页沿用 35:4 的品牌头 + 三步进度条,第 2/3 步高亮 | 与源码 `register` 单页三步结构一致,视觉连续 |
| A3 | 不画「已通过 / 已驳回」状态 | 用户只要求「补齐补充资料与申请状态」,默认展示提交后的待审核态;其余状态列入建议清单 |
| A4 | 3:3 版本更新日志内容用 0.0.1 / 2026-11-05 + 三条本次改动说明 | 与仓库 0.0.1 基线一致,且可追溯本次设计稿改动 |
| A5 | 3:3 协议入口以「›」行形式挂在信息卡内,不新增独立页面 | 用户要求「并入关于系统」,不新建协议页 |
| A6 | 申请状态详情中的门店名/昵称/时间为示意文案 | 设计稿无真实数据源,属推断示例 |
| A7 | 若渲染异常只做最小修正(宽/坐标/字号),不改结构、不删页、不改页名 | 用户通用约束 |
## Verification
1. **批次 5-A**:`capture_screenshot(["48:1"])` + `capture_layout({parentId:"48:1",problemsOnly:true})`;确认身份 chip、5 行菜单、红色退出按钮。
2. **批次 5-B**:`capture_screenshot(["7:1"])` + `capture_layout({parentId:"7:1",problemsOnly:true})`;确认 4 行信息卡与版本日志卡不重叠、不越界。
3. **批次 6**:一次性 `capture_screenshot([四个新页画板 id])`(单次配额内);确认 4 页各自 390×844、进度高亮正确、字段与按钮不裁剪。
4. **终检**:`fetch_editor_state` 复核页面总数 39、4 个新页名称唯一且无重复、无页面被改名/删除。
5. **汇报**:以「任务完成」开头,输出 改了什么 / 依据 / 与源码不一致处(日程不做月视图;35:3 手机号必填差异;3:3 协议入口与版本日志为新增;注册页仅覆盖待审核态)/ 推断项(微信登录未关联用户列表、申请状态示例数据、店员头像占位)/ 新增页面 ID 与命名 / 截图验证结论 / 建议清单。
@@ -1,66 +0,0 @@
# Ardot 设计稿优化:批次 3 收尾与批次 4–6 执行计划
## Context
目标文件 `https://ardot.tencent.com/file/744106780552731`(35 页基线),需按用户已确认的 8 项优化逐批落地,每批用 `capture_screenshot` 验证后再进下一批。批次 1(日程周/日视图)与批次 2(客户页、预约详情页)已完成并验证;批次 3 的改派美甲师页栅格对齐与美甲师页折叠按钮/折叠态画板已完成主体编辑,截图验证后只剩 1 个视觉小问题待修。
约束:不重建已有页面、不改已有页面名、不删页;只改内容或新增页面;仅使用本地 Ardot MCP;不改仓库文件、不提交 Git。
## 已完成(供上下文,不再重复)
- 35:1 日程:主画板改「周视图状态」(69:1 周条 + 7 日卡),新增 69:52「日视图状态」;删除浮层 37:43(取消预约),35:8 已有 53:3 同名浮层。
- 35:2 客户:删除「新增」文字按钮,搜索栏满宽,新增 69:167 悬浮加号;新增客户弹窗姓名加红星(69:168)。
- 35:8 预约详情:补「呼叫」按钮(69:170/69:171);修复基线遗留的 193×844 浅绿块与竖排「呼叫」占位;重排卡片高度,六字段栅格恢复可见。
- 35:13 改派美甲师:`61:39` 宽度设为 94,三行内容列统一到 x≈94。
- 35:11 美甲师:删除旧「2 项」(55:34),新增 69:173「列表标题右侧」→ 69:174「2 项」+ 69:175「折叠按钮」+ 69:176「︿」;新增 69:177「美甲师(折叠态)」画板(含状态栏、头部、工具栏、折叠审核卡、3 张美甲师卡、底部导航)。
## 剩余执行计划
### 步骤 0:批次 3 收尾修复
- `U("69:174",{width:30})`:修「2 项」在 20px 宽内换行的问题。
- 用 `capture_layout`(problemsOnly)确认 69:177 无重叠/溢出;不额外消耗截图配额。
### 步骤 1:批次 4 —— 35:3「新增美甲师档案页」
1. 只读读取 35:3 页面结构(主画板 + 浮层组),定位姓名、手机号、微信号/微信登录、专属颜色字段节点与星号节点。
2. 必填收敛:仅「姓名」「专属颜色」加红星(#D9534F,12.5px),其余字段星号删除;与源码 `JC-Salon-WeChat/pages/employee-create` 字段必填关系比对并记录差异。
3. 「微信登录」点击态:在 35:3 浮层组新增浮层画板「浮层:未关联微信用户列表」——底部面板,标题「选择微信用户」+ 说明「仅显示尚未关联门店账号的微信用户」+ 3 条用户行(头像/昵称/最近登录时间/「选择」按钮)+ 空列表态文案。**标注为推断设计,渲染结果需用户确认。**
4. 「专属颜色」点击态:新增浮层「浮层:专属颜色设置」——色板网格(复用设计已有美甲师色 #7BA7C7/#C7A58F/#A7BFA8 + 6 个扩展色)、当前选中预览、取消/确认按钮。
5. 截图验证 35:3 主画板 + 2 个新浮层。
### 步骤 2:批次 5 —— 35:9「我的」与 3:3「关于系统」
1. 读取 35:9 主画板,找到顶部「管理端」标识与菜单列表、退出登录按钮。
2. 身份态:同一画板内把「管理端」替换为「当前身份」切换控件(店长 / 美甲师 两个 chip,店长为选中态),并在下方菜单区同时满足两角色(菜单文案差异不大,采用同页切换,不拆画板);另加一行说明「切换身份仅影响可见菜单」。
3. 菜单顺序调整为:个人信息 → 店铺信息 → 账号安全 → 订单数据 → 关于系统。
4. 「退出登录」改为低饱和红色填充按钮(浅红底 #FBE9E7 + 深红字 #B3261E,保持原尺寸与圆角)。
5. 3:3「关于系统」:新增「用户协议」「隐私政策」两个入口行,新增「版本更新日志」区(版本号 + 日期 + 2–3 条更新说明)。
6. 截图验证 35:9 与 3:3。
### 步骤 3:批次 6 —— 注册相关 4 个新页面
1. 读取 `JC-Salon-WeChat/pages/register` 与 `WorkbenchRegistrationView.vue` 的补充资料、申请状态字段作为内容依据。
2. 用 `create_new_page` 新建 4 页,命名严格为:
- `salon-小程序端-补充资料(店长)`
- `salon-小程序端-补充资料(店员)`
- `salon-小程序端-申请状态(店长)`
- `salon-小程序端-申请状态(店员)`
3. 每页用 `locate_available_space` 后插入 390×844 画板:状态栏、标题、表单/状态卡、说明文案、主按钮,风格沿用既有 token(#247B63 / #F5F7F4 / #17211F)。
4. 截图验证 4 个新页;复核总页数 39、页面名无重复。
### 步骤 4:最终汇报
以「任务完成」开头,按:改了什么 / 依据 / 与源码不一致处(含「日程不做月视图——按用户要求」)/ 推断项(微信登录未关联用户列表)/ 新增页面 ID 与命名 / 截图验证结论 / 建议清单 逐项交付。
## 验证方式
- 每批:`capture_screenshot(nodeIds)` 一次覆盖该批所有改动节点;仅当截图暴露问题且已集中修复后才允许第二次。
- 结构类问题优先 `capture_layout(problemsOnly:true)`,不占用截图配额。
- 全部完成后只读复核页面数量与命名。
## 已知风险与处理
- 更新 `characters` 会把缺失字体重置为 Sarasa Gothic SC Regular,需显式 `U(fontName)` 恢复字重。
- TEXT 不支持 `textAlign`,居中/右对齐需手动 x 定位。
- 新增子级必须指定正确 parentId,避免文字堆叠在父容器顶部(本任务已出现过两次)。
@@ -1,84 +0,0 @@
# ArtList 账号加密与场景化脱敏执行清单
> 按项目规则不新增设计文档;本文件只是 plan 模式的执行清单,实施完成后不为它单独提交。
## 零、版本号自查结论(已核实)
- 查 dev 库 `jayucloud_artlist`:库内没有 `flyway_schema_history`,表数为 0 → **V3 从未在任何环境执行过**。
- 远端 `dev` 已被并行分支先推入 `V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql`(本地 HEAD `80d187d2` 已含);`core.yaml` 为 `out-of-order: false`。
- 因此把工作区里的 `V3__账号加密与账号哈希_20261104.sql` **改名为 `V5__账号加密与账号哈希_20261104.sql`**(V3 文件已删除,V5 未被占用),保证 V1→V2→V4→V5 顺序天然正确,无论 V4 是否已执行都能跑。
- 若后续发现 V3 曾执行过,则恢复 V3 命名且不改文件内容(不得改已执行迁移)。
## 一、前置结论:为什么保留 `account` 列名
- Salon 实际实现:`t_user.account` 列存密文 + `account_hash char(64) NULL` + `uk_user_account_hash`;没有 `account_cipher`。
- **不能**"新增 account_cipher 再 DROP account":V1 种子由 SQL 直接写 `account='xiaowang'`,SQL 层无密钥无法回填,DROP 会丢数据。
- 因此与 Salon 同构:`account` 改存 AES-GCM 密文(`varchar(128) NULL`)、新增 `account_hash`、删 `uk_account`、加 `uk_user_account_hash`。hash 输入 `trim()` + HMAC-SHA256 十六进制小写,与 Salon 逐字对齐。
- ArtList 唯一差异:账号允许字母数字自定义账号,**一律加密**(Salon 仅手机号形态加密)。`decryptAccount` 对无 `enc:v1:` 前缀的历史值原样返回,兼容 V1 种子。
## 二、V5 迁移(已落地)
`JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql`:
1. 幂等过程沿用 V2 风格:`sp_v5_add_column_if_not_exists`、`sp_v5_drop_index_if_exists`、`sp_v5_add_unique_index_if_not_exists`(`DELIMITER $$`,用后 DROP)。
2. `ALTER TABLE t_user MODIFY COLUMN account varchar(128) NULL COMMENT '账号AES-GCM密文(enc:v1: 前缀)'`。
3. 新增 `account_hash char(64) NULL COMMENT '账号HMAC-SHA256索引'`。
4. 删除 `uk_account`;新增 `uk_user_account_hash (account_hash)`(MySQL 唯一索引允许多行 NULL)。
5. 不做 SQL 数据迁移;历史/种子账号由启动时 `AccountHashBackfillRunner` 加密并回填 hash。
## 三、后端改造(已落地)
- `support/privacy/PhoneCrypto`:新增 `encryptAccount`(非空一律加密)、`decryptAccount`(仅 `enc:v1:` 前缀解密,legacy 明文原样返回);`index` 复用,输入仍 `trim()`;删除不再使用的 `maskIfMobile`。
- 新建 `support/privacy/AccountPhoneTypeHandler`:写 `encryptAccount`、读 `decryptAccount`。
- `UserDO`:`account` 挂 `AccountPhoneTypeHandler`;新增 `accountHash`(`@TableField("account_hash")`,与既有 phoneHash 一致,由 `MyMetaObjectHandler` 手工填充)。
- `MyMetaObjectHandler`:`fillPhoneHashes` 中补 account → accountHash。
- `UserServiceImpl`:
- 全部账号等值查询改 `.eq(UserDO::getAccountHash, phoneCrypto.index(x))`;**不在每条查询挂 legacy fallback**。
- `pageUsers` 删除 account LIKE,改 `account_hash` 精确匹配,保留 nickname like 与 phone/contactPhone hash。
- `deleteUser` 抽出包级静态 `buildSoftDeleteUpdate(...)`(供单测断言),显式 set 密文 account + accountHash,并清空 `phone`、`phoneHash`、**`contactPhone`、`contactPhoneHash`**(本次补齐的数据残留),再置 status=0、isDelete=1。
- `buildLoginFailKey` 改用 `phoneCrypto.index(account)`。
- `convertToVO(userDO, scenario)`:`getUserById`/`getUserByAccount` 传 `SELF_PROFILE`,列表/分页传 `ADMIN_LIST`。
- 新建 `support/privacy/AccountHashBackfillRunner`(`ApplicationRunner`):启动时对 `account_hash IS NULL AND account IS NOT NULL` 的行加密 account 并回填 hash,幂等。
- `UserController`、`OperationGuardService` 的账号查询/签名索引统一走 `account_hash` / `index`。
## 四、集中脱敏策略(核心,已落地)
`support/privacy/SensitiveFieldPolicy`:`Scenario` 枚举 `SELF_PROFILE / ADMIN_EDIT / ADMIN_LIST / THIRD_PARTY / DIAL / LOG`;`phone(value, scenario)`、`account(value, scenario)`。已支持先解密再处理。
| 场景 | 返回方式 | 依据 |
| --- | --- | --- |
| SELF_PROFILE(`/user/info`、本人资料回显) | 完整 | 本人查看/修改;小程序发验证码直接用 `userInfo.phone` |
| ADMIN_EDIT(`/user/get/{id}`、`/user/get/account/{account}`) | 完整 | 编辑表单需原值,配合前端"未修改不提交" |
| ADMIN_LIST(分页、列表、公告/消息作者) | 脱敏 | 批量浏览,无编辑/拨号需求 |
| DIAL(门店与客服联系方式) | 完整 | 拨号必需;受登录态、门店可见范围与 OperationGuard、限流约束 |
| THIRD_PARTY(评论昵称回退、公开主页、订单客户昵称回退) | 脱敏 | 公开/半公开场景 |
| LOG(审计、日志、短信投递记录) | 脱敏 | 多人可见的持久化介质 |
| 订单详情客户手机 | 脱敏(维持 `customerPhoneMasked`) | 拨号统一走联系方式接口,避免订单批量泄露 |
应用点:`UserServiceImpl.convertToVO`;`ContactInfoServiceImpl`(手机 DIAL 完整、姓名回退 THIRD_PARTY);`CommentServiceImpl` / `AnnouncementServiceImpl` / `SystemMessageServiceImpl` / `OrderServiceImpl`(账号回退 THIRD_PARTY 或 ADMIN_LIST);`SecurityAuditLogServiceImpl`(LOG)。
## 五、前端 / 小程序(已落地)
- `JC-ArtList-Frontend/src/views/ProfileView.vue`:打开编辑弹窗记录 `originalContactPhone`,提交时仅值变化才带 `contactPhone` 字段。
- `JC-ArtList-Frontend/src/views/AccountSettingsView.vue`:绑定/修改手机号均为用户新输入,旧号只展示不回传。
- `JC-ArtList-WeChat`:`pages/account-settings` 只提交 nickname/signature;`pages/settings`、`pages/password-settings` 的 `userInfo.phone` 仅展示/发码。
- 管理端用户编辑 UI 不在本仓库(`CreateUserRequest/UpdateUserRequest` 无页面使用)→ 未覆盖项。
## 六、验证(已执行部分)
1. `mvn -q clean test -Dtest="PhoneCryptoTest,SensitiveFieldPolicyTest,UserSoftDeleteUpdateTest,FlywayMigrationTempCheckTest"` → **EXIT=0**(含编译)。
2. 单测覆盖:account 加解密回环(含纯数字账号一律加密)、legacy `xiaowang` 原样读取 + hash trim 稳定、六场景矩阵断言、软删除 set 子句含 `account/account_hash/phone_cipher/phone_hash/contact_phone_cipher/contact_phone_hash`。
3. 临时库 `jayucloud_artlist_v5check_20261104`:V1→V2→V4→V5 四个迁移成功,二次 migrate "Schema is up to date",断言 `account_hash` 列、`uk_user_account_hash` 存在、`uk_account` 已删、`account` 长度 128;finally DROP DATABASE;临时测试文件已删除。
## 七、剩余步骤
1. 全仓检索确认无明文读写:`getAccount(`/`setAccount(`/`getPhone(`/`phone_cipher`/`account_hash`,结合上下文判断。
2. `node .gitnexus/run.cjs detect-changes --scope all --repo .`(提交前门禁;`partial/truncated` 需重跑)。
3. 中文提交,只含本次文件(V5 迁移、PhoneCrypto、AccountPhoneTypeHandler、SensitiveFieldPolicy、AccountHashBackfillRunner、UserDO、MyMetaObjectHandler、UserServiceImpl、UserController、ContactInfoServiceImpl、SecurityAuditLogServiceImpl、Comment/Announcement/SystemMessage/Order、OperationGuardService、3 个测试类、ProfileView.vue);不提交 `.trae/`、`docs/design/`。
4. `git push origin dev`(禁止 force);非快进 `git pull --rebase` 重试一次,仍失败原样报错停止。
## 八、风险与未覆盖项
- JWT claims 与 Redis 会话 value 仍含账号明文,本轮不改。
- `account` 一律加密与 Salon 条件加密存在行为差异,hash 语义一致。
- 管理端用户编辑页面不在本仓库,未覆盖。
@@ -1,178 +0,0 @@
# 散客预约拨号 + 协议新版本强制重新同意 实施计划
## Context
现有拨号取号端点 `POST /manager/customers/{customerId}/dial?orderId=...` 强制要求 `order.userId = customerId`。散客预约(`OrderDO.userId` 为空,客户信息只存在 `customerNameSnapshot` / `customerPhoneSnapshot`)无法取号,“呼叫”按钮也被前端按 `userId` 隐藏。
同时,V17 已发布 `2026.11.04` 协议,V18 只修订了该版本正文、不可再改。需要新增 V19 发布新版本 `2026.11.04-R2`,并让已登录但未同意新版本的用户强制重新同意。
目标:
1. 拨号接口支持 `appointmentId`(= 预约详情的 `orderItemId`)/ `orderId` 定位,`customerId` 可空;只校验预约/订单属于当前店铺,不要求客户有账号;号码来源优先订单快照、再客户档案;无号码返回明确业务码。
2. 发布 V19 新协议版本;复用现有 `t_user_agreement_consent` 同意记录表,新增 pending/accept 接口;前端登录后强制弹层。
3. 不修改 V18,不动 ArtList 与 `SystemSettingsView.vue`。
## 一、散客拨号(Salon Core)
### 1. 服务接口与实现
`JC-Salon-Core/src/main/java/.../modules/privacy/service/CustomerDialService.java`
- 改为 `CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request);`
`.../modules/privacy/service/impl/CustomerDialServiceImpl.java`
- 注入 `OrderItemMapper`(已有 `OrderMapper`、`UserService`)。
- 流程:
1. `adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号")`,取 `currentShopId`;`requestThrottleService.checkCustomerDial(...)`。
2. 三个定位参数全空 → `BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)")`。
3. `appointmentId` 存在:按 `orderItemMapper.selectById` 查 `OrderItemDO`(未删除),否则 `404 预约不存在`;由 `item.orderId` 取 `OrderDO`。
4. `orderId` 存在:若上一步已解析订单且不相等 → `403 预约与订单不匹配,或无权拨打`;否则按 `orderMapper.selectById` 取订单。
5. 订单存在时:未删除且 `order.shopId == currentShopId`,否则 `403 无权拨打其他店铺预约/订单客户`。
6. 客户解析:
- `customerId` 非空:加载并校验 `type=0`、未删除;`ensureUserAccessibleInCurrentShop`。
- 订单 `userId` 非空且 `customerId` 非空但不相等 → `403 该客户与订单不匹配`;订单 `userId` 为空但传了 `customerId` 同样视为不匹配 → 403。
- `customerId` 为空:若订单 `userId` 非空,用订单客户作档案兜底;散客则为 `null`。
7. `resolveProvider()` 取渠道,`provider.resolve(customer, order)`,审计 reason 固定包含 `customerId=;appointmentId=;orderId=;provider=;mode=;result=`,不含号码。
8. 成功/失败审计沿用 `SecurityAuditSupport`,失败记录 `errorCode`。
`.../modules/privacy/dial/DirectDialTargetProvider.java`
- 号码优先级改为:`order.customerPhoneSnapshot` → `customer.contactPhone` → `customer.phone`。
- 注:`OrderDO.customerPhoneSnapshot` 由 `PhoneEncryptionTypeHandler` 读取时已解密,`phoneCrypto.decrypt` 对明文是幂等 no-op,保留调用即可。
- 全部为空 → `BusinessException(422, "该预约/订单未登记可拨打的手机号(DIAL_NUMBER_UNAVAILABLE)")`,新增常量 `NUMBER_UNAVAILABLE_CODE = 422`、`NUMBER_UNAVAILABLE_BUSINESS_CODE`。
- `DialTargetProvider` / `DialTarget` / 隐私号占位实现保持不变。
### 2. 控制器
`.../modules/manager/controller/admin/AdminManagerController.java`
- 保留旧端点,参数放宽:
- `POST /manager/customers/{customerId}/dial`:`customerId` 路径参数;`orderId`、`appointmentId` 均 `required = false`。
- 新增 `POST /manager/customers/dial`:`customerId`、`appointmentId`、`orderId` 全部 `required = false`。
- 两个方法均 `@RequirePermission("user:view")`、设置 `Cache-Control: no-store`,调用新 service 签名。
### 3. 测试
`JC-Salon-Core/src/test/java/.../modules/privacy/service/impl/CustomerDialServiceImplTest.java`
- 适配 5 参数签名与新增 `OrderItemMapper` mock。
- 新增断言:
- 散客订单(`customerId=null`、`order.userId=null`、订单快照有号)取号成功,号码只来自快照。
- `appointmentId` 定位成功(订单项 → 订单)。
- `appointmentId` 与 `orderId` 归属不一致 → 403。
- 散客无快照且无客户档案 → 422 且含 `DIAL_NUMBER_UNAVAILABLE`。
- 现有“登录客户 + 订单”路径保持成功。
## 二、协议新版本 + 强制重新同意
### 1. Flyway V19(不改 V18)
新增 `JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql`:
```sql
-- 先停用当前生效的两个协议
UPDATE t_legal_agreement
SET status = 0, update_time = NOW()
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
AND is_delete = 0 AND status = 1;
-- 从停用前刚生效的正文复制新版本,不重复维护长文本
INSERT INTO t_legal_agreement
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
SELECT 313931273555140005, 'USER_TERMS', title, '2026.11.04-R2', content, 1,
'2026-11-04 00:00:00', NOW(), NOW(), 0
FROM t_legal_agreement
WHERE agreement_type = 'USER_TERMS' AND is_delete = 0
ORDER BY effective_time DESC, create_time DESC
LIMIT 1;
-- PRIVACY_POLICY 使用 id 313931273555140006,同样 INSERT ... SELECT
```
- `id` 显式常量(该表 id 无自增);`version = 2026.11.04-R2`;生效时间为本次修订日期;`status = 1`。
- 不修改 `V18__...sql`。
### 2. 同意机制:复用现有表
已确认仓库已有 `t_user_agreement_consent`(唯一键 `(user_id, agreement_type, version)`)与 `LegalAgreementServiceImpl.recordConsent/upsertConsent/getMyConsent`,**不新建 `t_user_agreement_acceptance`**。
`.../modules/system/service/LegalAgreementService.java` 新增:
- `AgreementPendingVO getPendingAgreements(Long userId);`
- `void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest request);`
新增 `.../modules/system/vo/AgreementPendingVO.java`:
- `Boolean pending`、`Map<String,String> currentVersions`、`Map<String,String> acceptedVersions`、`List<String> pendingTypes`。
`LegalAgreementServiceImpl`:
- `getPendingAgreements`:对 `USER_TERMS` / `PRIVACY_POLICY` 各取 `findCurrentAgreement`,与 `getMyConsent(userId).consentVersions` 比对;缺失或版本不同即 pending。
- `acceptCurrentAgreements`:读取两类当前发布版本,按 `upsertConsent(userId, type, version, "agreement-gate", clientType, ip)` 记录,不依赖客户端上报版本。
- 保留登录/注册链路现有 `requireAccepted` 不变。
`.../modules/system/controller/front/LegalAgreementController.java` 新增:
- `GET /legal-agreement/pending`:从 request attribute `userId` 取用户,`requestThrottleService.checkAgreementRead(request, "PENDING")`,返回 pending VO。
- `POST /legal-agreement/accept`:登录态,可选 body `{clientType}`(默认 `WEB`),记录当前版本同意。
- 两个端点**不加入** `WebMvcConfig` 白名单,因此必须登录;`/legal-agreement/current`、`/current/**` 仍免登录,协议阅读页不受影响。
### 3. 测试
新增 `JC-Salon-Core/src/test/java/.../modules/system/service/impl/LegalAgreementServiceImplTest.java`:
- 无同意记录 → `pending=true`,`pendingTypes` 含两类。
- 已同意旧版本、当前版本已变 → `pending=true`。
- 已同意当前版本 → `pending=false`。
- `acceptCurrentAgreements` 对两类各调用一次 `upsertConsent`(insert/update 均可)。
## 三、前端与小程序
### 1. 拨号按钮与参数
`JC-Salon-Frontend/src/api/user.ts`
- `dialCustomer(params: { customerId?: IdType; appointmentId?: IdType; orderId?: IdType })`,调用 `POST /manager/customers/dial`,仅传非空参数。
`JC-Salon-Frontend/src/views/ArtistOrderView.vue`
- 按钮条件:`v-if="order.customerPhoneMasked"`(去掉 `&& order.userId`)。
- `dialCustomer(order)`:只要求 `order.id`;调用 `userApi.dialCustomer({ customerId: order.userId || undefined, orderId: order.id })`。
`JC-Salon-WeChat/api/customers.js`
- `dialCustomer(params)`:`POST /manager/customers/dial`,透传 `customerId/appointmentId/orderId`。
`JC-Salon-WeChat/pages/appointment-detail/index.wxml`
- 条件改为 `appointment.customerPhoneAvailable && appointment.orderId`(去掉 `customerId`)。
`JC-Salon-WeChat/pages/appointment-detail/index.js`
- `dialCustomer()` 只要求 `customerPhoneAvailable && orderId`;传 `{ customerId: appointment.customerId, appointmentId: appointment.orderItemId, orderId: appointment.orderId }`。
### 2. Web 强制同意弹层
`JC-Salon-Frontend/src/api/auth.ts` 的 `legalAgreementApi` 新增:
- `getPending()` → `GET /legal-agreement/pending`
- `accept(clientType?)` → `POST /legal-agreement/accept`
新增 `JC-Salon-Frontend/src/utils/agreement-gate.ts`:
- 模块级 `pending` 标志与 `setAgreementPending/isAgreementPending`。
`JC-Salon-Frontend/src/api/index.ts` 请求拦截器:
- 若 `isAgreementPending()` 且 URL 不属于 `/legal-agreement/`、`/admin/auth/`、`/user/logout`,直接 reject 并提示“请先阅读并同意最新版用户协议与隐私政策”。
- 不改造鉴权链,只在现有 axios 拦截器加一个前置判断。
`JC-Salon-Frontend/src/views/admin/AdminLayout.vue`
- `onMounted` 调用 `legalAgreementApi.getPending()`;pending 时 `setAgreementPending(true)` 并显示不可关闭的 `a-modal`。
- 弹层内链接 `/legal/user-terms.html`、`/legal/privacy-policy.html`(静态页运行时读取后台当前协议)。
- “同意并继续”调用 `accept('WEB')`,成功后置 false 并关闭;不提供关闭/取消。
### 3. 小程序
- 现有 `app.js` 已在启动时用 `hasMatchingAgreementVersions(preference.agreementVersions, currentVersions)` 比对当前协议版本,不一致即清 session 并跳登录页重新勾选;登录页 `agreementPromptVisible` 弹层与 `agreementPayload()` 会把新版本写入登录请求并记录同意。V19 发布后该链路自动生效,无需改动鉴权链。
- `JC-Salon-WeChat/api/auth.js` 增加 `getPendingAgreements()` / `acceptCurrentAgreements(clientType)` 供后续页面使用(本次不改变现有登录流程)。
## 四、验证
1. 编译:`mvn -q -DskipTests compile`(`JC-Salon-Core`)。
2. 单测:`mvn -q "-Dtest=CustomerDialServiceImplTest,LegalAgreementServiceImplTest,PlanningServiceImplTest,UserServiceCustomerMatchingTest" test`。
3. 前端构建:`npm run build`(`JC-Salon-Frontend`)。
4. 微信端:`node JC-Salon-WeChat/app-login-flow.test.js`、`node JC-Salon-WeChat/employees-review.test.js`。
5. GitNexus:
- `impact` 检查 `dial`、`CustomerDialServiceImpl`、`DirectDialTargetProvider`、`LegalAgreementServiceImpl`、`LegalAgreementService`、`AdminManagerController.dialCustomer`、`LegalAgreementController`;`UNKNOWN` 用全仓文本检索交叉确认。
- `detect-changes --scope all` 必须非 partial/truncated。
6. 提交:仅暂存本次文件,中文提交;`git push origin dev`,非快进先 `git pull --rebase` 重试一次,仍失败原样报错停止。
## 五、约束与残余风险
- 不修改 `V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql`。
- 不动任何 ArtList 文件,不动 `SystemSettingsView.vue`。
- V19 假设库中存在现行协议行(V17 的 `2026.11.04`)。若某环境从未执行 V17/V18,则 `INSERT ... SELECT` 无数据可复制,新版本不会生成;需上线前确认该环境已执行到 V18。
- 散客号码优先取订单快照,可能与客户档案最新号码不一致;这是本次明确的产品口径。
- Web 同意拦截在 axios 层与弹层实现,属于前端强制;后端灰心接口仍可被直接调用,未改鉴权链。如需服务端硬拦截,后续单独增加受限路径的协议同意拦截器。
- 管理员登录本身不携带协议勾选,V19 后首次登录会出现强制同意弹层,属于预期行为。
+23 -122
View File
@@ -1,147 +1,48 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
This project is indexed by GitNexus as **xiaowang** (17889 symbols, 35678 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
## Always Do
- **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
- **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
- MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
- **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
- **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`.
## Never Do
- NEVER edit a function, class, or method before MCP/CLI impact analysis.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit before MCP/CLI graph change analysis.
- NEVER edit a function, class, or method without first running `gitnexus_impact` on it.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph.
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope.
## Resources
| Resource | Use for |
| --- | --- |
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
| `gitnexus://repo/JayuCloud/process/{name}` | Step-by-step execution trace |
|----------|---------|
| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness |
| `gitnexus://repo/xiaowang/clusters` | All functional areas |
| `gitnexus://repo/xiaowang/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace |
## CLI
| Task | Read this skill file |
| --- | --- |
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
|------|---------------------|
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end -->
## Project Workflow Rules
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
- 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。
- 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。
- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。
- Salon Core 的数据库变更必须放在 `JC-Salon-Core/src/main/resources/db/migration/` 下,使用递增的 Flyway 版本文件(如 `V2__功能说明_20261024.sql`);已在任一环境成功执行的迁移文件不得修改或删除。
- DEV、SIT、PROD 的数据库迁移由 Core 启动时的 Flyway 自动执行,Gitea 工作流不得直接连接数据库或绕过 Flyway 执行 SQL;合并到 SIT 前必须先在 DEV 验证迁移。
- 应用回退不会自动回滚数据库;需要撤销或修正时,必须新增向前兼容的补偿迁移,禁止依赖 Flyway `clean`、自动 baseline 或重新执行初始化 SQL。
- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。
- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。
- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `docs/scripts/运行与发布配置总说明.md`,并在任务记录中写明新增或调整的版本化文件。
- 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。
## Browser MCP Preference
- For any browser-related operation, including opening, navigating, clicking, typing, inspecting pages/devtools, taking screenshots, testing pages, or automating local/remote web targets, use the `edgedev` MCP server first.
- Do not use other browser automation providers such as Browser, browser-use, Chrome, Playwright MCP, or generic web browsing for browser operations unless `edgedev` is unavailable or the user explicitly requests a different browser/MCP in that turn.
## 项目概述
JayuCloud 是甲屿云双产品线仓库,包含两条业务线,各自拥有完整的端侧矩阵:
- **Salon(店务 / 指尖管理师)**:面向美甲门店经营的管理系统——门店与员工管理、排班规划、预约、订单履约、注册审核、协议与隐私合规。模块:`JC-Salon-Core`(后端)、`JC-Salon-Gateway`(网关)、`JC-Salon-Frontend`(Vue 管理端)、`JC-Salon-WeChat`(指尖管理师小程序)。
- **ArtList(指尖设计师)**:面向用户的设计师作品电商平台——作品浏览、购物车、下单、评价、VIP、优惠券。模块:`JC-ArtList-Core`、`JC-ArtList-Gateway`、`JC-ArtList-Frontend`(Vue 用户端+管理端)、`JC-ArtList-WeChat`(用户小程序)。
- 支撑目录:`nacos/`(各环境 Nacos 配置副本)、`scripts/` 与 `docs/scripts/`(部署脚本与中文配置说明)、`docs/`(文档)、`.gitea/`(Gitea Actions 工作流)。
项目背景、模块职责与关键业务流程详见 `docs/agent/PROJECT_CONTEXT.md`;不可违反的约束见 `docs/agent/PROJECT_CONSTRAINTS.md`。
## 技术栈与版本(已核实)
| 层 | 技术 | 版本 |
| --- | --- | --- |
| 后端语言 | Java | 17 |
| 后端框架 | Spring Boot / Spring Cloud / Spring Cloud Alibaba | 2.7.18 / 2021.0.8 / 2021.0.5.0 |
| ORM / 连接池 | MyBatis-Plus / Druid | 3.5.3.1 / 1.2.23 |
| 认证 | jjwt | 0.11.5 |
| 数据库 / 迁移 | MySQL / Flyway | 迁移文件在各 Core 的 `src/main/resources/db/migration/` |
| 缓存 / 消息 | Redis / RabbitMQ | 版本以 Nacos `infra.yaml` 为准 |
| 注册与配置中心 | Nacos | 命名空间按端侧划分(`jayucloud-salon` / `jayucloud-artlist`) |
| 对象存储 | MinIO → 七牛 Kodo → 阿里云 OSS 三副本编排 | 读取渠道优先级可配置 |
| 网关 | Spring Cloud Gateway + Reactive Redis | `AuthGlobalFilter` 负责白名单与 JWT 初筛 |
| 前端 | Vue 3 + Vite + Element Plus + Ant Design Vue(双组件库)+ Pinia + Vue Router + Axios | Vue 3.5.x |
| 小程序 | 微信原生小程序(非 Taro/uni-app) | 基础库 3.15.2 基线 |
| 构建 | Maven(各模块独立构建,非聚合工程)/ npm | Maven 3.9.x |
| CI/CD | Gitea Actions(dev Nacos 自动发布、prod 部署工作流) | 见 `.gitea/workflows/` |
不得把未经确认的目标版本写成当前使用版本;升级版本属于迁移任务,需单独方案。
## 项目架构
- 调用链:各端 → Gateway(路由、白名单、Token 初筛)→ Core(业务)→ MySQL / Redis / RabbitMQ / 对象存储;服务间内部接口走 `/internal/**`。
- Core 分层:`modules.<业务域>` 下 controller / service / mapper / entity / dto / vo;公共能力在 `common` 与 `config`;统一响应包装为 `common` 包的 `Result<T>`。
- Salon Core 业务域:`analytics、artist、auth、content、file、integration、inventory、manager、marketing、message、order、payment、planning、privacy、product、registration、security、shop、system、user`;ArtList Core 为其收敛子集(已清理 inventory/manager/analytics 等)。
- 配置体系:本地 `application.yaml`/`bootstrap.yaml` 只保留 Nacos 引导参数;运行配置在 Nacos 的 `core.yaml、gateway.yaml、infra.yaml、secret.yaml、logging.yaml`;`secret.yaml` 与 `infra.yaml` 的覆盖关系以实际加载顺序为准,敏感配置只放 Nacos,不入仓库。
- 路由与权限基线:管理端接口走 `/api/admin/**` 门禁;小程序业务走 `/api/**`;匿名白名单逐个端点枚举,禁止宽泛前缀。
## 目录与代码规范
- 新业务优先进入现有 `modules.<业务域>`;跨域引用走对方 Service,不直连他域 Mapper。
- Gateway 不承载业务写逻辑,只做路由、鉴权初筛与转发。
- 命名遵循现有风格:Java 包 `com.xiaowang.jayucloud.<salon|artlist>.<core|gateway>`;前端页面在 `src/views/`,请求封装在 `src/api/`;小程序请求封装在 `utils/request.js`、登录态在 `utils/auth.js`。
- 界面文案统一中文;前端保持现有双组件库用法与页面风格,改版式不改业务行为(接口调用、校验、权限逻辑原样保留)。
- 异常与日志:沿用现有统一异常处理与 Log4j2 配置;日志禁止输出手机号、口令、令牌等敏感明文。
## 数据库规范
- 结构变更一律走 Flyway 版本文件(规则见上方 Project Workflow Rules 与 `docs/agent/PROJECT_CONSTRAINTS.md`):`V{n}__中文功能说明_YYYYMMDD.sql`,完整可执行,已执行文件不得修改。
- 空库初始化仅用 `docs/scripts/sql/init/jayucloud-salon.sql` / `jayucloud-artlist.sql`;生产已部署库升级必须单独制定迁移方案。
- 主键与实体:遵循现有实体的主键策略与软删除/审计字段约定;新增实体需同步检查 `@MapperScan` 包清单与 MyBatis-Plus 自动填充处理器(单例合并)。
- 新增字段必须同时更新实体与版本迁移,并核对历史数据回填需求。
## API 规范
- 风格:REST 风格 + 统一 `Result<T>` 包装;URL 使用小写中划线资源名,遵循所在端既有前缀(`/api`、`/api/admin`、`/internal`)。
- 认证:Bearer JWT,Gateway 初筛 + Core 业务校验;匿名端点必须显式列入白名单并逐个说明理由。
- 权限:管理端按权限码裁剪菜单与接口;数据属主校验(门店作用域)在 Service 层完成。
- 敏感数据:手机号/账号等隐私字段默认脱敏返回,明文获取走独立授权端点(如单次拨号取号);不在列表接口返回完整隐私字段。
- 接口文档:以代码与 `docs/` 说明为准;新增对外契约需在任务说明中写明请求/响应/错误语义。
## 开发与验证要求
- 后端构建(非聚合工程,进对应模块):`mvn -f JC-Salon-Core/pom.xml -DskipTests compile`(ArtList 同理);本机 Maven 位于 `D:\software\apache-maven-3.9.12\bin\mvn.cmd`。
- 涉及 Bean 装配、事务、拦截器的改动:编译通过后还需启动烟测,编译通过不等于能启动。
- 前端:`JC-Salon-Frontend` / `JC-ArtList-Frontend` 下 `npm run build`;开发代理 `/admin/api` 与 `/api` 指向 `VITE_DEV_PROXY_TARGET`。
- 小程序:JS 改动后做 node 语法检查;有条件时用微信开发者工具冒烟。
- 测试:JUnit 5 + Mockito(spring-boot-starter-test);Mock 参数要么全字面量要么全 matcher。
- 修改符号前先做 GitNexus impact 分析,提交前做 detect_changes(见文首 GitNexus 规则);修改完成后按改动范围执行上述对应验证,并如实报告结果。
## 安全与变更保护
- 不擅自删除业务数据;不擅自操作生产环境(生产部署、Nacos 生产发布、生产 SQL 执行必须先核对环境、备份与凭据注入方式并取得确认)。
- 不擅自变更数据库结构(必须走 Flyway 版本文件);不覆盖用户已有配置;不将密钥、口令、令牌写入仓库、日志或文档。
- 重大变更(结构调整、迁移、发布)前先备份;破坏性操作必须先确认。
- 敏感配置只存放在 Nacos `secret.yaml`(按环境),仓库中的 `nacos/` 副本不得包含真实密钥。
## Agent 知识体系
- 项目级技能位于 `.agents/skills/`(`jayu-domain`、`jayu-database`、`jayu-api`、`jayu-devflow`、`jayu-release`),清单与触发条件见 `docs/agent/SKILLS_CATALOG.md`,使用说明见 `docs/agent/AGENT_SKILLS_GUIDE.md`。
- 通用能力(需求分析、架构设计、TDD、调试、评审、运维等)由全局 Skills 提供,项目级技能只承载本项目专属知识,两者不重复建设。
- 交接文档入口:`docs/handoff/`(PROJECT-MAP、CURRENT-STATE 等,部分内容滞后于代码,结论以源码为准);脚本与发布规则入口:`docs/scripts/运行与发布配置总说明.md`。
+23 -29
View File
@@ -1,49 +1,43 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
This project is indexed by GitNexus as **xiaowang** (17889 symbols, 35678 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
## Always Do
- **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
- **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
- MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
- **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
- **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`.
## Never Do
- NEVER edit a function, class, or method before MCP/CLI impact analysis.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit before MCP/CLI graph change analysis.
- NEVER edit a function, class, or method without first running `gitnexus_impact` on it.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph.
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope.
## Resources
| Resource | Use for |
| --- | --- |
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
| `gitnexus://repo/JayuCloud/process/{name}` | Step-by-step execution trace |
|----------|---------|
| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness |
| `gitnexus://repo/xiaowang/clusters` | All functional areas |
| `gitnexus://repo/xiaowang/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace |
## CLI
| Task | Read this skill file |
| --- | --- |
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
|------|---------------------|
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end -->
## Project Workflow Rules
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
+41
View File
@@ -0,0 +1,41 @@
const request = require('../utils/request')
const { API_DOMAIN } = require('../utils/config')
module.exports = {
login(data) {
return request({
url: '/auth/login',
method: 'POST',
data
})
},
register(data) {
return request({
url: '/auth/register',
method: 'POST',
data
})
},
sendCode(phone) {
return request({
url: '/user/send-verification-code',
method: 'POST',
params: {
__baseUrl: API_DOMAIN
},
data: {
phone,
sceneCode: 'PLANNING_MANAGER_REGISTER'
}
})
},
logout() {
return request({
url: '/auth/logout',
method: 'POST'
})
}
}
+20
View File
@@ -0,0 +1,20 @@
const request = require('../utils/request')
module.exports = {
list(params) {
return request({
url: '/user/list',
params: {
type: 0,
hasOrder: true,
...params
}
})
},
detail(id) {
return request({
url: `/user/detail/${id}`
})
}
}
+39
View File
@@ -0,0 +1,39 @@
const request = require('../utils/request')
module.exports = {
list(params) {
return request({
url: '/nail-artist/list',
params
})
},
detail(userId) {
return request({
url: `/nail-artist/get/${userId}`
})
},
save(data) {
return request({
url: '/nail-artist/save',
method: 'POST',
data
})
},
schedules(params) {
return request({
url: '/artist-schedule/list',
params
})
},
saveSchedule(data) {
return request({
url: '/artist-schedule/save',
method: 'POST',
data
})
}
}
+40
View File
@@ -0,0 +1,40 @@
const request = require('../utils/request')
module.exports = {
calendar(params) {
return request({
url: '/planning/calendar',
params
})
},
createAppointment(data) {
return request({
url: '/planning/appointments',
method: 'POST',
data
})
},
appointment(orderItemId) {
return request({
url: `/planning/appointments/${orderItemId}`
})
},
moveAppointment(orderItemId, data) {
return request({
url: `/planning/appointments/${orderItemId}/time-artist`,
method: 'PUT',
data
})
},
updateStatus(orderId, status) {
return request({
url: `/planning/appointments/${orderId}/status`,
method: 'PUT',
data: { status }
})
}
}
@@ -3,7 +3,7 @@ const request = require('../utils/request')
module.exports = {
list(params) {
return request({
url: '/manager/products',
url: '/product/list',
params
})
}
+24
View File
@@ -0,0 +1,24 @@
const request = require('../utils/request')
module.exports = {
settings() {
return request({
url: '/shops/current'
})
},
saveSettings(data) {
return request({
url: '/shops/current',
method: 'PUT',
data
})
},
exportData(params) {
return request({
url: '/export',
params
})
}
}
+31
View File
@@ -0,0 +1,31 @@
const auth = require('./utils/auth')
App({
globalData: {
appName: '指尖管理师',
shopName: 'Yumi Nail',
userInfo: null
},
onLaunch() {
this.bootstrapSession()
},
bootstrapSession() {
const session = auth.getSession()
this.globalData.userInfo = session.userInfo || null
if (session.shopName) {
this.globalData.shopName = session.shopName
}
},
setSession(session) {
auth.setSession(session)
this.bootstrapSession()
},
clearSession() {
auth.clearSession()
this.globalData.userInfo = null
}
})
+64
View File
@@ -0,0 +1,64 @@
{
"pages": [
"pages/login/index",
"pages/register/index",
"pages/planning/index",
"pages/appointment-form/index",
"pages/appointment-detail/index",
"pages/artist-transfer/index",
"pages/customers/index",
"pages/customer-detail/index",
"pages/employees/index",
"pages/employee-detail/index",
"pages/schedule-setting/index",
"pages/leave-management/index",
"pages/color-setting/index",
"pages/employee-orders/index",
"pages/profile/index",
"pages/shop-settings/index",
"pages/export/index",
"pages/password/index",
"pages/about/index"
],
"window": {
"navigationBarTitleText": "指尖管理师",
"navigationBarBackgroundColor": "#F8F5EF",
"navigationBarTextStyle": "black",
"backgroundColor": "#F8F5EF",
"backgroundTextStyle": "dark"
},
"tabBar": {
"color": "#8B8680",
"selectedColor": "#2F6F62",
"backgroundColor": "#FFFDF8",
"borderStyle": "white",
"list": [
{
"pagePath": "pages/planning/index",
"text": "规划",
"iconPath": "assets/tabbar/planning.png",
"selectedIconPath": "assets/tabbar/planning-active.png"
},
{
"pagePath": "pages/customers/index",
"text": "客户",
"iconPath": "assets/tabbar/customers.png",
"selectedIconPath": "assets/tabbar/customers-active.png"
},
{
"pagePath": "pages/employees/index",
"text": "员工",
"iconPath": "assets/tabbar/employees.png",
"selectedIconPath": "assets/tabbar/employees-active.png"
},
{
"pagePath": "pages/profile/index",
"text": "我的",
"iconPath": "assets/tabbar/profile.png",
"selectedIconPath": "assets/tabbar/profile-active.png"
}
]
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}
+279
View File
@@ -0,0 +1,279 @@
page {
min-height: 100%;
background: #f8f5ef;
color: #26231f;
font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 28rpx;
}
view,
text,
button,
input,
textarea,
picker,
scroll-view {
box-sizing: border-box;
}
button {
margin: 0;
padding: 0;
min-width: 0;
border-radius: 0;
background: transparent;
line-height: 1;
}
button::after {
border: 0;
}
.page {
min-height: 100vh;
padding: 22rpx 24rpx 140rpx;
background: #f8f5ef;
}
.page.no-tab {
padding-bottom: 196rpx;
}
.card {
border: 1rpx solid rgba(50, 43, 34, 0.06);
border-radius: 12px;
background: #fffdf8;
box-shadow: 0 10rpx 28rpx rgba(58, 48, 34, 0.06);
}
.section {
margin-top: 20rpx;
}
.section-title {
margin: 4rpx 4rpx 16rpx;
color: #4c4740;
font-size: 28rpx;
font-weight: 700;
}
.row {
display: flex;
align-items: center;
}
.between {
justify-content: space-between;
}
.muted {
color: #9d968e;
}
.tag {
display: inline-flex;
align-items: center;
min-height: 40rpx;
padding: 0 16rpx;
border-radius: 999rpx;
background: #f0ece5;
color: #6d675f;
font-size: 22rpx;
font-weight: 600;
}
.primary-btn,
.secondary-btn,
.text-btn,
.danger-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 76rpx;
border-radius: 12px;
font-size: 26rpx;
font-weight: 700;
}
.primary-btn,
.secondary-btn,
.danger-btn {
min-width: 100%;
max-width: 100%;
}
.primary-btn {
background: #6f8f83;
color: #fffdf8;
box-shadow: 0 12rpx 24rpx rgba(111, 143, 131, 0.22);
}
.secondary-btn {
border: 1rpx solid #d8d1c8;
background: #fffdf8;
color: #514b44;
}
.danger-btn {
background: #d98d8d;
color: #fff;
}
.text-btn {
width: auto;
min-width: 0;
max-width: none;
min-height: 56rpx;
color: #6f8f83;
font-size: 26rpx;
}
.compact-btn,
.small-action {
display: inline-flex;
align-items: center;
justify-content: center;
width: 112rpx;
min-width: 112rpx;
max-width: 112rpx;
height: 56rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: #e5eee9;
color: #55786d;
font-size: 24rpx;
font-weight: 800;
}
.small-action {
width: 112rpx;
min-width: 104rpx;
max-width: 112rpx;
height: 52rpx;
background: #f0ece5;
color: #5f5951;
}
.icon-btn {
display: flex;
align-items: center;
justify-content: center;
width: 64rpx;
min-width: 64rpx;
max-width: 64rpx;
height: 64rpx;
min-height: 64rpx;
padding: 0;
border-radius: 50%;
background: #fffdf8;
color: #4e4942;
box-shadow: 0 6rpx 14rpx rgba(58, 48, 34, 0.05);
}
.form-card {
padding: 8rpx 24rpx;
}
.field {
display: flex;
align-items: center;
min-height: 108rpx;
border-bottom: 1rpx solid #eee8df;
}
.field:last-child {
border-bottom: 0;
}
.field-label {
width: 180rpx;
color: #625c55;
font-size: 26rpx;
font-weight: 600;
}
.field input,
.field textarea,
.field-value {
flex: 1;
color: #27231f;
font-size: 28rpx;
}
.field textarea {
min-height: 140rpx;
padding: 34rpx 0;
}
.fixed-bottom {
position: fixed;
right: 0;
bottom: 0;
left: 0;
z-index: 20;
padding: 14rpx 24rpx calc(14rpx + env(safe-area-inset-bottom));
background: rgba(248, 245, 239, 0.94);
backdrop-filter: blur(18rpx);
}
.fab {
position: fixed;
right: 28rpx;
bottom: calc(100rpx + env(safe-area-inset-bottom));
z-index: 18;
display: flex;
align-items: center;
justify-content: center;
width: 84rpx;
min-width: 84rpx;
max-width: 84rpx;
height: 84rpx;
min-height: 84rpx;
padding: 0;
border-radius: 50%;
background: #6f8f83;
color: #fff;
font-size: 46rpx;
font-weight: 300;
line-height: 84rpx;
box-shadow: 0 12rpx 26rpx rgba(111, 143, 131, 0.24);
}
.list {
display: flex;
flex-direction: column;
gap: 18rpx;
}
.list-card {
padding: 24rpx;
}
.empty {
padding: 56rpx 24rpx;
color: #a39b91;
text-align: center;
}
.error-card {
display: flex;
flex-direction: column;
gap: 12rpx;
margin: 18rpx 0;
padding: 22rpx;
border-color: rgba(191, 111, 104, 0.22);
background: #fff8f6;
}
.error-title {
color: #7f4540;
font-size: 26rpx;
font-weight: 800;
}
.error-desc {
color: #9b6a62;
font-size: 24rpx;
line-height: 1.45;
}

Before

Width:  |  Height:  |  Size: 448 B

After

Width:  |  Height:  |  Size: 448 B

Before

Width:  |  Height:  |  Size: 306 B

After

Width:  |  Height:  |  Size: 306 B

Before

Width:  |  Height:  |  Size: 453 B

After

Width:  |  Height:  |  Size: 453 B

Before

Width:  |  Height:  |  Size: 290 B

After

Width:  |  Height:  |  Size: 290 B

Before

Width:  |  Height:  |  Size: 397 B

After

Width:  |  Height:  |  Size: 397 B

Before

Width:  |  Height:  |  Size: 240 B

After

Width:  |  Height:  |  Size: 240 B

Before

Width:  |  Height:  |  Size: 434 B

After

Width:  |  Height:  |  Size: 434 B

Before

Width:  |  Height:  |  Size: 285 B

After

Width:  |  Height:  |  Size: 285 B

@@ -0,0 +1 @@
Page({})
@@ -0,0 +1,11 @@
<view class="page no-tab about-page">
<view class="brand-card card">
<view class="logo">指</view>
<text class="name">指尖管理师</text>
<text class="desc">专为美甲店店长设计的预约排班日历子系统</text>
</view>
<view class="card about-list">
<view class="row between"><text>版本</text><text class="muted">1.0.0</text></view>
<view class="row between"><text>定位</text><text class="muted">规划 / 客户 / 员工 / 我的</text></view>
</view>
</view>
@@ -0,0 +1,40 @@
.about-page {
padding-top: 80rpx;
}
.brand-card {
display: flex;
flex-direction: column;
align-items: center;
padding: 52rpx 28rpx;
}
.logo {
display: flex;
align-items: center;
justify-content: center;
width: 112rpx;
height: 112rpx;
border-radius: 30rpx;
background: #6f8f83;
color: #fff;
font-size: 52rpx;
font-weight: 900;
}
.name {
margin-top: 22rpx;
font-size: 38rpx;
font-weight: 900;
}
.desc {
margin-top: 12rpx;
color: #90887e;
font-size: 24rpx;
}
.about-list {
margin-top: 20rpx;
padding: 24rpx;
}
@@ -0,0 +1,84 @@
const planningApi = require('../../api/planning')
const config = require('../../utils/config')
const mock = require('../../utils/mock')
Page({
data: {
id: '',
appointment: {},
avatarText: '',
timeText: '',
loadError: false,
errorMessage: ''
},
onLoad(options = {}) {
this.setData({ id: options.id || '' })
this.loadDetail()
},
async loadDetail() {
this.setData({ loadError: false, errorMessage: '' })
try {
const appointment = await planningApi.appointment(this.data.id)
this.applyAppointment(appointment)
} catch (error) {
if (config.USE_DEV_MOCK_DATA) {
const demo = mock.buildCalendar(new Date()).appointments[0]
this.applyAppointment(demo)
} else {
this.setData({
appointment: {},
avatarText: '',
timeText: '',
loadError: true,
errorMessage: error.message || '预约详情加载失败,请检查服务连接后重试'
})
}
}
},
applyAppointment(appointment) {
this.setData({
appointment,
avatarText: String(appointment.customerName || '客').slice(0, 1),
timeText: `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}`,
loadError: false,
errorMessage: ''
})
},
async updateStatus(status) {
if (!this.data.appointment.orderId) {
wx.showToast({ title: '预约数据未加载', icon: 'none' })
return
}
try {
await planningApi.updateStatus(this.data.appointment.orderId, status)
wx.showToast({ title: '已更新' })
this.loadDetail()
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
},
confirm() {
this.updateStatus(1)
},
complete() {
this.updateStatus(2)
},
cancel() {
this.updateStatus(3)
},
goTransfer() {
wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` })
},
back() {
wx.navigateBack()
}
})
@@ -0,0 +1,3 @@
{
"navigationBarTitleText": "预约详情"
}
@@ -0,0 +1,54 @@
<view class="page no-tab">
<view wx:if="{{loadError}}" class="card error-card">
<text class="error-title">数据加载失败</text>
<text class="error-desc">{{errorMessage}}</text>
<button class="compact-btn" bindtap="loadDetail">重试</button>
</view>
<block wx:else>
<view class="card detail-card">
<view class="detail-head">
<view class="detail-person">
<view class="avatar">{{avatarText}}</view>
<view>
<text class="customer">{{appointment.customerName}}</text>
<text class="phone">{{appointment.customerPhone}}</text>
</view>
</view>
<view class="detail-actions">
<text class="tag">{{appointment.statusText}}</text>
<button class="small-action" bindtap="goTransfer">改派</button>
</view>
</view>
<view class="detail-grid">
<view>
<text class="label">项目</text>
<text class="value">{{appointment.productTitle}}</text>
</view>
<view>
<text class="label">美甲师</text>
<text class="value">{{appointment.artistName}}</text>
</view>
<view>
<text class="label">时间</text>
<text class="value">{{timeText}}</text>
</view>
<view>
<text class="label">时长</text>
<text class="value">{{appointment.durationMinutes}}分钟</text>
</view>
</view>
</view>
<view class="section">
<view class="section-title">备注</view>
<view class="card note-card">{{appointment.remark || '暂无备注'}}</view>
</view>
<view class="fixed-bottom action-row">
<button class="secondary-btn" bindtap="confirm">确认</button>
<button class="primary-btn" bindtap="complete">完成</button>
<button class="danger-btn" bindtap="cancel">取消</button>
</view>
</block>
</view>
@@ -0,0 +1,99 @@
.detail-card {
padding: 24rpx;
}
.detail-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18rpx;
}
.detail-person {
display: flex;
align-items: center;
min-width: 0;
gap: 18rpx;
}
.avatar {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 82rpx;
height: 82rpx;
border-radius: 50%;
background: #e5eee9;
color: #5d8175;
font-size: 32rpx;
font-weight: 900;
}
.customer,
.phone {
display: block;
}
.customer {
color: #24211d;
font-size: 32rpx;
font-weight: 800;
}
.phone {
margin-top: 6rpx;
color: #928a81;
font-size: 24rpx;
}
.detail-actions {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 10rpx;
}
.detail-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 22rpx;
margin-top: 28rpx;
}
.label,
.value {
display: block;
}
.label {
color: #9a9288;
font-size: 22rpx;
}
.value {
margin-top: 8rpx;
color: #2d2924;
font-size: 28rpx;
font-weight: 700;
}
.note-card {
padding: 24rpx;
color: #6d655d;
line-height: 1.6;
}
.action-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 14rpx;
}
.action-row .primary-btn,
.action-row .secondary-btn,
.action-row .danger-btn {
width: 100%;
min-width: 0;
max-width: 100%;
}
@@ -0,0 +1,196 @@
const planningApi = require('../../api/planning')
const productsApi = require('../../api/products')
const config = require('../../utils/config')
const mock = require('../../utils/mock')
const dateUtil = require('../../utils/date')
const toDurationMinutes = value => {
if (typeof value === 'number') return value
const parsed = parseInt(String(value || ''), 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : 60
}
Page({
data: {
form: {
customerName: '',
phone: '',
appointmentDate: dateUtil.formatDate(new Date()),
appointmentTime: '13:00',
productId: '',
durationMinutes: '',
artistId: '',
remark: ''
},
products: [],
artists: config.USE_DEV_MOCK_DATA ? mock.artists : [],
selectedProduct: {},
selectedArtist: {},
conflictTip: '',
conflictLevel: 'free',
loading: false,
optionError: ''
},
onLoad(options = {}) {
this.setData({
'form.appointmentDate': options.date || dateUtil.formatDate(new Date()),
'form.artistId': options.artistId || ''
})
this.loadOptions()
},
async loadOptions() {
let products = []
let artists = []
let optionError = ''
try {
const productsData = await productsApi.list({ page: 1, size: 100 })
products = productsData.list || productsData || []
} catch (error) {
optionError = error.message || '项目数据加载失败'
products = config.USE_DEV_MOCK_DATA
? [
{ id: 1, title: '纯色美甲', approximateDuration: '90分钟' },
{ id: 2, title: '猫眼延长', approximateDuration: '120分钟' },
{ id: 3, title: '手部护理', approximateDuration: '60分钟' }
]
: []
}
try {
const calendar = await planningApi.calendar({
startDate: this.data.form.appointmentDate,
endDate: this.data.form.appointmentDate
})
artists = calendar.artists || []
} catch (error) {
optionError = optionError || error.message || '美甲师数据加载失败'
artists = config.USE_DEV_MOCK_DATA ? mock.artists : []
}
const selectedArtist = this.data.form.artistId
? artists.find(item => String(item.id) === String(this.data.form.artistId)) || {}
: {}
this.setData({ products, artists, selectedArtist, optionError })
this.checkAvailability()
},
onInput(event) {
this.setData({
[`form.${event.currentTarget.dataset.field}`]: event.detail.value
})
},
onDateChange(event) {
this.setData({ 'form.appointmentDate': event.detail.value })
this.loadOptions()
},
onTimeChange(event) {
this.setData({ 'form.appointmentTime': event.detail.value })
this.checkAvailability()
},
onProductChange(event) {
const selectedProduct = this.data.products[Number(event.detail.value)] || {}
this.setData({
selectedProduct,
'form.productId': selectedProduct.id,
'form.durationMinutes': String(toDurationMinutes(selectedProduct.approximateDuration))
})
this.checkAvailability()
},
onArtistChange(event) {
const selectedArtist = this.data.artists[Number(event.detail.value)] || {}
this.setData({
selectedArtist,
'form.artistId': selectedArtist.id
})
this.checkAvailability()
},
async checkAvailability() {
const form = this.data.form
if (!form.appointmentDate || !form.appointmentTime || !form.artistId) {
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
const durationMinutes = Number(form.durationMinutes || 0) || 60
const startMinute = dateUtil.minutesOfDay(form.appointmentTime)
const endMinute = startMinute + durationMinutes
if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) {
const tip = '该时间超出营业时间 10:00-22:00'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
let calendar
try {
calendar = await planningApi.calendar({
startDate: form.appointmentDate,
endDate: form.appointmentDate,
artistId: form.artistId
})
} catch (error) {
if (config.USE_DEV_MOCK_DATA) {
calendar = mock.buildCalendar(form.appointmentDate)
} else {
const tip = error.message || '暂未获取到排班,无法确认该时段是否可预约'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
}
const conflicts = (calendar.appointments || []).filter(item => {
if (String(item.artistId) !== String(form.artistId) || item.date !== form.appointmentDate) return false
if (item.status === 3 || item.statusText === '已取消') return false
const itemStart = Number(item.startMinute || dateUtil.minutesOfDay((item.startTime || '').slice(11, 16)))
const itemEnd = itemStart + Number(item.durationMinutes || 60)
return startMinute < itemEnd && endMinute > itemStart
})
if (conflicts.length > 0) {
const first = conflicts[0]
const itemStart = Number(first.startMinute || dateUtil.minutesOfDay((first.startTime || '').slice(11, 16)))
const itemEnd = itemStart + Number(first.durationMinutes || 60)
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约`
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约`
this.setData({ conflictTip: tip, conflictLevel: 'free' })
return { ok: true, tip }
},
async submit() {
const form = this.data.form
if (!form.customerName || !form.phone || !form.productId || !form.artistId) {
wx.showToast({ title: '请补全预约信息', icon: 'none' })
return
}
const availability = await this.checkAvailability()
if (!availability.ok) {
wx.showToast({ title: availability.tip || '该时段不可预约', icon: 'none' })
return
}
this.setData({ loading: true })
try {
const result = await planningApi.createAppointment({
...form,
productId: Number(form.productId),
artistId: Number(form.artistId),
durationMinutes: Number(form.durationMinutes || 0) || undefined
})
wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` })
} catch (error) {
wx.showToast({ title: error.message || '保存失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
},
back() {
wx.navigateBack()
}
})
@@ -0,0 +1,3 @@
{
"navigationBarTitleText": "新建预约"
}
@@ -0,0 +1,65 @@
<view class="page no-tab">
<view wx:if="{{optionError}}" class="card error-card">
<text class="error-title">选项加载不完整</text>
<text class="error-desc">{{optionError}}</text>
<button class="compact-btn" bindtap="loadOptions">重试</button>
</view>
<view class="card form-card">
<view class="field">
<text class="field-label">客户姓名</text>
<input value="{{form.customerName}}" data-field="customerName" bindinput="onInput" placeholder="请输入客户姓名" />
</view>
<view class="field">
<text class="field-label">手机号</text>
<input value="{{form.phone}}" data-field="phone" bindinput="onInput" placeholder="请输入手机号" />
</view>
<view class="field">
<text class="field-label">预约日期</text>
<picker mode="date" value="{{form.appointmentDate}}" bindchange="onDateChange">
<view class="field-value">{{form.appointmentDate}}</view>
</picker>
</view>
<view class="field">
<text class="field-label">预约时间</text>
<picker mode="time" value="{{form.appointmentTime}}" start="10:00" end="22:00" bindchange="onTimeChange">
<view class="field-value">{{form.appointmentTime}}</view>
</picker>
</view>
<view class="field">
<text class="field-label">项目内容</text>
<picker range="{{products}}" range-key="title" bindchange="onProductChange">
<view class="field-value">{{selectedProduct.title || '请选择项目'}}</view>
</picker>
</view>
<view class="field">
<text class="field-label">预计时长</text>
<input value="{{form.durationMinutes}}" data-field="durationMinutes" bindinput="onInput" type="number" placeholder="默认读取项目时长" />
<text class="unit">分钟</text>
</view>
<view class="field">
<text class="field-label">指定员工</text>
<picker range="{{artists}}" range-key="name" bindchange="onArtistChange">
<view class="field-value">{{selectedArtist.name || '请选择美甲师'}}</view>
</picker>
</view>
<view class="field textarea-field">
<text class="field-label">备注</text>
<textarea value="{{form.remark}}" data-field="remark" bindinput="onInput" placeholder="客户偏好、款式说明" />
</view>
</view>
<view class="capacity-tip card">
<text class="tip-title">容量校验</text>
<text class="tip-text">保存时会校验营业时间、美甲师休息和同时间段容量,冲突会直接拦截。</text>
</view>
<view wx:if="{{conflictTip}}" class="availability-tip card {{conflictLevel}}">
<text class="tip-title">时段检查</text>
<text class="tip-text">{{conflictTip}}</text>
</view>
<view class="fixed-bottom">
<button class="primary-btn" loading="{{loading}}" bindtap="submit">保存预约</button>
</view>
</view>
@@ -0,0 +1,60 @@
.unit {
color: #9a9288;
font-size: 24rpx;
}
.textarea-field {
align-items: flex-start;
}
.capacity-tip {
display: flex;
flex-direction: column;
gap: 8rpx;
margin-top: 20rpx;
padding: 22rpx;
}
.tip-title {
color: #4e4942;
font-size: 26rpx;
font-weight: 800;
}
.tip-text {
color: #90877e;
font-size: 24rpx;
line-height: 1.5;
}
.availability-tip {
display: flex;
flex-direction: column;
gap: 8rpx;
margin-top: 16rpx;
padding: 22rpx;
}
.availability-tip.free {
background: #f3faf5;
}
.availability-tip.warn {
background: #fff8e8;
}
.availability-tip.danger {
background: #fff2f2;
}
.availability-tip.free .tip-title {
color: #4f7d62;
}
.availability-tip.warn .tip-title {
color: #a2763d;
}
.availability-tip.danger .tip-title {
color: #c36a6a;
}
@@ -0,0 +1,95 @@
const planningApi = require('../../api/planning')
const config = require('../../utils/config')
const mock = require('../../utils/mock')
const dateUtil = require('../../utils/date')
const normalizeArtists = artists => (artists || []).map((item, index) => ({
id: item.id || item.userId || item.artistId,
name: item.name || item.nickname || item.artistName || `美甲师${index + 1}`,
shortName: item.shortName || String(item.name || item.nickname || '师').slice(-1),
color: item.color || ['#7BA7C7', '#89A98B', '#A893BC', '#D49A89'][index % 4],
statusText: item.statusText || '可接单',
availableStatus: item.availableStatus || 'free',
availableText: item.availableText || '可接'
}))
Page({
data: {
id: '',
artists: [],
selectedArtistId: '',
date: dateUtil.formatDate(new Date()),
time: '13:00',
loading: false,
loadError: false,
errorMessage: ''
},
onLoad(options = {}) {
this.setData({ id: options.id || '' })
this.loadArtists()
},
async loadArtists() {
this.setData({ loadError: false, errorMessage: '' })
try {
const calendar = await planningApi.calendar({
startDate: this.data.date,
endDate: this.data.date
})
this.setData({ artists: normalizeArtists(calendar.artists || []) })
} catch (error) {
if (config.USE_DEV_MOCK_DATA) {
this.setData({ artists: normalizeArtists(mock.artists) })
} else {
this.setData({
artists: [],
loadError: true,
errorMessage: error.message || '美甲师可接状态加载失败,请检查服务连接后重试'
})
}
}
},
selectArtist(event) {
this.setData({ selectedArtistId: event.currentTarget.dataset.id })
},
onDateChange(event) {
this.setData({ date: event.detail.value, selectedArtistId: '' })
this.loadArtists()
},
onTimeChange(event) {
this.setData({ time: event.detail.value })
},
async submit() {
if (this.data.loadError) {
wx.showToast({ title: '请先重新加载可接员工', icon: 'none' })
return
}
if (!this.data.selectedArtistId) {
wx.showToast({ title: '请选择美甲师', icon: 'none' })
return
}
this.setData({ loading: true })
try {
await planningApi.moveAppointment(this.data.id, {
artistId: Number(this.data.selectedArtistId),
appointmentDate: this.data.date,
appointmentTime: this.data.time
})
wx.showToast({ title: '已改派' })
setTimeout(() => wx.navigateBack(), 500)
} catch (error) {
wx.showToast({ title: error.message || '改派失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
},
back() {
wx.navigateBack()
}
})
@@ -0,0 +1,3 @@
{
"navigationBarTitleText": "改派员工"
}
@@ -0,0 +1,43 @@
<view class="page no-tab">
<view wx:if="{{loadError}}" class="card error-card">
<text class="error-title">数据加载失败</text>
<text class="error-desc">{{errorMessage}}</text>
<button class="compact-btn" bindtap="loadArtists">重试</button>
</view>
<view wx:elif="{{!artists.length}}" class="empty">暂无可改派美甲师</view>
<view wx:else class="list">
<view wx:for="{{artists}}" wx:key="id" class="card transfer-card {{selectedArtistId == item.id ? 'active' : ''}}" data-id="{{item.id}}" bindtap="selectArtist">
<view class="row between">
<view class="row">
<view class="chip-dot large" style="background: {{item.color}};"></view>
<view>
<text class="artist-name">{{item.name}}</text>
<text class="artist-status">{{item.statusText}}</text>
</view>
</view>
<text class="tag {{item.availableStatus}}">{{item.availableText}}</text>
</view>
</view>
</view>
<view class="card form-card section">
<view class="field">
<text class="field-label">新日期</text>
<picker mode="date" value="{{date}}" bindchange="onDateChange">
<view class="field-value">{{date}}</view>
</picker>
</view>
<view class="field">
<text class="field-label">新时间</text>
<picker mode="time" value="{{time}}" start="10:00" end="22:00" bindchange="onTimeChange">
<view class="field-value">{{time}}</view>
</picker>
</view>
</view>
<view class="fixed-bottom">
<button class="primary-btn" loading="{{loading}}" bindtap="submit">确认改派</button>
</view>
</view>
@@ -0,0 +1,45 @@
.transfer-card {
padding: 24rpx;
}
.transfer-card.active {
outline: 3rpx solid #8fb89a;
}
.chip-dot.large {
width: 24rpx;
height: 24rpx;
margin-right: 16rpx;
}
.artist-name,
.artist-status {
display: block;
}
.artist-name {
color: #25211d;
font-size: 30rpx;
font-weight: 800;
}
.artist-status {
margin-top: 6rpx;
color: #948c83;
font-size: 22rpx;
}
.tag.free {
background: #e5eee9;
color: #55786d;
}
.tag.busy {
background: #fbedd7;
color: #a5722a;
}
.tag.full {
background: #f8e2e6;
color: #b06070;
}
@@ -0,0 +1,40 @@
Page({
data: {
selected: '#7BA7C7',
customColor: '#7BA7C7',
wheelColors: [
'#E0627A', '#E7785B', '#E2A64B', '#D8C85C', '#9EBB63', '#63B77B',
'#4CB7A6', '#56A7D6', '#5F82D7', '#7C70D4', '#A66BC8', '#CF72A8'
],
recommendedColors: ['#7BA7C7', '#8FB89A', '#A894C7', '#D7A86E', '#D98DA5', '#79A6A3', '#B9A16B', '#9BA9C8'],
paletteColors: [
'#6F8F83', '#7BA7C7', '#8AAECA', '#9BA9C8', '#A894C7', '#C19AB7',
'#D98DA5', '#D9958D', '#D7A86E', '#C8B47E', '#B9A16B', '#9FAD7B',
'#8FB89A', '#79A6A3', '#6E9E92', '#A6B7A4', '#B8B0A6', '#C7B7A3',
'#8E8A7D', '#A4A097', '#B6A6A0', '#C9A2A2', '#B58A8A', '#8C7C92',
'#6D8491', '#829A9A', '#A9B3A2', '#C6B7D1', '#E0C2B6', '#F0D6A8'
]
},
select(event) {
const color = event.currentTarget.dataset.color
this.setData({ selected: color, customColor: color })
},
selectWheelColor(event) {
const color = event.currentTarget.dataset.color
this.setData({ selected: color, customColor: color })
},
onCustomInput(event) {
this.setData({ customColor: event.detail.value })
},
applyCustomColor() {
let color = (this.data.customColor || '').trim()
if (color && color[0] !== '#') color = `#${color}`
if (!/^#[0-9a-fA-F]{6}$/.test(color)) {
wx.showToast({ title: '请输入6位色值', icon: 'none' })
return
}
this.setData({ selected: color.toUpperCase(), customColor: color.toUpperCase() })
},
save() { wx.showToast({ title: '已保存到本地' }) },
back() { wx.navigateBack() }
})
@@ -0,0 +1,27 @@
<view class="page no-tab">
<view class="card color-preview" style="background: {{selected}};">{{selected}}</view>
<view class="section-title">推荐色</view>
<view class="palette recommended-palette">
<view wx:for="{{recommendedColors}}" wx:key="*this" class="color-swatch recommended {{selected === item ? 'active' : ''}}" style="background: {{item}};" data-color="{{item}}" bindtap="select"></view>
</view>
<view class="section-title">色盘选择</view>
<view class="card color-wheel-card">
<view class="color-wheel-wrap">
<view class="color-wheel">
<view wx:for="{{wheelColors}}" wx:key="*this" class="wheel-hit hit-{{index}}" data-color="{{item}}" bindtap="selectWheelColor"></view>
<view class="wheel-center" style="background: {{selected}};">
<text>{{selected}}</text>
</view>
</view>
</view>
<view class="palette-grid compact">
<view wx:for="{{paletteColors}}" wx:key="*this" class="palette-dot {{selected === item ? 'active' : ''}}" style="background: {{item}};" data-color="{{item}}" bindtap="select"></view>
</view>
</view>
<view class="card custom-color-card">
<view class="custom-color-preview" style="background: {{customColor}};"></view>
<input class="custom-color-input" value="{{customColor}}" maxlength="7" placeholder="#7BA7C7" bindinput="onCustomInput" />
<button class="small-action" bindtap="applyCustomColor">应用</button>
</view>
<view class="fixed-bottom"><button class="primary-btn" bindtap="save">保存颜色</button></view>
</view>
@@ -0,0 +1,148 @@
.color-preview {
display: flex;
align-items: center;
justify-content: center;
height: 168rpx;
color: #fff;
font-size: 34rpx;
font-weight: 900;
}
.palette {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 14rpx;
margin-top: 12rpx;
}
.color-swatch {
height: 92rpx;
border-radius: 12px;
box-shadow: 0 8rpx 18rpx rgba(58, 48, 34, 0.08);
}
.color-swatch.active {
outline: 6rpx solid rgba(47, 111, 98, 0.22);
}
.color-wheel-card {
padding: 22rpx 18rpx 18rpx;
}
.color-wheel-wrap {
display: flex;
justify-content: center;
}
.color-wheel {
position: relative;
width: 308rpx;
height: 308rpx;
border-radius: 50%;
background: conic-gradient(#e0627a, #e7785b, #e2a64b, #d8c85c, #9ebb63, #63b77b, #4cb7a6, #56a7d6, #5f82d7, #7c70d4, #a66bc8, #cf72a8, #e0627a);
box-shadow: inset 0 0 0 2rpx rgba(255, 255, 255, 0.45), 0 12rpx 28rpx rgba(58, 48, 34, 0.12);
}
.color-wheel::after {
position: absolute;
top: 42rpx;
right: 42rpx;
bottom: 42rpx;
left: 42rpx;
border-radius: 50%;
background: radial-gradient(circle at 34% 30%, rgba(255,255,255,0.78), rgba(255,255,255,0.18) 38%, rgba(38,35,31,0.12) 100%);
content: "";
}
.wheel-center {
position: absolute;
top: 94rpx;
left: 94rpx;
z-index: 2;
display: flex;
align-items: center;
justify-content: center;
width: 120rpx;
height: 120rpx;
border: 8rpx solid #fffdf8;
border-radius: 50%;
color: #fff;
font-size: 20rpx;
font-weight: 900;
text-shadow: 0 2rpx 6rpx rgba(31, 25, 20, 0.22);
box-shadow: 0 10rpx 24rpx rgba(58, 48, 34, 0.16);
}
.wheel-hit {
position: absolute;
top: 0;
left: 50%;
z-index: 3;
width: 70rpx;
height: 154rpx;
margin-left: -35rpx;
transform-origin: 50% 154rpx;
}
.hit-0 { transform: rotate(0deg); }
.hit-1 { transform: rotate(30deg); }
.hit-2 { transform: rotate(60deg); }
.hit-3 { transform: rotate(90deg); }
.hit-4 { transform: rotate(120deg); }
.hit-5 { transform: rotate(150deg); }
.hit-6 { transform: rotate(180deg); }
.hit-7 { transform: rotate(210deg); }
.hit-8 { transform: rotate(240deg); }
.hit-9 { transform: rotate(270deg); }
.hit-10 { transform: rotate(300deg); }
.hit-11 { transform: rotate(330deg); }
.palette-grid.compact {
margin-top: 22rpx;
}
.palette-grid {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 12rpx;
}
.palette-dot {
width: 68rpx;
height: 68rpx;
border-radius: 50%;
box-shadow: inset 0 0 0 1rpx rgba(255, 255, 255, 0.42), 0 6rpx 14rpx rgba(58, 48, 34, 0.08);
}
.palette-dot.active {
outline: 6rpx solid rgba(47, 111, 98, 0.24);
outline-offset: 3rpx;
}
.custom-color-card {
display: flex;
align-items: center;
gap: 16rpx;
margin-top: 18rpx;
padding: 18rpx;
}
.custom-color-preview {
width: 58rpx;
height: 58rpx;
flex-shrink: 0;
border-radius: 50%;
box-shadow: inset 0 0 0 1rpx rgba(255, 255, 255, 0.45);
}
.custom-color-input {
flex: 1;
min-width: 0;
height: 58rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #f4f0ea;
color: #2f2a25;
font-size: 26rpx;
font-weight: 700;
}
@@ -0,0 +1,25 @@
Page({
data: {
id: '',
avatarText: '客',
customer: { name: '王女士', phone: '138****1201' },
stats: { orderCount: 12, amount: 2860, lastTime: '06-01' },
orders: [
{ id: 1, date: '2026-06-01', project: '纯色美甲', amount: 168, artist: '小王' },
{ id: 2, date: '2026-05-18', project: '猫眼延长', amount: 268, artist: '小李' },
{ id: 3, date: '2026-05-02', project: '手部护理', amount: 98, artist: '小张' }
]
},
onLoad(options) {
this.setData({ id: options.id || '' })
},
createAppointment() {
wx.navigateTo({ url: '/pages/appointment-form/index' })
},
back() {
wx.navigateBack()
}
})
@@ -0,0 +1,40 @@
<view class="page no-tab">
<view class="card customer-head">
<view class="customer-identity">
<view class="avatar">{{avatarText}}</view>
<view>
<text class="customer-name">{{customer.name}}</text>
<text class="customer-phone">{{customer.phone}}</text>
</view>
</view>
<button class="small-action" bindtap="createAppointment">新预约</button>
</view>
<view class="stats">
<view class="card stat">
<text class="stat-value">{{stats.orderCount}}</text>
<text class="stat-label">累计订单</text>
</view>
<view class="card stat">
<text class="stat-value">¥{{stats.amount}}</text>
<text class="stat-label">累计消费</text>
</view>
<view class="card stat">
<text class="stat-value">{{stats.lastTime}}</text>
<text class="stat-label">最近消费</text>
</view>
</view>
<view class="section">
<view class="section-title">历史订单</view>
<view class="list">
<view wx:for="{{orders}}" wx:key="id" class="card list-card order-card">
<view>
<text class="order-title">{{item.project}}</text>
<text class="meta">{{item.date}} · {{item.artist}}</text>
</view>
<text class="amount">¥{{item.amount}}</text>
</view>
</view>
</view>
</view>
@@ -0,0 +1,89 @@
.customer-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18rpx;
padding: 24rpx;
}
.customer-identity {
display: flex;
align-items: center;
min-width: 0;
gap: 18rpx;
}
.avatar {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 84rpx;
height: 84rpx;
border-radius: 50%;
background: #e5eee9;
color: #5b7f73;
font-size: 32rpx;
font-weight: 900;
}
.customer-name,
.customer-phone {
display: block;
}
.customer-name {
font-size: 32rpx;
font-weight: 800;
}
.customer-phone {
margin-top: 8rpx;
color: #928a81;
font-size: 24rpx;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 14rpx;
margin-top: 18rpx;
}
.stat {
padding: 16rpx 12rpx;
}
.stat-value,
.stat-label {
display: block;
}
.stat-value {
color: #26231f;
font-size: 28rpx;
font-weight: 800;
}
.stat-label {
margin-top: 8rpx;
color: #91897f;
font-size: 20rpx;
}
.order-card {
display: flex;
align-items: center;
justify-content: space-between;
}
.order-title {
display: block;
font-size: 28rpx;
font-weight: 800;
}
.amount {
color: #6f8f83;
font-weight: 900;
}
@@ -0,0 +1,44 @@
const customersApi = require('../../api/customers')
Page({
data: {
keyword: '',
customers: []
},
onLoad() {
this.loadCustomers()
},
onSearchInput(event) {
this.setData({ keyword: event.detail.value })
clearTimeout(this._timer)
this._timer = setTimeout(() => this.loadCustomers(), 300)
},
async loadCustomers() {
const fallback = [
{ id: 1, name: '王女士', phone: '138****1201', lastTime: '2026-06-01' },
{ id: 2, name: '陈女士', phone: '136****8842', lastTime: '2026-05-29' },
{ id: 3, name: '林女士', phone: '159****6671', lastTime: '2026-05-27' }
]
try {
const data = await customersApi.list({ keyword: this.data.keyword, page: 1, size: 30 })
const list = data.list || data || []
this.setData({
customers: list.map(item => ({
id: item.id,
name: item.nickname || item.name || item.account || '客户',
phone: item.contactPhone || item.phone || '未填写',
lastTime: item.lastOrderTime || item.lastConsumeTime || '-'
}))
})
} catch (error) {
this.setData({ customers: fallback })
}
},
openDetail(event) {
wx.navigateTo({ url: `/pages/customer-detail/index?id=${event.currentTarget.dataset.id}` })
}
})

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