Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
688a4eed6d | ||
|
|
583bace2e1 | ||
|
|
3b689878b1 | ||
|
|
69ea01eaa4 | ||
|
|
4aaa179852 | ||
|
|
6f6625bc0d | ||
|
|
4bc7ddf08e | ||
|
|
ae5bc3ef2b | ||
|
|
2eefae834a | ||
|
|
b8904d92d1 | ||
|
|
8797732357 | ||
|
|
338283090b | ||
|
|
0dfa3bc5a8 | ||
|
|
daae69c6a0 | ||
|
|
771625d8cf | ||
|
|
e0154a9edb | ||
|
|
419eccad79 | ||
|
|
98308928e2 | ||
|
|
fb27f94deb | ||
|
|
6ca3ed64df | ||
|
|
60e9e1e9d0 | ||
|
|
b1360d9552 | ||
|
|
5dfea1a73b | ||
|
|
caf61b1163 | ||
|
|
f01662b185 | ||
|
|
50f3ad4e30 | ||
|
|
e870285300 | ||
|
|
69a32672c9 | ||
|
|
7da346d3aa | ||
|
|
4d111d8257 | ||
|
|
4f80a09619 | ||
|
|
ed33066ef6 | ||
|
|
b7baaa5b6e | ||
|
|
3d73ac7db7 | ||
|
|
71ddf0210c | ||
|
|
ae6317903a | ||
|
|
5fae5163ff | ||
|
|
1482bda1fa | ||
|
|
a5f050286b | ||
|
|
54215ffd50 | ||
|
|
c2c5c27453 | ||
|
|
380e7b42de | ||
|
|
c9ff29d048 | ||
|
|
60d9bba61a | ||
|
|
2ff83a5ec1 | ||
|
|
70f5462d88 | ||
|
|
3e51247312 | ||
|
|
701b75e57f | ||
|
|
61b443ff0a | ||
|
|
3bfc32777d | ||
|
|
7e16e1820a | ||
|
|
46e724334c | ||
|
|
5ca1d8bf96 | ||
|
|
6c2e094d58 | ||
|
|
6848491678 | ||
|
|
3a91246e0c | ||
|
|
1949c81c11 | ||
|
|
385c4b06ec | ||
|
|
942718b8d9 | ||
|
|
3f825682fb | ||
|
|
702c186f65 | ||
|
|
fb19fcf05f | ||
|
|
88589e2575 | ||
|
|
114a8a423c | ||
|
|
90b07bf33e | ||
|
|
99fa38f110 | ||
|
|
05493923e4 | ||
|
|
bbe1473b70 | ||
|
|
80d187d23c | ||
|
|
e6ecca7d47 | ||
|
|
47fced8175 | ||
|
|
ac35984ca3 | ||
|
|
772835d80d | ||
|
|
b5ebe0efdb | ||
|
|
6e4ee2cd54 | ||
|
|
544725f25e | ||
|
|
8f57158eab | ||
|
|
7d37432f4c | ||
|
|
9ddc77415c | ||
|
|
5de9c20ebc | ||
|
|
a961cc4bb2 | ||
|
|
3c28fe5544 | ||
|
|
0e4b8b1981 | ||
|
|
b8d930695b | ||
|
|
d4fc48bc2a | ||
|
|
029b7cc578 | ||
|
|
46a2763d72 | ||
|
|
b3e33c9fb9 | ||
|
|
c25e023e84 | ||
|
|
4b4c1ddef5 | ||
|
|
1fc46f3835 | ||
|
|
5f72324e60 | ||
|
|
92df97810a | ||
|
|
53a3cc9cc9 | ||
|
|
c626a1e6d6 | ||
|
|
19e2cd2594 | ||
|
|
6aafbd4eac | ||
|
|
b08fe4b486 | ||
|
|
b2fc23cd34 | ||
|
|
dac1d3dc20 | ||
|
|
6047348a21 | ||
|
|
db48259f1c | ||
|
|
de014483a8 | ||
|
|
752de63cec | ||
|
|
083ec972e3 | ||
|
|
e7e340b780 | ||
|
|
506fd8273f | ||
|
|
2f40bd2ee5 | ||
|
|
eec4507aad | ||
|
|
39d9b0c232 | ||
|
|
4e5c553b33 | ||
|
|
c3d9cd938d | ||
|
|
19ca9e2965 | ||
|
|
3e439543bc | ||
|
|
71943092ae | ||
|
|
fc3d38b247 | ||
|
|
9e47371442 | ||
|
|
52b7dcb7d3 | ||
|
|
203dac2370 | ||
|
|
f30abbc26c | ||
|
|
e52e04685d | ||
|
|
5426df3ef2 | ||
|
|
c8e0806c4d | ||
|
|
ddc04705e3 | ||
|
|
0e4043628e | ||
|
|
506ee86436 | ||
|
|
0e72050e3e | ||
|
|
bdc425183a | ||
|
|
8b205f3220 | ||
|
|
9a2c158fdd | ||
|
|
7b9a5e4d1c | ||
|
|
53b6fcaa11 | ||
|
|
7b40ee1650 | ||
|
|
5a787a93f3 | ||
|
|
eb1a41bfd1 | ||
|
|
6697b7e193 | ||
|
|
369f58d24e | ||
|
|
762be0d907 | ||
|
|
b3a8c7e01c | ||
|
|
bb3d00c51e | ||
|
|
6a278616a8 | ||
|
|
48050fb985 | ||
|
|
47d8cf555b | ||
|
|
f6b8f9b72a | ||
|
|
8f8f89e3b7 | ||
|
|
5793bf2390 | ||
|
|
976ca68687 | ||
|
|
6fbcf9896e | ||
|
|
6fb8ffd067 | ||
|
|
ba118c514a | ||
|
|
cf789b90b2 | ||
|
|
d10161a583 | ||
|
|
d24a6ac5b8 | ||
|
|
44dda21976 | ||
|
|
50af9b3fb0 | ||
|
|
fd9ff73c00 | ||
|
|
0151367333 | ||
|
|
433853c6a7 | ||
|
|
e4124d1e37 | ||
|
|
525882f3c2 | ||
|
|
b8327146cb | ||
|
|
17cf16db36 | ||
|
|
ed97bc0591 | ||
|
|
76917d92ad | ||
|
|
c1b282d465 | ||
|
|
9395d2781b | ||
|
|
9a13f20691 | ||
|
|
ed3daee8e5 | ||
|
|
38caec77af | ||
|
|
2e2548d68f | ||
|
|
a923702578 | ||
|
|
7cca502a98 | ||
|
|
da1f2d2cba | ||
|
|
1120f9d5a9 | ||
|
|
6e9ad54e94 | ||
|
|
9925c7f83b | ||
|
|
8d3f092084 | ||
|
|
68533738e0 | ||
|
|
527754af02 | ||
|
|
274c6af30b | ||
|
|
c952a913e8 | ||
|
|
4a7bd90088 | ||
|
|
3d18a1972b | ||
|
|
c7f5e7e808 | ||
|
|
94f3f3a4fa | ||
|
|
2f21b11117 | ||
|
|
3ad792115c | ||
|
|
21986185ab | ||
|
|
3ffa920d1c | ||
|
|
b9cd8caaab | ||
|
|
768b7848c5 | ||
|
|
52fc3df992 | ||
|
|
51cf60f242 | ||
|
|
b27f1f58b1 | ||
|
|
eb1a18d7be | ||
|
|
15e4947891 | ||
|
|
cbd2efeeb5 | ||
|
|
af85d6320d | ||
|
|
ac3daf4626 | ||
|
|
d2a2840fa8 | ||
|
|
9a0a33ee51 | ||
|
|
ce810e8ded | ||
|
|
b1be204220 | ||
|
|
59fe99bec8 | ||
|
|
7e5027b17d | ||
|
|
ac84f8f206 | ||
|
|
697708d754 | ||
|
|
28510db233 | ||
|
|
2b621a6fe0 | ||
|
|
6c7f8aef30 | ||
|
|
39fce9da7e | ||
|
|
8635eccb06 | ||
|
|
065a5c7fb8 | ||
|
|
a29a468ed3 | ||
|
|
d6cc82a4bc | ||
|
|
c957994006 | ||
|
|
fe782b47d5 | ||
|
|
52ac5d6cea | ||
|
|
4cedbb826d | ||
|
|
7eb1f9a62f | ||
|
|
3cf2fbdcc6 | ||
|
|
138d3eae57 | ||
|
|
261723bc6e | ||
|
|
d6f3652a70 | ||
|
|
4101ab3408 | ||
|
|
5145dc44c6 | ||
|
|
bd8d95fcd9 | ||
|
|
3ab615ccd4 | ||
|
|
59608ef57f | ||
|
|
3b98e4746a | ||
|
|
fa1fed006e | ||
|
|
2714bd7201 | ||
|
|
e4aff0803a | ||
|
|
247472fcae | ||
|
|
960c042c17 | ||
|
|
7411414419 | ||
|
|
e18c2b06d5 | ||
|
|
09db9fceaa | ||
|
|
66b9e2dc2d | ||
|
|
f185ec4ba5 | ||
|
|
7cbfba7cf6 | ||
|
|
48b25583ee | ||
|
|
63097311ef | ||
|
|
ceb210a582 | ||
|
|
126ec43c10 | ||
|
|
cbd6e23104 | ||
|
|
d25f9674c3 | ||
|
|
943fa79d16 | ||
|
|
4d2918f8a8 | ||
|
|
faa9cadc62 | ||
|
|
10a3b6413c | ||
|
|
4004506b65 | ||
|
|
fc148afc69 | ||
|
|
bd4ed62368 | ||
|
|
f00c753fd6 | ||
|
|
0e7e60fefd | ||
|
|
ef5f638e7e | ||
|
|
89f51440a0 | ||
|
|
d57f9b736a | ||
|
|
ff98e89ab7 | ||
|
|
cd08d3c3b0 | ||
|
|
0ceea1578f | ||
|
|
d3e9404c17 | ||
|
|
7e62fed56d | ||
|
|
804c69c296 | ||
|
|
72bfcffc25 | ||
|
|
9148bdb027 | ||
|
|
d511070fc7 | ||
|
|
d38c5cd4fe | ||
|
|
ae1b568131 | ||
|
|
34e6536b0f | ||
|
|
e69498cc15 | ||
|
|
e7de04717a | ||
|
|
297af45fea | ||
|
|
c4c17a67d4 | ||
|
|
6f62137bf8 | ||
|
|
fff1a0a97f | ||
|
|
9e3b37a36c | ||
|
|
043dfff1b1 | ||
|
|
4bb8665aab | ||
|
|
dd3bcd40bc | ||
|
|
bda3933959 | ||
|
|
1587d1dd8f | ||
|
|
cfe5cfeaf7 | ||
|
|
fab7d7789d | ||
|
|
be3d0cccec | ||
|
|
5288dbf9b0 | ||
|
|
e8e8e5a404 | ||
|
|
0c827782ff | ||
|
|
52dcd143ff | ||
|
|
7b68ef32e1 | ||
|
|
672cd936fe | ||
|
|
8906eb39db | ||
|
|
d2d17cef93 | ||
|
|
381dad1fed | ||
|
|
2ebaaeec77 | ||
|
|
e9a2e74b91 | ||
|
|
8c5170cb7e | ||
|
|
966a911014 | ||
|
|
8d84cb25d4 | ||
|
|
c0979f447c | ||
|
|
c849f44787 | ||
|
|
8cb5cae808 | ||
|
|
003dedf5d0 | ||
|
|
f02601c25c | ||
|
|
63b226fe61 | ||
|
|
a26252c020 | ||
|
|
b4af2d6ab1 | ||
|
|
28c2c2603e | ||
|
|
4f4d985673 | ||
|
|
6c8b3f8447 | ||
|
|
ddf7e4823b | ||
|
|
29ad14b24a | ||
|
|
edc14b3d41 | ||
|
|
f3e480de33 | ||
|
|
211cdc9838 | ||
|
|
e3bb72b3f1 | ||
|
|
3401c2f5e5 | ||
|
|
dc46ff359b | ||
|
|
7c43ab636a | ||
|
|
4260da2942 | ||
|
|
1aee997e48 | ||
|
|
db3defffdf | ||
|
|
1dd4b1c2cb | ||
|
|
54414f56cd | ||
|
|
a65063e419 | ||
|
|
ed4cc4e83d | ||
|
|
285fed64fa | ||
|
|
c3a6287547 | ||
|
|
2942f29438 | ||
|
|
fd76865a0a | ||
|
|
048c19e5fe | ||
|
|
a50b7b6c66 | ||
|
|
852a715722 | ||
|
|
9ac56115d0 | ||
|
|
4209ee732c | ||
|
|
89c9deeeb2 | ||
|
|
c0a51a278e | ||
|
|
d5535fbfa2 | ||
|
|
c3511d2f47 | ||
|
|
6dd2233c16 | ||
|
|
aee4c0ff3d | ||
|
|
b2fe9dc53a | ||
|
|
47611d5c7a | ||
|
|
c0fc27a175 | ||
|
|
2bf5e9d45b | ||
|
|
b1e8b5a723 | ||
|
|
006306171b | ||
|
|
dddb55f462 | ||
|
|
fd35a330e0 | ||
|
|
5235c77e4a | ||
|
|
6110227ad6 | ||
|
|
63cdf3ef2d | ||
|
|
629375cd2e | ||
|
|
8c7c919ddd | ||
|
|
cad7afb12e | ||
|
|
f62fb02ef0 | ||
|
|
82f660ff6d | ||
|
|
317e482534 | ||
|
|
5aef5bbe79 | ||
|
|
d5815bcaf4 | ||
|
|
29291b7b35 | ||
|
|
a2b3cab0e3 | ||
|
|
a8a2d94626 | ||
|
|
0fab855185 | ||
|
|
ad599674e1 | ||
|
|
63c991b1d5 | ||
|
|
347414470e | ||
|
|
184ec8444d | ||
|
|
3e53561caf | ||
|
|
1c3b61bc33 | ||
|
|
10be2b2e9d | ||
|
|
e1f7e04d05 | ||
|
|
f4a4191a4c | ||
|
|
c50695d249 | ||
|
|
0bc40b5823 | ||
|
|
0a355a7e68 | ||
|
|
b0181edbd3 | ||
|
|
cbd00d0597 | ||
|
|
d38fd639bc | ||
|
|
1bec2e5bcd | ||
|
|
2054b32267 | ||
|
|
31112b1b1c | ||
|
|
d63f2011ec | ||
|
|
a2c8f0baea | ||
|
|
ccadd8dc62 | ||
|
|
57dfe82a5d | ||
|
|
5211c2d6cd | ||
|
|
0df0a86d9a | ||
|
|
e9748119ef | ||
|
|
216efa6b3c | ||
|
|
c08a65e14f | ||
|
|
a0f659c5c4 | ||
|
|
025af6ba9b | ||
|
|
fe4baad70c | ||
|
|
a10769de45 | ||
|
|
bfe4d4c344 | ||
|
|
8270784e39 | ||
|
|
346dde8197 | ||
|
|
581136cb24 | ||
|
|
2ad41221ff | ||
|
|
449d57916d | ||
|
|
abf34267a1 | ||
|
|
4e9b8c8ede | ||
|
|
47a49cd6b3 | ||
|
|
df1ec06d39 | ||
|
|
4703f1e9ed | ||
|
|
911e759827 | ||
|
|
2ca3cc3652 | ||
|
|
3ac1f5a7c8 | ||
|
|
857a07fd7b | ||
|
|
42919aad21 | ||
|
|
a6ecf47020 | ||
|
|
63d133d7c9 | ||
|
|
24018c42f2 | ||
|
|
90f00feefd | ||
|
|
56eb63ca0c | ||
|
|
2a5d18e339 | ||
|
|
074cbd0c8c | ||
|
|
e59bb424f0 | ||
|
|
4223f42e43 | ||
|
|
ee12fee6b6 | ||
|
|
8f1b85ec7f | ||
|
|
55b8b8e73c | ||
|
|
4ae6cffdf1 | ||
|
|
8af439f1d2 | ||
|
|
8e303f5d9d | ||
|
|
da6d1b7f5b | ||
|
|
2d9cf472a8 | ||
|
|
65193c6b6c | ||
|
|
0d30999768 | ||
|
|
542403cf0e | ||
|
|
bf29f27629 | ||
|
|
501054ce12 | ||
|
|
75e6d37603 | ||
|
|
2831543bac | ||
|
|
4e14468bc1 | ||
|
|
0c83acc7c2 | ||
|
|
a2491b72b9 | ||
|
|
abce4a2787 | ||
|
|
aa93695704 | ||
|
|
c7b2daba71 |
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: jayu-api
|
||||
description: JayuCloud 接口与权限规则:Gateway 路由前缀(/api、/api/admin、/internal)、白名单与 JWT 门禁、小程序与管理端基址差异、脱敏与授权取数出口、接口变更检查清单。用于新增/修改后端接口或前后端联调契约时;通用 API 设计方法用全局 $api-design
|
||||
---
|
||||
|
||||
# JayuCloud 接口规则
|
||||
|
||||
本项目接口变更最常见的事故是**路由前缀与门禁错配**(管理接口暴露、小程序被误拦)。新增或修改接口必须按本技能核对。
|
||||
|
||||
## 路由与门禁基线
|
||||
|
||||
| 前缀 | 用途 | 门禁 |
|
||||
|------|------|------|
|
||||
| `/api/**` | 业务接口(小程序与前端业务路由) | Gateway JWT 初筛 + 白名单 |
|
||||
| `/api/admin/**` | 管理端接口 | 管理员门禁(Core 按 URL 前缀判断) |
|
||||
| `/internal/**` | 服务间内部接口 | 仅限内部调用,禁止暴露到公网路由 |
|
||||
|
||||
关键事实:
|
||||
|
||||
- Salon Core 的管理员门禁按 `/admin/**` URL 前缀判断:**小程序绝不能复用 `/api/admin` 基址**,否则店长/员工业务会被误拒;小程序用 `/api` 业务路由,需要时由 Core 提供非 `/admin` 路由别名。
|
||||
- 给小程序提供别名时不得整控制器映射:只映射实际需要的端点(例如对象存储只映射上传端点,不映射列表/更新/删除)。
|
||||
- 生产小程序请求走 `https://yunail.art/api/admin`(管理师小程序)与 `/api`(用户端);本地开发用 `utils/config.local.js`(不入 Git)。
|
||||
- 匿名白名单:逐个端点枚举,禁止 `/wechat-mini/**` 这类宽泛前缀——后续新增认证端点会被静默暴露。白名单需同时核对服务拦截器与 Gateway 各份配置。
|
||||
|
||||
## 新增接口检查清单
|
||||
|
||||
1. 确定归属端与前缀(对照上表);拿不准时先看同域现有接口。
|
||||
2. 认证与授权:匿名还是登录?管理端权限码?数据属主(门店作用域)校验写在 Service 层。
|
||||
3. 请求/响应:统一 `Result<T>` 包装;参数校验注解;错误语义与现有错误码一致。
|
||||
4. 隐私字段:默认脱敏返回;需要明文时走独立授权端点(一次一取,按门店/订单上下文授权),并记录审计。
|
||||
5. 幂等与并发:写接口明确重复提交语义;金额/配额操作原子化。
|
||||
6. 前端/小程序同步:`src/api/` 或 `api/` 封装、免登录路径、请求基址是否需要同步修改。
|
||||
7. Gateway 白名单与路由是否需要同步(Nacos `gateway.yaml`)。
|
||||
8. 涉及 SQL 时转 $jayu-database;涉及配置时转 $jayu-release。
|
||||
|
||||
## 联调约定
|
||||
|
||||
- 前端开发代理:`/admin/api` 与 `/api` → `VITE_DEV_PROXY_TARGET`(vite.config.ts)。
|
||||
- 小程序:`utils/request.js` 统一封装;401 处理全局唯一,清会话要彻底(含 `wx.uploadFile` 路径)。
|
||||
- 大数 ID:雪花 ID 传前端按字符串处理,避免 `JSON.parse` 精度丢失。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 不新增绕过门禁的「临时匿名接口」;确有需要必须逐个列出理由并提示安全评审。
|
||||
- 不在接口返回中携带密钥、内部堆栈、完整隐私字段。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 清单 8 项逐一给出结论(含「不涉及」);前缀与门禁选择有依据;联调端同步修改已列出。
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: jayu-database
|
||||
description: JayuCloud 数据库与迁移纪律:Flyway 版本文件规则(中文命名、已执行不可改、向前兼容补偿)、空库初始化基线、实体与迁移同步清单、MySQL 已知坑。用于新增/修改表结构、字段、索引或写 SQL 时;通用数据库设计方法用全局 $database-design
|
||||
---
|
||||
|
||||
# JayuCloud 数据库纪律
|
||||
|
||||
本项目数据库变更是高危操作:DEV/SIT/PROD 由 Core 启动时 Flyway 自动执行,**没有人工补救窗口**。任何结构改动必须按本技能执行。
|
||||
|
||||
## 硬性规则(不可违反)
|
||||
|
||||
1. 结构变更只走 Flyway 版本文件:
|
||||
- Salon:`JC-Salon-Core/src/main/resources/db/migration/V{n}__中文功能说明_YYYYMMDD.sql`
|
||||
- ArtList:`JC-ArtList-Core/src/main/resources/db/migration/` 同规则
|
||||
- 版本号取当前目录最大版本号 +1;文件名中文体现功能与日期;内容必须完整可执行。
|
||||
2. 已在任一环境执行过的迁移文件**不得修改或删除**;撤销/修正必须新增向前兼容的补偿迁移。禁止 Flyway `clean`、自动 baseline、重跑初始化 SQL。
|
||||
3. 空库初始化仅用 `docs/scripts/sql/init/jayucloud-salon.sql` / `jayucloud-artlist.sql`(0.0.1 基线);只有负责人明确要求重整基线时才把变更合并进初始化 SQL。
|
||||
4. 生产已部署库升级不直接执行初始化 SQL,必须单独制定迁移方案。
|
||||
5. Gitea 工作流不得直连数据库或绕过 Flyway;合并 SIT 前先在 DEV 验证迁移。
|
||||
|
||||
## 工作流程
|
||||
|
||||
### 1. 设计
|
||||
|
||||
- 先读现有表结构(初始化 SQL + 已有版本文件)与对应实体,遵循既有命名/主键/字符集约定。
|
||||
- 字段类型注意:金额用 DECIMAL;时间遵循现有约定;枚举落库策略与现有一致。
|
||||
- 索引从实际查询出发;唯一约束必须显式建唯一索引。
|
||||
|
||||
### 2. 实体与迁移同步清单(逐项核对)
|
||||
|
||||
- [ ] 实体类字段与 SQL 列一一对应(`@TableName`/`@TableField`)。
|
||||
- [ ] 新 Mapper 包已加入 `MyBatisPlusConfig` 的 `@MapperScan` 清单(编译过≠启动过)。
|
||||
- [ ] 自动填充逻辑合并进现有 `MetaObjectHandler`(只接受单例)。
|
||||
- [ ] 所有插入入口都覆盖新字段(静态搜索该实体的全部保存入口)。
|
||||
- [ ] 存量数据需要回填时,在同一版本文件或后续版本中写幂等回填。
|
||||
- [ ] 历史迁移中不得夹带本次之外的变更。
|
||||
|
||||
### 3. 已知坑(写 SQL 前对照)
|
||||
|
||||
- 排序规则冲突:`utf8mb4_0900_ai_ci` 与旧列 `utf8mb4_unicode_ci` 混用会报 1267;跨 collation 比较显式 `CONVERT(... USING utf8mb4) COLLATE utf8mb4_unicode_ci`。
|
||||
- MySQL 迁移失败不回滚已执行 DDL:可重试迁移要先检查字段/索引是否已存在(幂等)。
|
||||
- `flyway repair` 只清失败历史记录,不回滚结构;独立调用 repair 必须显式设置完整 `locations`,否则可能误删历史。
|
||||
- 整理/合并初始化 SQL 时检查脚本尾部 DROP 语句,别把运行必需表删掉。
|
||||
- 雪花 ID:MyBatis-Plus `ASSIGN_ID` 在应用层分配,表定义可能仍是 `AUTO_INCREMENT`,判断主键策略要三处核对(注解/生成策略/SQL)。
|
||||
- 无斜杠的 `test/` gitignore 规则会忽略任意层级的 test 目录,新增测试文件用 `git check-ignore -v` 确认。
|
||||
|
||||
### 4. 验证与交付
|
||||
|
||||
- 能在临时库执行就实际执行验证;不能执行时记录阻塞原因。
|
||||
- 任务说明中写明:新增的版本文件路径、影响的表、是否需要回填、DEV 验证结果。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 不对任何真实环境数据库直接执行 DDL/DML;执行由 Core 启动的 Flyway 完成。
|
||||
- 不在 SQL 中写入真实客户数据;种子数据只保留运行必需项(平台管理员 `xiaowang`、权限、协议、系统参数等)。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 版本文件命名与位置合规、可独立执行;实体与列一致;清单全部勾选;任务记录包含验证结论。
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: jayu-devflow
|
||||
description: JayuCloud 开发与验证流程:各模块构建命令(Maven/npm/node 语法检查)、启动烟测要求、提交前检查(GitNexus detect_changes、中文提交)、常见陷阱清单。用于在本仓库写代码、构建、测试、提交时;TDD 方法论用全局 $test-driven-development,调试方法用 $systematic-debugging
|
||||
---
|
||||
|
||||
# JayuCloud 开发流程
|
||||
|
||||
## 构建与验证命令(按改动范围选择)
|
||||
|
||||
| 改动范围 | 验证命令 | 说明 |
|
||||
|----------|----------|------|
|
||||
| Salon 后端 | `mvn -f JC-Salon-Core/pom.xml -DskipTests compile`(测试:`... test`) | 非聚合工程,必须 `-f` 指定模块;本机 Maven:`D:\software\apache-maven-3.9.12\bin\mvn.cmd` |
|
||||
| ArtList 后端 | `mvn -f JC-ArtList-Core/pom.xml -DskipTests compile` | 同上 |
|
||||
| Gateway | `mvn -f JC-Salon-Gateway/pom.xml -DskipTests compile`(ArtList 同理) | |
|
||||
| 前端 | `JC-Salon-Frontend` / `JC-ArtList-Frontend` 下 `npm run build` | 开发 `npm run dev` |
|
||||
| 小程序 | `node --check <改动文件>` 语法检查 | 有条件时微信开发者工具冒烟 |
|
||||
| SQL | 临时库执行或记录阻塞原因 | 见 $jayu-database |
|
||||
|
||||
**升级规则**:涉及 Bean 装配、事务、拦截器、`@MapperScan`、自动填充的改动,编译通过后必须做一次 Core 启动烟测——编译通过不等于能启动。
|
||||
|
||||
## 开发节奏
|
||||
|
||||
1. 动手前:`git status` 确认工作区;有他人未提交改动时先按项目规则处理(中文回溯提交)。
|
||||
2. 修改符号前:GitNexus impact 分析(AGENTS.md 文首规则);业务域不熟时先读 $jayu-domain。
|
||||
3. 实施:遵循模块分层与命名约定;接口改动走 $jayu-api 清单;SQL 改动走 $jayu-database。
|
||||
4. 验证:按上表执行对应命令;测试遵循红绿纪律,Mock 参数全字面量或全 matcher。
|
||||
5. 提交前:GitNexus `detect_changes`(失败时记录原因,用 `git diff` + 测试结果兜底);只暂存本任务文件。
|
||||
6. 提交:中文提交信息;任务记录写明新增/调整的版本化文件(SQL/配置说明)。
|
||||
|
||||
## 提交与分支纪律
|
||||
|
||||
- 每次任务完成后整理相关改动创建 git 提交,提交信息必须中文。
|
||||
- 只暂存和提交本次任务涉及的文件,保留其他并行改动。
|
||||
- 注意 `.gitignore` 陷阱:无斜杠的 `test/` 会忽略任意层级 test 目录,新增测试用 `git check-ignore -v` 确认,必要时 `git add -f`。
|
||||
|
||||
## 常见陷阱(改前对照,详见 references/pitfalls.md)
|
||||
|
||||
1. 编译过 ≠ 启动过(扫描清单、Bean 冲突在启动期暴露)。
|
||||
2. 事务自调用失效;事务内远程调用不可回滚。
|
||||
3. 多构造器时注入构造器要显式 `@Autowired`(Spring Boot 2.x)。
|
||||
4. 共享基类字段(软删除等)并非所有实体都有,查询前先核对继承链。
|
||||
5. 配置覆盖链:`secret.yaml`/环境变量可能覆盖 `infra.yaml` 与本地文件。
|
||||
6. 旧 class 残留:移除组件后 clean 构建再验证。
|
||||
7. 雪花 ID 传 JS 前端的精度问题(字符串传输)。
|
||||
8. 小程序 401 清会话不彻底导致反复跳登录。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 不在本地验证中连接生产数据库/生产 Nacos;本地联调用 dev 环境或本机中间件。
|
||||
- 验证失败如实报告,不以「应该没问题」代替证据(全局 $verification-before-completion 约束同样适用)。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 对应范围的验证命令已实际执行且输出通过;提交信息中文、范围干净;任务记录含版本化文件清单。
|
||||
@@ -0,0 +1,43 @@
|
||||
# JayuCloud 常见陷阱清单
|
||||
|
||||
来源:历史任务教训沉淀(全局 error-memory 与本项目复盘),仅保留与本项目技术栈相关的通用条目。
|
||||
|
||||
## Spring / MyBatis-Plus
|
||||
|
||||
- `MyBatisPlusConfig` 使用显式 `@MapperScan` 包清单:新增 `@Mapper` 模块包必须同步加入,否则编译通过但启动缺 Bean。
|
||||
- MyBatis Mapper statement ID = namespace + 方法名(无参数类型):同一 Mapper 不能重载同名 SQL 方法,否则一条注解映射被忽略。
|
||||
- MyBatis-Plus 自动填充只接受单个 `MetaObjectHandler`:新增填充逻辑合并进同一处理器;移除旧组件后 clean 构建,防止旧 class 被扫描。
|
||||
- MyBatis lambda 查询共享基类字段(如 `isDelete`)前,确认具体实体继承链上确实有该字段。
|
||||
- Spring Bean 多构造器时,注入构造器显式 `@Autowired`;用一次真实容器启动烟测确认。
|
||||
- Mockito 验证不混用字面量与 `any()`,参数要么全字面量要么全 matcher。
|
||||
- 事务:自调用不走代理;事务内不做远程调用/发消息等不可回滚操作。
|
||||
|
||||
## 配置与环境
|
||||
|
||||
- Nacos 配置写入成功后集群读回可能短暂落后:发布/回退都要做有限重试 + 内容摘要校验,失败要 fail closed。
|
||||
- 排查配置问题不能只看单一文件:后加载的 `secret.yaml`、systemd `EnvironmentFile`、环境变量都可能覆盖。
|
||||
- 本地 `application.yaml`/`bootstrap.yaml` 只放 Nacos 引导参数,运行配置改 Nacos 并同步 `nacos/` 仓库副本与说明文档。
|
||||
|
||||
## 前端 / 小程序
|
||||
|
||||
- 小程序不要复用 `/api/admin` 基址(管理门禁按前缀误拒业务);别名只映射需要的端点。
|
||||
- 雪花 `Long` ID 经 `JSON.parse` 丢精度:前端回传按字符串保留,补回归测试。
|
||||
- 上传到私有对象存储后不要直接拿响应 `fileUrl` 做预览:可能是私有桶/内网地址;先用本地临时路径预览,以服务端文件 ID 提交。
|
||||
- 对象存储 URL 解析必须按环境配置处理 MinIO 内网端点、公共端点与 `oss://` 引用;签名失败不得把私有地址原样返回。
|
||||
- 401 处理:清会话要覆盖 `wx.request` 与 `wx.uploadFile` 全部路径,防重状态保持到新登录成功,避免残留旧登录态反复跳登录。
|
||||
- 提供 HTML demo 做参照时,实现前完整检查其 HTML/CSS/交互脚本再映射组件,不能只按截图复刻。
|
||||
|
||||
## 数据库 / 迁移
|
||||
|
||||
- 新增必需业务字段:静态搜索实体所有插入入口逐一补齐 + 幂等回填存量空值。
|
||||
- 排序规则冲突(`utf8mb4_0900_ai_ci` vs `utf8mb4_unicode_ci`):跨 collation 比较显式 `CONVERT ... COLLATE`。
|
||||
- MySQL 迁移失败不回滚已执行 DDL:可重试迁移先查字段/索引是否已存在。
|
||||
- 独立调用 Flyway `repair` 必须显式完整 `locations`,执行后立即检查 `flyway_schema_history`。
|
||||
- 整理初始化 SQL 时核对尾部 DROP 与实体表清单,防止误删运行必需表。
|
||||
- 注册/申请类「取最新记录」查询:按创建时间排序后还要按雪花 ID 倒序,避免同秒提交取旧。
|
||||
|
||||
## 工具链
|
||||
|
||||
- 本机 `node`/`mvn` 可能不在 PATH:Node 在 `D:\software\nodejs`(PowerShell 用 `npm.cmd`/`npx.cmd`),Maven 在 `D:\software\apache-maven-3.9.12\bin\mvn.cmd`。
|
||||
- GitNexus 特定版本在本机分析可能失败,优先用项目 `.gitnexus/run.cjs analyze --index-only` 或可用版本。
|
||||
- GitNexus 对 Vue/Java 同名局部符号可能跨语言误关联:critical 风险提示先核对实际引用与构建结果再决策。
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: jayu-domain
|
||||
description: JayuCloud 项目领域知识:Salon 店务与 ArtList 设计师两条产品线的模块地图、核心业务流程(预约/排班/订单/注册审核/协议/拨号/内容审核)、角色权限模型。用于理解或修改本项目业务功能前;通用需求分析方法用全局 $requirements-analysis
|
||||
---
|
||||
|
||||
# JayuCloud 领域知识
|
||||
|
||||
JayuCloud 是双产品线仓库:**Salon(店务/指尖管理师)** 与 **ArtList(指尖设计师)**。修改业务代码前先读本技能与 [references/module-map.md](references/module-map.md),确认改动落在哪个业务域、影响哪些端。
|
||||
|
||||
## 产品线速览
|
||||
|
||||
| 产品线 | 服务对象 | 端 | 后端 |
|
||||
|--------|----------|----|------|
|
||||
| Salon | 美甲门店(平台管理员/店长/美甲师) | 管理端 Vue + 指尖管理师小程序 | JC-Salon-Core / JC-Salon-Gateway |
|
||||
| ArtList | C 端用户 + 平台运营 | 用户端/管理端 Vue + 用户小程序 | JC-ArtList-Core / JC-ArtList-Gateway |
|
||||
|
||||
## 核心业务流程(改前必查上下游)
|
||||
|
||||
1. **预约与排班(Salon)**:门店每周营业排班 → 美甲师可约时段 → 客户预约(散客支持拨号联系)→ 订单履约。改动排班/预约时核对 `planning`、`order`、`shop` 三域。
|
||||
2. **订单与收款**:下单 → 状态流转 → 收款(线上/线下收款登记)→ 完成。订单完成强制校验收款状态;补单创建即 PAID。
|
||||
3. **注册与审核**:门店/美甲师注册申请 → 店长审核模式 → 门店经营有效期;驳回重申保留历史版本并新建申请。
|
||||
4. **内容审核与协议**:对外内容审核(图片/作品)、协议版本管理、用户同意状态拦截(微信端 4510 流程)。
|
||||
5. **隐私与拨号**:手机号/账号全链路加密存储(AES-GCM + hash 查询),所有接口默认脱敏返回;明文一次一取,走独立授权端点(按门店与订单上下文授权)。
|
||||
6. **文件体系**:上传按 `MINIO → QINIU_KODO → ALIYUN_OSS` 优先级补副本,读取按配置的渠道优先级生成签名地址;历史数据可能存 MinIO 内网端点或 `oss://` 引用,统一 URL 工具按环境解析。
|
||||
7. **ArtList 电商链路**:浏览 → 购物车 → 下单 → 评价/改派 → VIP/优惠券;订单镜像与 Salon 侧存在同步契约(事件/状态映射)。
|
||||
|
||||
## 角色与权限
|
||||
|
||||
- 角色:平台管理员(`xiaowang`)、店长、美甲师、普通用户 + 门店自定义角色。
|
||||
- 权限码裁剪菜单与接口;数据属主校验(门店作用域)在 Service 层;管理端走 `/api/admin/**` 门禁。
|
||||
- 新增权限/菜单种子后必须授权给平台管理员。
|
||||
|
||||
## 使用要求
|
||||
|
||||
- 修改业务功能前:先定位业务域(module-map)→ 按 AGENTS.md 要求做 GitNexus impact → 再动手。
|
||||
- 涉及流程 1-7 的改动,完成后在任务说明中写明对上下游的影响。
|
||||
- 本技能只提供项目知识,不替代开发流程技能($jayu-devflow)与数据库纪律($jayu-database)。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 不输出、不记录任何真实客户手机号/账号明文;示例一律用占位符。
|
||||
- 隐私字段相关改动必须保持「默认脱敏、授权取明文」的基线,不得新开完整号码出口。
|
||||
@@ -0,0 +1,50 @@
|
||||
# JayuCloud 模块地图
|
||||
|
||||
> 依据 2026-11-05 源码目录核实;如有出入以源码为准。
|
||||
|
||||
## 后端业务域(Core `modules/`)
|
||||
|
||||
| 域 | Salon | ArtList | 职责 |
|
||||
|----|:---:|:---:|------|
|
||||
| auth | ✓ | ✓ | 登录、令牌、会话(微信登录/账号登录) |
|
||||
| user | ✓ | ✓ | 用户资料、客户管理、隐私字段加密与脱敏出口 |
|
||||
| shop | ✓ | ✓ | 门店/店铺、营业设置、有效期、主题 |
|
||||
| artist | ✓ | ✓ | 美甲师/艺术家资料、注册申请关联 |
|
||||
| product | ✓ | ✓ | 作品/服务项、分类标签、价格与时长 |
|
||||
| order | ✓ | ✓ | 订单状态机、收款登记、完成校验 |
|
||||
| payment | ✓ | ✓ | 支付/退款集成 |
|
||||
| planning | ✓ | ✓ | 排班、预约占用、规划日历 |
|
||||
| marketing | ✓ | ✓ | 优惠券、营销活动、VIP |
|
||||
| message | ✓ | ✓ | 系统消息、订阅消息、跳转与弹窗 |
|
||||
| content | ✓ | ✓ | 内容审核(图片/作品/对外文案) |
|
||||
| file | ✓ | ✓ | 上传编排、对象存储三副本、签名地址 |
|
||||
| integration | ✓ | ✓ | 第三方集成(微信审核回调、内容审核、短信等) |
|
||||
| security | ✓ | ✓ | 审计日志、安全接入配置 |
|
||||
| system | ✓ | ✓ | 系统参数、协议版本、诊断 |
|
||||
| privacy | ✓ | — | 隐私政策、脱敏策略、拨号取号授权 |
|
||||
| registration | ✓ | — | 门店/员工注册审核流 |
|
||||
| manager | ✓ | — | 店长/管理端专属能力 |
|
||||
| inventory | ✓ | — | 库存耗材 |
|
||||
| analytics | ✓ | — | 经营分析、绩效统计 |
|
||||
|
||||
ArtList 已清理 inventory/manager/analytics/planning 实现等(保留订单容量校验所需依赖);新增 ArtList 功能前先确认该域仍存在。
|
||||
|
||||
## 端侧入口
|
||||
|
||||
| 端 | 页面/视图位置 | 请求封装 | 登录态 |
|
||||
|----|--------------|----------|--------|
|
||||
| JC-Salon-Frontend | `src/views/` | `src/api/*.ts` | Axios 拦截器 |
|
||||
| JC-ArtList-Frontend | `src/views/` | `src/api/*.ts` | Axios 拦截器 |
|
||||
| JC-Salon-WeChat | `pages/`(planning/customers/employees/appointment…) | `utils/request.js` | `utils/auth.js` |
|
||||
| JC-ArtList-WeChat | `pages/`(home/products/cart/orders/vip-center…) | `utils/request.js` | `utils/auth.js` |
|
||||
|
||||
## 网关与公共件
|
||||
|
||||
- `JC-*-Gateway`:`filter/AuthGlobalFilter`(白名单 + JWT 初筛)、路由配置在 Nacos `gateway.yaml`。
|
||||
- Core 公共:`common/`(`Result<T>`、DTO/VO 基类)、`config/`(MyBatis-Plus、加密组件、对象存储编排等)。
|
||||
|
||||
## 关键横切组件
|
||||
|
||||
- 手机号/账号加密:AES-GCM 加密组件 + `*_hash` 查询列;日志脱敏。
|
||||
- 协议拦截:服务端拦截未同意最新协议用户,微信端 4510 原地同意后重试。
|
||||
- 对象存储读取渠道优先级:配置项控制,历史数据多端点兼容解析。
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: jayu-release
|
||||
description: JayuCloud 发布与配置管理:Nacos 配置分层(core/gateway/infra/secret/logging)、dev→sit→prod 晋级流程、Gitea 工作流边界、配置变更说明文档要求、发布回滚纪律。用于修改配置、发布环境、部署脚本或 Nacos 相关任务;线上故障排查用全局 $incident-troubleshooting
|
||||
---
|
||||
|
||||
# JayuCloud 发布与配置管理
|
||||
|
||||
配置与发布是本项目的高风险动作:生产配置由 Nacos 管理、发布由 Gitea 工作流驱动、数据库迁移随应用启动自动执行。任何配置/发布改动按本技能执行。
|
||||
|
||||
## 配置体系
|
||||
|
||||
- 仓库副本:`nacos/namespaces/<environment>/<namespace>/DEFAULT_GROUP/`,environment ∈ dev/sit/prod,namespace ∈ `jayucloud-salon` / `jayucloud-artlist`。
|
||||
- 每个命名空间五个 dataId:`core.yaml`(业务运行)、`gateway.yaml`(路由与网关)、`infra.yaml`(中间件地址/开关)、`secret.yaml`(敏感配置)、`logging.yaml`。
|
||||
- 覆盖关系:后加载来源覆盖先加载来源;排查配置问题必须核对全部来源的最终生效值(含 systemd EnvironmentFile 与环境变量)。
|
||||
- 仓库副本不得包含真实密钥;敏感值只存在于对应环境的 Nacos `secret.yaml`。
|
||||
- dev 分支推送触发 Gitea 工作流自动发布 dev Nacos 配置(带失败自动回退);发布后有读回校验(SHA256 比对)。
|
||||
|
||||
## 发布流程(dev → sit → prod)
|
||||
|
||||
1. **先 DEV 验证**:迁移、配置、代码必须在 DEV 验证通过;迁移未过不得合并 SIT。
|
||||
2. **SIT**:合并后由 SIT 部署流程发布;核对 Nacos 发布快照与读回校验结果。
|
||||
3. **PROD**:走发布提交 + `自动部署prod环境` 工作流(构建发布包 → 部署脚本 → 记录部署,失败自动回退);生产发布前核对目标环境、备份状态与凭据注入方式,并取得确认。
|
||||
4. 发布顺序契约:数据库迁移随 Core 启动由 Flyway 执行,变更设计必须向前兼容(先加后删),应用回退不会回滚数据库。
|
||||
|
||||
## 配置变更任务要求
|
||||
|
||||
1. 修改前先读取现有配置(Nacos 只读查询或仓库副本),备份原配置内容到任务记录。
|
||||
2. 仓库 `nacos/` 副本与 Nacos 实际内容同步修改;dev 走分支推送自动发布,sit/prod 按既有发布流程。
|
||||
3. **必须提供中文说明文档**:按「功能+日期」命名(如 `Salon××配置说明_20261105.md`),放在 `docs/scripts/`,写明变更内容、生效环境、验证方式、回退方式。
|
||||
4. 涉及脚本/配置/SQL 的任务,先读 `docs/scripts/运行与发布配置总说明.md`。
|
||||
5. 发布后验证:服务日志、Nacos 实例健康、读回校验结果。
|
||||
|
||||
## Gitea 工作流边界
|
||||
|
||||
- 工作流不得直连数据库、不得绕过 Flyway 执行 SQL。
|
||||
- 不可绕过的分支保护检查必须由目标分支定义的工作流(`pull_request_target` 类)完成,且不得检出/执行来源分支代码。
|
||||
- 修改工作流定义属于发布基础设施变更:先说明影响,单独提交。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 生产环境动作(发布、Nacos 生产写、生产 SQL)必须先取得明确确认;未授权只读。
|
||||
- 不在仓库、日志、说明文档中写入密钥/口令/令牌;示例用占位符。
|
||||
- 回滚优先使用工作流与发布脚本的既有回退机制;数据库问题用补偿迁移,不依赖 clean/baseline。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 配置变更有说明文档且命名合规;环境晋级顺序未跳级;发布后验证结果已记录;仓库副本与 Nacos 一致。
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
name: gitnexus-cli
|
||||
description: "Use when the user needs to run GitNexus CLI commands like analyze/index a repo, check status, clean the index, generate a wiki, or list indexed repos. Examples: \"Index this repo\", \"Reanalyze the codebase\", \"Generate a wiki\""
|
||||
---
|
||||
|
||||
# GitNexus CLI Commands
|
||||
|
||||
Commands below use `node .gitnexus/run.cjs <command>` — the project-local runner `gitnexus analyze` drops next to the index. It auto-selects an available runner at call time (global `gitnexus`, else `pnpm dlx`, else `bunx`, else `npx`), so no package-manager assumption and no global install is required — including on a bun-only machine, which has no npm, npx or pnpm at all.
|
||||
|
||||
> **Not analyzed yet, or `node .gitnexus/run.cjs` reports `Cannot find module`** (the gitignored runner is absent — e.g. a fresh clone or `git clean`)? (Re)generate it with `npx gitnexus analyze` from the project root, or `bunx gitnexus@latest analyze` on a bun-only machine. On **npm 11.x**, if `npx` crashes during install (`node.target is null`), install once with `npm i -g gitnexus` (then `gitnexus analyze`), or use `bunx gitnexus@latest analyze`, or `pnpm --allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx gitnexus@latest analyze`. See [#1939](https://github.com/abhigyanpatwari/GitNexus/issues/1939).
|
||||
|
||||
## Commands
|
||||
|
||||
### analyze — Build or refresh the index
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs analyze
|
||||
```
|
||||
|
||||
Run from the project root. This parses all source files, builds the knowledge graph, writes it to `.gitnexus/`, and generates CLAUDE.md / AGENTS.md context files.
|
||||
|
||||
| Flag | Effect |
|
||||
| -------------- | ---------------------------------------------------------------- |
|
||||
| `--watch` | Keep a Git repository index current with serialized refreshes |
|
||||
| `--debounce <ms>` | Watch quiet period before refresh (default: 300 ms) |
|
||||
| `--force` | Force full re-index even if up to date |
|
||||
| `--embeddings` | Enable embedding generation for semantic search (off by default) |
|
||||
| `--drop-embeddings` | Drop existing embeddings on rebuild. By default, an `analyze` without `--embeddings` preserves them. |
|
||||
| `--pdg` | Build the program-dependence layers used by `explain` and `pdg_query` (taint, CDG, and REACHING_DEF). |
|
||||
| `--spring-actuator <path>` | Import opt-in Spring Boot Actuator mappings, beans, conditions, configprops, and env snapshots. Forces a full rebuild; unsupported with `--watch`. |
|
||||
| `--asyncapi-spec <path>` | Read opt-in AsyncAPI 3.x documents (directory or single file) and mint `Destination` nodes from their operations. 2.x is refused, not mapped. Unsupported with `--watch`. |
|
||||
|
||||
**When to run:** First time in a project, after major code changes, or when `gitnexus://repo/{name}/context` reports the index is stale. In Claude Code, a PostToolUse hook detects staleness after `git commit` and `git merge` and notifies the agent to run `analyze` — the hook does not run analyze itself, to avoid blocking the agent for up to 120s and risking KuzuDB corruption on timeout.
|
||||
|
||||
For Spring runtime enrichment, pass a JSON bundle, one endpoint JSON file, or a directory containing endpoint files. Route evidence is authoritative only when `runtimeConfirmed === true`; `runtimeSource` records provenance and may also accompany `handler-conflict`. Env/configprops values are never persisted.
|
||||
|
||||
## Index storage and retention
|
||||
|
||||
Default location is `<repo>/.gitnexus/`. Override with environment variables (also documented in README):
|
||||
|
||||
| Env | Effect |
|
||||
| --- | ------ |
|
||||
| `GITNEXUS_STORAGE_PATH` | One complete external index directory. Wins if both storage vars are set. |
|
||||
| `GITNEXUS_STORAGE_ROOT` | Absolute root; GitNexus creates an isolated `<repo-basename>-<12-hex>/` slot per repository. |
|
||||
| `GITNEXUS_CONTENT_RETENTION` | `full` (default) keeps file text; `symbol` keeps snippets; `none` keeps the graph only. |
|
||||
|
||||
`list_repos`, `gitnexus://repo/{name}/context`, and HTTP `GET /api/repos` / `GET /api/repo` expose `storagePath`, `contentRetention`, and `sourceAvailable`. HTTP `/api/file` and `/api/grep` return 410 unless retention is `full`. MCP `include_content` may still return symbol spans when retention is `symbol`.
|
||||
|
||||
Use `node .gitnexus/run.cjs analyze --watch` for a long-lived local Git repository. It performs an initial analysis, queues scanner-admitted file changes, and retries intact failed batches with bounded backoff. Watch refreshes update only the graph: they skip AGENTS.md / CLAUDE.md injection and standard skill installation, so run a one-shot `analyze` when those generated files need updating. Watch rejects one-shot or context-output flags including `--force`, embedding flags, `--skills`, `--default-branch`, `--skip-agents-md`, `--skip-skills`, `--no-stats`, `--self-commit`, `--index-only`, and `--skip-git`. It never pulls remotes. Scheduled remote clone/pull is a different command: `gitnexus auto-sync`. Bare `gitnexus watch` is reserved and does not start either job. Running MCP and `serve` processes periodically check for a published replacement and reopen it without a restart. MCP checks are throttled to once every five seconds, so a tool call before the next check can briefly use the previous index.
|
||||
|
||||
### status — Check index freshness
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs status
|
||||
```
|
||||
|
||||
Shows whether the current repo has a GitNexus index, when it was last updated, and symbol/relationship counts. Use this to check if re-indexing is needed.
|
||||
|
||||
### clean — Delete the index
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs clean
|
||||
```
|
||||
|
||||
Deletes the `.gitnexus/` directory and unregisters the repo from the global registry. Use before re-indexing if the index is corrupt or after removing GitNexus from a project.
|
||||
|
||||
| Flag | Effect |
|
||||
| --------- | ------------------------------------------------- |
|
||||
| `--force` | Skip confirmation prompt |
|
||||
| `--all` | Clean all indexed repos, not just the current one |
|
||||
|
||||
### wiki — Generate documentation from the graph
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs wiki
|
||||
```
|
||||
|
||||
Generates repository documentation from the knowledge graph using an LLM. HTTP providers require an API key (saved to `~/.gitnexus/config.json` on first use). Local CLI providers (`--provider cursor|claude|codex|opencode|grok`) use your existing CLI login.
|
||||
|
||||
| Flag | Effect |
|
||||
| ------------------- | ----------------------------------------- |
|
||||
| `--force` | Force full regeneration, also required to re-generate an existing wiki in a different language |
|
||||
| `--provider <name>` | LLM provider: minimax, openai, openrouter, azure, custom, cursor, claude, codex, opencode, or grok (default: minimax). Local CLIs (`cursor`, `claude`, `codex`, `opencode`, `grok`) use your existing CLI login and skip `--api-key`. |
|
||||
| `--model <model>` | LLM model (default: MiniMax-M3) |
|
||||
| `--base-url <url>` | LLM API base URL |
|
||||
| `--api-key <key>` | LLM API key |
|
||||
| `--concurrency <n>` | Parallel LLM calls (default: 3) |
|
||||
| `--timeout <seconds>` | LLM request timeout in seconds (default: disabled) |
|
||||
| `--retries <n>` | Max LLM retry attempts per request (default: 3) |
|
||||
| `--lang <lang>` | Output language for generated documentation (e.g. english, chinese, spanish, japanese) |
|
||||
| `--gist` | Publish wiki as a public GitHub Gist |
|
||||
|
||||
### list — Show all indexed repos
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs list
|
||||
```
|
||||
|
||||
Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information.
|
||||
|
||||
## After Indexing
|
||||
|
||||
1. **Read `gitnexus://repo/{name}/context`** to verify the index loaded
|
||||
2. Use the other GitNexus skills (`exploring`, `debugging`, `impact-analysis`, `refactoring`) for your task
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **"Not inside a git repository"**: Run from a directory inside a git repo
|
||||
- **Index is stale after re-analyzing**: Wait for the next MCP tool call to reopen the published index; this normally takes no more than five seconds
|
||||
- **Embeddings slow**: Omit `--embeddings` (it's off by default) or set `OPENAI_API_KEY` for faster API-based embedding
|
||||
@@ -0,0 +1,131 @@
|
||||
---
|
||||
name: gitnexus-debugging
|
||||
description: "Use when the user is debugging a bug, tracing an error, or asking why something fails. Examples: \"Why is X failing?\", \"Where does this error come from?\", \"Trace this bug\""
|
||||
---
|
||||
|
||||
# Debugging with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Why is this function failing?"
|
||||
- "Trace where this error comes from"
|
||||
- "Who calls this method?"
|
||||
- "This endpoint returns 500"
|
||||
- Investigating bugs, errors, or unexpected behavior
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
A root cause traced in the wrong repository is a wrong root cause.
|
||||
|
||||
Call `list_repos {}` before the first tool call. With one indexed repository,
|
||||
use the examples below as written. With more than one, pass `repo` on every
|
||||
call: an omitted `repo` normally errors, but under an MCP policy with a
|
||||
configured default it resolves to that default silently. If you cannot tell
|
||||
which repository is meant, stop and ask. This matters most for `cypher`, whose
|
||||
statement carries no in-band hint of which database it ran against.
|
||||
|
||||
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
|
||||
`hasMore` is false before concluding a repository is absent.
|
||||
|
||||
A stale index describes the code from before your bug, so refresh before
|
||||
trusting a trace, and state the repository and index freshness with the
|
||||
diagnosis.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
0. list_repos {} → Bind repo
|
||||
1. query({search_query: "<error or symptom>"}) → Find related execution flows
|
||||
2. context({name: "<suspect>"}) → See callers/callees/processes
|
||||
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow
|
||||
4. cypher({statement: "MATCH path..."}) → Custom traces if needed
|
||||
```
|
||||
|
||||
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
|
||||
## Checklist
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] Understand the symptom (error message, unexpected behavior)
|
||||
- [ ] query for error text or related code
|
||||
- [ ] Identify the suspect function from returned processes
|
||||
- [ ] context to see callers and callees
|
||||
- [ ] Trace execution flow via process resource if applicable
|
||||
- [ ] cypher for custom call chain traces if needed
|
||||
- [ ] Read source files to confirm root cause
|
||||
- [ ] State the repository and index freshness with the diagnosis
|
||||
```
|
||||
|
||||
## Debugging Patterns
|
||||
|
||||
| Symptom | GitNexus Approach |
|
||||
| -------------------- | ---------------------------------------------------------- |
|
||||
| Error message | `query` for error text → `context` on throw sites |
|
||||
| Wrong return value | `context` on the function → trace callees for data flow |
|
||||
| Intermittent failure | `context` → look for external calls, async deps |
|
||||
| Performance issue | `context` → find symbols with many callers (hot paths) |
|
||||
| Recent regression | `detect_changes` to see what your changes affect — pass `worktree` for a linked worktree |
|
||||
| "How does A reach B?" | `trace` between the two symbols — shortest call chain in one call |
|
||||
|
||||
## Tools
|
||||
|
||||
**query** — find code related to error:
|
||||
|
||||
```
|
||||
query({search_query: "payment validation error", repo: "my-app"})
|
||||
→ Processes: CheckoutFlow, ErrorHandling
|
||||
→ Symbols: validatePayment, handlePaymentError, PaymentException
|
||||
```
|
||||
|
||||
**context** — full context for a suspect:
|
||||
|
||||
```
|
||||
context({name: "validatePayment", repo: "my-app"})
|
||||
→ Incoming calls: processCheckout, webhookHandler
|
||||
→ Outgoing calls: verifyCard, fetchRates (external API!)
|
||||
→ Processes: CheckoutFlow (step 3/7)
|
||||
```
|
||||
|
||||
**cypher** — custom call chain traces. Pass `repo` alongside the statement; the
|
||||
Cypher text itself names no repository, so the result is unattributable without
|
||||
it:
|
||||
|
||||
```cypher
|
||||
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"})
|
||||
RETURN [n IN nodes(path) | n.name] AS chain
|
||||
```
|
||||
|
||||
**trace** — shortest call chain between two symbols ("how does A reach B?"), one call instead of chaining `context` hops:
|
||||
|
||||
```
|
||||
trace({ from: "processCheckout", to: "fetchRates", repo: "my-app" })
|
||||
→ status: ok, hopCount: 3
|
||||
→ hops: processCheckout → validatePayment → verifyCard → fetchRates
|
||||
→ edges: CALLS (1.0), CALLS (0.95), CALLS (1.0)
|
||||
```
|
||||
|
||||
When no path exists, `trace` reports the furthest reachable node — exactly where the chain breaks (dynamic dispatch, reflection, or an external boundary).
|
||||
|
||||
## Example: "Payment endpoint returns 500 intermittently"
|
||||
|
||||
```
|
||||
0. list_repos {}
|
||||
→ total: 2 (my-app, billing-api) — bind my-app explicitly on every call
|
||||
|
||||
1. query({search_query: "payment error handling", repo: "my-app"})
|
||||
→ Processes: CheckoutFlow, ErrorHandling
|
||||
→ Symbols: validatePayment, handlePaymentError
|
||||
|
||||
2. context({name: "validatePayment", repo: "my-app"})
|
||||
→ Outgoing calls: verifyCard, fetchRates (external API!)
|
||||
|
||||
3. READ gitnexus://repo/my-app/process/CheckoutFlow
|
||||
→ Step 3: validatePayment → calls fetchRates (external)
|
||||
|
||||
4. Root cause: fetchRates calls external API without proper timeout
|
||||
Repository: my-app Index: current
|
||||
```
|
||||
|
||||
With a single indexed repository, step 0 returns `total: 1` and the `repo`
|
||||
argument drops out of every call above.
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
name: gitnexus-exploring
|
||||
description: "Use when the user asks how code works, wants to understand architecture, trace execution flows, or explore unfamiliar parts of the codebase. Examples: \"How does X work?\", \"What calls this function?\", \"Show me the auth flow\""
|
||||
---
|
||||
|
||||
# Exploring Codebases with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "How does authentication work?"
|
||||
- "What's the project structure?"
|
||||
- "Show me the main components"
|
||||
- "Where is the database logic?"
|
||||
- Understanding code you haven't seen before
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
Step 1 discovers what is indexed; every call after it must say which of those
|
||||
it means. With one indexed repository, use the examples below as written. With
|
||||
more than one, pass `repo` on every call: an omitted `repo` normally errors,
|
||||
but under an MCP policy with a configured default it resolves to that default
|
||||
silently. If you cannot tell which repository is meant, stop and ask. Report
|
||||
the bound repository and index freshness alongside your explanation.
|
||||
|
||||
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
|
||||
`hasMore` is false before concluding a repository is absent.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
1. list_repos {} or READ gitnexus://repos → Discover indexed repos
|
||||
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
|
||||
3. query({search_query: "<what you want to understand>"}) → Find related execution flows
|
||||
4. context({name: "<symbol>"}) → Deep dive on specific symbol
|
||||
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow
|
||||
```
|
||||
|
||||
> If step 2 says "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
|
||||
## Checklist
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] READ gitnexus://repo/{name}/context
|
||||
- [ ] query for the concept you want to understand
|
||||
- [ ] Review returned processes (execution flows)
|
||||
- [ ] context on key symbols for callers/callees
|
||||
- [ ] READ process resource for full execution traces
|
||||
- [ ] Read source files for implementation details
|
||||
- [ ] State the repository and index freshness with the explanation
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | What you get |
|
||||
| --------------------------------------- | ------------------------------------------------------- |
|
||||
| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) |
|
||||
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores (~300 tokens) |
|
||||
| `gitnexus://repo/{name}/cluster/{name}` | Area members with file paths (~500 tokens) |
|
||||
| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) |
|
||||
|
||||
## Tools
|
||||
|
||||
**query** — find execution flows related to a concept:
|
||||
|
||||
```
|
||||
query({search_query: "payment processing", repo: "my-app"})
|
||||
→ Processes: CheckoutFlow, RefundFlow, WebhookHandler
|
||||
→ Symbols grouped by flow with file locations
|
||||
```
|
||||
|
||||
**context** — 360-degree view of a symbol:
|
||||
|
||||
```
|
||||
context({name: "validateUser", repo: "my-app"})
|
||||
→ Incoming calls: loginHandler, apiMiddleware
|
||||
→ Outgoing calls: checkToken, getUserById
|
||||
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3)
|
||||
```
|
||||
|
||||
`repo` is required once more than one repository is indexed, and may be omitted
|
||||
with a single one.
|
||||
|
||||
## Example: "How does payment processing work?"
|
||||
|
||||
```
|
||||
1. list_repos {} → total: 1 (my-app) — bind it
|
||||
READ gitnexus://repo/my-app/context → 918 symbols, 45 processes
|
||||
2. query({search_query: "payment processing"})
|
||||
→ CheckoutFlow: processPayment → validateCard → chargeStripe
|
||||
→ RefundFlow: initiateRefund → calculateRefund → processRefund
|
||||
3. context({name: "processPayment"})
|
||||
→ Incoming: checkoutHandler, webhookHandler
|
||||
→ Outgoing: validateCard, chargeStripe, saveTransaction
|
||||
4. Read src/payments/processor.ts for implementation details
|
||||
5. Answer, noting: Repository my-app, index current
|
||||
```
|
||||
|
||||
Had step 1 returned two repositories, every call above would carry
|
||||
`repo: "my-app"`.
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
name: gitnexus-guide
|
||||
description: "Use when the user asks about GitNexus itself — available tools, how to query the knowledge graph, MCP resources, graph schema, or workflow reference. Examples: \"What GitNexus tools are available?\", \"How do I use GitNexus?\""
|
||||
---
|
||||
|
||||
# GitNexus Guide
|
||||
|
||||
Quick reference for all GitNexus MCP tools, resources, and the knowledge graph schema.
|
||||
|
||||
## Always Start Here
|
||||
|
||||
For any task involving code understanding, debugging, impact analysis, or refactoring:
|
||||
|
||||
1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness
|
||||
2. **Match your task to a skill below** and **read that skill file**
|
||||
3. **Follow the skill's workflow and checklist**
|
||||
|
||||
> If step 1 warns the index is stale, run `node .gitnexus/run.cjs analyze` in the terminal first.
|
||||
|
||||
## Skills
|
||||
|
||||
| Task | Skill to read |
|
||||
| -------------------------------------------- | ------------------- |
|
||||
| Understand architecture / "How does X work?" | `gitnexus-exploring` |
|
||||
| Blast radius / "What breaks if I change X?" | `gitnexus-impact-analysis` |
|
||||
| Trace bugs / "Why is X failing?" | `gitnexus-debugging` |
|
||||
| Rename / extract / split / refactor | `gitnexus-refactoring` |
|
||||
| Tools, resources, schema reference | `gitnexus-guide` (this file) |
|
||||
| Index, status, clean, wiki CLI commands | `gitnexus-cli` |
|
||||
|
||||
## Tools Reference
|
||||
|
||||
| Tool | What it gives you |
|
||||
| ---------------- | ------------------------------------------------------------------------ |
|
||||
| `query` | Process-grouped code intelligence — execution flows related to a concept |
|
||||
| `context` | 360-degree symbol view — categorized refs, processes it participates in |
|
||||
| `impact` | Symbol blast radius — what breaks at depth 1/2/3 with confidence |
|
||||
| `trace` | Shortest path between two symbols — "how does A reach B?" in one call |
|
||||
| `detect_changes` | Git-diff impact — what do your current changes affect |
|
||||
| `rename` | Multi-file coordinated rename with confidence-tagged edits |
|
||||
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) |
|
||||
| `explain` | Persisted taint findings — source→sink data flows (needs `analyze --pdg`) |
|
||||
| `pdg_query` | Control/data dependence — what gates X (CDG) / where Y flows (REACHING_DEF); needs `analyze --pdg` |
|
||||
| `check` | Check graph invariants such as circular imports |
|
||||
| `route_map` | API route map — which components/hooks fetch which endpoints, and the handler files that serve them |
|
||||
| `shape_check` | Response-shape drift — keys each route returns vs keys its consumers access (flags MISMATCH) |
|
||||
| `api_impact` | Pre-change report for an API route — consumers, middleware, shape mismatches, risk level |
|
||||
| `tool_map` | MCP/RPC tool definitions and the files that handle them |
|
||||
| `group_list` | List configured multi-repo groups, or one group's config |
|
||||
| `group_sync` | Rebuild a group's Contract Registry (cross-repo HTTP contract links); run after `group.yaml` changes or member re-index |
|
||||
| `list_repos` | Discover indexed repos (paginated — `limit`/`offset`) |
|
||||
|
||||
### Paginating `list_repos`
|
||||
|
||||
`list_repos` is paginated so a large registry is not truncated by MCP/LLM token limits. It takes optional `limit` (default **50**, max **200**) and `offset`, and returns:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"repositories": [
|
||||
{ "name": "...", "path": "...", "indexedAt": "...", "lastCommit": "...", "stats": { } }
|
||||
],
|
||||
"pagination": {
|
||||
"total": 437,
|
||||
"limit": 50,
|
||||
"offset": 0,
|
||||
"returned": 50,
|
||||
"hasMore": true,
|
||||
"nextOffset": 50
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To enumerate **every** repository, keep calling with `offset` set to `pagination.nextOffset` until `hasMore` is `false`:
|
||||
|
||||
```text
|
||||
list_repos {} → repos 1–50, nextOffset 50, hasMore true
|
||||
list_repos { offset: 50 } → repos 51–100, nextOffset 100, hasMore true
|
||||
…
|
||||
list_repos { offset: 400 } → repos 401–437, hasMore false (done)
|
||||
```
|
||||
|
||||
Notes: `offset` ≥ `total` returns an empty page (with `total` still reported). Out-of-range or malformed `limit`/`offset` (non-integer, `limit` outside `[1, 200]`, `offset < 0`) are rejected with a clear error — `limit` above the max is rejected, not silently capped. The order is deterministic (lower-cased name, then path), so paging never skips or duplicates an entry while the registry is unchanged.
|
||||
|
||||
### Taint findings (`explain`)
|
||||
|
||||
`explain` returns taint findings recorded by `gitnexus analyze --pdg` — intra-procedural `TAINTED` edges plus cross-function `TAINT_PATH` hops where the interprocedural taint phase found a function-level source→sink chain. Each finding includes a sink category (command-injection, code-injection, path-traversal, sql-injection, xss), source/sink lines, and the ordered hop path with the variable carried on each hop.
|
||||
|
||||
- `explain {}` — enumerate all findings for the repo (bounded by `limit`, deterministic order)
|
||||
- `explain { target: "src/vuln.ts" }` — findings in a file (suffix path match accepted)
|
||||
- `explain { target: "runUserCommand" }` — findings in a function (resolved like `context`; ambiguous names return ranked candidates)
|
||||
|
||||
A repo indexed without `--pdg` returns a clear "no taint layer" note. Caveats: closure/callback, property/field, and implicit flows are not modeled, and interprocedural findings are function-level `TAINT_PATH` hops rather than statement-level path proof, so the absence of a finding is **not** proof of safety. `SANITIZES` (sanitizer-kill) edges are queryable via `cypher`.
|
||||
|
||||
### Control & data dependence (`pdg_query`)
|
||||
|
||||
`pdg_query` reads the control/data-dependence layers `gitnexus analyze --pdg` records (CDG + REACHING_DEF, basic-block granular) — the control/data analog of `explain`. It is **always anchored** (a `target` file path or symbol, resolved like `context`) and has two modes:
|
||||
|
||||
- `pdg_query { mode: "controls", target: "..." }` — CDG: "under what condition does X run?". Each edge is a controlling predicate block → dependent block with the branch sense (`'T'`/`'F'`) in `reason`; an edge into an early `return`/`throw` is flagged `guard: true` (guard-clause discovery — the sense depends on the predicate, so don't filter guards by a fixed label).
|
||||
- `pdg_query { mode: "flows", target: "...", variable?: "..." }` — REACHING_DEF def→use edges within the function; pass `variable` to trace one binding.
|
||||
|
||||
A repo indexed without `--pdg` returns a "no PDG layer" note (or "status unknown" when the layer can't be confirmed). Intra-procedural only — cross-function flow is taint's domain (`explain`). The raw CDG/REACHING_DEF edges are also queryable via `cypher`. See the `gitnexus-pdg-query` skill for the full query surface.
|
||||
|
||||
### Shortest path between two symbols (`trace`)
|
||||
|
||||
`trace` answers "how does A reach B?" in one call — the shortest directed path over `CALLS` (plus `HAS_METHOD`, so a class-rooted trace descends into its methods) instead of chaining 3–8 `context`/`impact` hops by hand.
|
||||
|
||||
- `trace { from: "validateUser", to: "executeQuery" }` — shortest path between two symbols.
|
||||
- Disambiguate common names with `from_uid`/`to_uid` (zero-ambiguity) or `from_file`/`to_file`; an ambiguous name returns ranked candidates.
|
||||
- `maxDepth` (default 10, max 30) bounds the search; `includeTests` (default false) lets the traversal pass through test-file symbols.
|
||||
|
||||
Returns ordered `hops` (each `{ name, filePath, startLine }`) and an aligned `edges[]` of `{ relType, confidence }`, so call hops and containment (`HAS_METHOD`) hops stay distinguishable. When no path exists it reports the **furthest** reachable node (where the chain breaks) and sets `truncated: true` if a traversal cap was hit first. Every result carries a `status`: `ok` / `no_path` / `ambiguous` / `not_found` / `error`.
|
||||
|
||||
Cross-repo (experimental): pass `repo: "@groupName"` to trace across a group's member repos — the path may cross **one** `ContractLink` boundary (reported as a `CONTRACT_LINK` hop with the bridged contract in `crossings[]`). Omit `to` entirely to follow `from`'s outgoing HTTP call to whatever provider endpoint it lands on. Groups are configured via `group_list` / `group_sync`.
|
||||
|
||||
## Resources Reference
|
||||
|
||||
Lightweight reads (~100-500 tokens) for navigation:
|
||||
|
||||
| Resource | Content |
|
||||
| ---------------------------------------------- | ----------------------------------------- |
|
||||
| `gitnexus://repo/{name}/context` | Stats, staleness check |
|
||||
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores |
|
||||
| `gitnexus://repo/{name}/cluster/{clusterName}` | Area members |
|
||||
| `gitnexus://repo/{name}/processes` | All execution flows |
|
||||
| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace |
|
||||
| `gitnexus://repo/{name}/schema` | Graph schema for Cypher |
|
||||
|
||||
## Graph Schema
|
||||
|
||||
**Nodes:** File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, Route, Tool, plus language-specific types (Struct, Enum, Trait, Impl, Namespace, Module, …) and BasicBlock (`--pdg` indexes only). The full node list lives in `gitnexus://repo/{name}/schema`.
|
||||
**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, CONTAINS, MEMBER_OF, HAS_METHOD, HAS_PROPERTY, ACCESSES, METHOD_OVERRIDES, METHOD_IMPLEMENTS, STEP_IN_PROCESS, HANDLES_ROUTE, FETCHES, HANDLES_TOOL, ENTRY_POINT_OF, WRAPS, QUERIES, INJECTS, plus `--pdg`-only types (CFG, REACHING_DEF, TAINTED, SANITIZES, TAINT_PATH, CDG — zero rows on a default index).
|
||||
|
||||
Read `gitnexus://repo/{name}/schema` before writing Cypher — it is the authoritative schema for the indexed repo.
|
||||
|
||||
```cypher
|
||||
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"})
|
||||
RETURN caller.name, caller.filePath
|
||||
```
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
name: gitnexus-impact-analysis
|
||||
description: "Use when the user wants to know what will break if they change something, or needs safety analysis before editing code. Examples: \"Is it safe to change X?\", \"What depends on this?\", \"What will break?\""
|
||||
---
|
||||
|
||||
# Impact Analysis with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Is it safe to change this function?"
|
||||
- "What will break if I modify X?"
|
||||
- "Show me the blast radius"
|
||||
- "Who uses this code?"
|
||||
- Before making non-trivial code changes
|
||||
- Before committing — to understand what your changes affect
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
Impact analysis is the gate that authorizes an edit, so it must answer for the
|
||||
repository you are about to edit.
|
||||
|
||||
Call `list_repos {}` before the first tool call. With one indexed repository,
|
||||
use the examples below as written. With more than one, pass `repo` on every
|
||||
call: an omitted `repo` normally errors, but under an MCP policy with a
|
||||
configured default it resolves to that default silently. If you cannot tell
|
||||
which repository is meant, stop and ask — every result below an ambiguous
|
||||
identity inherits the ambiguity. `list_repos` is paginated, so page with
|
||||
`offset: pagination.nextOffset` until `hasMore` is false before concluding a
|
||||
repository is absent.
|
||||
|
||||
`detect_changes` takes `worktree` when your changes are in a linked worktree
|
||||
the MCP server was not launched from. The server auto-detects a worktree only
|
||||
when it was launched from inside one; otherwise `git diff` runs in the wrong
|
||||
checkout and reports zero changed symbols — a false clean check that carries
|
||||
none of the degradation flags described below. In the CLI fallbacks, `--repo .`
|
||||
means the current checkout; pass the intended repository path instead when you
|
||||
are not standing in it.
|
||||
|
||||
State the bound identity with your risk report:
|
||||
|
||||
```
|
||||
Repository: <name> (<path>) Worktree: <path> Index: <commit>, <n> behind HEAD
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
0. list_repos {} → Bind repo (and worktree)
|
||||
1. impact({target: "X", direction: "upstream"}) or `node .gitnexus/run.cjs impact "X" --direction upstream --repo .`
|
||||
2. READ gitnexus://repo/{name}/processes → Check affected execution flows
|
||||
3. detect_changes({scope: "all"}) or `node .gitnexus/run.cjs detect-changes --scope all --repo .`
|
||||
4. Assess risk and report to user, echoing repo/worktree/index identity
|
||||
```
|
||||
|
||||
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
> If `.gitnexus/run.cjs` is missing, replace `node .gitnexus/run.cjs` with `npx gitnexus` in the fallback commands.
|
||||
|
||||
## Checklist
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] impact({target, direction: "upstream"}) or CLI fallback to find dependents
|
||||
- [ ] Review d=1 items first (these WILL BREAK)
|
||||
- [ ] Check high-confidence (>0.8) dependencies
|
||||
- [ ] READ processes to check affected execution flows
|
||||
- [ ] detect_changes({scope: "all"}) or CLI fallback for pre-commit check
|
||||
- [ ] Confirm the checkout you edited is the checkout that was diffed
|
||||
- [ ] Assess risk level and report, stating repo/worktree/index identity
|
||||
```
|
||||
|
||||
## Understanding Output
|
||||
|
||||
| Depth | Risk Level | Meaning |
|
||||
| ----- | ---------------- | ------------------------ |
|
||||
| d=1 | **WILL BREAK** | Direct callers/importers |
|
||||
| d=2 | LIKELY AFFECTED | Indirect dependencies |
|
||||
| d=3 | MAY NEED TESTING | Transitive effects |
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Affected | Risk |
|
||||
| ------------------------------ | -------- |
|
||||
| <5 symbols, few processes | LOW |
|
||||
| 5-15 symbols, 2-5 processes | MEDIUM |
|
||||
| >15 symbols or many processes | HIGH |
|
||||
| Critical path (auth, payments) | CRITICAL |
|
||||
| **Zero callers found** | **UNKNOWN** |
|
||||
|
||||
`UNKNOWN` is not a low rung on this scale — it means the walk could not answer.
|
||||
An empty caller set is equally consistent with "genuinely unused" and "the
|
||||
callers are not resolvable by the index" (plain-object property access, dynamic
|
||||
dispatch, cross-language calls), so few-callers ⇒ LOW does **not** apply. The
|
||||
result carries a `riskNote` saying so. Confirm with a text search before
|
||||
treating the symbol as safe to change or delete.
|
||||
|
||||
`risk` is the edit gate: warn on HIGH/CRITICAL and stop on UNKNOWN until the
|
||||
uncertainty is resolved. Within single-repo mode, compare File and symbol
|
||||
targets with local `riskSharedAxes` (direct/total only). Within group mode,
|
||||
compare only group results: their `riskSharedAxes` overlays resolved
|
||||
cross-repo crossings on that local value. Never use either field to waive the
|
||||
edit gate. Check `riskScale.unusedAxes` before comparing kinds: MCP File walks
|
||||
omit process/module axes, while web Graph-RAG expands File targets to in-file
|
||||
symbols before enrichment.
|
||||
|
||||
## Tools
|
||||
|
||||
**impact** — the primary tool for symbol blast radius. If MCP is unavailable, use `node .gitnexus/run.cjs impact <symbol> --direction upstream --repo .` instead:
|
||||
|
||||
```
|
||||
impact({
|
||||
target: "validateUser",
|
||||
repo: "my-app", // required once >1 repository is indexed
|
||||
direction: "upstream",
|
||||
minConfidence: 0.8,
|
||||
maxDepth: 3
|
||||
})
|
||||
|
||||
→ d=1 (WILL BREAK):
|
||||
- loginHandler (src/auth/login.ts:42) [CALLS, 100%]
|
||||
- apiMiddleware (src/api/middleware.ts:15) [CALLS, 100%]
|
||||
|
||||
→ d=2 (LIKELY AFFECTED):
|
||||
- authRouter (src/routes/auth.ts:22) [CALLS, 95%]
|
||||
```
|
||||
|
||||
**detect_changes** — git-diff based impact analysis. If MCP is unavailable, use `node .gitnexus/run.cjs detect-changes --scope all --repo .` instead:
|
||||
|
||||
```
|
||||
detect_changes({scope: "all"})
|
||||
|
||||
→ Changed: 5 symbols in 3 files
|
||||
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
|
||||
→ Risk: MEDIUM
|
||||
```
|
||||
|
||||
Add `repo` once more than one repository is indexed, and `worktree: "<abs
|
||||
path>"` when your changes are in a linked worktree the server was not launched
|
||||
from.
|
||||
|
||||
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
|
||||
listing was capped) means the result is short of the truth, and reads like
|
||||
`UNKNOWN` above: a zero there means unseen, not unaffected. Re-run it rather
|
||||
than tick the pre-commit check.
|
||||
|
||||
A wrong-worktree zero carries neither flag and is shape-identical to a genuine
|
||||
clean result, so confirm the checkout you edited is the one that was diffed
|
||||
before treating an empty change set as a passed check.
|
||||
|
||||
## Example: "What breaks if I change validateUser?"
|
||||
|
||||
```
|
||||
0. list_repos {}
|
||||
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
|
||||
|
||||
1. impact({target: "validateUser", repo: "my-app", direction: "upstream"}) or `node .gitnexus/run.cjs impact "validateUser" --direction upstream --repo .`
|
||||
→ d=1: loginHandler, apiMiddleware (WILL BREAK)
|
||||
→ d=2: authRouter, sessionManager (LIKELY AFFECTED)
|
||||
|
||||
2. READ gitnexus://repo/my-app/processes
|
||||
→ LoginFlow and TokenRefresh touch validateUser
|
||||
|
||||
3. Risk: 2 direct callers, 2 processes = MEDIUM
|
||||
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
|
||||
```
|
||||
|
||||
With a single indexed repository, step 0 returns `total: 1` and the `repo`
|
||||
argument drops out of every call above.
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
name: gitnexus-refactoring
|
||||
description: "Use when the user wants to rename, extract, split, move, or restructure code safely. Examples: \"Rename this function\", \"Extract this into a module\", \"Refactor this class\", \"Move this to a separate file\""
|
||||
---
|
||||
|
||||
# Refactoring with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Rename this function safely"
|
||||
- "Extract this into a module"
|
||||
- "Split this service"
|
||||
- "Move this to a new file"
|
||||
- Any task involving renaming, extracting, splitting, or restructuring code
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
Refactoring writes to disk. `rename` with `dry_run: false` edits files in
|
||||
whichever repository was resolved, so binding identity here is a safety gate,
|
||||
not bookkeeping.
|
||||
|
||||
Call `list_repos {}` before the first tool call. With one indexed repository,
|
||||
use the examples below as written. With more than one, pass `repo` on every
|
||||
call: an omitted `repo` normally errors, but under an MCP policy with a
|
||||
configured default it resolves to that default silently. If you cannot tell
|
||||
which repository is meant, stop and ask. Never run `rename` with
|
||||
`dry_run: false` until the preview in the same bound repository has been
|
||||
reviewed — its returned `file_path` values show which checkout is about to be
|
||||
written, so read them as a confirmation of identity.
|
||||
|
||||
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
|
||||
`hasMore` is false before concluding a repository is absent.
|
||||
|
||||
`detect_changes` takes `worktree` when you are editing a linked worktree the
|
||||
MCP server was not launched from; otherwise `git diff` runs in the wrong
|
||||
checkout and reports nothing changed, which reads as a verified refactor.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
0. list_repos {} → Bind repo (and worktree)
|
||||
1. impact({target: "X", direction: "upstream"}) → Map all dependents
|
||||
2. query({search_query: "X"}) → Find execution flows involving X
|
||||
3. context({name: "X"}) → See all incoming/outgoing refs
|
||||
4. Plan update order: interfaces → implementations → callers → tests
|
||||
```
|
||||
|
||||
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
|
||||
## Checklists
|
||||
|
||||
### Rename Symbol
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
|
||||
- [ ] Confirm the previewed file paths are in the bound repository/worktree
|
||||
- [ ] Review graph edits (high confidence) and text_search edits (review carefully)
|
||||
- [ ] If satisfied: rename({..., dry_run: false}) — apply edits
|
||||
- [ ] detect_changes() — verify only expected files changed
|
||||
- [ ] Run tests for affected processes
|
||||
```
|
||||
|
||||
### Extract Module
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] context({name: target}) — see all incoming/outgoing refs
|
||||
- [ ] impact({target, direction: "upstream"}) — find all external callers
|
||||
- [ ] Define new module interface
|
||||
- [ ] Extract code, update imports
|
||||
- [ ] detect_changes() — verify affected scope
|
||||
- [ ] Run tests for affected processes
|
||||
```
|
||||
|
||||
### Split Function/Service
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] context({name: target}) — understand all callees
|
||||
- [ ] Group callees by responsibility
|
||||
- [ ] impact({target, direction: "upstream"}) — map callers to update
|
||||
- [ ] Create new functions/services
|
||||
- [ ] Update callers
|
||||
- [ ] detect_changes() — verify affected scope
|
||||
- [ ] Run tests for affected processes
|
||||
```
|
||||
|
||||
## Tools
|
||||
|
||||
**rename** — automated multi-file rename:
|
||||
|
||||
```
|
||||
rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
|
||||
→ 12 edits across 8 files
|
||||
→ 10 graph edits (high confidence), 2 text_search edits (review)
|
||||
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}]
|
||||
```
|
||||
|
||||
**impact** — map all dependents first:
|
||||
|
||||
```
|
||||
impact({target: "validateUser", repo: "my-app", direction: "upstream"})
|
||||
→ d=1: loginHandler, apiMiddleware, testUtils
|
||||
→ Affected Processes: LoginFlow, TokenRefresh
|
||||
```
|
||||
|
||||
**detect_changes** — verify your changes after refactoring:
|
||||
|
||||
```
|
||||
detect_changes({scope: "all"})
|
||||
→ Changed: 8 files, 12 symbols
|
||||
→ Affected processes: LoginFlow, TokenRefresh
|
||||
→ Risk: MEDIUM
|
||||
```
|
||||
|
||||
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
|
||||
listing was capped) means the result is short of the truth: a short or empty
|
||||
list is not proof that only the expected files changed. Re-run it rather than
|
||||
treat the refactor as verified.
|
||||
|
||||
A wrong-worktree zero carries neither flag and is indistinguishable from a
|
||||
clean verification, so confirm the diffed checkout is the one you edited.
|
||||
|
||||
**cypher** — custom reference queries:
|
||||
|
||||
```cypher
|
||||
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"})
|
||||
RETURN caller.name, caller.filePath ORDER BY caller.filePath
|
||||
```
|
||||
|
||||
## Risk Rules
|
||||
|
||||
| Risk Factor | Mitigation |
|
||||
| ------------------- | ----------------------------------------- |
|
||||
| Many callers (>5) | Use rename for automated updates |
|
||||
| Cross-area refs | Use detect_changes after to verify scope |
|
||||
| String/dynamic refs | query to find them |
|
||||
| External/public API | Version and deprecate properly |
|
||||
| Same name in another indexed repo | Bind `repo`; verify previewed paths before applying |
|
||||
|
||||
## Example: Rename `validateUser` to `authenticateUser`
|
||||
|
||||
```
|
||||
0. list_repos {}
|
||||
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
|
||||
|
||||
1. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
|
||||
→ 12 edits: 10 graph (safe), 2 text_search (review)
|
||||
→ Files: validator.ts, login.ts, middleware.ts, config.json...
|
||||
|
||||
2. Review text_search edits (config.json: dynamic reference!)
|
||||
|
||||
3. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: false})
|
||||
→ Applied 12 edits across 8 files
|
||||
|
||||
4. detect_changes({scope: "all", repo: "my-app"})
|
||||
→ Affected: LoginFlow, TokenRefresh
|
||||
→ Risk: MEDIUM — run tests for these flows
|
||||
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
|
||||
```
|
||||
|
||||
With a single indexed repository, step 0 returns `total: 1` and the `repo`
|
||||
argument drops out of every call above.
|
||||
@@ -0,0 +1,18 @@
|
||||
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));
|
||||
@@ -0,0 +1,20 @@
|
||||
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}`);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export async function verifyConfigReadback(url, expectedContent, expectExists, options = {}) {
|
||||
const request = options.request || fetch;
|
||||
const attempts = options.attempts || 3;
|
||||
const delayMs = options.delayMs ?? 1000;
|
||||
const expectedHash = expectExists ? sha256(expectedContent) : null;
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const response = await request(url);
|
||||
const actual = await response.text();
|
||||
const matches = expectExists
|
||||
? response.ok && sha256(actual) === expectedHash
|
||||
: response.status === 404;
|
||||
if (matches) return true;
|
||||
if (attempt + 1 < attempts && delayMs > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function sha256(value) {
|
||||
return createHash('sha256').update(value ?? '', 'utf8').digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { verifyConfigReadback } from './nacos-readback.mjs';
|
||||
|
||||
test('retries a stale read until the restored config is visible', async () => {
|
||||
const responses = [
|
||||
new Response('old config', { status: 200 }),
|
||||
new Response('restored config', { status: 200 })
|
||||
];
|
||||
let calls = 0;
|
||||
|
||||
const verified = await verifyConfigReadback('http://nacos/config', 'restored config', true, {
|
||||
request: async () => responses[calls++],
|
||||
attempts: 3,
|
||||
delayMs: 0
|
||||
});
|
||||
|
||||
assert.equal(verified, true);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('fails closed when the config does not match after bounded retries', async () => {
|
||||
let calls = 0;
|
||||
const verified = await verifyConfigReadback('http://nacos/config', 'restored config', true, {
|
||||
request: async () => {
|
||||
calls += 1;
|
||||
return new Response('different config', { status: 200 });
|
||||
},
|
||||
attempts: 3,
|
||||
delayMs: 0
|
||||
});
|
||||
|
||||
assert.equal(verified, false);
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
|
||||
test('confirms deletion only after the config is absent', async () => {
|
||||
const verified = await verifyConfigReadback('http://nacos/config', null, false, {
|
||||
request: async () => new Response(null, { status: 404 }),
|
||||
attempts: 1,
|
||||
delayMs: 0
|
||||
});
|
||||
|
||||
assert.equal(verified, true);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
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}`); } }
|
||||
@@ -0,0 +1,37 @@
|
||||
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; } }
|
||||
@@ -0,0 +1,10 @@
|
||||
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}`);
|
||||
@@ -0,0 +1,62 @@
|
||||
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('\\', '/');
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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; }
|
||||
@@ -0,0 +1,87 @@
|
||||
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
|
||||
@@ -0,0 +1,78 @@
|
||||
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
|
||||
@@ -0,0 +1,46 @@
|
||||
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
|
||||
@@ -0,0 +1,57 @@
|
||||
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
|
||||
@@ -0,0 +1,54 @@
|
||||
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
|
||||
@@ -0,0 +1,43 @@
|
||||
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
|
||||
@@ -0,0 +1,44 @@
|
||||
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
|
||||
@@ -0,0 +1,52 @@
|
||||
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
|
||||
@@ -0,0 +1,49 @@
|
||||
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
|
||||
@@ -0,0 +1,85 @@
|
||||
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
|
||||
@@ -0,0 +1,82 @@
|
||||
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
|
||||
+4
-3
@@ -8,8 +8,9 @@
|
||||
# Full-regression database backups may contain development user data.
|
||||
artifacts/full-regression/*backup*.sql
|
||||
|
||||
# Local Codex agent skill mirrors; canonical project skills live under .claude/.
|
||||
.agents/
|
||||
# Local agent skill mirrors stay ignored; project skills under .agents/skills/ are versioned.
|
||||
.agents/*
|
||||
!.agents/skills/
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
@@ -268,7 +269,7 @@ jspm_packages/
|
||||
|
||||
# Mini program local overrides
|
||||
WeChatProgram/utils/config.local.js
|
||||
FingertipDesigner-Admin-Program/utils/config.local.js
|
||||
JayuCloudArtList-Admin-Program/utils/config.local.js
|
||||
FM-Wechat-Fronted/utils/config.local.js
|
||||
|
||||
# 本地敏感服务器信息
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Ardot 图标补齐剩余步骤
|
||||
|
||||
## Context
|
||||
|
||||
用户反馈 Ardot 文件 `https://ardot.tencent.com/file/744106780552731` 中已复刻的 35 个页面(Web 11 页、小程序 24 页)图标缺失,要求用本地 MCP(`mcp_ardot_*`)补齐真实图标,不重建页面、不改页面名、不动布局文案、不删页面、不改仓库、不提交 Git。
|
||||
|
||||
已完成部分:
|
||||
- 品牌 logo 4 页:`3:3`(`7:18`)、`3:8`(`10:40`)、`3:9`(`10:15`)、`35:4`(`35:17`),已用 `upload_images` 应用 `assets/images/app-icon.png` 并删除原文字占位。
|
||||
- tabBar 4 页:`35:1`(`36:625/630/635/640`)、`35:2`(`38:81/86/91/96`)、`35:11`(`55:117/122/127/132`)、`35:9`(`48:118/123/128/133`),已用 `assets/tabbar/*.png` 替换内层 SVG 容器。
|
||||
|
||||
剩余问题:两个页面的缺省头像仍是字母/文字占位,需要替换为 `assets/images/default-user-avatar.png`。
|
||||
|
||||
## 执行步骤(均在本地 MCP,只读仓库)
|
||||
|
||||
### 1. 定位头像容器(只读)
|
||||
- 对页面 `3:12`(salon-小程序端-个人信息)用 `batch_read` 搜索 `^管$`,已得 TEXT `15:21`(21×25,x=0,y=2)。再读取其父节点,确认 50×50 或等效头像框 id。
|
||||
- 对页面 `35:3`(salon-小程序端-新增美甲师)用 `batch_read` 读取整页树(已有 JSONL:`C:\Users\21616\AppData\Local\Temp\.ardot\reads\batch_read-35_3-3987-20261105_175025311.jsonl`),定位 50×50 头像框 id。
|
||||
|
||||
### 2. 替换为真实头像
|
||||
- `upload_images` 将 `e:\code\JayuCloud\JC-Salon-WeChat\assets\images\default-user-avatar.png` 应用到上述两个头像框。
|
||||
- `batch_edit` 删除字母/文字子节点(`3:12` 的 `15:21`,以及 `35:3` 中对应占位文字),保持外框尺寸、圆角与位置不变。
|
||||
|
||||
### 3. Web 端图标核对(只读 + 汇报,不新增页面)
|
||||
- 用 `batch_read` 抽查 `3:1`(登录)、`3:2`(首页)、`3:7` 等页面的 VECTOR 节点,确认侧栏菜单、header 刷新/审核/待处理、列表操作图标已导入并渲染(记录尺寸与描边)。
|
||||
- 源码侧 `JC-Salon-Frontend/src/assets` 仅 `vue.svg`,图标全部来自 `@ant-design/icons-vue`;侧栏与登录页品牌标记源码本身是文字「S」,无图片使用 → 在汇报中标注「源码无图片使用,保持近似」。
|
||||
- 整理「还原 / 近似 / 缺失」三类清单。
|
||||
|
||||
### 4. 最终复核
|
||||
- `fetch_editor_state` 确认 pageList 仍为 35 页(`3:20` 不恢复,`0:1` 不恢复)。
|
||||
- 抽查补图标页面节点(`3:3`、`3:8`、`3:9`、`35:4`、`35:1`、`35:2`、`35:9`、`35:11`、`3:12`、`35:3`),确认 fills 为 IMAGE。
|
||||
|
||||
### 5. 汇报
|
||||
- 以「图标补齐已完成」开头,给出:
|
||||
- 小程序端:品牌 logo、tabBar、缺省头像的还原清单与节点 id;
|
||||
- Web 端:已存在的 Ant Design Vue 图标(近似还原)清单、源码无图片的说明;
|
||||
- 仍有缺失:上传失败或工具不支持(SVG 不能 `register_assets`,必要时内联)的条目与原因。
|
||||
|
||||
## 验证方式
|
||||
|
||||
- `batch_read` 返回节点 `fills` 含 `type: "IMAGE"`;
|
||||
- `fetch_editor_state` 页面数量与名称未变;
|
||||
- 截图抽查 `capture_screenshot` 对应 pageId 的局部区域(可选)。
|
||||
|
||||
## 约束
|
||||
|
||||
- 只增补图标节点,不重建页面、不改页面名、不动布局文案;
|
||||
- 不改仓库文件、不提交 Git、不导出;
|
||||
- 上传失败贴原始错误并跳过,继续其余页面。
|
||||
```
|
||||
@@ -0,0 +1,161 @@
|
||||
# Ardot 设计稿批次 5 收尾与批次 6 执行计划
|
||||
|
||||
## Summary
|
||||
|
||||
针对 Ardot 文件 `https://ardot.tencent.com/file/744106780552731`(当前 35 页)继续完成已确认的 8 项优化中剩余部分:
|
||||
|
||||
- **批次 5 收尾**:验证 `salon-小程序端-我的`(35:9)本批改动;为 `salon-小程序端-关于系统`(3:3)补「用户协议 / 隐私政策」入口与「版本更新日志」。
|
||||
- **批次 6**:新增 4 个注册相关页面(`补充资料(店长)`、`补充资料(店员)`、`申请状态(店长)`、`申请状态(店员)`)。
|
||||
- 全部完成后按用户要求以「任务完成」开头,按「改了什么 / 依据 / 与源码不一致处 / 推断项 / 新增页面 ID 与命名 / 截图验证结论」汇报。
|
||||
|
||||
约束:不重建已有页面、不改页面名、不删页;只改内容或新增页面;不改仓库文件、不提交 Git、不导出。
|
||||
|
||||
## Current State Analysis
|
||||
|
||||
### 已核实(只读读取结果)
|
||||
|
||||
**35:9 我的页(48:1)** — 编辑已执行,待截图验证:
|
||||
|
||||
- `48:28` 96×23 r11.5,内含 `69:277` 选中胶囊 42×19 #247B63、`69:278`「店长」11px Bold 白、`69:279`「美甲师」11px Regular #71807A;旧「管理端」节点 `48:29` 已删。
|
||||
- 菜单卡 `48:70/48:113` 高 250,`48:73` 内 5 行 × 49:`48:74` 个人信息 → `48:80` 店铺信息 → `48:86` 账号安全 → `48:92` 订单数据 → `48:110` 关于系统(文案已按顺序改写,文案字体为 Sarasa Bold)。
|
||||
- 退出登录 `48:114` 357×44 r10 #FBE9E7(r0.984,g0.914,b0.906),y=538;`48:115` 14px Sarasa Semi Bold #B3261E(r0.702,g0.149,b0.118),x=152、y=12。
|
||||
|
||||
**3:3 关于系统(7:1)** — 尚未修改:
|
||||
|
||||
- `7:1` 390×844,底色 #F5F7F4;`7:2` vertical gap 0 → `7:3` 状态栏 44、`7:8` 导航头 44(返回 18×18 @x16、标题「关于系统」17px SemiBold)、`7:16` 内容区 vertical gap 10 / padding-top 42。
|
||||
- `7:16` 子节点:`7:17` 品牌卡 366×175(`7:18` logo 58×58 imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`、`7:20`「甲屿手纪」20px Black、`7:22` 描述 12.5px #908865);`7:24` 信息卡 366×112 r12 白底。
|
||||
- `7:24` → `7:25` vertical,padding 1/1/13/15;行 `7:26`「版本 / 0.0.1」340×43、`7:29`「定位 / 日程 / 客户 / 美甲师 / 我的」340×43;行内 padding 6/6/12/12,标签 14.5px #17211F、值 14.5px #71807A。
|
||||
|
||||
**35:4 注册页(40:1)** — 仅含第 1 步「选择工作身份」,第 2/3 步无画板,作为批次 6 的复用样式源:
|
||||
|
||||
- 页面 390×844 #F5F7F4;`40:15` 内容层为 `layout:"none"`,子节点全部 ABSOLUTE 定位。
|
||||
- 品牌头 `40:16`:360.8×47.1 @(15,19),logo 45.8×45.8 r13.5 @(6.5,0.65) 同 imageHash,brand 文案列 156 宽。
|
||||
- 进度条 `40:24`:360.8×40 @(15,84),三步 40×40 @x0/160/321,圆点 21.8×21.8 r10.9(激活 #247B63 / 未激活 #E0E9E2),连线 108×1 #DCE6DE @y12。
|
||||
- 卡片 `40:42`:360.8×283.6 @(15,137),r12.5,填充 #FBFDFB(0.984,0.992,0.984),描边 #E7ECE9,标题 17.7px ExtraBold,描述 12px #879792,角色项 58.2 高 r8.3 #F5F7F4 描边 #E7ECE9。
|
||||
- 主按钮 `40:70`:329.6×43.7 r7.3 #247B63 @(16,221),文字 14.6px Bold 白。
|
||||
- 页脚注 `40:72`:11px #9AA9A0,居中 x=44。
|
||||
|
||||
### 源码依据(只读)
|
||||
|
||||
- `JC-Salon-WeChat/pages/register/index.wxml`:
|
||||
- 进度条三步:选择身份 / 补充资料 / 申请状态。
|
||||
- 第 2 步店长:`店铺名称*`、`店铺地址(选填)+ 地图选点` + 提示「地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。」;副标题「提交后由平台管理员审核」。
|
||||
- 第 2 步店员:`选择店铺*`(picker,占位「请选择要加入的店铺」)、`昵称*`(提示「可从微信昵称中选择,也可以手动填写,最多20个字。」)、`头像*`(默认头像 + 「点击选择微信头像」)、notice「审核通过前不会获得门店业务权限」;副标题「提交后由对应店长审核,昵称和头像为必填资料」。
|
||||
- 第 2 步底部:主按钮「提交审核」+ 文字链「返回上一步」。
|
||||
- 第 3 步:结果图标(…/✓/!)、标题(申请已提交 / 申请已通过 / 申请未通过)、描述、`当前状态:待审核`、详情行(申请门店、申请身份、[申请昵称]、[申请编号]、提交时间)、主按钮「返回登录」(驳回态为「返回登录并重新申请」)。
|
||||
- `JC-Salon-WeChat/pages/profile/index.js`:`menus` 顺序为用户协议/隐私政策在第 5/6 位,并入「关于系统」后需在 3:3 提供入口。
|
||||
- `JC-Salon-WeChat/pages/about/index.wxml`:仅「版本 / 定位」两行,无协议入口、无更新日志 —— 3:3 的两处补充均属「按用户要求新增」,需在汇报中标注与源码不一致。
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
### 批次 5-A:35:9 我的页截图验证(不改内容)
|
||||
|
||||
1. `capture_screenshot(nodeIds:["48:1"])`,核对:
|
||||
- 身份切换 chip 显示「店长(选中)/ 美甲师」,无溢出、无换行;
|
||||
- 菜单五项顺序为 个人信息 → 店铺信息 → 账号安全 → 订单数据 → 关于系统,行高一致无重叠;
|
||||
- 退出登录为低饱和红底按钮,文字居中。
|
||||
2. `capture_layout({parentId:"48:1", problemsOnly:true})` 复核裁剪/重叠。
|
||||
3. 如发现渲染问题,仅做最小修正(改宽度/坐标/字号),不改结构。
|
||||
|
||||
### 批次 5-B:3:3 关于系统补协议入口与版本更新日志(`batch_edit` 于 `7:1`)
|
||||
|
||||
1. 信息卡扩容:
|
||||
- `U("7:24",{"height":200})`
|
||||
- `U("7:25",{"height":200})`
|
||||
2. 新增两行入口(父节点 `7:25`,行样式对齐 `7:26`):
|
||||
- `I("7:25",{ FRAME 名称「用户协议」340×43, layout:"none" })` → 子项:`TEXT`「用户协议」14.5px #17211F @(6,12);`TEXT`「›」22.9px #B0A79A @(320,10)
|
||||
- `I("7:25",{ FRAME 名称「隐私政策」340×43, layout:"none" })` → 同上,文字「隐私政策」
|
||||
3. 新增「版本更新日志」卡片(父节点 `7:16`,插入在 `7:24` 之后,顺序即视觉顺序):
|
||||
- 卡片 `366×190` r12 白底 `layout:"none"`
|
||||
- 标题「版本更新日志」15px Bold #17211F @(16,16)
|
||||
- 条目块(横向:版本胶囊 + 日期,随后三行说明,均 11.5px):
|
||||
- 版本胶囊 `58×22` r11 #E5F4ED,「0.0.1」11px Bold #247B63 居中;日期「2026-11-05」11.5px #71807A @x=82,y≈4
|
||||
- 说明行 1「新增补充资料与申请状态设计稿(店长 / 店员)」@y=52
|
||||
- 说明行 2「我的页支持店长 / 美甲师身份切换」@y=74
|
||||
- 说明行 3「用户协议与隐私政策入口并入关于系统」@y=96
|
||||
- 底部说明「后续版本更新将在此处按时间倒序展示」11px #9AA9A0 @y=140
|
||||
4. 校验内容总高:42 + 175 + 10 + 200 + 10 + 190 = 627 < 800(扣除状态栏与导航头后可用 756),无溢出。
|
||||
|
||||
### 批次 6:新增 4 个注册相关页面
|
||||
|
||||
**通用构造**(每页一张 390×844 画板,页面底色 #F5F7F4,`layout:"none"` + 子节点 ABSOLUTE):
|
||||
|
||||
- 状态栏 44:`9:41`(13px SemiBold #17211F @x28 垂直居中)、`●●●` 与 `▮`(13px SemiBold,#17211F,gap 5,右侧 @x≈332)。
|
||||
- 品牌头(复用 35:4 `40:16` 几何):logo 45.8×45.8 r13.5 @(21.5,20.3) imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`;右侧文案列 @(77.2,19):主标题「Salon」20px Black #17211F,副标题「用微信身份申请门店工作权限」11.380px #879792。
|
||||
- 进度条 @(15,84):三步圆点 21.8×21.8 r10.9;未激活 #E0E9E2、已激活 #247B63;完成步数字「✓」7.6px Bold 白,当前步白字「2」或「3」,未开始步 #6B7B74;步名 10px #6B7B74 / 当前步 #247B63 Bold(「选择身份」「补充资料」「申请状态」);连线 108×1 #DCE6DE @y12 @x46 与 @x207。
|
||||
- 卡片 @(15,137):360.8 宽,r12.5,#FBFDFB 填充 + #E7ECE9 1px 描边。
|
||||
|
||||
**1) `salon-小程序端-补充资料(店长)`**
|
||||
|
||||
- 进度:第 1 步完成、第 2 步激活、第 3 步未开始。
|
||||
- 卡片高 352:
|
||||
- 标题「补充资料」17.7px ExtraBold @(16,19);副标题「提交后由平台管理员审核」12px #879792 @(16,48)
|
||||
- 字段 1:标签「* 店铺名称」(`*` 6.9px #C0392B + 文案 14px #17211F)@(16,84);输入框 329.6×44 r8 #F5F7F4 描边 #E7ECE9 @(16,106),占位「请输入店铺名称」12px #9AA9A0 @(12,12)
|
||||
- 字段 2:标签「店铺地址 选填」(「选填」10px #9AA9A0)@(16,166);输入框 238×44 @(16,188) 占位「可手动填写门店地址」;按钮 83.6×44 r8 #E5F4ED @(262,188),文字「地图选点」11.5px Bold #247B63
|
||||
- 提示「地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。」11px #9AA9A0,宽 329.6 @(16,240),两行
|
||||
- 主按钮 329.6×43.7 r7.3 #247B63 @(16,278),文字「提交审核」14.6px Bold 白
|
||||
- 文字链「返回上一步」11.5px #71807A @(y=330) 居中
|
||||
- 页脚注 11px #9AA9A0 居中:「OpenID 仅用于识别你的微信身份,不会在页面中展示。」
|
||||
|
||||
**2) `salon-小程序端-补充资料(店员)`**
|
||||
|
||||
- 进度同 1)。
|
||||
- 卡片高 430:
|
||||
- 标题「补充资料」@(16,19);副标题「提交后由对应店长审核,昵称和头像为必填资料」@(16,48)
|
||||
- 字段 1「* 选择店铺」@(16,84);选择行 329.6×44 r8 @(16,106),占位「请选择要加入的店铺」12px #9AA9A0,右箭头「›」22.9px #B0A79A @x≈318
|
||||
- 字段 2「* 昵称」@(16,166);输入框 329.6×44 @(16,188),占位「点击输入框选择或填写微信昵称」;提示「可从微信昵称中选择,也可以手动填写,最多20个字。」11px #9AA9A0 @(16,240)
|
||||
- 字段 3「* 头像」@(16,266);头像行 @(16,288):圆形 56×56 r28 默认头像(复用 imageHash `ed433c1485641a6f4827a00c8dc568d176750c75`,若该图为品牌图则改用首字占位「微」#E5F4ED/#247B63),右侧文字「点击选择微信头像」12px #71807A;提示「请选择头像,头像会先上传并完成资料登记,提交时只引用已上传的文件。」11px @(16,350)
|
||||
- 提示条 329.6×34 r8 #FDF3E7(0.992,0.953,0.906),文字「审核通过前不会获得门店业务权限」11.5px #A9743B @(16,382)
|
||||
- 主按钮「提交审核」@(16,428)——卡片高需同步扩为 500,避免按钮与文字链越界
|
||||
- 文字链「返回上一步」11.5px #71807A @y=484 居中
|
||||
- 页脚注同 1)。
|
||||
|
||||
> 说明:头像占位若不使用品牌图,需在汇报中标注为「推断的默认头像占位」。
|
||||
|
||||
**3) `salon-小程序端-申请状态(店长)`**
|
||||
|
||||
- 进度:第 1、2 步完成、第 3 步激活。
|
||||
- 卡片高 396:
|
||||
- 结果图标 72×72 r36 #E5F4ED @(144.4,24),内「…」20px Bold #247B63 居中
|
||||
- 标题「申请已提交」17.7px ExtraBold 居中 @y=112
|
||||
- 描述「申请由平台管理员处理,通过后即可使用快捷登录。」12px #879792 居中,宽 300 @(30,144),两行
|
||||
- 状态行「当前状态:待审核」12.5px #17211F @(16,186),「待审核」#D59A52 Bold
|
||||
- 详情区 @(16,212):三行 40 高(申请门店「甲屿手纪·望京店」/ 申请身份「店长」/ 提交时间「2026-11-05 14:32」),行内左侧 11.5px #71807A、右侧 11.5px #17211F 右对齐 @x≈250;每行底部 1px #EDEDED
|
||||
- 主按钮「返回登录」329.6×43.7 @(16,336)
|
||||
- 页脚注「申请进度会随审核结果更新,可在登录页重新进入查看。」11px #9AA9A0 居中 @y=392(卡片外)
|
||||
|
||||
**4) `salon-小程序端-申请状态(店员)`**
|
||||
|
||||
- 进度同 3)。
|
||||
- 卡片高 436:
|
||||
- 结果图标、标题、描述同 3),描述为「申请由门店店长处理,通过后即可使用快捷登录。」
|
||||
- 详情四行(申请门店「甲屿手纪·望京店」/ 申请身份「店员」/ 申请昵称「小雨」/ 提交时间「2026-11-05 14:32」),y 起点 212,每行 40
|
||||
- 主按钮「返回登录」@(16,376)
|
||||
- 页脚注同 3) @y=432
|
||||
|
||||
**页面创建与定位步骤(每页)**:
|
||||
|
||||
1. `create_new_page({name:"salon-小程序端-补充资料(店长)"})` 等 4 次,按序创建。
|
||||
2. `locate_available_space` 取该页可用区(page 级插入前必须调用)。
|
||||
3. `batch_edit` 在该页插入 390×844 顶层画板,`layout:"none"`,`I(pageId,{...})` 逐节点构建(每批 ≤ 60 行,操作行换行分隔,不用分号)。
|
||||
4. 数字/中文混排节点显式设置 `fontName:{family:"Sarasa Gothic SC", style:"Semi Bold"}`,避免缺字回退。
|
||||
|
||||
## Assumptions & Decisions
|
||||
|
||||
| # | 决策 | 理由 |
|
||||
|---|---|---|
|
||||
| A1 | 4 个注册页各自独立成页,不复用 35:4 页面 | 用户明确要求「新增页面 ID 与命名」,且命名按「补充资料(店长)」等给出 |
|
||||
| A2 | 新页沿用 35:4 的品牌头 + 三步进度条,第 2/3 步高亮 | 与源码 `register` 单页三步结构一致,视觉连续 |
|
||||
| A3 | 不画「已通过 / 已驳回」状态 | 用户只要求「补齐补充资料与申请状态」,默认展示提交后的待审核态;其余状态列入建议清单 |
|
||||
| A4 | 3:3 版本更新日志内容用 0.0.1 / 2026-11-05 + 三条本次改动说明 | 与仓库 0.0.1 基线一致,且可追溯本次设计稿改动 |
|
||||
| A5 | 3:3 协议入口以「›」行形式挂在信息卡内,不新增独立页面 | 用户要求「并入关于系统」,不新建协议页 |
|
||||
| A6 | 申请状态详情中的门店名/昵称/时间为示意文案 | 设计稿无真实数据源,属推断示例 |
|
||||
| A7 | 若渲染异常只做最小修正(宽/坐标/字号),不改结构、不删页、不改页名 | 用户通用约束 |
|
||||
|
||||
## Verification
|
||||
|
||||
1. **批次 5-A**:`capture_screenshot(["48:1"])` + `capture_layout({parentId:"48:1",problemsOnly:true})`;确认身份 chip、5 行菜单、红色退出按钮。
|
||||
2. **批次 5-B**:`capture_screenshot(["7:1"])` + `capture_layout({parentId:"7:1",problemsOnly:true})`;确认 4 行信息卡与版本日志卡不重叠、不越界。
|
||||
3. **批次 6**:一次性 `capture_screenshot([四个新页画板 id])`(单次配额内);确认 4 页各自 390×844、进度高亮正确、字段与按钮不裁剪。
|
||||
4. **终检**:`fetch_editor_state` 复核页面总数 39、4 个新页名称唯一且无重复、无页面被改名/删除。
|
||||
5. **汇报**:以「任务完成」开头,输出 改了什么 / 依据 / 与源码不一致处(日程不做月视图;35:3 手机号必填差异;3:3 协议入口与版本日志为新增;注册页仅覆盖待审核态)/ 推断项(微信登录未关联用户列表、申请状态示例数据、店员头像占位)/ 新增页面 ID 与命名 / 截图验证结论 / 建议清单。
|
||||
@@ -0,0 +1,66 @@
|
||||
# Ardot 设计稿优化:批次 3 收尾与批次 4–6 执行计划
|
||||
|
||||
## Context
|
||||
|
||||
目标文件 `https://ardot.tencent.com/file/744106780552731`(35 页基线),需按用户已确认的 8 项优化逐批落地,每批用 `capture_screenshot` 验证后再进下一批。批次 1(日程周/日视图)与批次 2(客户页、预约详情页)已完成并验证;批次 3 的改派美甲师页栅格对齐与美甲师页折叠按钮/折叠态画板已完成主体编辑,截图验证后只剩 1 个视觉小问题待修。
|
||||
|
||||
约束:不重建已有页面、不改已有页面名、不删页;只改内容或新增页面;仅使用本地 Ardot MCP;不改仓库文件、不提交 Git。
|
||||
|
||||
## 已完成(供上下文,不再重复)
|
||||
|
||||
- 35:1 日程:主画板改「周视图状态」(69:1 周条 + 7 日卡),新增 69:52「日视图状态」;删除浮层 37:43(取消预约),35:8 已有 53:3 同名浮层。
|
||||
- 35:2 客户:删除「新增」文字按钮,搜索栏满宽,新增 69:167 悬浮加号;新增客户弹窗姓名加红星(69:168)。
|
||||
- 35:8 预约详情:补「呼叫」按钮(69:170/69:171);修复基线遗留的 193×844 浅绿块与竖排「呼叫」占位;重排卡片高度,六字段栅格恢复可见。
|
||||
- 35:13 改派美甲师:`61:39` 宽度设为 94,三行内容列统一到 x≈94。
|
||||
- 35:11 美甲师:删除旧「2 项」(55:34),新增 69:173「列表标题右侧」→ 69:174「2 项」+ 69:175「折叠按钮」+ 69:176「︿」;新增 69:177「美甲师(折叠态)」画板(含状态栏、头部、工具栏、折叠审核卡、3 张美甲师卡、底部导航)。
|
||||
|
||||
## 剩余执行计划
|
||||
|
||||
### 步骤 0:批次 3 收尾修复
|
||||
|
||||
- `U("69:174",{width:30})`:修「2 项」在 20px 宽内换行的问题。
|
||||
- 用 `capture_layout`(problemsOnly)确认 69:177 无重叠/溢出;不额外消耗截图配额。
|
||||
|
||||
### 步骤 1:批次 4 —— 35:3「新增美甲师档案页」
|
||||
|
||||
1. 只读读取 35:3 页面结构(主画板 + 浮层组),定位姓名、手机号、微信号/微信登录、专属颜色字段节点与星号节点。
|
||||
2. 必填收敛:仅「姓名」「专属颜色」加红星(#D9534F,12.5px),其余字段星号删除;与源码 `JC-Salon-WeChat/pages/employee-create` 字段必填关系比对并记录差异。
|
||||
3. 「微信登录」点击态:在 35:3 浮层组新增浮层画板「浮层:未关联微信用户列表」——底部面板,标题「选择微信用户」+ 说明「仅显示尚未关联门店账号的微信用户」+ 3 条用户行(头像/昵称/最近登录时间/「选择」按钮)+ 空列表态文案。**标注为推断设计,渲染结果需用户确认。**
|
||||
4. 「专属颜色」点击态:新增浮层「浮层:专属颜色设置」——色板网格(复用设计已有美甲师色 #7BA7C7/#C7A58F/#A7BFA8 + 6 个扩展色)、当前选中预览、取消/确认按钮。
|
||||
5. 截图验证 35:3 主画板 + 2 个新浮层。
|
||||
|
||||
### 步骤 2:批次 5 —— 35:9「我的」与 3:3「关于系统」
|
||||
|
||||
1. 读取 35:9 主画板,找到顶部「管理端」标识与菜单列表、退出登录按钮。
|
||||
2. 身份态:同一画板内把「管理端」替换为「当前身份」切换控件(店长 / 美甲师 两个 chip,店长为选中态),并在下方菜单区同时满足两角色(菜单文案差异不大,采用同页切换,不拆画板);另加一行说明「切换身份仅影响可见菜单」。
|
||||
3. 菜单顺序调整为:个人信息 → 店铺信息 → 账号安全 → 订单数据 → 关于系统。
|
||||
4. 「退出登录」改为低饱和红色填充按钮(浅红底 #FBE9E7 + 深红字 #B3261E,保持原尺寸与圆角)。
|
||||
5. 3:3「关于系统」:新增「用户协议」「隐私政策」两个入口行,新增「版本更新日志」区(版本号 + 日期 + 2–3 条更新说明)。
|
||||
6. 截图验证 35:9 与 3:3。
|
||||
|
||||
### 步骤 3:批次 6 —— 注册相关 4 个新页面
|
||||
|
||||
1. 读取 `JC-Salon-WeChat/pages/register` 与 `WorkbenchRegistrationView.vue` 的补充资料、申请状态字段作为内容依据。
|
||||
2. 用 `create_new_page` 新建 4 页,命名严格为:
|
||||
- `salon-小程序端-补充资料(店长)`
|
||||
- `salon-小程序端-补充资料(店员)`
|
||||
- `salon-小程序端-申请状态(店长)`
|
||||
- `salon-小程序端-申请状态(店员)`
|
||||
3. 每页用 `locate_available_space` 后插入 390×844 画板:状态栏、标题、表单/状态卡、说明文案、主按钮,风格沿用既有 token(#247B63 / #F5F7F4 / #17211F)。
|
||||
4. 截图验证 4 个新页;复核总页数 39、页面名无重复。
|
||||
|
||||
### 步骤 4:最终汇报
|
||||
|
||||
以「任务完成」开头,按:改了什么 / 依据 / 与源码不一致处(含「日程不做月视图——按用户要求」)/ 推断项(微信登录未关联用户列表)/ 新增页面 ID 与命名 / 截图验证结论 / 建议清单 逐项交付。
|
||||
|
||||
## 验证方式
|
||||
|
||||
- 每批:`capture_screenshot(nodeIds)` 一次覆盖该批所有改动节点;仅当截图暴露问题且已集中修复后才允许第二次。
|
||||
- 结构类问题优先 `capture_layout(problemsOnly:true)`,不占用截图配额。
|
||||
- 全部完成后只读复核页面数量与命名。
|
||||
|
||||
## 已知风险与处理
|
||||
|
||||
- 更新 `characters` 会把缺失字体重置为 Sarasa Gothic SC Regular,需显式 `U(fontName)` 恢复字重。
|
||||
- TEXT 不支持 `textAlign`,居中/右对齐需手动 x 定位。
|
||||
- 新增子级必须指定正确 parentId,避免文字堆叠在父容器顶部(本任务已出现过两次)。
|
||||
@@ -0,0 +1,84 @@
|
||||
# ArtList 账号加密与场景化脱敏执行清单
|
||||
|
||||
> 按项目规则不新增设计文档;本文件只是 plan 模式的执行清单,实施完成后不为它单独提交。
|
||||
|
||||
## 零、版本号自查结论(已核实)
|
||||
|
||||
- 查 dev 库 `jayucloud_artlist`:库内没有 `flyway_schema_history`,表数为 0 → **V3 从未在任何环境执行过**。
|
||||
- 远端 `dev` 已被并行分支先推入 `V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql`(本地 HEAD `80d187d2` 已含);`core.yaml` 为 `out-of-order: false`。
|
||||
- 因此把工作区里的 `V3__账号加密与账号哈希_20261104.sql` **改名为 `V5__账号加密与账号哈希_20261104.sql`**(V3 文件已删除,V5 未被占用),保证 V1→V2→V4→V5 顺序天然正确,无论 V4 是否已执行都能跑。
|
||||
- 若后续发现 V3 曾执行过,则恢复 V3 命名且不改文件内容(不得改已执行迁移)。
|
||||
|
||||
## 一、前置结论:为什么保留 `account` 列名
|
||||
|
||||
- Salon 实际实现:`t_user.account` 列存密文 + `account_hash char(64) NULL` + `uk_user_account_hash`;没有 `account_cipher`。
|
||||
- **不能**"新增 account_cipher 再 DROP account":V1 种子由 SQL 直接写 `account='xiaowang'`,SQL 层无密钥无法回填,DROP 会丢数据。
|
||||
- 因此与 Salon 同构:`account` 改存 AES-GCM 密文(`varchar(128) NULL`)、新增 `account_hash`、删 `uk_account`、加 `uk_user_account_hash`。hash 输入 `trim()` + HMAC-SHA256 十六进制小写,与 Salon 逐字对齐。
|
||||
- ArtList 唯一差异:账号允许字母数字自定义账号,**一律加密**(Salon 仅手机号形态加密)。`decryptAccount` 对无 `enc:v1:` 前缀的历史值原样返回,兼容 V1 种子。
|
||||
|
||||
## 二、V5 迁移(已落地)
|
||||
|
||||
`JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql`:
|
||||
|
||||
1. 幂等过程沿用 V2 风格:`sp_v5_add_column_if_not_exists`、`sp_v5_drop_index_if_exists`、`sp_v5_add_unique_index_if_not_exists`(`DELIMITER $$`,用后 DROP)。
|
||||
2. `ALTER TABLE t_user MODIFY COLUMN account varchar(128) NULL COMMENT '账号AES-GCM密文(enc:v1: 前缀)'`。
|
||||
3. 新增 `account_hash char(64) NULL COMMENT '账号HMAC-SHA256索引'`。
|
||||
4. 删除 `uk_account`;新增 `uk_user_account_hash (account_hash)`(MySQL 唯一索引允许多行 NULL)。
|
||||
5. 不做 SQL 数据迁移;历史/种子账号由启动时 `AccountHashBackfillRunner` 加密并回填 hash。
|
||||
|
||||
## 三、后端改造(已落地)
|
||||
|
||||
- `support/privacy/PhoneCrypto`:新增 `encryptAccount`(非空一律加密)、`decryptAccount`(仅 `enc:v1:` 前缀解密,legacy 明文原样返回);`index` 复用,输入仍 `trim()`;删除不再使用的 `maskIfMobile`。
|
||||
- 新建 `support/privacy/AccountPhoneTypeHandler`:写 `encryptAccount`、读 `decryptAccount`。
|
||||
- `UserDO`:`account` 挂 `AccountPhoneTypeHandler`;新增 `accountHash`(`@TableField("account_hash")`,与既有 phoneHash 一致,由 `MyMetaObjectHandler` 手工填充)。
|
||||
- `MyMetaObjectHandler`:`fillPhoneHashes` 中补 account → accountHash。
|
||||
- `UserServiceImpl`:
|
||||
- 全部账号等值查询改 `.eq(UserDO::getAccountHash, phoneCrypto.index(x))`;**不在每条查询挂 legacy fallback**。
|
||||
- `pageUsers` 删除 account LIKE,改 `account_hash` 精确匹配,保留 nickname like 与 phone/contactPhone hash。
|
||||
- `deleteUser` 抽出包级静态 `buildSoftDeleteUpdate(...)`(供单测断言),显式 set 密文 account + accountHash,并清空 `phone`、`phoneHash`、**`contactPhone`、`contactPhoneHash`**(本次补齐的数据残留),再置 status=0、isDelete=1。
|
||||
- `buildLoginFailKey` 改用 `phoneCrypto.index(account)`。
|
||||
- `convertToVO(userDO, scenario)`:`getUserById`/`getUserByAccount` 传 `SELF_PROFILE`,列表/分页传 `ADMIN_LIST`。
|
||||
- 新建 `support/privacy/AccountHashBackfillRunner`(`ApplicationRunner`):启动时对 `account_hash IS NULL AND account IS NOT NULL` 的行加密 account 并回填 hash,幂等。
|
||||
- `UserController`、`OperationGuardService` 的账号查询/签名索引统一走 `account_hash` / `index`。
|
||||
|
||||
## 四、集中脱敏策略(核心,已落地)
|
||||
|
||||
`support/privacy/SensitiveFieldPolicy`:`Scenario` 枚举 `SELF_PROFILE / ADMIN_EDIT / ADMIN_LIST / THIRD_PARTY / DIAL / LOG`;`phone(value, scenario)`、`account(value, scenario)`。已支持先解密再处理。
|
||||
|
||||
| 场景 | 返回方式 | 依据 |
|
||||
| --- | --- | --- |
|
||||
| SELF_PROFILE(`/user/info`、本人资料回显) | 完整 | 本人查看/修改;小程序发验证码直接用 `userInfo.phone` |
|
||||
| ADMIN_EDIT(`/user/get/{id}`、`/user/get/account/{account}`) | 完整 | 编辑表单需原值,配合前端"未修改不提交" |
|
||||
| ADMIN_LIST(分页、列表、公告/消息作者) | 脱敏 | 批量浏览,无编辑/拨号需求 |
|
||||
| DIAL(门店与客服联系方式) | 完整 | 拨号必需;受登录态、门店可见范围与 OperationGuard、限流约束 |
|
||||
| THIRD_PARTY(评论昵称回退、公开主页、订单客户昵称回退) | 脱敏 | 公开/半公开场景 |
|
||||
| LOG(审计、日志、短信投递记录) | 脱敏 | 多人可见的持久化介质 |
|
||||
| 订单详情客户手机 | 脱敏(维持 `customerPhoneMasked`) | 拨号统一走联系方式接口,避免订单批量泄露 |
|
||||
|
||||
应用点:`UserServiceImpl.convertToVO`;`ContactInfoServiceImpl`(手机 DIAL 完整、姓名回退 THIRD_PARTY);`CommentServiceImpl` / `AnnouncementServiceImpl` / `SystemMessageServiceImpl` / `OrderServiceImpl`(账号回退 THIRD_PARTY 或 ADMIN_LIST);`SecurityAuditLogServiceImpl`(LOG)。
|
||||
|
||||
## 五、前端 / 小程序(已落地)
|
||||
|
||||
- `JC-ArtList-Frontend/src/views/ProfileView.vue`:打开编辑弹窗记录 `originalContactPhone`,提交时仅值变化才带 `contactPhone` 字段。
|
||||
- `JC-ArtList-Frontend/src/views/AccountSettingsView.vue`:绑定/修改手机号均为用户新输入,旧号只展示不回传。
|
||||
- `JC-ArtList-WeChat`:`pages/account-settings` 只提交 nickname/signature;`pages/settings`、`pages/password-settings` 的 `userInfo.phone` 仅展示/发码。
|
||||
- 管理端用户编辑 UI 不在本仓库(`CreateUserRequest/UpdateUserRequest` 无页面使用)→ 未覆盖项。
|
||||
|
||||
## 六、验证(已执行部分)
|
||||
|
||||
1. `mvn -q clean test -Dtest="PhoneCryptoTest,SensitiveFieldPolicyTest,UserSoftDeleteUpdateTest,FlywayMigrationTempCheckTest"` → **EXIT=0**(含编译)。
|
||||
2. 单测覆盖:account 加解密回环(含纯数字账号一律加密)、legacy `xiaowang` 原样读取 + hash trim 稳定、六场景矩阵断言、软删除 set 子句含 `account/account_hash/phone_cipher/phone_hash/contact_phone_cipher/contact_phone_hash`。
|
||||
3. 临时库 `jayucloud_artlist_v5check_20261104`:V1→V2→V4→V5 四个迁移成功,二次 migrate "Schema is up to date",断言 `account_hash` 列、`uk_user_account_hash` 存在、`uk_account` 已删、`account` 长度 128;finally DROP DATABASE;临时测试文件已删除。
|
||||
|
||||
## 七、剩余步骤
|
||||
|
||||
1. 全仓检索确认无明文读写:`getAccount(`/`setAccount(`/`getPhone(`/`phone_cipher`/`account_hash`,结合上下文判断。
|
||||
2. `node .gitnexus/run.cjs detect-changes --scope all --repo .`(提交前门禁;`partial/truncated` 需重跑)。
|
||||
3. 中文提交,只含本次文件(V5 迁移、PhoneCrypto、AccountPhoneTypeHandler、SensitiveFieldPolicy、AccountHashBackfillRunner、UserDO、MyMetaObjectHandler、UserServiceImpl、UserController、ContactInfoServiceImpl、SecurityAuditLogServiceImpl、Comment/Announcement/SystemMessage/Order、OperationGuardService、3 个测试类、ProfileView.vue);不提交 `.trae/`、`docs/design/`。
|
||||
4. `git push origin dev`(禁止 force);非快进 `git pull --rebase` 重试一次,仍失败原样报错停止。
|
||||
|
||||
## 八、风险与未覆盖项
|
||||
|
||||
- JWT claims 与 Redis 会话 value 仍含账号明文,本轮不改。
|
||||
- `account` 一律加密与 Salon 条件加密存在行为差异,hash 语义一致。
|
||||
- 管理端用户编辑页面不在本仓库,未覆盖。
|
||||
@@ -0,0 +1,178 @@
|
||||
# 散客预约拨号 + 协议新版本强制重新同意 实施计划
|
||||
|
||||
## Context
|
||||
|
||||
现有拨号取号端点 `POST /manager/customers/{customerId}/dial?orderId=...` 强制要求 `order.userId = customerId`。散客预约(`OrderDO.userId` 为空,客户信息只存在 `customerNameSnapshot` / `customerPhoneSnapshot`)无法取号,“呼叫”按钮也被前端按 `userId` 隐藏。
|
||||
|
||||
同时,V17 已发布 `2026.11.04` 协议,V18 只修订了该版本正文、不可再改。需要新增 V19 发布新版本 `2026.11.04-R2`,并让已登录但未同意新版本的用户强制重新同意。
|
||||
|
||||
目标:
|
||||
1. 拨号接口支持 `appointmentId`(= 预约详情的 `orderItemId`)/ `orderId` 定位,`customerId` 可空;只校验预约/订单属于当前店铺,不要求客户有账号;号码来源优先订单快照、再客户档案;无号码返回明确业务码。
|
||||
2. 发布 V19 新协议版本;复用现有 `t_user_agreement_consent` 同意记录表,新增 pending/accept 接口;前端登录后强制弹层。
|
||||
3. 不修改 V18,不动 ArtList 与 `SystemSettingsView.vue`。
|
||||
|
||||
## 一、散客拨号(Salon Core)
|
||||
|
||||
### 1. 服务接口与实现
|
||||
|
||||
`JC-Salon-Core/src/main/java/.../modules/privacy/service/CustomerDialService.java`
|
||||
- 改为 `CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request);`
|
||||
|
||||
`.../modules/privacy/service/impl/CustomerDialServiceImpl.java`
|
||||
- 注入 `OrderItemMapper`(已有 `OrderMapper`、`UserService`)。
|
||||
- 流程:
|
||||
1. `adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号")`,取 `currentShopId`;`requestThrottleService.checkCustomerDial(...)`。
|
||||
2. 三个定位参数全空 → `BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)")`。
|
||||
3. `appointmentId` 存在:按 `orderItemMapper.selectById` 查 `OrderItemDO`(未删除),否则 `404 预约不存在`;由 `item.orderId` 取 `OrderDO`。
|
||||
4. `orderId` 存在:若上一步已解析订单且不相等 → `403 预约与订单不匹配,或无权拨打`;否则按 `orderMapper.selectById` 取订单。
|
||||
5. 订单存在时:未删除且 `order.shopId == currentShopId`,否则 `403 无权拨打其他店铺预约/订单客户`。
|
||||
6. 客户解析:
|
||||
- `customerId` 非空:加载并校验 `type=0`、未删除;`ensureUserAccessibleInCurrentShop`。
|
||||
- 订单 `userId` 非空且 `customerId` 非空但不相等 → `403 该客户与订单不匹配`;订单 `userId` 为空但传了 `customerId` 同样视为不匹配 → 403。
|
||||
- `customerId` 为空:若订单 `userId` 非空,用订单客户作档案兜底;散客则为 `null`。
|
||||
7. `resolveProvider()` 取渠道,`provider.resolve(customer, order)`,审计 reason 固定包含 `customerId=;appointmentId=;orderId=;provider=;mode=;result=`,不含号码。
|
||||
8. 成功/失败审计沿用 `SecurityAuditSupport`,失败记录 `errorCode`。
|
||||
|
||||
`.../modules/privacy/dial/DirectDialTargetProvider.java`
|
||||
- 号码优先级改为:`order.customerPhoneSnapshot` → `customer.contactPhone` → `customer.phone`。
|
||||
- 注:`OrderDO.customerPhoneSnapshot` 由 `PhoneEncryptionTypeHandler` 读取时已解密,`phoneCrypto.decrypt` 对明文是幂等 no-op,保留调用即可。
|
||||
- 全部为空 → `BusinessException(422, "该预约/订单未登记可拨打的手机号(DIAL_NUMBER_UNAVAILABLE)")`,新增常量 `NUMBER_UNAVAILABLE_CODE = 422`、`NUMBER_UNAVAILABLE_BUSINESS_CODE`。
|
||||
- `DialTargetProvider` / `DialTarget` / 隐私号占位实现保持不变。
|
||||
|
||||
### 2. 控制器
|
||||
|
||||
`.../modules/manager/controller/admin/AdminManagerController.java`
|
||||
- 保留旧端点,参数放宽:
|
||||
- `POST /manager/customers/{customerId}/dial`:`customerId` 路径参数;`orderId`、`appointmentId` 均 `required = false`。
|
||||
- 新增 `POST /manager/customers/dial`:`customerId`、`appointmentId`、`orderId` 全部 `required = false`。
|
||||
- 两个方法均 `@RequirePermission("user:view")`、设置 `Cache-Control: no-store`,调用新 service 签名。
|
||||
|
||||
### 3. 测试
|
||||
|
||||
`JC-Salon-Core/src/test/java/.../modules/privacy/service/impl/CustomerDialServiceImplTest.java`
|
||||
- 适配 5 参数签名与新增 `OrderItemMapper` mock。
|
||||
- 新增断言:
|
||||
- 散客订单(`customerId=null`、`order.userId=null`、订单快照有号)取号成功,号码只来自快照。
|
||||
- `appointmentId` 定位成功(订单项 → 订单)。
|
||||
- `appointmentId` 与 `orderId` 归属不一致 → 403。
|
||||
- 散客无快照且无客户档案 → 422 且含 `DIAL_NUMBER_UNAVAILABLE`。
|
||||
- 现有“登录客户 + 订单”路径保持成功。
|
||||
|
||||
## 二、协议新版本 + 强制重新同意
|
||||
|
||||
### 1. Flyway V19(不改 V18)
|
||||
|
||||
新增 `JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql`:
|
||||
```sql
|
||||
-- 先停用当前生效的两个协议
|
||||
UPDATE t_legal_agreement
|
||||
SET status = 0, update_time = NOW()
|
||||
WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY')
|
||||
AND is_delete = 0 AND status = 1;
|
||||
|
||||
-- 从停用前刚生效的正文复制新版本,不重复维护长文本
|
||||
INSERT INTO t_legal_agreement
|
||||
(id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
|
||||
SELECT 313931273555140005, 'USER_TERMS', title, '2026.11.04-R2', content, 1,
|
||||
'2026-11-04 00:00:00', NOW(), NOW(), 0
|
||||
FROM t_legal_agreement
|
||||
WHERE agreement_type = 'USER_TERMS' AND is_delete = 0
|
||||
ORDER BY effective_time DESC, create_time DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- PRIVACY_POLICY 使用 id 313931273555140006,同样 INSERT ... SELECT
|
||||
```
|
||||
- `id` 显式常量(该表 id 无自增);`version = 2026.11.04-R2`;生效时间为本次修订日期;`status = 1`。
|
||||
- 不修改 `V18__...sql`。
|
||||
|
||||
### 2. 同意机制:复用现有表
|
||||
|
||||
已确认仓库已有 `t_user_agreement_consent`(唯一键 `(user_id, agreement_type, version)`)与 `LegalAgreementServiceImpl.recordConsent/upsertConsent/getMyConsent`,**不新建 `t_user_agreement_acceptance`**。
|
||||
|
||||
`.../modules/system/service/LegalAgreementService.java` 新增:
|
||||
- `AgreementPendingVO getPendingAgreements(Long userId);`
|
||||
- `void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest request);`
|
||||
|
||||
新增 `.../modules/system/vo/AgreementPendingVO.java`:
|
||||
- `Boolean pending`、`Map<String,String> currentVersions`、`Map<String,String> acceptedVersions`、`List<String> pendingTypes`。
|
||||
|
||||
`LegalAgreementServiceImpl`:
|
||||
- `getPendingAgreements`:对 `USER_TERMS` / `PRIVACY_POLICY` 各取 `findCurrentAgreement`,与 `getMyConsent(userId).consentVersions` 比对;缺失或版本不同即 pending。
|
||||
- `acceptCurrentAgreements`:读取两类当前发布版本,按 `upsertConsent(userId, type, version, "agreement-gate", clientType, ip)` 记录,不依赖客户端上报版本。
|
||||
- 保留登录/注册链路现有 `requireAccepted` 不变。
|
||||
|
||||
`.../modules/system/controller/front/LegalAgreementController.java` 新增:
|
||||
- `GET /legal-agreement/pending`:从 request attribute `userId` 取用户,`requestThrottleService.checkAgreementRead(request, "PENDING")`,返回 pending VO。
|
||||
- `POST /legal-agreement/accept`:登录态,可选 body `{clientType}`(默认 `WEB`),记录当前版本同意。
|
||||
- 两个端点**不加入** `WebMvcConfig` 白名单,因此必须登录;`/legal-agreement/current`、`/current/**` 仍免登录,协议阅读页不受影响。
|
||||
|
||||
### 3. 测试
|
||||
|
||||
新增 `JC-Salon-Core/src/test/java/.../modules/system/service/impl/LegalAgreementServiceImplTest.java`:
|
||||
- 无同意记录 → `pending=true`,`pendingTypes` 含两类。
|
||||
- 已同意旧版本、当前版本已变 → `pending=true`。
|
||||
- 已同意当前版本 → `pending=false`。
|
||||
- `acceptCurrentAgreements` 对两类各调用一次 `upsertConsent`(insert/update 均可)。
|
||||
|
||||
## 三、前端与小程序
|
||||
|
||||
### 1. 拨号按钮与参数
|
||||
|
||||
`JC-Salon-Frontend/src/api/user.ts`
|
||||
- `dialCustomer(params: { customerId?: IdType; appointmentId?: IdType; orderId?: IdType })`,调用 `POST /manager/customers/dial`,仅传非空参数。
|
||||
|
||||
`JC-Salon-Frontend/src/views/ArtistOrderView.vue`
|
||||
- 按钮条件:`v-if="order.customerPhoneMasked"`(去掉 `&& order.userId`)。
|
||||
- `dialCustomer(order)`:只要求 `order.id`;调用 `userApi.dialCustomer({ customerId: order.userId || undefined, orderId: order.id })`。
|
||||
|
||||
`JC-Salon-WeChat/api/customers.js`
|
||||
- `dialCustomer(params)`:`POST /manager/customers/dial`,透传 `customerId/appointmentId/orderId`。
|
||||
|
||||
`JC-Salon-WeChat/pages/appointment-detail/index.wxml`
|
||||
- 条件改为 `appointment.customerPhoneAvailable && appointment.orderId`(去掉 `customerId`)。
|
||||
|
||||
`JC-Salon-WeChat/pages/appointment-detail/index.js`
|
||||
- `dialCustomer()` 只要求 `customerPhoneAvailable && orderId`;传 `{ customerId: appointment.customerId, appointmentId: appointment.orderItemId, orderId: appointment.orderId }`。
|
||||
|
||||
### 2. Web 强制同意弹层
|
||||
|
||||
`JC-Salon-Frontend/src/api/auth.ts` 的 `legalAgreementApi` 新增:
|
||||
- `getPending()` → `GET /legal-agreement/pending`
|
||||
- `accept(clientType?)` → `POST /legal-agreement/accept`
|
||||
|
||||
新增 `JC-Salon-Frontend/src/utils/agreement-gate.ts`:
|
||||
- 模块级 `pending` 标志与 `setAgreementPending/isAgreementPending`。
|
||||
|
||||
`JC-Salon-Frontend/src/api/index.ts` 请求拦截器:
|
||||
- 若 `isAgreementPending()` 且 URL 不属于 `/legal-agreement/`、`/admin/auth/`、`/user/logout`,直接 reject 并提示“请先阅读并同意最新版用户协议与隐私政策”。
|
||||
- 不改造鉴权链,只在现有 axios 拦截器加一个前置判断。
|
||||
|
||||
`JC-Salon-Frontend/src/views/admin/AdminLayout.vue`
|
||||
- `onMounted` 调用 `legalAgreementApi.getPending()`;pending 时 `setAgreementPending(true)` 并显示不可关闭的 `a-modal`。
|
||||
- 弹层内链接 `/legal/user-terms.html`、`/legal/privacy-policy.html`(静态页运行时读取后台当前协议)。
|
||||
- “同意并继续”调用 `accept('WEB')`,成功后置 false 并关闭;不提供关闭/取消。
|
||||
|
||||
### 3. 小程序
|
||||
|
||||
- 现有 `app.js` 已在启动时用 `hasMatchingAgreementVersions(preference.agreementVersions, currentVersions)` 比对当前协议版本,不一致即清 session 并跳登录页重新勾选;登录页 `agreementPromptVisible` 弹层与 `agreementPayload()` 会把新版本写入登录请求并记录同意。V19 发布后该链路自动生效,无需改动鉴权链。
|
||||
- `JC-Salon-WeChat/api/auth.js` 增加 `getPendingAgreements()` / `acceptCurrentAgreements(clientType)` 供后续页面使用(本次不改变现有登录流程)。
|
||||
|
||||
## 四、验证
|
||||
|
||||
1. 编译:`mvn -q -DskipTests compile`(`JC-Salon-Core`)。
|
||||
2. 单测:`mvn -q "-Dtest=CustomerDialServiceImplTest,LegalAgreementServiceImplTest,PlanningServiceImplTest,UserServiceCustomerMatchingTest" test`。
|
||||
3. 前端构建:`npm run build`(`JC-Salon-Frontend`)。
|
||||
4. 微信端:`node JC-Salon-WeChat/app-login-flow.test.js`、`node JC-Salon-WeChat/employees-review.test.js`。
|
||||
5. GitNexus:
|
||||
- `impact` 检查 `dial`、`CustomerDialServiceImpl`、`DirectDialTargetProvider`、`LegalAgreementServiceImpl`、`LegalAgreementService`、`AdminManagerController.dialCustomer`、`LegalAgreementController`;`UNKNOWN` 用全仓文本检索交叉确认。
|
||||
- `detect-changes --scope all` 必须非 partial/truncated。
|
||||
6. 提交:仅暂存本次文件,中文提交;`git push origin dev`,非快进先 `git pull --rebase` 重试一次,仍失败原样报错停止。
|
||||
|
||||
## 五、约束与残余风险
|
||||
|
||||
- 不修改 `V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql`。
|
||||
- 不动任何 ArtList 文件,不动 `SystemSettingsView.vue`。
|
||||
- V19 假设库中存在现行协议行(V17 的 `2026.11.04`)。若某环境从未执行 V17/V18,则 `INSERT ... SELECT` 无数据可复制,新版本不会生成;需上线前确认该环境已执行到 V18。
|
||||
- 散客号码优先取订单快照,可能与客户档案最新号码不一致;这是本次明确的产品口径。
|
||||
- Web 同意拦截在 axios 层与弹层实现,属于前端强制;后端灰心接口仍可被直接调用,未改鉴权链。如需服务端硬拦截,后续单独增加受限路径的协议同意拦截器。
|
||||
- 管理员登录本身不携带协议勾选,V19 后首次登录会出现强制同意弹层,属于预期行为。
|
||||
@@ -1,58 +1,147 @@
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **FingertipDesigner** (15270 symbols, 32958 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
|
||||
- **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
|
||||
- **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
|
||||
- MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
|
||||
- **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
|
||||
- **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
|
||||
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER edit a function, class, or method before MCP/CLI impact analysis.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
|
||||
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
|
||||
- NEVER commit changes without running `detect_changes()` to check affected scope.
|
||||
- NEVER commit before MCP/CLI graph change analysis.
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/FingertipDesigner/clusters` | All functional areas |
|
||||
| `gitnexus://repo/FingertipDesigner/processes` | All execution flows |
|
||||
| `gitnexus://repo/FingertipDesigner/process/{name}` | Step-by-step execution trace |
|
||||
| --- | --- |
|
||||
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
|
||||
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
|
||||
| `gitnexus://repo/JayuCloud/process/{name}` | Step-by-step execution trace |
|
||||
|
||||
## CLI
|
||||
|
||||
| Task | Read this skill file |
|
||||
|------|---------------------|
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
|
||||
| --- | --- |
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->
|
||||
|
||||
## Project Workflow Rules
|
||||
|
||||
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
|
||||
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
|
||||
- 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。
|
||||
- 后端修改如果涉及 SQL,不要修改初始化 SQL;必须新增版本变更 SQL。
|
||||
- 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。
|
||||
- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。
|
||||
- Salon Core 的数据库变更必须放在 `JC-Salon-Core/src/main/resources/db/migration/` 下,使用递增的 Flyway 版本文件(如 `V2__功能说明_20261024.sql`);已在任一环境成功执行的迁移文件不得修改或删除。
|
||||
- DEV、SIT、PROD 的数据库迁移由 Core 启动时的 Flyway 自动执行,Gitea 工作流不得直接连接数据库或绕过 Flyway 执行 SQL;合并到 SIT 前必须先在 DEV 验证迁移。
|
||||
- 应用回退不会自动回滚数据库;需要撤销或修正时,必须新增向前兼容的补偿迁移,禁止依赖 Flyway `clean`、自动 baseline 或重新执行初始化 SQL。
|
||||
- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。
|
||||
- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;`scripts/sql/init/FingertipDesigner.sql` 从该版本起冻结为仅空库首次初始化使用,后续 SQL、脚本和配置都必须通过版本迭代文件新增或调整。
|
||||
- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `scripts/0.0.1版本基线与后续迭代规则_20260628.md`,并在任务记录中写明新增或调整的版本化文件。
|
||||
- 当前代码、脚本、配置、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`。
|
||||
|
||||
@@ -1,43 +1,49 @@
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **FingertipDesigner** (15270 symbols, 32958 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
|
||||
- **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
|
||||
- **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
|
||||
- MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
|
||||
- **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
|
||||
- **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
|
||||
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER edit a function, class, or method before MCP/CLI impact analysis.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
|
||||
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
|
||||
- NEVER commit changes without running `detect_changes()` to check affected scope.
|
||||
- NEVER commit before MCP/CLI graph change analysis.
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/FingertipDesigner/clusters` | All functional areas |
|
||||
| `gitnexus://repo/FingertipDesigner/processes` | All execution flows |
|
||||
| `gitnexus://repo/FingertipDesigner/process/{name}` | Step-by-step execution trace |
|
||||
| --- | --- |
|
||||
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
|
||||
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
|
||||
| `gitnexus://repo/JayuCloud/process/{name}` | Step-by-step execution trace |
|
||||
|
||||
## CLI
|
||||
|
||||
| Task | Read this skill file |
|
||||
|------|---------------------|
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
|
||||
| --- | --- |
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->
|
||||
|
||||
## Project Workflow Rules
|
||||
|
||||
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
|
||||
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
|
||||
|
||||
-313
@@ -1,313 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.7.18</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.xiaowang</groupId>
|
||||
<artifactId>FingertipDesigner-Core</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>FingertipDesigner-Core</name>
|
||||
<description>FingertipDesigner-Core-核心业务微服务</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<spring-cloud.version>2021.0.8</spring-cloud.version>
|
||||
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
|
||||
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
|
||||
<druid.version>1.2.23</druid.version>
|
||||
<jwt.version>0.11.5</jwt.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- Web Starter -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Log4j2 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-log4j2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- RabbitMQ -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Nacos Discovery -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Bootstrap for Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- MySQL & Druid & MyBatis-Plus -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>${druid.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- AOP -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Validation -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- JWT -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- BCrypt for password encryption -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-crypto</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Caffeine -->
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Qiniu Kodo primary object storage -->
|
||||
<dependency>
|
||||
<groupId>com.qiniu</groupId>
|
||||
<artifactId>qiniu-java-sdk</artifactId>
|
||||
<version>[7.19.0, 7.19.99]</version>
|
||||
</dependency>
|
||||
|
||||
<!-- MinIO object storage -->
|
||||
<dependency>
|
||||
<groupId>io.minio</groupId>
|
||||
<artifactId>minio</artifactId>
|
||||
<version>8.5.17</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Aliyun OSS backup storage -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>3.18.5</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Lombok -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.32</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- Test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>${spring-cloud-alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<finalName>FingertipDesigner-Core</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-release-jar</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<mkdir dir="${project.basedir}/../docx/product"/>
|
||||
<copy file="${project.build.directory}/${project.build.finalName}.jar"
|
||||
tofile="${project.basedir}/../docx/product/FingertipDesigner-Core.jar"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.32</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@EnableDiscoveryClient
|
||||
@EnableScheduling
|
||||
@SpringBootApplication
|
||||
/**
|
||||
* Purpose: FingertipDesignerCoreApplication supports FingertipDesignerCoreApplication.java by holding or executing the fingertip designer core application business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class FingertipDesignerCoreApplication {
|
||||
|
||||
/**
|
||||
* Purpose: main supports FingertipDesignerCoreApplication.java by holding or executing the main business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(FingertipDesignerCoreApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.annotation;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
/**
|
||||
* Purpose: OperationGuard supports OperationGuard.java by holding or executing the operation guard business role.
|
||||
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public @interface OperationGuard {
|
||||
|
||||
String action();
|
||||
|
||||
OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING;
|
||||
|
||||
int ttlSeconds() default 10;
|
||||
|
||||
String message() default "操作进行中,请勿重复点击";
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
/**
|
||||
* Purpose: RequirePermission supports RequirePermission.java by holding or executing the require permission business role.
|
||||
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public @interface RequirePermission {
|
||||
|
||||
String value() default "";
|
||||
|
||||
int requireUserType() default -1;
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.aspect;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard;
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardService;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.Duration;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@Order(100)
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* Purpose: OperationGuardAspect supports OperationGuardAspect.java by holding or executing the operation guard aspect business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class OperationGuardAspect {
|
||||
|
||||
/**
|
||||
* Purpose: operationGuardService supports OperationGuardAspect.java by holding or executing the operation guard service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final OperationGuardService operationGuardService;
|
||||
|
||||
@Around("@annotation(operationGuard)")
|
||||
/**
|
||||
* Purpose: guardOperation supports OperationGuardAspect.java by holding or executing the guard operation business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (attributes == null) {
|
||||
return Result.error(500, "无法获取请求信息");
|
||||
}
|
||||
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire(
|
||||
request,
|
||||
operationGuard.action(),
|
||||
Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds()))
|
||||
);
|
||||
if (!handle.acquired()) {
|
||||
if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) {
|
||||
return Result.success();
|
||||
}
|
||||
return Result.error(409, operationGuard.message());
|
||||
}
|
||||
|
||||
try {
|
||||
return joinPoint.proceed();
|
||||
} finally {
|
||||
operationGuardService.release(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.aspect;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission;
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.service.PermissionService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionCatalog;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* Purpose: PermissionAspect supports PermissionAspect.java by holding or executing the permission aspect business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class PermissionAspect {
|
||||
|
||||
/**
|
||||
* Purpose: permissionService supports PermissionAspect.java by holding or executing the permission service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final PermissionService permissionService;
|
||||
/**
|
||||
* Purpose: permissionMapper supports PermissionAspect.java by holding or executing the permission mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final PermissionMapper permissionMapper;
|
||||
/**
|
||||
* Purpose: userMapper supports PermissionAspect.java by holding or executing the user mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@Around("@annotation(com.xiaowang.fingertipdesigner.core.annotation.RequirePermission)")
|
||||
/**
|
||||
* Purpose: checkPermission supports PermissionAspect.java by holding or executing the check permission business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (attributes == null) {
|
||||
return Result.error(403, "无法获取请求信息");
|
||||
}
|
||||
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
if (userId == null) {
|
||||
return Result.error(401, "未登录");
|
||||
}
|
||||
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequirePermission requirePermission = method.getAnnotation(RequirePermission.class);
|
||||
if (requirePermission == null) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
if (userDO == null) {
|
||||
return Result.error(404, "用户不存在");
|
||||
}
|
||||
|
||||
String permissionCode = requirePermission.value();
|
||||
Long currentShopId = parseShopId(request.getAttribute("currentShopId"));
|
||||
if (Integer.valueOf(4).equals(userDO.getType())
|
||||
&& currentShopId == null
|
||||
&& StringUtils.hasText(permissionCode)
|
||||
&& !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
|
||||
return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作");
|
||||
}
|
||||
|
||||
if (Integer.valueOf(4).equals(userDO.getType())
|
||||
&& currentShopId == null
|
||||
&& StringUtils.hasText(permissionCode)
|
||||
&& PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
boolean hasPermission = !StringUtils.hasText(permissionCode)
|
||||
|| permissionService.hasPermission(userId, permissionCode);
|
||||
if (!hasPermission) {
|
||||
return Result.error(403, buildPermissionDeniedMessage(permissionCode));
|
||||
}
|
||||
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildPermissionDeniedMessage supports PermissionAspect.java by holding or executing the build permission denied message business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String buildPermissionDeniedMessage(String permissionCode) {
|
||||
if (!StringUtils.hasText(permissionCode)) {
|
||||
return "权限不足";
|
||||
}
|
||||
|
||||
PermissionDO permissionDO = permissionMapper.selectOne(
|
||||
Wrappers.lambdaQuery(PermissionDO.class)
|
||||
.eq(PermissionDO::getPermissionCode, permissionCode)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) {
|
||||
return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")";
|
||||
}
|
||||
return "权限不足:缺少权限代码 " + permissionCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: parseShopId supports PermissionAspect.java by holding or executing the parse shop id business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Long parseShopId(Object value) {
|
||||
if (value instanceof Number number) {
|
||||
long shopId = number.longValue();
|
||||
return shopId > 0 ? shopId : null;
|
||||
}
|
||||
if (value instanceof String text && StringUtils.hasText(text)) {
|
||||
try {
|
||||
long shopId = Long.parseLong(text.trim());
|
||||
return shopId > 0 ? shopId : null;
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.common;
|
||||
|
||||
/**
|
||||
* 业务异常。
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
/**
|
||||
* Purpose: code supports BusinessException.java by holding or executing the code business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final Integer code;
|
||||
|
||||
public BusinessException(String message) {
|
||||
this(500, message);
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public BusinessException(String message, Throwable cause) {
|
||||
this(500, message, cause);
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getCode supports BusinessException.java by holding or executing the get code business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.common;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
|
||||
/**
|
||||
* 全局异常处理器。
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* Purpose: MAX_UPLOAD_SIZE_BYTES supports GlobalExceptionHandler.java by holding or executing the max upload size bytes business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024;
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
/**
|
||||
* Purpose: handleMethodArgumentNotValidException supports GlobalExceptionHandler.java by holding or executing the handle method argument not valid exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
String message = e.getBindingResult().getAllErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.findFirst()
|
||||
.orElse("请求参数不合法");
|
||||
return Result.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(BindException.class)
|
||||
/**
|
||||
* Purpose: handleBindException supports GlobalExceptionHandler.java by holding or executing the handle bind exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleBindException(BindException e) {
|
||||
String message = e.getBindingResult().getAllErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.findFirst()
|
||||
.orElse("请求参数不合法");
|
||||
return Result.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
/**
|
||||
* Purpose: handleConstraintViolationException supports GlobalExceptionHandler.java by holding or executing the handle constraint violation exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
|
||||
String message = e.getConstraintViolations().stream()
|
||||
.map(violation -> violation.getMessage())
|
||||
.findFirst()
|
||||
.orElse("请求参数不合法");
|
||||
return Result.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
/**
|
||||
* Purpose: handleMaxUploadSizeExceededException supports GlobalExceptionHandler.java by holding or executing the handle max upload size exceeded exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
|
||||
log.warn("上传文件超过限制: {}", e.getMessage());
|
||||
return Result.error(buildUploadLimitMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MultipartException.class)
|
||||
/**
|
||||
* Purpose: handleMultipartException supports GlobalExceptionHandler.java by holding or executing the handle multipart exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleMultipartException(MultipartException e) {
|
||||
log.warn("文件上传请求异常: {}", e.getMessage());
|
||||
return Result.error(buildUploadLimitMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
/**
|
||||
* Purpose: handleIllegalStateException supports GlobalExceptionHandler.java by holding or executing the handle illegal state exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleIllegalStateException(IllegalStateException e) {
|
||||
if (isUploadLimitException(e)) {
|
||||
log.warn("上传文件超过限制: {}", e.getMessage());
|
||||
return Result.error(buildUploadLimitMessage());
|
||||
}
|
||||
log.error("非法状态异常", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
/**
|
||||
* Purpose: handleBusinessException supports GlobalExceptionHandler.java by holding or executing the handle business exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleBusinessException(BusinessException e) {
|
||||
log.warn("业务异常: {}", e.getMessage());
|
||||
return Result.error(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
/**
|
||||
* Purpose: handleRuntimeException supports GlobalExceptionHandler.java by holding or executing the handle runtime exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleRuntimeException(RuntimeException e) {
|
||||
log.error("运行时异常", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
/**
|
||||
* Purpose: handleException supports GlobalExceptionHandler.java by holding or executing the handle exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<Void> handleException(Exception e) {
|
||||
log.error("系统异常", e);
|
||||
return Result.error("系统繁忙,请稍后再试");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildUploadLimitMessage supports GlobalExceptionHandler.java by holding or executing the build upload limit message business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String buildUploadLimitMessage() {
|
||||
return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB";
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isUploadLimitException supports GlobalExceptionHandler.java by holding or executing the is upload limit exception business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean isUploadLimitException(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
String message = current.getMessage();
|
||||
if (message != null && (message.contains("maximum permitted size")
|
||||
|| message.contains("FileSizeLimitExceededException")
|
||||
|| message.contains("exceeds its maximum permitted size"))) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.common;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 统一响应结果类
|
||||
*
|
||||
* @param <T> 数据类型
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Result<T> implements Serializable {
|
||||
|
||||
/**
|
||||
* Purpose: code supports Result.java by holding or executing the code business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Integer code;
|
||||
/**
|
||||
* Purpose: message supports Result.java by holding or executing the message business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String message;
|
||||
/**
|
||||
* Purpose: data supports Result.java by holding or executing the data business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* Purpose: success supports Result.java by holding or executing the success business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static <T> Result<T> success() {
|
||||
return new Result<>(200, "操作成功", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: success supports Result.java by holding or executing the success business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static <T> Result<T> success(T data) {
|
||||
return new Result<>(200, "操作成功", data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: error supports Result.java by holding or executing the error business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static <T> Result<T> error(String message) {
|
||||
return new Result<>(500, message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: error supports Result.java by holding or executing the error business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static <T> Result<T> error(Integer code, String message) {
|
||||
return new Result<>(code, message, null);
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.common.dto;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Purpose: AgreementAwareRequest supports AgreementAwareRequest.java by holding or executing the agreement aware request business role.
|
||||
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public interface AgreementAwareRequest {
|
||||
|
||||
Boolean getAgreementAccepted();
|
||||
|
||||
Map<String, String> getAgreementVersions();
|
||||
|
||||
String getClientType();
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.common.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 实体类基类
|
||||
* 提取公共字段,方便后续实体类扩展
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Data
|
||||
public abstract class BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.common.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
/**
|
||||
* PageResultVO is a response VO. Services build it and controllers return it to the frontend.
|
||||
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
|
||||
*/
|
||||
public class PageResultVO<T> {
|
||||
/**
|
||||
* Field `list` (List<T>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private List<T> list;
|
||||
/**
|
||||
* Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long total;
|
||||
/**
|
||||
* Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer page;
|
||||
/**
|
||||
* Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer size;
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 多级缓存配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.cache")
|
||||
public class AppCacheProperties {
|
||||
|
||||
/**
|
||||
* Purpose: localMaxSize supports AppCacheProperties.java by holding or executing the local max size business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long localMaxSize = 2048;
|
||||
|
||||
private CacheSpec productDetail = new CacheSpec(120, 900);
|
||||
|
||||
private CacheSpec productList = new CacheSpec(60, 300);
|
||||
|
||||
private CacheSpec productSearch = new CacheSpec(60, 300);
|
||||
|
||||
private CacheSpec shop = new CacheSpec(180, 900);
|
||||
|
||||
private CacheSpec tag = new CacheSpec(300, 1200);
|
||||
|
||||
private CacheSpec objectStorageFile = new CacheSpec(300, 1800);
|
||||
|
||||
private CacheSpec dashboard = new CacheSpec(30, 90);
|
||||
|
||||
@Data
|
||||
/**
|
||||
* Purpose: CacheSpec supports AppCacheProperties.java by holding or executing the cache spec business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static class CacheSpec {
|
||||
/**
|
||||
* Purpose: localTtlSeconds supports AppCacheProperties.java by holding or executing the local ttl seconds business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long localTtlSeconds;
|
||||
/**
|
||||
* Purpose: redisTtlSeconds supports AppCacheProperties.java by holding or executing the redis ttl seconds business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long redisTtlSeconds;
|
||||
|
||||
public CacheSpec() {
|
||||
}
|
||||
|
||||
public CacheSpec(long localTtlSeconds, long redisTtlSeconds) {
|
||||
this.localTtlSeconds = localTtlSeconds;
|
||||
this.redisTtlSeconds = redisTtlSeconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
-230
@@ -1,230 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.support.RequestShopContext;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.RequestSignatureService;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService;
|
||||
import com.xiaowang.fingertipdesigner.core.utils.JwtUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* Purpose: AuthInterceptor supports AuthInterceptor.java by holding or executing the auth interceptor business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
/**
|
||||
* Purpose: jwtUtil supports AuthInterceptor.java by holding or executing the jwt util business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final JwtUtil jwtUtil;
|
||||
/**
|
||||
* Purpose: userMapper supports AuthInterceptor.java by holding or executing the user mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final UserMapper userMapper;
|
||||
/**
|
||||
* Purpose: userShopBindingSupport supports AuthInterceptor.java by holding or executing the user shop binding support business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
/**
|
||||
* Purpose: userSessionService supports AuthInterceptor.java by holding or executing the user session service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final UserSessionService userSessionService;
|
||||
/**
|
||||
* Purpose: requestSignatureService supports AuthInterceptor.java by holding or executing the request signature service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final RequestSignatureService requestSignatureService;
|
||||
/**
|
||||
* Purpose: requestThrottleService supports AuthInterceptor.java by holding or executing the request throttle service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
|
||||
/**
|
||||
* Purpose: AUTHORIZATION_HEADER supports AuthInterceptor.java by holding or executing the authorization header business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
/**
|
||||
* Purpose: BEARER_PREFIX supports AuthInterceptor.java by holding or executing the bearer prefix business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: preHandle supports AuthInterceptor.java by holding or executing the pre handle business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String path = request.getRequestURI();
|
||||
|
||||
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
|
||||
|
||||
if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":401,\"message\":\"未提供认证Token\"}");
|
||||
return false;
|
||||
}
|
||||
|
||||
String token = authHeader.substring(BEARER_PREFIX.length());
|
||||
|
||||
if (!jwtUtil.validateToken(token)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!jwtUtil.isAccessToken(token)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误");
|
||||
return false;
|
||||
}
|
||||
|
||||
Long userId = jwtUtil.getUserIdFromToken(token);
|
||||
String account = jwtUtil.getAccountFromToken(token);
|
||||
Long currentShopId = jwtUtil.getShopIdFromToken(token);
|
||||
String sessionId = jwtUtil.getSessionIdFromToken(token);
|
||||
String jti = jwtUtil.getJtiFromToken(token);
|
||||
if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录");
|
||||
return false;
|
||||
}
|
||||
|
||||
UserDO currentUser = userMapper.selectById(userId);
|
||||
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (currentUser.getStatus() != null && !Integer.valueOf(1).equals(currentUser.getStatus())) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "账号已被禁用");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean adminPath = isAdminPath(path);
|
||||
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
|
||||
userId,
|
||||
currentShopId,
|
||||
adminPath,
|
||||
currentUser.getType()
|
||||
);
|
||||
if (!canAccessShop) {
|
||||
String message = currentShopId == null || currentShopId <= 0
|
||||
? "当前登录未选择可用店铺,请重新登录"
|
||||
: (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId)
|
||||
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
|
||||
? "店铺已被冻结"
|
||||
: "当前登录店铺已停用或账号已失去该店铺访问权限");
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (adminPath
|
||||
&& !Integer.valueOf(4).equals(currentUser.getType())
|
||||
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
|
||||
&& !isExpiredAdminAllowedPath(path)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requiresSignature(request)) {
|
||||
try {
|
||||
requestSignatureService.validateRequest(request, token, userId);
|
||||
} catch (RuntimeException exception) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (requiresWriteRateLimit(request)) {
|
||||
try {
|
||||
requestThrottleService.checkAuthenticatedWrite(request, userId);
|
||||
} catch (RuntimeException exception) {
|
||||
writeJsonResponse(response, 429, exception.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
request.setAttribute("userId", userId);
|
||||
request.setAttribute("account", account);
|
||||
request.setAttribute("userType", currentUser.getType());
|
||||
request.setAttribute("accessToken", token);
|
||||
request.setAttribute("sessionId", sessionId);
|
||||
request.setAttribute("tokenJti", jti);
|
||||
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: requiresSignature supports AuthInterceptor.java by holding or executing the requires signature business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean requiresSignature(HttpServletRequest request) {
|
||||
return requiresWriteRateLimit(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: requiresWriteRateLimit supports AuthInterceptor.java by holding or executing the requires write rate limit business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean requiresWriteRateLimit(HttpServletRequest request) {
|
||||
String method = request.getMethod();
|
||||
if (!StringUtils.hasText(method)) {
|
||||
return false;
|
||||
}
|
||||
String normalized = method.toUpperCase();
|
||||
return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized));
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isAdminPath supports AuthInterceptor.java by holding or executing the is admin path business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean isAdminPath(String path) {
|
||||
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean isExpiredAdminAllowedPath(String path) {
|
||||
return path.startsWith("/admin/auth/")
|
||||
|| path.equals("/admin/user/info")
|
||||
|| path.equals("/permission/list/user/current")
|
||||
|| path.equals("/api/permission/list/user/current")
|
||||
|| path.startsWith("/admin/planning/")
|
||||
|| path.startsWith("/admin/shops/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception {
|
||||
response.setStatus(status);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}");
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 平台品牌文案配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.brand")
|
||||
public class BrandProperties {
|
||||
|
||||
/**
|
||||
* 短信模板中的平台名称。
|
||||
*/
|
||||
private String messageTemplateName = "FingertipDesigner";
|
||||
|
||||
/**
|
||||
* 管理师注册店铺的默认描述。
|
||||
*/
|
||||
private String managerRegisterShopDescription = "甲屿店务注册店铺";
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Configuration
|
||||
/**
|
||||
* Purpose: HttpClientConfig supports HttpClientConfig.java by holding or executing the http client config business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class HttpClientConfig {
|
||||
|
||||
@Bean
|
||||
/**
|
||||
* Purpose: poolingHttpClientConnectionManager supports HttpClientConfig.java by holding or executing the pooling http client connection manager business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(HttpClientProperties properties) {
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
|
||||
connectionManager.setMaxTotal(properties.getMaxTotalConnections());
|
||||
connectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute());
|
||||
return connectionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate(HttpClientProperties properties,
|
||||
PoolingHttpClientConnectionManager connectionManager) {
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(properties.getConnectTimeoutMs())
|
||||
.setSocketTimeout(properties.getReadTimeoutMs())
|
||||
.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs())
|
||||
.build();
|
||||
CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.disableCookieManagement()
|
||||
.evictIdleConnections(30, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
requestFactory.setConnectTimeout(properties.getConnectTimeoutMs());
|
||||
requestFactory.setReadTimeout(properties.getReadTimeoutMs());
|
||||
requestFactory.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs());
|
||||
return new RestTemplate(requestFactory);
|
||||
}
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.http-client")
|
||||
/**
|
||||
* Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class HttpClientProperties {
|
||||
|
||||
/**
|
||||
* Purpose: connectTimeoutMs supports HttpClientProperties.java by holding or executing the connect timeout ms business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int connectTimeoutMs = 3000;
|
||||
|
||||
/**
|
||||
* Purpose: readTimeoutMs supports HttpClientProperties.java by holding or executing the read timeout ms business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int readTimeoutMs = 5000;
|
||||
|
||||
/**
|
||||
* Purpose: connectionRequestTimeoutMs supports HttpClientProperties.java by holding or executing the connection request timeout ms business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int connectionRequestTimeoutMs = 1000;
|
||||
|
||||
/**
|
||||
* Purpose: maxTotalConnections supports HttpClientProperties.java by holding or executing the max total connections business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int maxTotalConnections = 200;
|
||||
|
||||
/**
|
||||
* Purpose: maxConnectionsPerRoute supports HttpClientProperties.java by holding or executing the max connections per route business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int maxConnectionsPerRoute = 50;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.io.IOException;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Configuration
|
||||
/**
|
||||
* Purpose: JacksonConfig supports JacksonConfig.java by holding or executing the jackson config business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class JacksonConfig {
|
||||
|
||||
@Bean
|
||||
/**
|
||||
* Purpose: longToStringJacksonCustomizer supports JacksonConfig.java by holding or executing the long to string jackson customizer business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
|
||||
return builder -> {
|
||||
// Snowflake IDs are serialized as strings so the web and mini program do not lose precision.
|
||||
builder.serializerByType(Long.class, ToStringSerializer.instance);
|
||||
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
|
||||
|
||||
JavaTimeModule javaTimeModule = new JavaTimeModule();
|
||||
javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer());
|
||||
builder.modules(javaTimeModule);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: FlexibleLocalDateTimeDeserializer supports JacksonConfig.java by holding or executing the flexible local date time deserializer business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
|
||||
private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: deserialize supports JacksonConfig.java by holding or executing the deserialize business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||
String value = parser.getValueAsString();
|
||||
if (value == null || value.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String normalized = value.trim();
|
||||
if (normalized.contains("T")) {
|
||||
return LocalDateTime.parse(normalized);
|
||||
}
|
||||
return LocalDateTime.parse(normalized, SPACE_FORMATTER);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* JWT 配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.security.jwt")
|
||||
public class JwtProperties {
|
||||
|
||||
/**
|
||||
* HS512 密钥,生产环境请通过 Nacos 覆盖。
|
||||
*/
|
||||
private String secret = "fingertip-designer-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
|
||||
|
||||
/**
|
||||
* Token 发行者。
|
||||
*/
|
||||
private String issuer = "fingertip-designer";
|
||||
|
||||
/**
|
||||
* AccessToken 有效期,单位秒。
|
||||
*/
|
||||
private long accessTokenExpirationSeconds = 2 * 60 * 60;
|
||||
|
||||
/**
|
||||
* 记住登录 AccessToken 有效期,单位秒。
|
||||
*/
|
||||
private long rememberMeAccessTokenExpirationSeconds = 7 * 24 * 60 * 60;
|
||||
|
||||
/**
|
||||
* RefreshToken 有效期,单位秒。
|
||||
*/
|
||||
private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60;
|
||||
|
||||
/**
|
||||
* 时钟偏移容忍,单位秒。
|
||||
*/
|
||||
private long clockSkewSeconds = 30;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.security.login-lock")
|
||||
/**
|
||||
* Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class LoginLockProperties {
|
||||
|
||||
/**
|
||||
* Purpose: maxFailures supports LoginLockProperties.java by holding or executing the max failures business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int maxFailures = 5;
|
||||
|
||||
/**
|
||||
* Purpose: windowSeconds supports LoginLockProperties.java by holding or executing the window seconds business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long windowSeconds = 600;
|
||||
|
||||
/**
|
||||
* Purpose: lockSeconds supports LoginLockProperties.java by holding or executing the lock seconds business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long lockSeconds = 900;
|
||||
}
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus配置类
|
||||
* 配置分页、乐观锁和防止全表更新等插件
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Configuration
|
||||
@MapperScan({
|
||||
"com.xiaowang.fingertipdesigner.core.modules.artist.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.auth.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.content.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.file.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.integration.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.inventory.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.marketing.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.message.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.order.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.payment.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.planning.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.product.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.security.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.shop.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.system.mapper",
|
||||
"com.xiaowang.fingertipdesigner.core.modules.user.mapper"
|
||||
})
|
||||
public class MyBatisPlusConfig {
|
||||
|
||||
/**
|
||||
* 配置MyBatis-Plus插件
|
||||
*/
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
|
||||
// 1. 分页插件
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
|
||||
// 2. 乐观锁插件
|
||||
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
|
||||
|
||||
// 3. 防止全表更新与删除插件
|
||||
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
/**
|
||||
* Purpose: identifierGenerator supports MyBatisPlusConfig.java by holding or executing the identifier generator business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
|
||||
return new IdentifierGenerator() {
|
||||
@Override
|
||||
/**
|
||||
* Purpose: nextId supports MyBatisPlusConfig.java by holding or executing the next id business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Number nextId(Object entity) {
|
||||
return snowflakeIdGenerator.nextId();
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: nextUUID supports MyBatisPlusConfig.java by holding or executing the next uuid business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public String nextUUID(Object entity) {
|
||||
return snowflakeIdGenerator.nextIdString();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus 自动填充配置
|
||||
* 用于自动填充实体类中的创建时间、更新时间等字段
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: insertFill supports MyMetaObjectHandler.java by holding or executing the insert fill business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
log.info("start insert fill ....");
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: updateFill supports MyMetaObjectHandler.java by holding or executing the update fill business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
log.info("start update fill ....");
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@Validated
|
||||
@ConfigurationProperties(prefix = "object-storage")
|
||||
public class ObjectStorageProperties {
|
||||
|
||||
@NotEmpty
|
||||
private List<String> providerOrder = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS");
|
||||
|
||||
@NotEmpty
|
||||
private List<String> replicaRequiredProviders = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS");
|
||||
|
||||
private String primaryProvider;
|
||||
|
||||
private String backupProvider;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer signedUrlExpireMinutes;
|
||||
|
||||
@NotBlank
|
||||
private String backupQueueName;
|
||||
|
||||
@NotBlank
|
||||
private String backupExchangeName;
|
||||
|
||||
@NotBlank
|
||||
private String backupRoutingKey;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer backupRetryBatchLimit;
|
||||
|
||||
@NotBlank
|
||||
private String backupRetryCron;
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.amqp.core.Binding;
|
||||
import org.springframework.amqp.core.BindingBuilder;
|
||||
import org.springframework.amqp.core.DirectExchange;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
|
||||
import org.springframework.amqp.support.converter.MessageConverter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class RabbitMQConfig {
|
||||
|
||||
public static final String EXAMPLE_QUEUE = "fingertip-designer.example.queue";
|
||||
public static final String EXAMPLE_EXCHANGE = "fingertip-designer.example.exchange";
|
||||
public static final String EXAMPLE_ROUTING_KEY = "fingertip-designer.example.routing.key";
|
||||
|
||||
private final ObjectStorageProperties objectStorageProperties;
|
||||
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter() {
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue exampleQueue() {
|
||||
return new Queue(EXAMPLE_QUEUE, true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DirectExchange exampleExchange() {
|
||||
return new DirectExchange(EXAMPLE_EXCHANGE);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding exampleBinding() {
|
||||
return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue objectStorageBackupQueue() {
|
||||
return new Queue(objectStorageProperties.getBackupQueueName(), true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DirectExchange objectStorageBackupExchange() {
|
||||
return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding objectStorageBackupBinding() {
|
||||
return BindingBuilder.bind(objectStorageBackupQueue())
|
||||
.to(objectStorageBackupExchange())
|
||||
.with(objectStorageProperties.getBackupRoutingKey());
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 限流配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.security.rate-limit")
|
||||
public class RateLimitProperties {
|
||||
|
||||
private LimitRule login = new LimitRule(10, 60);
|
||||
|
||||
private LimitRule register = new LimitRule(5, 300);
|
||||
|
||||
private LimitRule sendCode = new LimitRule(5, 60);
|
||||
|
||||
private LimitRule resetPassword = new LimitRule(5, 600);
|
||||
|
||||
private LimitRule wechatMiniLogin = new LimitRule(10, 60);
|
||||
|
||||
private LimitRule agreementRead = new LimitRule(60, 60);
|
||||
|
||||
private LimitRule authenticatedWrite = new LimitRule(80, 60);
|
||||
|
||||
private LimitRule orderCreate = new LimitRule(10, 60);
|
||||
|
||||
@Data
|
||||
/**
|
||||
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static class LimitRule {
|
||||
/**
|
||||
* Purpose: limit supports RateLimitProperties.java by holding or executing the limit business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private int limit;
|
||||
/**
|
||||
* Purpose: windowSeconds supports RateLimitProperties.java by holding or executing the window seconds business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long windowSeconds;
|
||||
|
||||
public LimitRule() {
|
||||
}
|
||||
|
||||
public LimitRule(int limit, long windowSeconds) {
|
||||
this.limit = limit;
|
||||
this.windowSeconds = windowSeconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
|
||||
import org.springframework.cache.annotation.CachingConfigurerSupport;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/**
|
||||
* Redis配置类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class RedisConfig extends CachingConfigurerSupport {
|
||||
|
||||
@Bean
|
||||
/**
|
||||
* Purpose: redisTemplate supports RedisConfig.java by holding or executing the redis template business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(factory);
|
||||
|
||||
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(om);
|
||||
|
||||
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
|
||||
|
||||
// key采用String的序列化方式
|
||||
template.setKeySerializer(stringRedisSerializer);
|
||||
// hash的key也采用String的序列化方式
|
||||
template.setHashKeySerializer(stringRedisSerializer);
|
||||
// value序列化方式采用jackson
|
||||
template.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
// hash的value序列化方式采用jackson
|
||||
template.setHashValueSerializer(jackson2JsonRedisSerializer);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
return template;
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 请求签名配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.security.signature")
|
||||
public class RequestSignatureProperties {
|
||||
|
||||
/**
|
||||
* 是否启用签名校验。
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* 时间窗口,单位秒。
|
||||
*/
|
||||
private long windowSeconds = 300;
|
||||
|
||||
/**
|
||||
* nonce 额外保留时间,单位秒。
|
||||
*/
|
||||
private long nonceRetentionSeconds = 600;
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
/**
|
||||
* Purpose: SecurityHeadersFilter supports SecurityHeadersFilter.java by holding or executing the security headers filter business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class SecurityHeadersFilter implements Filter {
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: doFilter supports SecurityHeadersFilter.java by holding or executing the do filter business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
if (response instanceof HttpServletResponse httpResponse) {
|
||||
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
|
||||
httpResponse.setHeader("X-Frame-Options", "DENY");
|
||||
httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||
httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:");
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.slow-request")
|
||||
/**
|
||||
* Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class SlowRequestLogProperties {
|
||||
|
||||
/**
|
||||
* Purpose: enabled supports SlowRequestLogProperties.java by holding or executing the enabled business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* Purpose: thresholdMs supports SlowRequestLogProperties.java by holding or executing the threshold ms business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long thresholdMs = 300;
|
||||
|
||||
/**
|
||||
* Purpose: logResponseHeaderRequestId supports SlowRequestLogProperties.java by holding or executing the log response header request id business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean logResponseHeaderRequestId = true;
|
||||
}
|
||||
-172
@@ -1,172 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
/**
|
||||
* Purpose: SlowRequestLoggingInterceptor supports SlowRequestLoggingInterceptor.java by holding or executing the slow request logging interceptor business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class SlowRequestLoggingInterceptor implements HandlerInterceptor {
|
||||
|
||||
/**
|
||||
* Purpose: REQUEST_ID_HEADER supports SlowRequestLoggingInterceptor.java by holding or executing the request id header business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
|
||||
private static final String START_TIME_ATTRIBUTE = SlowRequestLoggingInterceptor.class.getName() + ".startTime";
|
||||
private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("core-slow");
|
||||
|
||||
/**
|
||||
* Purpose: properties supports SlowRequestLoggingInterceptor.java by holding or executing the properties business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final SlowRequestLogProperties properties;
|
||||
|
||||
public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: preHandle supports SlowRequestLoggingInterceptor.java by holding or executing the pre handle business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
String requestId = resolveRequestId(request);
|
||||
request.setAttribute(REQUEST_ID_HEADER, requestId);
|
||||
if (properties.isLogResponseHeaderRequestId()) {
|
||||
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
}
|
||||
if (properties.isEnabled()) {
|
||||
request.setAttribute(START_TIME_ATTRIBUTE, System.nanoTime());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: afterCompletion supports SlowRequestLoggingInterceptor.java by holding or executing the after completion business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
|
||||
if (!properties.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
Object startTimeValue = request.getAttribute(START_TIME_ATTRIBUTE);
|
||||
if (!(startTimeValue instanceof Long)) {
|
||||
return;
|
||||
}
|
||||
|
||||
long durationMs = Math.max(0L, (System.nanoTime() - (Long) startTimeValue) / 1_000_000L);
|
||||
if (durationMs < properties.getThresholdMs()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String requestId = (String) request.getAttribute(REQUEST_ID_HEADER);
|
||||
String bestMatchingPattern = toStringValue(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
|
||||
String controllerMethod = resolveControllerMethod(handler);
|
||||
String exceptionClass = ex == null ? "" : ex.getClass().getSimpleName();
|
||||
|
||||
SLOW_REQUEST_LOGGER.warn(
|
||||
"requestId={} method={} uri={} query={} bestMatchingPattern={} controllerMethod={} status={} durationMs={} userId={} userType={} shopId={} clientIp={} contentLength={} exceptionClass={}",
|
||||
sanitize(requestId),
|
||||
request.getMethod(),
|
||||
request.getRequestURI(),
|
||||
sanitize(request.getQueryString()),
|
||||
sanitize(bestMatchingPattern),
|
||||
sanitize(controllerMethod),
|
||||
response.getStatus(),
|
||||
durationMs,
|
||||
castLong(request.getAttribute("userId")),
|
||||
castInteger(request.getAttribute("userType")),
|
||||
castLong(request.getAttribute("currentShopId")),
|
||||
resolveClientIp(request),
|
||||
request.getContentLengthLong(),
|
||||
sanitize(exceptionClass)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveRequestId supports SlowRequestLoggingInterceptor.java by holding or executing the resolve request id business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String resolveRequestId(HttpServletRequest request) {
|
||||
String requestId = request.getHeader(REQUEST_ID_HEADER);
|
||||
return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveControllerMethod supports SlowRequestLoggingInterceptor.java by holding or executing the resolve controller method business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String resolveControllerMethod(Object handler) {
|
||||
if (handler instanceof HandlerMethod handlerMethod) {
|
||||
return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveClientIp supports SlowRequestLoggingInterceptor.java by holding or executing the resolve client ip business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String resolveClientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.hasText(forwarded)) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
if (StringUtils.hasText(realIp)) {
|
||||
return realIp.trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sanitize supports SlowRequestLoggingInterceptor.java by holding or executing the sanitize business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String sanitize(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
return value.replace('\n', '_').replace('\r', '_');
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toStringValue supports SlowRequestLoggingInterceptor.java by holding or executing the to string value business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String toStringValue(Object value) {
|
||||
return value == null ? "" : value.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: castLong supports SlowRequestLoggingInterceptor.java by holding or executing the cast long business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Long castLong(Object value) {
|
||||
return value instanceof Long ? (Long) value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: castInteger supports SlowRequestLoggingInterceptor.java by holding or executing the cast integer business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Integer castInteger(Object value) {
|
||||
return value instanceof Integer ? (Integer) value : null;
|
||||
}
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.security.upload")
|
||||
/**
|
||||
* Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class UploadSecurityProperties {
|
||||
|
||||
/**
|
||||
* Purpose: maxSize supports UploadSecurityProperties.java by holding or executing the max size business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private long maxSize = 10 * 1024 * 1024;
|
||||
|
||||
private long maxTotalSize = 500L * 1024 * 1024;
|
||||
|
||||
private List<String> allowedMimeTypes = new ArrayList<>(List.of(
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/gif"
|
||||
));
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* Purpose: WebMvcConfig supports WebMvcConfig.java by holding or executing the web mvc config business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
/**
|
||||
* Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final AuthInterceptor authInterceptor;
|
||||
/**
|
||||
* Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(slowRequestLoggingInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(-100);
|
||||
|
||||
registry.addInterceptor(authInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(0)
|
||||
.excludePathPatterns(
|
||||
"/user/login",
|
||||
"/user/register",
|
||||
"/user/check/**",
|
||||
"/user/refresh-token",
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/wechat-mini/**",
|
||||
"/user/reset-password-by-phone",
|
||||
"/legal-agreement/current",
|
||||
"/legal-agreement/current/**",
|
||||
"/api/legal-agreement/current",
|
||||
"/api/legal-agreement/current/**",
|
||||
"/product/get/**",
|
||||
"/product/list/**",
|
||||
"/comment/list/product/**",
|
||||
"/api/comment/list/product/**",
|
||||
"/nail-artist/profile/**",
|
||||
"/nail-artist/*/availability",
|
||||
"/nail-artist/*/reviews",
|
||||
"/shop/get/**",
|
||||
"/shop/trust-profile/**",
|
||||
"/shop/list",
|
||||
"/shop/list/public",
|
||||
"/shop/list/simple",
|
||||
"/tag/list/all",
|
||||
"/tag/list/filter-options",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/login-shops/**",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
);
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 微信小程序登录配置。
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "fingertip-designer.wechat.mini")
|
||||
public class WechatMiniProperties {
|
||||
|
||||
/**
|
||||
* Purpose: appId supports WechatMiniProperties.java by holding or executing the app id business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String appId;
|
||||
/**
|
||||
* Purpose: appSecret supports WechatMiniProperties.java by holding or executing the app secret business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String appSecret;
|
||||
/**
|
||||
* Purpose: code2sessionUrl supports WechatMiniProperties.java by holding or executing the code2session url business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
|
||||
/**
|
||||
* Purpose: phoneNumberUrl supports WechatMiniProperties.java by holding or executing the phone number url business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
|
||||
/**
|
||||
* Purpose: accessTokenBufferSeconds supports WechatMiniProperties.java by holding or executing the access token buffer seconds business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Integer accessTokenBufferSeconds = 60;
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.filter;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.CachedBodyHttpServletRequest;
|
||||
import com.xiaowang.fingertipdesigner.core.support.security.RequestSignatureService;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 缓存 JSON 请求体,供签名校验复用。
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestBodyCacheFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
if (!shouldWrap(request)) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] body = StreamUtils.copyToByteArray(request.getInputStream());
|
||||
CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body);
|
||||
wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body);
|
||||
filterChain.doFilter(wrappedRequest, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: shouldWrap supports RequestBodyCacheFilter.java by holding or executing the should wrap business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean shouldWrap(HttpServletRequest request) {
|
||||
String method = request.getMethod();
|
||||
if (!StringUtils.hasText(method)) {
|
||||
return false;
|
||||
}
|
||||
String normalizedMethod = method.toUpperCase();
|
||||
if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) {
|
||||
return false;
|
||||
}
|
||||
String contentType = request.getContentType();
|
||||
if (!StringUtils.hasText(contentType)) {
|
||||
return false;
|
||||
}
|
||||
String normalizedType = contentType.toLowerCase();
|
||||
return normalizedType.contains("application/json");
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.analytics.controller.admin;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission;
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.service.WorkbenchService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.StoreWorkbenchVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/workbench")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminWorkbenchController {
|
||||
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final WorkbenchService workbenchService;
|
||||
|
||||
@GetMapping("/summary")
|
||||
@RequirePermission("workbench:view")
|
||||
public Result<StoreWorkbenchVO> summary(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
Long artistId = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
|
||||
return Result.success(workbenchService.getWorkbench(shopId, artistId));
|
||||
}
|
||||
}
|
||||
-451
@@ -1,451 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.analytics.controller.front;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission;
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.content.entity.CommentDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.content.mapper.CommentMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.service.OperationsAnalyticsService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.DashboardStatsVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.vo.HotProductVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.RecentActivityVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/dashboard")
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
|
||||
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
|
||||
*/
|
||||
public class DashboardController {
|
||||
/**
|
||||
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final UserMapper userMapper;
|
||||
/**
|
||||
* Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ProductMapper productMapper;
|
||||
/**
|
||||
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ShopMapper shopMapper;
|
||||
/**
|
||||
* Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final CommentMapper commentMapper;
|
||||
/**
|
||||
* Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final OrderMapper orderMapper;
|
||||
/**
|
||||
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
/**
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
/**
|
||||
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
/**
|
||||
* Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final MultiLevelCacheService multiLevelCacheService;
|
||||
/**
|
||||
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
private final OperationsAnalyticsService operationsAnalyticsService;
|
||||
|
||||
@GetMapping("/stats")
|
||||
@RequirePermission("dashboard:view")
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<DashboardStatsVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<DashboardStatsVO> getDashboardStats(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
Long shopIdScope = resolveShopScope(currentUser);
|
||||
String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope);
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
|
||||
DashboardStatsVO stats = multiLevelCacheService.getOrLoad(
|
||||
"cache:dashboard:stats:" + cacheScope,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<DashboardStatsVO>() {
|
||||
},
|
||||
() -> buildDashboardStats(currentUser, shopIdScope)
|
||||
);
|
||||
return Result.success(stats);
|
||||
}
|
||||
|
||||
@GetMapping("/analytics")
|
||||
@RequirePermission("analytics:view")
|
||||
public Result<OperationsAnalyticsVO> getAnalytics(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
Long shopIdScope = resolveShopScope(currentUser);
|
||||
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
|
||||
return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `buildDashboardStats`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param currentUser parameter `currentUser` supplied by the caller
|
||||
* @param shopIdScope parameter `shopIdScope` supplied by the caller
|
||||
* @return private DashboardStatsVO result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
|
||||
DashboardStatsVO stats = new DashboardStatsVO();
|
||||
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
|
||||
|
||||
if (currentUser != null) {
|
||||
// 根据用户类型显示不同的数据
|
||||
if (currentUser.getType() == 4) { // 管理员
|
||||
stats.setTotalUsers(userMapper.selectCount(null));
|
||||
stats.setTotalProducts(productMapper.selectCount(null));
|
||||
stats.setTotalShops(shopMapper.selectCount(null));
|
||||
stats.setTodayOrders(getTodayOrders(null));
|
||||
stats.setTotalCustomers(countUsers(null, 0, null, null));
|
||||
stats.setTotalArtists(countUsers(null, 3, null, null));
|
||||
} else { // 店长或美甲师
|
||||
Long shopId = currentUser.getShopId();
|
||||
if (shopId != null) {
|
||||
shopIdScope = shopId;
|
||||
// 只显示当前店铺的数据
|
||||
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
|
||||
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
|
||||
stats.setTotalShops(0L); // 非管理员不显示店铺数量
|
||||
stats.setTodayOrders(getTodayOrders(shopId));
|
||||
stats.setTotalCustomers(countUsers(shopId, 0, null, null));
|
||||
stats.setTotalArtists(countUsers(shopId, 3, null, null));
|
||||
} else {
|
||||
// 没有店铺ID的情况
|
||||
stats.setTotalUsers(0L);
|
||||
stats.setTotalProducts(0L);
|
||||
stats.setTotalShops(0L);
|
||||
stats.setTodayOrders(0L);
|
||||
stats.setTotalCustomers(0L);
|
||||
stats.setTotalArtists(0L);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 无法获取用户信息的情况
|
||||
stats.setTotalUsers(0L);
|
||||
stats.setTotalProducts(0L);
|
||||
stats.setTotalShops(0L);
|
||||
stats.setTodayOrders(0L);
|
||||
stats.setTotalCustomers(0L);
|
||||
stats.setTotalArtists(0L);
|
||||
}
|
||||
|
||||
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
|
||||
LocalDateTime weekStart = todayStart.minusDays(6);
|
||||
stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null));
|
||||
stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null));
|
||||
stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null));
|
||||
stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null));
|
||||
stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null));
|
||||
stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null));
|
||||
long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null);
|
||||
long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null);
|
||||
stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders);
|
||||
stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null));
|
||||
|
||||
stats.setHotProducts(getHotProducts(shopIdScope));
|
||||
stats.setRecentActivities(getRecentActivities(shopIdScope));
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `resolveShopScope`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param currentUser parameter `currentUser` supplied by the caller
|
||||
* @return private Long result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private Long resolveShopScope(UserDO currentUser) {
|
||||
if (currentUser == null || currentUser.getType() == 4) {
|
||||
return null;
|
||||
}
|
||||
return currentUser.getShopId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: countUsers supports DashboardController.java by holding or executing the count users business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) {
|
||||
LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
|
||||
if (type != null) {
|
||||
wrapper.eq(UserDO::getType, type);
|
||||
}
|
||||
if (from != null) {
|
||||
wrapper.ge(UserDO::getCreateTime, from);
|
||||
}
|
||||
if (to != null) {
|
||||
wrapper.le(UserDO::getCreateTime, to);
|
||||
}
|
||||
if (shopId != null) {
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
|
||||
if (userIds.isEmpty()) {
|
||||
return 0L;
|
||||
}
|
||||
wrapper.in(UserDO::getId, userIds);
|
||||
}
|
||||
return userMapper.selectCount(wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
|
||||
return (long) listScopedOrders(shopId, artistId, status, from, to).size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) {
|
||||
return listScopedOrders(shopId, artistId, null, from, to).stream()
|
||||
.map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount())
|
||||
.filter(amount -> amount != null)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private List<OrderDO> listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
|
||||
LambdaQueryWrapper<OrderDO> wrapper = new LambdaQueryWrapper<>();
|
||||
if (shopId != null) {
|
||||
wrapper.eq(OrderDO::getShopId, shopId);
|
||||
}
|
||||
if (status != null) {
|
||||
wrapper.eq(OrderDO::getStatus, status);
|
||||
}
|
||||
if (from != null) {
|
||||
wrapper.ge(OrderDO::getCreateTime, from);
|
||||
}
|
||||
if (to != null) {
|
||||
wrapper.le(OrderDO::getCreateTime, to);
|
||||
}
|
||||
if (artistId != null) {
|
||||
Set<Long> orderIds = listOrderIdsByArtist(artistId);
|
||||
if (orderIds.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
wrapper.in(OrderDO::getId, orderIds);
|
||||
}
|
||||
return orderMapper.selectList(wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Set<Long> listOrderIdsByArtist(Long artistId) {
|
||||
List<OrderItemDO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
|
||||
.select(OrderItemDO::getOrderId)
|
||||
.eq(OrderItemDO::getArtistId, artistId));
|
||||
return items.stream()
|
||||
.map(OrderItemDO::getOrderId)
|
||||
.filter(id -> id != null)
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param shopId parameter `shopId` supplied by the caller
|
||||
* @return private Long result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private Long getTodayOrders(Long shopId) {
|
||||
// 获取今天的开始时间
|
||||
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
|
||||
String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
if (shopId != null) {
|
||||
// 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺
|
||||
java.util.Map<String, Object> result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr);
|
||||
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
|
||||
} else {
|
||||
// 管理员查询所有订单
|
||||
java.util.Map<String, Object> result = orderItemMapper.countTodayOrders(todayStartStr);
|
||||
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param shopId parameter `shopId` supplied by the caller
|
||||
* @return private List<HotProductVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private List<HotProductVO> getHotProducts(Long shopId) {
|
||||
// 通过订单商品表统计每个商品的订单数量,按订单数量排序
|
||||
// 使用SQL查询获取商品及其订单数量
|
||||
List<Map<String, Object>> productOrderCounts = orderItemMapper.selectMaps(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrderItemDO>()
|
||||
.select("product_id, COUNT(*) as order_count")
|
||||
.groupBy("product_id")
|
||||
.orderByDesc("order_count")
|
||||
.last("LIMIT 5")
|
||||
);
|
||||
|
||||
List<HotProductVO> hotProducts = new ArrayList<>();
|
||||
|
||||
// 遍历查询结果,获取商品详情
|
||||
for (Map<String, Object> map : productOrderCounts) {
|
||||
Long productId = Long.valueOf(map.get("product_id").toString());
|
||||
ProductDO product = productMapper.selectById(productId);
|
||||
|
||||
if (product != null && (shopId == null || shopId.equals(product.getShopId()))) {
|
||||
HotProductVO vo = new HotProductVO();
|
||||
BeanUtils.copyProperties(product, vo);
|
||||
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
|
||||
hotProducts.add(vo);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果按订单数量查询没有结果,使用点赞数作为备选
|
||||
if (hotProducts.isEmpty()) {
|
||||
LambdaQueryWrapper<ProductDO> wrapper = new LambdaQueryWrapper<>();
|
||||
if (shopId != null) {
|
||||
wrapper.eq(ProductDO::getShopId, shopId);
|
||||
}
|
||||
wrapper.orderByDesc(ProductDO::getLikeCount)
|
||||
.last("LIMIT 5");
|
||||
List<ProductDO> products = productMapper.selectList(wrapper);
|
||||
|
||||
hotProducts = products.stream().map(product -> {
|
||||
HotProductVO vo = new HotProductVO();
|
||||
BeanUtils.copyProperties(product, vo);
|
||||
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
|
||||
return vo;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
return hotProducts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param shopId parameter `shopId` supplied by the caller
|
||||
* @return private List<RecentActivityVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private List<RecentActivityVO> getRecentActivities(Long shopId) {
|
||||
List<RecentActivityVO> activities = new ArrayList<>();
|
||||
|
||||
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
|
||||
if (shopId != null) {
|
||||
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
|
||||
if (userIds.isEmpty()) {
|
||||
userWrapper.eq(UserDO::getId, -1L);
|
||||
} else {
|
||||
userWrapper.in(UserDO::getId, userIds);
|
||||
}
|
||||
}
|
||||
userWrapper.orderByDesc(UserDO::getCreateTime)
|
||||
.last("LIMIT 3");
|
||||
List<UserDO> recentUsers = userMapper.selectList(userWrapper);
|
||||
|
||||
for (UserDO user : recentUsers) {
|
||||
RecentActivityVO vo = new RecentActivityVO();
|
||||
vo.setId(user.getId());
|
||||
vo.setType("user");
|
||||
vo.setTitle("新用户注册");
|
||||
vo.setDescription("用户\"" + user.getNickname() + "\"注册成功");
|
||||
vo.setTime(user.getCreateTime());
|
||||
vo.setColor("");
|
||||
activities.add(vo);
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<ProductDO> productWrapper = new LambdaQueryWrapper<>();
|
||||
if (shopId != null) {
|
||||
productWrapper.eq(ProductDO::getShopId, shopId);
|
||||
}
|
||||
productWrapper.orderByDesc(ProductDO::getCreateTime)
|
||||
.last("LIMIT 2");
|
||||
List<ProductDO> recentProducts = productMapper.selectList(productWrapper);
|
||||
|
||||
for (ProductDO product : recentProducts) {
|
||||
RecentActivityVO vo = new RecentActivityVO();
|
||||
vo.setId(product.getId());
|
||||
vo.setType("product");
|
||||
vo.setTitle("新品上架");
|
||||
vo.setDescription("新品\"" + product.getTitle() + "\"已上架");
|
||||
vo.setTime(product.getCreateTime());
|
||||
vo.setColor("blue");
|
||||
activities.add(vo);
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<CommentDO> commentWrapper = new LambdaQueryWrapper<>();
|
||||
if (shopId != null) {
|
||||
commentWrapper.eq(CommentDO::getShopId, shopId);
|
||||
}
|
||||
commentWrapper.orderByDesc(CommentDO::getCreateTime)
|
||||
.last("LIMIT 2");
|
||||
List<CommentDO> recentComments = commentMapper.selectList(commentWrapper);
|
||||
|
||||
for (CommentDO comment : recentComments) {
|
||||
RecentActivityVO vo = new RecentActivityVO();
|
||||
vo.setId(comment.getId());
|
||||
vo.setType("comment");
|
||||
vo.setTitle("用户评论");
|
||||
String content = comment.getCommentContent();
|
||||
if (content != null && content.length() > 20) {
|
||||
content = content.substring(0, 20) + "...";
|
||||
}
|
||||
vo.setDescription(content != null ? content : "用户发表了评论");
|
||||
vo.setTime(comment.getCreateTime());
|
||||
vo.setColor("green");
|
||||
activities.add(vo);
|
||||
}
|
||||
|
||||
activities.sort((a, b) -> b.getTime().compareTo(a.getTime()));
|
||||
|
||||
return activities.stream().limit(5).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.analytics.service;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO;
|
||||
|
||||
public interface OperationsAnalyticsService {
|
||||
OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId);
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.analytics.service;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.StoreWorkbenchVO;
|
||||
|
||||
public interface WorkbenchService {
|
||||
StoreWorkbenchVO getWorkbench(Long shopId, Long artistId);
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.analytics.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserGrowthRecordDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserGrowthRecordMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.service.OperationsAnalyticsService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService {
|
||||
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final UserGrowthRecordMapper userGrowthRecordMapper;
|
||||
|
||||
@Override
|
||||
public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) {
|
||||
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
|
||||
.eq(shopId != null, OrderDO::getShopId, shopId)
|
||||
.eq(OrderDO::getIsDelete, 0));
|
||||
if (artistId != null) {
|
||||
Set<Long> orderIds = new HashSet<>();
|
||||
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
|
||||
.eq(OrderItemDO::getArtistId, artistId)
|
||||
.eq(OrderItemDO::getIsDelete, 0))
|
||||
.forEach(item -> orderIds.add(item.getOrderId()));
|
||||
orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
|
||||
}
|
||||
OperationsAnalyticsVO vo = new OperationsAnalyticsVO();
|
||||
vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
|
||||
.eq(shopId != null, ProductDO::getShopId, shopId)
|
||||
.eq(ProductDO::getIsDelete, 0))
|
||||
.stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
|
||||
vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
|
||||
.eq(shopId != null, ProductDO::getShopId, shopId)
|
||||
.eq(ProductDO::getIsDelete, 0))
|
||||
.stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
|
||||
vo.setCartCount(0L);
|
||||
vo.setOrderCount((long) orders.size());
|
||||
vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count());
|
||||
vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
|
||||
vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
|
||||
.eq(UserGrowthRecordDO::getSourceType, "REVIEW")));
|
||||
vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
|
||||
.eq(UserGrowthRecordDO::getSourceType, "REBOOK")));
|
||||
vo.setTotalAmount(orders.stream()
|
||||
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.controller.front;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 美甲师信息Controller(前台)
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/nail-artist")
|
||||
public class NailArtistController {
|
||||
|
||||
@Autowired
|
||||
/**
|
||||
* Purpose: nailArtistInfoService supports NailArtistController.java by holding or executing the nail artist info service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private NailArtistInfoService nailArtistInfoService;
|
||||
|
||||
/**
|
||||
* 获取所有可用的美甲师信息(前台使用)
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
public Result<List<NailArtistInfoDTO>> getAllAvailableNailArtists() {
|
||||
List<NailArtistInfoDTO> nailArtistInfoDTOList = nailArtistInfoService.getAllAvailableNailArtists();
|
||||
return Result.success(nailArtistInfoDTOList);
|
||||
}
|
||||
|
||||
@GetMapping("/list/shop/{shopId}")
|
||||
public Result<List<NailArtistInfoDTO>> listByShopId(@PathVariable Long shopId) {
|
||||
return Result.success(nailArtistInfoService.getByShopId(shopId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户ID获取美甲师信息(前台使用)
|
||||
*/
|
||||
@GetMapping("/get/{userId}")
|
||||
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId) {
|
||||
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
|
||||
return Result.success(nailArtistInfoDTO);
|
||||
}
|
||||
|
||||
@GetMapping("/profile/{artistId}")
|
||||
public Result<NailArtistProfileVO> getPublicProfile(@PathVariable Long artistId) {
|
||||
return Result.success(nailArtistInfoService.getPublicProfile(artistId));
|
||||
}
|
||||
|
||||
@GetMapping("/{artistId}/availability")
|
||||
public Result<List<NailArtistAvailabilityVO>> getAvailability(@PathVariable Long artistId) {
|
||||
return Result.success(nailArtistInfoService.getAvailability(artistId));
|
||||
}
|
||||
|
||||
@GetMapping("/{artistId}/reviews")
|
||||
public Result<List<NailArtistReviewVO>> listPublicReviews(@PathVariable Long artistId) {
|
||||
return Result.success(nailArtistInfoService.listPublicReviews(artistId));
|
||||
}
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.dto;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalTime;
|
||||
|
||||
/**
|
||||
* 美甲师信息DTO
|
||||
*/
|
||||
@Data
|
||||
public class NailArtistInfoDTO {
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 关联用户表主键(美甲师用户)
|
||||
*/
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 身份
|
||||
*/
|
||||
private String identity;
|
||||
|
||||
/**
|
||||
* 从业年限
|
||||
*/
|
||||
private Integer experience;
|
||||
|
||||
/**
|
||||
* 技能标签ID集合,多个ID以逗号分隔
|
||||
*/
|
||||
private String skills;
|
||||
|
||||
/**
|
||||
* 评分
|
||||
*/
|
||||
private BigDecimal rating;
|
||||
|
||||
/**
|
||||
* 状态:1-营业中,0-休息中
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer participateProduction;
|
||||
|
||||
/**
|
||||
* Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private LocalTime workStartTime;
|
||||
|
||||
/**
|
||||
* Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private LocalTime workEndTime;
|
||||
|
||||
/**
|
||||
* Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer userType;
|
||||
|
||||
/**
|
||||
* Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String userTypeName;
|
||||
|
||||
/**
|
||||
* 作品集商品ID集合,多个ID以逗号分隔
|
||||
*/
|
||||
private String portfolio;
|
||||
|
||||
/**
|
||||
* 美甲师姓名(从用户表获取)
|
||||
*/
|
||||
private String nickname;
|
||||
|
||||
/**
|
||||
* 所属店铺ID
|
||||
*/
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 店铺名称
|
||||
*/
|
||||
private String shopName;
|
||||
|
||||
/**
|
||||
* 用户签名
|
||||
*/
|
||||
private String signature;
|
||||
|
||||
/**
|
||||
* 头像访问地址
|
||||
*/
|
||||
private String avatar;
|
||||
|
||||
/**
|
||||
* 排班模式摘要
|
||||
*/
|
||||
private String scheduleModeSummary;
|
||||
|
||||
/**
|
||||
* 排班时间摘要
|
||||
*/
|
||||
private String scheduleTimeSummary;
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity;
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_artist_schedule")
|
||||
public class ArtistScheduleDO extends BaseEntity {
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
@TableField("artist_id")
|
||||
private Long artistId;
|
||||
@TableField("work_date")
|
||||
private LocalDate workDate;
|
||||
@TableField("start_time")
|
||||
private LocalTime startTime;
|
||||
@TableField("end_time")
|
||||
private LocalTime endTime;
|
||||
@TableField("slot_minutes")
|
||||
private Integer slotMinutes;
|
||||
@TableField("capacity")
|
||||
private Integer capacity;
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
@TableField("is_delete")
|
||||
@TableLogic
|
||||
private Integer isDelete;
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_artist_schedule_exception")
|
||||
public class ArtistScheduleExceptionDO extends BaseEntity {
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
@TableField("artist_id")
|
||||
private Long artistId;
|
||||
@TableField("work_date")
|
||||
private LocalDate workDate;
|
||||
@TableField("exception_type")
|
||||
private String exceptionType;
|
||||
@TableField("start_time")
|
||||
private LocalTime startTime;
|
||||
@TableField("end_time")
|
||||
private LocalTime endTime;
|
||||
@TableField("slot_minutes")
|
||||
private Integer slotMinutes;
|
||||
@TableField("capacity")
|
||||
private Integer capacity;
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
@TableField("is_delete")
|
||||
@TableLogic
|
||||
private Integer isDelete;
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_artist_schedule_rule")
|
||||
public class ArtistScheduleRuleDO extends BaseEntity {
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
@TableField("artist_id")
|
||||
private Long artistId;
|
||||
@TableField("preset_type")
|
||||
private String presetType;
|
||||
@TableField("work_days")
|
||||
private String workDays;
|
||||
@TableField("start_time")
|
||||
private LocalTime startTime;
|
||||
@TableField("end_time")
|
||||
private LocalTime endTime;
|
||||
@TableField("slot_minutes")
|
||||
private Integer slotMinutes;
|
||||
@TableField("capacity")
|
||||
private Integer capacity;
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
@TableField("is_delete")
|
||||
@TableLogic
|
||||
private Integer isDelete;
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity;
|
||||
/**
|
||||
* 美甲师信息实体类
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_nail_artist_info")
|
||||
public class NailArtistInfoDO extends BaseEntity {
|
||||
/**
|
||||
* 关联用户表主键(美甲师用户)
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 身份
|
||||
*/
|
||||
private String identity;
|
||||
|
||||
/**
|
||||
* 从业年限
|
||||
*/
|
||||
private Integer experience;
|
||||
|
||||
/**
|
||||
* 技能标签ID集合,多个ID以逗号分隔
|
||||
*/
|
||||
private String skills;
|
||||
|
||||
/**
|
||||
* 评分
|
||||
*/
|
||||
private BigDecimal rating;
|
||||
|
||||
/**
|
||||
* 状态:1-营业中,0-休息中
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
@TableField("participate_production")
|
||||
/**
|
||||
* Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer participateProduction;
|
||||
|
||||
@TableField("work_start_time")
|
||||
/**
|
||||
* Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private LocalTime workStartTime;
|
||||
|
||||
@TableField("work_end_time")
|
||||
/**
|
||||
* Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private LocalTime workEndTime;
|
||||
|
||||
/**
|
||||
* 作品集商品ID集合,多个ID以逗号分隔
|
||||
*/
|
||||
private String portfolio;
|
||||
|
||||
/**
|
||||
* 逻辑删除:0-未删,1-已删
|
||||
*/
|
||||
@TableField("is_delete")
|
||||
@TableLogic
|
||||
private Integer isDelete;
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface ArtistScheduleExceptionMapper extends BaseMapper<ArtistScheduleExceptionDO> {
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Mapper
|
||||
public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> {
|
||||
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
|
||||
"AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " +
|
||||
"AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE")
|
||||
ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId,
|
||||
@Param("artistId") Long artistId,
|
||||
@Param("workDate") LocalDate workDate,
|
||||
@Param("startTime") LocalTime startTime,
|
||||
@Param("endTime") LocalTime endTime);
|
||||
|
||||
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
|
||||
"AND work_date = #{workDate} AND is_delete = 0 ORDER BY start_time ASC LIMIT 1 FOR UPDATE")
|
||||
ArtistScheduleDO selectDayScheduleForUpdate(@Param("shopId") Long shopId,
|
||||
@Param("artistId") Long artistId,
|
||||
@Param("workDate") LocalDate workDate);
|
||||
|
||||
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
|
||||
"AND work_date = #{workDate} AND start_time = #{startTime} AND is_delete = 0 LIMIT 1 FOR UPDATE")
|
||||
ArtistScheduleDO selectSlotScheduleForUpdate(@Param("shopId") Long shopId,
|
||||
@Param("artistId") Long artistId,
|
||||
@Param("workDate") LocalDate workDate,
|
||||
@Param("startTime") LocalTime startTime);
|
||||
|
||||
@Update("UPDATE t_artist_schedule SET start_time = #{startTime}, end_time = #{endTime}, " +
|
||||
"slot_minutes = #{slotMinutes}, capacity = #{capacity}, status = #{status}, remark = #{remark}, " +
|
||||
"update_time = NOW() WHERE id = #{id} AND is_delete = 0")
|
||||
int updateGeneratedSchedule(@Param("id") Long id,
|
||||
@Param("startTime") LocalTime startTime,
|
||||
@Param("endTime") LocalTime endTime,
|
||||
@Param("slotMinutes") Integer slotMinutes,
|
||||
@Param("capacity") Integer capacity,
|
||||
@Param("status") Integer status,
|
||||
@Param("remark") String remark);
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface ArtistScheduleRuleMapper extends BaseMapper<ArtistScheduleRuleDO> {
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 美甲师信息Mapper
|
||||
*/
|
||||
@Mapper
|
||||
public interface NailArtistInfoMapper extends BaseMapper<NailArtistInfoDO> {
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.service;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
public interface ArtistScheduleService {
|
||||
ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto);
|
||||
|
||||
List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate);
|
||||
|
||||
ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId);
|
||||
|
||||
ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto);
|
||||
|
||||
ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto);
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 美甲师信息服务
|
||||
*/
|
||||
public interface NailArtistInfoService extends IService<NailArtistInfoDO> {
|
||||
/**
|
||||
* 根据用户ID获取美甲师信息
|
||||
* @param userId 用户ID
|
||||
* @return 美甲师信息
|
||||
*/
|
||||
NailArtistInfoDTO getByUserId(Long userId);
|
||||
|
||||
/**
|
||||
* 获取所有美甲师信息
|
||||
* @return 美甲师信息列表
|
||||
*/
|
||||
List<NailArtistInfoDTO> getAllNailArtists();
|
||||
|
||||
/**
|
||||
* 根据店铺ID获取美甲师信息
|
||||
* @param shopId 店铺ID
|
||||
* @return 美甲师信息列表
|
||||
*/
|
||||
List<NailArtistInfoDTO> getByShopId(Long shopId);
|
||||
|
||||
/**
|
||||
* 保存或更新美甲师信息
|
||||
* @param nailArtistInfoDTO 美甲师信息DTO
|
||||
* @return 保存后的美甲师信息
|
||||
*/
|
||||
NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO);
|
||||
|
||||
/**
|
||||
* 获取所有可用的美甲师信息(前台使用)
|
||||
* @return 美甲师信息列表
|
||||
*/
|
||||
List<NailArtistInfoDTO> getAllAvailableNailArtists();
|
||||
|
||||
NailArtistProfileVO getPublicProfile(Long artistId);
|
||||
|
||||
List<NailArtistAvailabilityVO> getAvailability(Long artistId);
|
||||
|
||||
List<NailArtistReviewVO> listPublicReviews(Long artistId);
|
||||
}
|
||||
-832
@@ -1,832 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistWorkVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.common.Result;
|
||||
@Service
|
||||
/**
|
||||
* NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects.
|
||||
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
|
||||
*/
|
||||
public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper, NailArtistInfoDO> implements NailArtistInfoService {
|
||||
|
||||
private static final int REVIEW_STATUS_SUBMITTED = 1;
|
||||
private static final int ORDER_STATUS_COMPLETED = 2;
|
||||
private static final int AVAILABILITY_DAYS = 7;
|
||||
private static final int SLOT_MINUTES = 60;
|
||||
private static final int MAX_AVAILABILITY_SLOTS = 16;
|
||||
private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
|
||||
private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
|
||||
private static final String PRESET_DOUBLE_REST = "DOUBLE_REST";
|
||||
private static final String PRESET_SINGLE_REST = "SINGLE_REST";
|
||||
|
||||
@Autowired
|
||||
/**
|
||||
* Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
/**
|
||||
* Purpose: shopMapper supports NailArtistInfoServiceImpl.java by holding or executing the shop mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private ShopMapper shopMapper;
|
||||
|
||||
@Autowired
|
||||
/**
|
||||
* Purpose: userShopBindingSupport supports NailArtistInfoServiceImpl.java by holding or executing the user shop binding support business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Autowired
|
||||
private ProductMapper productMapper;
|
||||
|
||||
@Autowired
|
||||
private OrderMapper orderMapper;
|
||||
|
||||
@Autowired
|
||||
private OrderItemMapper orderItemMapper;
|
||||
|
||||
@Autowired
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
|
||||
@Autowired
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
|
||||
@Autowired
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Autowired(required = false)
|
||||
private ArtistScheduleMapper artistScheduleMapper;
|
||||
|
||||
@Autowired(required = false)
|
||||
private ArtistScheduleRuleMapper artistScheduleRuleMapper;
|
||||
|
||||
@Autowired(required = false)
|
||||
private AppointmentReservationMapper appointmentReservationMapper;
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public NailArtistInfoDTO getByUserId(Long userId) {
|
||||
NailArtistInfoDO info = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getUserId, userId)
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||
.last("LIMIT 1"));
|
||||
return info == null ? null : convertToDTO(info);
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public List<NailArtistInfoDTO> getAllNailArtists() {
|
||||
List<NailArtistInfoDTO> result = new ArrayList<>();
|
||||
List<NailArtistInfoDO> records = list(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0));
|
||||
for (NailArtistInfoDO record : records) {
|
||||
NailArtistInfoDTO dto = convertToDTO(record);
|
||||
if (isVisibleServiceUser(dto)) {
|
||||
result.add(dto);
|
||||
}
|
||||
}
|
||||
enrichScheduleSummaries(result, null);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param shopId parameter `shopId` supplied by the caller
|
||||
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public List<NailArtistInfoDTO> getByShopId(Long shopId) {
|
||||
List<Long> serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
|
||||
if (serviceUserIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<UserDO> users = userMapper.selectList(new LambdaQueryWrapper<UserDO>()
|
||||
.in(UserDO::getId, serviceUserIds)
|
||||
.eq(UserDO::getType, 3)
|
||||
.eq(UserDO::getStatus, 1)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.orderByAsc(UserDO::getCreateTime)
|
||||
.orderByAsc(UserDO::getId));
|
||||
List<NailArtistInfoDTO> result = new ArrayList<>();
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
for (UserDO user : users) {
|
||||
NailArtistInfoDTO dto = getByUserId(user.getId());
|
||||
if (dto == null) {
|
||||
dto = buildFallbackArtistInfo(user);
|
||||
}
|
||||
dto.setShopId(shopId);
|
||||
dto.setShopName(shop == null ? null : shop.getShopName());
|
||||
result.add(dto);
|
||||
}
|
||||
enrichScheduleSummaries(result, shopId);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Save submitted data.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param dto parameter `dto` supplied by the caller
|
||||
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) {
|
||||
NailArtistInfoDO entity = new NailArtistInfoDO();
|
||||
BeanUtils.copyProperties(dto, entity);
|
||||
|
||||
NailArtistInfoDO existing = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getUserId, dto.getUserId())
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||
.last("LIMIT 1"));
|
||||
if (existing != null) {
|
||||
entity.setId(existing.getId());
|
||||
}
|
||||
if (entity.getStatus() == null) {
|
||||
entity.setStatus(1);
|
||||
}
|
||||
if (entity.getParticipateProduction() == null) {
|
||||
UserDO user = userMapper.selectById(dto.getUserId());
|
||||
entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save submitted data.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param entity parameter `entity` supplied by the caller
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
saveOrUpdate(entity);
|
||||
/**
|
||||
* Run business method `convertToDTO`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param entity parameter `entity` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return convertToDTO(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public List<NailArtistInfoDTO> getAllAvailableNailArtists() {
|
||||
List<NailArtistInfoDTO> result = new ArrayList<>();
|
||||
List<NailArtistInfoDO> records = list(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getStatus, 1)
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0));
|
||||
for (NailArtistInfoDO record : records) {
|
||||
NailArtistInfoDTO dto = convertToDTO(record);
|
||||
if (isBookableServiceUser(dto)) {
|
||||
result.add(dto);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NailArtistProfileVO getPublicProfile(Long artistId) {
|
||||
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null || isDeleted(artist.getIsDelete())) {
|
||||
throw new RuntimeException("美甲师信息不存在");
|
||||
}
|
||||
|
||||
List<OrderItemDO> servedItems = loadArtistOrderItems(artistId, true);
|
||||
List<NailArtistReviewVO> reviews = listPublicReviews(artistId);
|
||||
NailArtistProfileVO profile = new NailArtistProfileVO();
|
||||
profile.setArtistId(artistId);
|
||||
profile.setArtistName(resolveArtistName(artistInfo, artist));
|
||||
profile.setAvatar(artist.getAvatar());
|
||||
profile.setIdentity(artistInfo.getIdentity());
|
||||
profile.setSignature(artistInfo.getSignature());
|
||||
profile.setExperience(artistInfo.getExperience());
|
||||
profile.setStatus(artistInfo.getStatus());
|
||||
profile.setShopId(artistInfo.getShopId());
|
||||
profile.setShopName(artistInfo.getShopName());
|
||||
profile.setRating(resolvePublicRating(artistId, artistInfo));
|
||||
profile.setServiceCount(countServiceQuantity(servedItems));
|
||||
profile.setWorkStartTime(artistInfo.getWorkStartTime());
|
||||
profile.setWorkEndTime(artistInfo.getWorkEndTime());
|
||||
profile.setStyleTags(parseTextTokens(artistInfo.getSkills()));
|
||||
profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 24));
|
||||
profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList()));
|
||||
profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList()));
|
||||
return profile;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<NailArtistAvailabilityVO> getAvailability(Long artistId) {
|
||||
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
|
||||
if (!Integer.valueOf(1).equals(artistInfo.getStatus())) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<NailArtistAvailabilityVO> scheduleSlots = buildScheduleAvailabilitySlots(artistId, artistInfo);
|
||||
if (!scheduleSlots.isEmpty()) {
|
||||
return scheduleSlots;
|
||||
}
|
||||
|
||||
LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime();
|
||||
LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime();
|
||||
if (!workEnd.isAfter(workStart)) {
|
||||
workStart = LocalTime.of(10, 0);
|
||||
workEnd = LocalTime.of(20, 0);
|
||||
}
|
||||
|
||||
LocalDate today = LocalDate.now();
|
||||
LocalDateTime rangeStart = today.atStartOfDay();
|
||||
LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay();
|
||||
Set<LocalDateTime> bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
List<NailArtistAvailabilityVO> slots = new ArrayList<>();
|
||||
|
||||
for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) {
|
||||
LocalDate date = today.plusDays(dayOffset);
|
||||
LocalTime cursor = workStart;
|
||||
while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) {
|
||||
LocalDateTime slotStart = date.atTime(cursor);
|
||||
LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES);
|
||||
if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) {
|
||||
slots.add(buildAvailabilitySlot(slotStart, slotEnd));
|
||||
}
|
||||
cursor = cursor.plusMinutes(SLOT_MINUTES);
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
private List<NailArtistAvailabilityVO> buildScheduleAvailabilitySlots(Long artistId, NailArtistInfoDTO artistInfo) {
|
||||
if (artistScheduleMapper == null || artistInfo.getShopId() == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
LocalDate today = LocalDate.now();
|
||||
List<ArtistScheduleDO> schedules = artistScheduleMapper.selectList(new LambdaQueryWrapper<ArtistScheduleDO>()
|
||||
.eq(ArtistScheduleDO::getShopId, artistInfo.getShopId())
|
||||
.eq(ArtistScheduleDO::getArtistId, artistId)
|
||||
.eq(ArtistScheduleDO::getStatus, 1)
|
||||
.eq(ArtistScheduleDO::getIsDelete, 0)
|
||||
.ge(ArtistScheduleDO::getWorkDate, today)
|
||||
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(AVAILABILITY_DAYS))
|
||||
.orderByAsc(ArtistScheduleDO::getWorkDate)
|
||||
.orderByAsc(ArtistScheduleDO::getStartTime));
|
||||
if (schedules == null || schedules.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
LocalDateTime minStart = LocalDateTime.now().plusMinutes(30);
|
||||
List<NailArtistAvailabilityVO> slots = new ArrayList<>();
|
||||
for (ArtistScheduleDO schedule : schedules) {
|
||||
int slotMinutes = schedule.getSlotMinutes() == null || schedule.getSlotMinutes() < 15 ? SLOT_MINUTES : schedule.getSlotMinutes();
|
||||
int capacity = schedule.getCapacity() == null || schedule.getCapacity() < 1 ? 1 : schedule.getCapacity();
|
||||
LocalTime cursor = schedule.getStartTime();
|
||||
while (cursor != null && schedule.getEndTime() != null
|
||||
&& !cursor.plusMinutes(slotMinutes).isAfter(schedule.getEndTime())
|
||||
&& slots.size() < MAX_AVAILABILITY_SLOTS) {
|
||||
LocalDateTime slotStart = schedule.getWorkDate().atTime(cursor);
|
||||
LocalDateTime slotEnd = slotStart.plusMinutes(slotMinutes);
|
||||
int used = appointmentReservationMapper == null ? 0
|
||||
: appointmentReservationMapper.countOverlappingActive(artistId, slotStart, slotEnd);
|
||||
if (slotStart.isAfter(minStart) && used < capacity) {
|
||||
slots.add(buildAvailabilitySlot(slotStart, slotEnd));
|
||||
}
|
||||
cursor = cursor.plusMinutes(slotMinutes);
|
||||
}
|
||||
if (slots.size() >= MAX_AVAILABILITY_SLOTS) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<NailArtistReviewVO> listPublicReviews(Long artistId) {
|
||||
if (artistId == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<OrderArtistReviewDO> reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper<OrderArtistReviewDO>()
|
||||
.eq(OrderArtistReviewDO::getArtistId, artistId)
|
||||
.eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED)
|
||||
.eq(OrderArtistReviewDO::getIsDelete, 0)
|
||||
.orderByDesc(OrderArtistReviewDO::getSubmittedAt)
|
||||
.orderByDesc(OrderArtistReviewDO::getId));
|
||||
if (reviews == null || reviews.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<OrderArtistReviewDO> limitedReviews = reviews.stream().limit(20).collect(Collectors.toList());
|
||||
Map<Long, UserDO> customerMap = loadUsers(limitedReviews.stream()
|
||||
.map(OrderArtistReviewDO::getCustomerId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
Map<Long, ProductDO> productMap = loadProducts(limitedReviews.stream()
|
||||
.map(OrderArtistReviewDO::getProductId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
Set<Long> imageIds = new LinkedHashSet<>();
|
||||
for (OrderArtistReviewDO review : limitedReviews) {
|
||||
imageIds.addAll(parseLongTokens(review.getImageFileIds()));
|
||||
}
|
||||
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(imageIds);
|
||||
|
||||
List<NailArtistReviewVO> result = new ArrayList<>();
|
||||
for (OrderArtistReviewDO review : limitedReviews) {
|
||||
result.add(buildReviewVO(review, customerMap, productMap, fileMap));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `convertToDTO`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param entity parameter `entity` supplied by the caller
|
||||
* @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) {
|
||||
NailArtistInfoDTO dto = new NailArtistInfoDTO();
|
||||
BeanUtils.copyProperties(entity, dto);
|
||||
|
||||
UserDO user = userMapper.selectById(entity.getUserId());
|
||||
if (user != null) {
|
||||
dto.setNickname(user.getNickname());
|
||||
dto.setSignature(user.getSignature());
|
||||
dto.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
|
||||
dto.setUserType(user.getType());
|
||||
dto.setUserTypeName(resolveUserTypeName(user.getType()));
|
||||
if (dto.getParticipateProduction() == null) {
|
||||
dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
|
||||
}
|
||||
|
||||
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
|
||||
if (!shopOptions.isEmpty()) {
|
||||
ShopSimpleVO primaryShop = shopOptions.get(0);
|
||||
dto.setShopId(primaryShop.getId());
|
||||
dto.setShopName(primaryShop.getShopName());
|
||||
} else if (user.getShopId() != null && user.getShopId() > 0) {
|
||||
ShopDO shop = shopMapper.selectById(user.getShopId());
|
||||
if (shop != null) {
|
||||
dto.setShopId(shop.getId());
|
||||
dto.setShopName(shop.getShopName());
|
||||
}
|
||||
}
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
private NailArtistInfoDTO buildFallbackArtistInfo(UserDO user) {
|
||||
NailArtistInfoDTO dto = new NailArtistInfoDTO();
|
||||
dto.setUserId(user.getId());
|
||||
dto.setNickname(user.getNickname());
|
||||
dto.setSignature(user.getSignature());
|
||||
dto.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
|
||||
dto.setUserType(user.getType());
|
||||
dto.setUserTypeName(resolveUserTypeName(user.getType()));
|
||||
dto.setIdentity("美甲师");
|
||||
dto.setStatus(1);
|
||||
dto.setParticipateProduction(1);
|
||||
dto.setShopId(user.getShopId());
|
||||
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
|
||||
if (!shopOptions.isEmpty()) {
|
||||
ShopSimpleVO primaryShop = shopOptions.get(0);
|
||||
dto.setShopId(primaryShop.getId());
|
||||
dto.setShopName(primaryShop.getShopName());
|
||||
} else if (user.getShopId() != null && user.getShopId() > 0) {
|
||||
ShopDO shop = shopMapper.selectById(user.getShopId());
|
||||
if (shop != null) {
|
||||
dto.setShopId(shop.getId());
|
||||
dto.setShopName(shop.getShopName());
|
||||
}
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
private void enrichScheduleSummaries(List<NailArtistInfoDTO> artists, Long shopId) {
|
||||
if (artistScheduleRuleMapper == null || artists == null || artists.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<Long> artistIds = artists.stream()
|
||||
.map(NailArtistInfoDTO::getUserId)
|
||||
.filter(userId -> userId != null && userId > 0)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
if (artistIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<ArtistScheduleRuleDO> wrapper = new LambdaQueryWrapper<ArtistScheduleRuleDO>()
|
||||
.in(ArtistScheduleRuleDO::getArtistId, artistIds)
|
||||
.eq(ArtistScheduleRuleDO::getIsDelete, 0);
|
||||
if (shopId != null && shopId > 0) {
|
||||
wrapper.eq(ArtistScheduleRuleDO::getShopId, shopId);
|
||||
}
|
||||
Map<Long, ArtistScheduleRuleDO> ruleByArtistId = artistScheduleRuleMapper.selectList(wrapper).stream()
|
||||
.collect(Collectors.toMap(ArtistScheduleRuleDO::getArtistId, rule -> rule, (left, right) -> left));
|
||||
artists.forEach(artist -> applyScheduleSummary(artist, ruleByArtistId.get(artist.getUserId())));
|
||||
}
|
||||
|
||||
private void applyScheduleSummary(NailArtistInfoDTO artist, ArtistScheduleRuleDO rule) {
|
||||
if (artist == null) {
|
||||
return;
|
||||
}
|
||||
if (rule == null || !Integer.valueOf(1).equals(rule.getStatus())) {
|
||||
artist.setScheduleModeSummary("未设置");
|
||||
artist.setScheduleTimeSummary("");
|
||||
return;
|
||||
}
|
||||
artist.setScheduleModeSummary(resolveScheduleModeSummary(rule.getPresetType()));
|
||||
artist.setScheduleTimeSummary(formatScheduleTimeSummary(rule.getStartTime(), rule.getEndTime()));
|
||||
}
|
||||
|
||||
private String resolveScheduleModeSummary(String presetType) {
|
||||
if (PRESET_DOUBLE_REST.equals(presetType)) {
|
||||
return "双休";
|
||||
}
|
||||
if (PRESET_SINGLE_REST.equals(presetType)) {
|
||||
return "单休";
|
||||
}
|
||||
return "自定义";
|
||||
}
|
||||
|
||||
private String formatScheduleTimeSummary(LocalTime startTime, LocalTime endTime) {
|
||||
if (startTime == null || endTime == null) {
|
||||
return "";
|
||||
}
|
||||
return TIME_TEXT_FORMATTER.format(startTime) + "-" + TIME_TEXT_FORMATTER.format(endTime);
|
||||
}
|
||||
|
||||
private String resolveAccessibleAvatar(String avatar) {
|
||||
if (!StringUtils.hasText(avatar)) {
|
||||
return null;
|
||||
}
|
||||
String accessibleUrl = objectStorageUrlSupport.toAccessibleUrl(avatar);
|
||||
return StringUtils.hasText(accessibleUrl) ? accessibleUrl : avatar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `isVisibleServiceUser`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param dto parameter `dto` supplied by the caller
|
||||
* @return private boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private boolean isVisibleServiceUser(NailArtistInfoDTO dto) {
|
||||
if (dto == null || dto.getUserType() == null) {
|
||||
return false;
|
||||
}
|
||||
return Integer.valueOf(3).equals(dto.getUserType())
|
||||
|| Integer.valueOf(2).equals(dto.getUserType());
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `isBookableServiceUser`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param dto parameter `dto` supplied by the caller
|
||||
* @return private boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private boolean isBookableServiceUser(NailArtistInfoDTO dto) {
|
||||
return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `resolveUserTypeName`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param type parameter `type` supplied by the caller
|
||||
* @return private String result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private String resolveUserTypeName(Integer type) {
|
||||
if (Integer.valueOf(2).equals(type)) {
|
||||
return "店长";
|
||||
}
|
||||
if (Integer.valueOf(3).equals(type)) {
|
||||
return "美甲师";
|
||||
}
|
||||
return "用户";
|
||||
}
|
||||
|
||||
private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) {
|
||||
if (artistId == null) {
|
||||
throw new RuntimeException("美甲师信息不存在");
|
||||
}
|
||||
NailArtistInfoDTO artistInfo = getByUserId(artistId);
|
||||
if (artistInfo != null && isVisibleServiceUser(artistInfo)) {
|
||||
return artistInfo;
|
||||
}
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null
|
||||
|| isDeleted(artist.getIsDelete())
|
||||
|| !Integer.valueOf(3).equals(artist.getType())
|
||||
|| !Integer.valueOf(1).equals(artist.getStatus())) {
|
||||
throw new RuntimeException("美甲师信息不存在");
|
||||
}
|
||||
return buildFallbackArtistInfo(artist);
|
||||
}
|
||||
|
||||
private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) {
|
||||
BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
|
||||
BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating;
|
||||
if (rating == null) {
|
||||
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
|
||||
}
|
||||
return rating.setScale(1, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private List<OrderItemDO> loadArtistOrderItems(Long artistId, boolean completedOnly) {
|
||||
List<OrderDO> orders = orderMapper.selectByArtistId(artistId);
|
||||
if (orders == null || orders.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
Set<Long> allowedOrderIds = orders.stream()
|
||||
.filter(order -> !isDeleted(order.getIsDelete()))
|
||||
.filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus()))
|
||||
.map(OrderDO::getId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
if (allowedOrderIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<OrderItemDO> items = new ArrayList<>();
|
||||
for (Long orderId : allowedOrderIds) {
|
||||
List<OrderItemDO> orderItems = orderItemMapper.selectByOrderId(orderId);
|
||||
if (orderItems == null) {
|
||||
continue;
|
||||
}
|
||||
for (OrderItemDO item : orderItems) {
|
||||
if (item != null
|
||||
&& artistId.equals(item.getArtistId())
|
||||
&& !isDeleted(item.getIsDelete())) {
|
||||
items.add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private long countServiceQuantity(List<OrderItemDO> items) {
|
||||
if (items == null || items.isEmpty()) {
|
||||
return 0L;
|
||||
}
|
||||
long count = 0L;
|
||||
for (OrderItemDO item : items) {
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private List<NailArtistWorkVO> buildWorks(String portfolio, List<OrderItemDO> servedItems, int limit) {
|
||||
LinkedHashSet<Long> productIds = new LinkedHashSet<>(parseLongTokens(portfolio));
|
||||
if (servedItems != null) {
|
||||
servedItems.stream()
|
||||
.sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.map(OrderItemDO::getProductId)
|
||||
.filter(productId -> productId != null && productId > 0)
|
||||
.forEach(productIds::add);
|
||||
}
|
||||
if (productIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<Long> limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList());
|
||||
Map<Long, ProductDO> productMap = loadProducts(new LinkedHashSet<>(limitedIds));
|
||||
Set<Long> fileIds = new LinkedHashSet<>();
|
||||
for (ProductDO product : productMap.values()) {
|
||||
fileIds.addAll(parseLongTokens(product.getImageFileIds()));
|
||||
}
|
||||
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(fileIds);
|
||||
|
||||
List<NailArtistWorkVO> works = new ArrayList<>();
|
||||
for (Long productId : limitedIds) {
|
||||
ProductDO product = productMap.get(productId);
|
||||
if (product == null || isDeleted(product.getIsDelete()) || !isFrontVisible(product)) {
|
||||
continue;
|
||||
}
|
||||
works.add(buildWorkVO(product, fileMap));
|
||||
}
|
||||
return works;
|
||||
}
|
||||
|
||||
private NailArtistWorkVO buildWorkVO(ProductDO product, Map<Long, ObjectStorageFileVO> fileMap) {
|
||||
NailArtistWorkVO work = new NailArtistWorkVO();
|
||||
work.setId(product.getId());
|
||||
work.setTitle(product.getTitle());
|
||||
work.setDescription(product.getDescription());
|
||||
work.setPrice(product.getPrice());
|
||||
work.setTags(parseTextTokens(product.getTags()));
|
||||
work.setLikeCount(product.getLikeCount());
|
||||
work.setCollectCount(product.getCollectCount());
|
||||
List<String> imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap);
|
||||
work.setImageUrls(imageUrls);
|
||||
work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0));
|
||||
return work;
|
||||
}
|
||||
|
||||
private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review,
|
||||
Map<Long, UserDO> customerMap,
|
||||
Map<Long, ProductDO> productMap,
|
||||
Map<Long, ObjectStorageFileVO> fileMap) {
|
||||
NailArtistReviewVO vo = new NailArtistReviewVO();
|
||||
vo.setId(review.getId());
|
||||
vo.setArtistId(review.getArtistId());
|
||||
vo.setCustomerId(review.getCustomerId());
|
||||
UserDO customer = customerMap.get(review.getCustomerId());
|
||||
vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname());
|
||||
vo.setCustomerAvatar(customer == null ? null : customer.getAvatar());
|
||||
vo.setProductId(review.getProductId());
|
||||
ProductDO product = productMap.get(review.getProductId());
|
||||
vo.setProductTitle(product == null ? null : product.getTitle());
|
||||
vo.setRating(review.getRatingScore());
|
||||
vo.setContent(review.getContent());
|
||||
List<Long> imageFileIds = parseLongTokens(review.getImageFileIds());
|
||||
vo.setImageFileIds(imageFileIds);
|
||||
vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap));
|
||||
vo.setSubmittedAt(review.getSubmittedAt());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private Set<LocalDateTime> loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) {
|
||||
List<OrderItemDO> bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd);
|
||||
if (bookedItems == null || bookedItems.isEmpty()) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return bookedItems.stream()
|
||||
.map(OrderItemDO::getAppointmentTime)
|
||||
.filter(appointmentTime -> appointmentTime != null)
|
||||
.map(this::truncateToMinute)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO();
|
||||
slot.setStartTime(startTime);
|
||||
slot.setEndTime(endTime);
|
||||
slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate()));
|
||||
slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime()));
|
||||
slot.setAvailable(true);
|
||||
return slot;
|
||||
}
|
||||
|
||||
private Map<Long, ProductDO> loadProducts(Set<Long> productIds) {
|
||||
if (productIds == null || productIds.isEmpty()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
List<ProductDO> products = productMapper.selectBatchIds(productIds);
|
||||
if (products == null || products.isEmpty()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return products.stream()
|
||||
.filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete()) && isFrontVisible(product))
|
||||
.collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new));
|
||||
}
|
||||
|
||||
private Map<Long, UserDO> loadUsers(Set<Long> userIds) {
|
||||
if (userIds == null || userIds.isEmpty()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
List<UserDO> users = userMapper.selectBatchIds(new ArrayList<>(userIds));
|
||||
if (users == null || users.isEmpty()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return users.stream()
|
||||
.filter(user -> user != null && user.getId() != null)
|
||||
.collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new));
|
||||
}
|
||||
|
||||
private Map<Long, ObjectStorageFileVO> loadFiles(Set<Long> fileIds) {
|
||||
if (fileIds == null || fileIds.isEmpty()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
Map<Long, ObjectStorageFileVO> files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds);
|
||||
return files == null ? new HashMap<>() : files;
|
||||
}
|
||||
|
||||
private List<String> resolveImageUrls(List<Long> fileIds, Map<Long, ObjectStorageFileVO> fileMap) {
|
||||
if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<String> urls = new ArrayList<>();
|
||||
for (Long fileId : fileIds) {
|
||||
ObjectStorageFileVO file = fileMap.get(fileId);
|
||||
if (file != null && StringUtils.hasText(file.getFileUrl())) {
|
||||
urls.add(objectStorageUrlSupport.toAccessibleUrl(file));
|
||||
}
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
private List<Long> parseLongTokens(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
LinkedHashSet<Long> ids = new LinkedHashSet<>();
|
||||
for (String token : raw.split("[,;,;\\s]+")) {
|
||||
if (!StringUtils.hasText(token)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ids.add(Long.parseLong(token.trim()));
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Some legacy fields store tag names instead of ids.
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(ids);
|
||||
}
|
||||
|
||||
private List<String> parseTextTokens(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
LinkedHashSet<String> tokens = new LinkedHashSet<>();
|
||||
for (String token : raw.split("[,;,;、\\s]+")) {
|
||||
if (StringUtils.hasText(token)) {
|
||||
tokens.add(token.trim());
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(tokens);
|
||||
}
|
||||
|
||||
private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) {
|
||||
if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) {
|
||||
return artistInfo.getNickname();
|
||||
}
|
||||
if (artist != null && StringUtils.hasText(artist.getNickname())) {
|
||||
return artist.getNickname();
|
||||
}
|
||||
return "美甲师";
|
||||
}
|
||||
|
||||
private boolean isDeleted(Integer isDelete) {
|
||||
return Integer.valueOf(1).equals(isDelete);
|
||||
}
|
||||
|
||||
private boolean isFrontVisible(ProductDO product) {
|
||||
return product != null && Integer.valueOf(1).equals(product.getFrontVisible());
|
||||
}
|
||||
|
||||
private LocalDateTime truncateToMinute(LocalDateTime value) {
|
||||
return value == null ? null : value.withSecond(0).withNano(0);
|
||||
}
|
||||
}
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.support;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport;
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
/**
|
||||
* Purpose: BookableArtistSupport supports BookableArtistSupport.java by holding or executing the bookable artist support business role.
|
||||
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public class BookableArtistSupport {
|
||||
|
||||
/**
|
||||
* Purpose: userMapper supports BookableArtistSupport.java by holding or executing the user mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final UserMapper userMapper;
|
||||
/**
|
||||
* Purpose: nailArtistInfoMapper supports BookableArtistSupport.java by holding or executing the nail artist info mapper business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final NailArtistInfoMapper nailArtistInfoMapper;
|
||||
/**
|
||||
* Purpose: userShopBindingSupport supports BookableArtistSupport.java by holding or executing the user shop binding support business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
/**
|
||||
* Purpose: isValidBookableArtist supports BookableArtistSupport.java by holding or executing the is valid bookable artist business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public boolean isValidBookableArtist(Long shopId, Long artistId) {
|
||||
if (artistId == null || artistId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
if (!isBookableServiceUser(artist)) {
|
||||
return false;
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(artist.getStatus())) {
|
||||
return false;
|
||||
}
|
||||
return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isBookableServiceUser supports BookableArtistSupport.java by holding or executing the is bookable service user business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public boolean isBookableServiceUser(UserDO user) {
|
||||
if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) {
|
||||
return false;
|
||||
}
|
||||
if (Integer.valueOf(3).equals(user.getType())) {
|
||||
return true;
|
||||
}
|
||||
if (!Integer.valueOf(2).equals(user.getType())) {
|
||||
return false;
|
||||
}
|
||||
NailArtistInfoDO info = nailArtistInfoMapper.selectOne(
|
||||
new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getUserId, user.getId())
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
return info != null
|
||||
&& Integer.valueOf(1).equals(info.getStatus())
|
||||
&& Integer.valueOf(1).equals(info.getParticipateProduction());
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: filterValidBookableArtists supports BookableArtistSupport.java by holding or executing the filter valid bookable artists business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public String filterValidBookableArtists(Long shopId, String rawBookableArtists) {
|
||||
if (!StringUtils.hasText(rawBookableArtists)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
Set<Long> validArtistIds = new LinkedHashSet<>();
|
||||
for (String artistIdText : rawBookableArtists.split(",")) {
|
||||
if (!StringUtils.hasText(artistIdText)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
Long artistId = Long.parseLong(artistIdText.trim());
|
||||
if (isValidBookableArtist(shopId, artistId)) {
|
||||
validArtistIds.add(artistId);
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Ignore invalid configured IDs and only expose currently valid artists.
|
||||
}
|
||||
}
|
||||
|
||||
return validArtistIds.stream()
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus;
|
||||
@Data
|
||||
/**
|
||||
* ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend.
|
||||
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
|
||||
*/
|
||||
public class ArtistCalendarAppointmentVO {
|
||||
/**
|
||||
* Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long orderId;
|
||||
/**
|
||||
* Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String orderNo;
|
||||
/**
|
||||
* Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private BigDecimal totalAmount;
|
||||
/**
|
||||
* Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private BigDecimal actualAmount;
|
||||
/**
|
||||
* Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer orderStatus;
|
||||
/**
|
||||
* Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String orderStatusText;
|
||||
/**
|
||||
* Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long orderItemId;
|
||||
/**
|
||||
* Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long productId;
|
||||
/**
|
||||
* Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String productTitle;
|
||||
/**
|
||||
* Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long artistId;
|
||||
/**
|
||||
* Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String artistName;
|
||||
/**
|
||||
* Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String customerNickname;
|
||||
/**
|
||||
* Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String customerPhoneMasked;
|
||||
/**
|
||||
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long shopId;
|
||||
/**
|
||||
* Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String shopName;
|
||||
/**
|
||||
* Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private LocalDateTime appointmentStartTime;
|
||||
/**
|
||||
* Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private LocalDateTime appointmentEndTime;
|
||||
/**
|
||||
* Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer quantity;
|
||||
/**
|
||||
* Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long durationMinutes;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class NailArtistAvailabilityVO {
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private String dateText;
|
||||
private String timeText;
|
||||
private Boolean available;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class NailArtistProfileVO {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long artistId;
|
||||
private String artistName;
|
||||
private String avatar;
|
||||
private String identity;
|
||||
private String signature;
|
||||
private Integer experience;
|
||||
private Integer status;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
private BigDecimal rating;
|
||||
private Long serviceCount;
|
||||
private LocalTime workStartTime;
|
||||
private LocalTime workEndTime;
|
||||
private List<String> styleTags = new ArrayList<>();
|
||||
private List<NailArtistWorkVO> works = new ArrayList<>();
|
||||
private List<NailArtistReviewVO> reviews = new ArrayList<>();
|
||||
private List<NailArtistAvailabilityVO> availability = new ArrayList<>();
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class NailArtistReviewVO {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long artistId;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long customerId;
|
||||
private String customerName;
|
||||
private String customerAvatar;
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long productId;
|
||||
private String productTitle;
|
||||
private BigDecimal rating;
|
||||
private String content;
|
||||
private List<Long> imageFileIds = new ArrayList<>();
|
||||
private List<String> imageUrls = new ArrayList<>();
|
||||
private LocalDateTime submittedAt;
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class NailArtistWorkVO {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
private String title;
|
||||
private String description;
|
||||
private BigDecimal price;
|
||||
private String coverImageUrl;
|
||||
private List<String> imageUrls = new ArrayList<>();
|
||||
private List<String> tags = new ArrayList<>();
|
||||
private Integer likeCount;
|
||||
private Integer collectCount;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user