From fc31804f4e774b5428ab50f27f5806cda4bcd6fb Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 2 Nov 2026 22:29:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(msgCenter):=20=E8=A1=A5=E9=BD=90=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E4=B8=AD=E5=BF=83=E6=97=8F=2050=20=E6=9D=A1=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E5=B9=B6=E5=90=8C=E6=AD=A5=E5=A5=91=E7=BA=A6=E4=B8=89?= =?UTF-8?q?=E5=A4=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 影响:面 B 新增 51 条 `/api/message/**` 端点(契约端点 714 → 765,面 B 684 → 735),官方端点覆盖 700/706 → 751/757,`fe-gap` 的 `msgCenter` 列 49/50 → 50/50。 - 改动:新增 `platform/compat/msg_center.rs` —— 真落库 44 条(账号/发送配置/模板含两张子表/敏感词/接收/监控/供应商,落官方 `base_msg_*` + `base_intg_supplier*` 表),诚实失败 7 条(无 HTTP 客户端 ⇒ 接不了任何消息服务商)。 - 改动:契约生成器新增 msgCenter 族(7 个官方 Controller + 3 条官方前端独有路径),`[ENDPOINT]` +51、`[OFFICIAL]` +51,`[FACE]` 面 B 同步。 - 改动:修 8 处创建人/修改人列(存登录账号不是 UUID)、账号复制列与 CAST 长度错位、子表 `SELECT *` 抄错列、复制账号复制出两个默认账号。 - 改动:新增 `tests/batch20_it.rs`(6 条)—— 逐条打 51 条路径防 matchit 冲突 + CRUD 落库 + 两个 ListVO 形状 + 诚实失败断言 + 未登录 602。 - 设计:官方前端 `testConfig` 声明的是动态路径 ⇒ 加同语义别名 `POST /api/message/Account/{id}` 接住;官方 Java 多暴露、官方前端从不调的 12 条端点本期不做。 Co-Authored-By: Claude Code --- .workbuddy/memory/2026-11-02.md | 59 + CLAUDE.md | 4 +- HANDOFF.md | 149 +- docs/contract.md | 109 +- docs/known-limitations.md | 5 + scripts/gen-contract-endpoints.py | 173 +- src/backend/src/platform/compat/mod.rs | 2 + src/backend/src/platform/compat/msg_center.rs | 4411 +++++++++++++++++ src/backend/src/routes.rs | 132 + src/backend/tests/batch20_it.rs | 899 ++++ 10 files changed, 5924 insertions(+), 19 deletions(-) create mode 100644 src/backend/src/platform/compat/msg_center.rs create mode 100644 src/backend/tests/batch20_it.rs diff --git a/.workbuddy/memory/2026-11-02.md b/.workbuddy/memory/2026-11-02.md index a83760e..fb0f5d6 100644 --- a/.workbuddy/memory/2026-11-02.md +++ b/.workbuddy/memory/2026-11-02.md @@ -370,3 +370,62 @@ - 暂缓(用户 2026-11-02 决定):`aiCenter` 75 / `extend` 64 / `msgCenter` 50 / `teamwork` 40 - `systemData` 还剩 3 条(官方声明了但后端从无映射 ⇒ 已记 `oos`,不是待办) - `onlineDev` 还剩 1 条(`docs/fe/endpoints.tsv` 的**旧记录**,官方实际无路径参数 ⇒ 不是待办) + +--- + +## 批次 20(2026-11-02)—— msgCenter 全族(前端 50 条) + +**用户指示**:「msgCenter 50 去做完吧」⇒ 官方前端 `src/api/msgCenter/**` 的**全部 50 个接口** +⇒ 新增 `platform/compat/msg_center.rs` + **51 条面 B 端点**(50 + 1 条动态路径别名)。 + +### 落地分类(一条假数据都没有) +- **真落库 44 条**:消息账号 / 发送配置 / 模板(含**参数、变量两张子表**)/ 敏感词 / + 接收配置 / 监控 / 供应商 —— 落官方 `base_msg_*` + `base_intg_supplier*` 表。 + 🔴 **本批没加表**(那些表早就在 `schema.sql` + `BASE_TABLES` 里)。 +- **诚实失败 7 条**:本仓**没有 HTTP 客户端** ⇒ 接不了任何消息服务商 + ⇒ `400` + `data:null` + 人话(不返假发送结果 / 假模板 / 假连通性): + `Account/testSendMail`、`Account/{id}`(别名)、`Send/testSendConfig`、 + `Template/testSendMail`、`Monitor/{id}/Retry`、`Supplier/SyncTemplate`、`Supplier/TestConnect`。 + +### 定下的口径 +- 🔴 **密钥字段照官方返明文**(`smtpPassword` / `secretKey`):官方 DDL 即明文存、 + 前端要拿回来编辑 ⇒ 照官方。**与「用户登录口令不外泄」是两条不同的红线**。 +- 🔴 **供应商新增/更新跳过连通性检查**(官方先真连服务商)⇒ 写库照做、其余校验全做。 +- 🔴 **无 `msgSendType` 字典** ⇒ `Monitor/Info` 的 `msgTypeList` 由官方 `MessageTypeEnum`(8 项)推。 +- 🔴 **`f_category` 三种语义**:账号/供应商 = 供应商类别码;发送配置/模板/监控 = 业务分类 id 的 JSON 数组。 +- 🔴 **创建人/修改人列存「登录账号」不是 UUID** ⇒ 列表 JOIN `base_user` ON `f_account`(`f_id` 兜底)。 +- 🔴 **msgCenter 不做应用隔离**(`base_msg_*` / `base_intg_supplier*` 没有 `f_system_id` 列)。 +- 🔴 **复制账号不复制 `f_is_default`**(官方会复制出两个默认账号)⇒ 保守不复制 + 复制件停用; + 复制模板 `f_template_type` 硬编码 `"0"`。 +- 🔴 **模板复制要抄两张子表,而两张子表列不一样**(`TemplateParamEntity` vs `MsgVariableEntity`) + ⇒ 各写各的显式列,**禁 `SELECT *`**(`base_msg_variable` 没有 `f_field_name` 列)。 +- 🔴 **`GET /api/message/Receive` 与 `GET /api/message/Supplier` 返 ListVO**(不是 PageListVO)。 +- 🔴 **`Monitor/{id}/Retry` 能力判定排在数据判定之前**(本仓永远发不出去)。 + +### 踩到的坑(都写进 HANDOFF §5「批次 20 新增的坑」了) +1. 🔴🔴 **axum/matchit 同一位置不允许两个不同参数名** ⇒ 注册 + `POST /api/message/Account/{testType}` **启动即 panic** + (`Insertion failed due to conflict with previously registered route: .../{id}`) + ⇒ 静态闸门看不出来、编译也过 ⇒ 只有**真把 router 建起来**才炸 ⇒ 路由扫描测试必须留着。 + ⇒ 同一位置只留一个参数名(本批用 `{id}`,段内容其实是前端的 `testType`)。 +2. 🔴🔴 **写库助手三组长度必须一致**(列 / CAST / 值)⇒ 不一致会**静默写错列**; + 本批真踩到(25 列 vs 24 CAST ⇒ `index out of bounds`)⇒ 已给 `insert_row` 加**运行时形状校验**。 +3. 🔴 **静态抽端点器分不清「动态段」和「路径参数」** ⇒ 官方前端 + ``url: `${Api.Prefix}/${data.testType}` `` 那段其实是**常量**(唯一调用点写死 `'testSendMail'`) + ⇒ 抽端点器记成 `{param}` ⇒ `fe-gap.py` 报缺口 ⇒ 本批加**同语义别名**接住 + (**别为了让尺子变绿去改尺子的判定**)。 +4. 🔴 抄子表禁 `SELECT *`(两张子表列不同);`check-arch` MEM1 会当场判红。 +5. 🔴 官方复制账号会复制出「两个默认账号」⇒ 本仓保守不复制 `f_is_default`。 + +### 数字 +- 契约端点 **765 条**(面 A 28 + 面 B **735** + AB 2);`tables` 153(**本批没加表**) +- `batch20_it` **6 passed**;`cargo test --offline --workspace` **654 passed / 0 failed** +- `check-contract` **PASS=10 FAIL=0**(反自证 12 例全过);官方覆盖 **751/757** + (implemented 581 / partial 170 / absent 6;oos 4 单列) +- `verify.sh --fast` / `--lib` / `--smoke` **全 ✅**(14 步,含 perm-smoke 43 / perm-smoke-jnpf 23 / + lowcode-smoke 15 / baseline-smoke 10 / mcp-smoke 48) +- `fe-gap` 合计 **717/900(79.7%)**;**`msgCenter` 50/50 = 100%**(上轮 667/900 = 74.1%) + +### 剩余 +- 暂缓(用户 2026-11-02 决定,本批**未动**):`aiCenter` 75 / `extend` 64 / `teamwork` 40 +- 官方 Java 多暴露 12 条、官方前端从不调的 msgCenter 端点 ⇒ **本期不做**(已记已知限制 (ap)) diff --git a/CLAUDE.md b/CLAUDE.md index 631c46d..758af79 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -232,7 +232,7 @@ ssw-platform/ 每把尺子结尾比对「实际断言数 vs 契约登记数」,对不上即失败 —— 尺子不会被悄悄改弱。 **加任何业务模块 / 改任何契约 / 加任何 crate 依赖 / 改任何内部标识 / 加任何表,十二道闸门必须全绿才算完成。** -🔴 **`cargo test --workspace` 当前 550 条**(内核 + contract 13 + store 17 + sdk 2 + pack-asset 5 + mcp 52 + adapter-baseline 19 + lowcode 112 + 集成测试)—— +🔴 **`cargo test --workspace` 当前 654 条**(内核 + contract 13 + store 17 + sdk 2 + pack-asset 5 + mcp 52 + adapter-baseline 19 + lowcode 112 + 集成测试)—— 拆 crate 后总数会变,**不许把断言数写死**,跑一遍看实际值。 cipher 自证(免 node):`./target/release/ssw-platform --enc 123456`。 @@ -286,7 +286,7 @@ cp .env.example .env && ./run.sh install && ./run.sh dev ```bash cargo build --release # 编译(workspace 根,含 crates/* 与 packs/*) -cargo test --workspace # 单测(当前 550 条) +cargo test --workspace # 单测(当前 654 条) bash run.sh dev # 起后端(30010) + 前端(5173) bash scripts/perm-smoke.sh # 面 A 43 条 bash scripts/perm-smoke-jnpf.sh # 面 B 23 条 diff --git a/HANDOFF.md b/HANDOFF.md index 39ec58f..2c06e5d 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -353,21 +353,29 @@ React 模板的加模块成本 = **改/加 8 个文件、15~20 分钟**(`HOWTO --- -## 1. 一句话现状(2026-11-02 批次 19 —— workFlow 104 条收尾) +## 1. 一句话现状(2026-11-02 批次 20 —— msgCenter 全族 50 条收尾) **📌 当前数字(以此为准,下面各批的「当时数字」仅存档)**: -- 契约端点 **714 条**(面 A 28 + 面 B **684** + 两面共用 2);`tables` → **153** +- 契约端点 **765 条**(面 A 28 + 面 B **735** + 两面共用 2);`tables` → **153** (`schema.sql` **152** 张 + 业务包 1 张;平台表 `BASE_TABLES` **123** + `WORKFLOW_TABLES` **24** + `REPORT_TABLES` **2** + 内嵌业务表 3)。 -- `cargo test --offline --workspace` = **全绿 0 failed**(**648 passed**;主 lib 105; - `batch19_it` **7 passed**)。 -- 十二道闸门全绿;`check-contract` `PASS=10 FAIL=0`,官方端点覆盖 **700/706** - (implemented 537 / partial 163 / absent 6;oos 4 单列)。 -- `python3 scripts/fe-gap.py`:合计 **667 / 900(74.1%)**、**`workFlow` 104/104(100%)**、 - **`core` 27/27(100%)**、**`onlineDev` 100/101(99.0%)**、 +- `cargo test --offline --workspace` = **全绿 0 failed**(**654 passed**;主 lib 105; + `batch19_it` **7 passed**、`batch20_it` **6 passed**)。 +- 十二道闸门全绿;`check-contract` `PASS=10 FAIL=0`,官方端点覆盖 **751/757** + (implemented 581 / partial 170 / absent 6;oos 4 单列)。 +- `python3 scripts/fe-gap.py`:合计 **717 / 900(79.7%)**、**`msgCenter` 50/50(100%)**、 + **`workFlow` 104/104(100%)**、**`core` 27/27(100%)**、**`onlineDev` 100/101(99.0%)**、 **`permission` 137/137(100%)**、**`system` 196/196(100%)**、 **`systemData` 103/106(97.2%)**。 +- 🔴 **批次 20 把 msgCenter 做完了**(用户 2026-11-02 指示「msgCenter 50 去做完吧」): + 官方前端 `src/api/msgCenter/**` 的**全部 50 个接口** ⇒ 落 **51 条面 B 端点** + (50 条前端接口 + 1 条**动态路径别名**,见下),新增 `platform/compat/msg_center.rs`。 + **真落库 44 条**(消息账号 / 发送配置 / 模板(含参数、变量两张子表)/ 敏感词 / + 接收配置 / 监控记录 / 供应商,落官方 `base_msg_*` + `base_intg_supplier*` 表,DDL 逐字照官方)、 + **诚实失败 7 条**(本仓**无 HTTP 客户端** ⇒ 接不了任何消息服务商: + 测试发信 3 + 测试连接 1 + 同步模板 1 + 重发 1 + 动态路径别名 1)。 + **没有一条返假数据**(不返假发送结果、不返假模板、不返假连通性)。 - 🔴 **批次 19 把 workFlow 做完了**(官方 `jnpf-flowable` + `api/workFlow/**` 共 **104 条**): **真实现 62 条**(流程模板/版本/节点/任务/评论/委托/监控的**元数据**面, 落在**官方 24 张 `workflow_*` 表**上,DDL 逐字导入)、 @@ -1134,6 +1142,72 @@ CRUD 落 `base_time_task`(数据真实、可编辑、重启不丢),`runCou 模板 CRUD 落官方表、评论/委托落库、**27 条引擎端点逐条断言「诚实失败」**、 多应用隔离、未登录 602。 +### 批次 20(2026-11-02)—— msgCenter 全族(前端 50 条) + +**范围**:官方前端 `src/api/msgCenter/**`(`accountConfig` / `sendConfig` / `msgTemplate` / +`sensitive` / `receive` / `monitor` / `supplier`)**全部 50 个接口** +⇒ 新增 `platform/compat/msg_center.rs` + **51 条面 B 端点** +(50 条前端接口 + 1 条**动态路径别名**,见下)。 + +**落地分类(一条假数据都没有)**: +- **真落库 44 条** —— 消息账号(`base_msg_account`)、发送配置(`base_msg_send` + + `base_msg_send_template`)、模板(`base_msg_template` + **两张子表** + `base_msg_template_param` / `base_msg_variable`)、敏感词(`base_msg_sensitive`)、 + 接收配置(`base_msg_receive`)、监控(`base_msg_monitor` / `base_msg_record`)、 + 供应商(`base_intg_supplier`)。🔴 **本批没加表** —— `base_msg_*` / + `base_intg_supplier*` 早就在 `schema.sql` + `BASE_TABLES` 里(官方 DDL 逐字)。 +- **诚实失败 7 条** —— 本仓**没有 HTTP 客户端**(`reqwest`/`ureq` 都没有)⇒ + 接不了任何消息服务商 ⇒ `400` + `data:null` + 人话: + `Account/testSendMail`、`Account/{testType}`(别名)、`Send/testSendConfig`、 + `Template/testSendMail`、`Monitor/{id}/Retry`、`Supplier/SyncTemplate`、 + `Supplier/TestConnect`。 + +**本批定下的口径(都写进了契约 `[OFFICIAL]` 的 note)**: +- 🔴 **密钥字段照官方返明文**(`smtpPassword` / `secretKey`):官方 DDL 就是**明文**存 + (`base_msg_account.f_smtp_password` / `base_intg_supplier.f_secret_key`), + 且官方前端**要拿回来编辑** ⇒ 本仓**照官方**。 + (与「用户登录口令不得外泄」是**两条不同的红线** —— 那条只管 `base_user.f_password`。) +- 🔴 **供应商的新增 / 更新跳过连通性检查**(官方落库前会**真连服务商**做「测试连接」) + ⇒ 本仓**写库照做**、名称 / 编码 / 密钥重复校验全做,只跳过连通性 ⇒ 状态 `implemented`。 +- 🔴 **`msgSendType` 没有官方字典表** ⇒ `Monitor/Info` 的 `msgTypeInfo.msgTypeList` + 由官方 `MessageTypeEnum`(8 项)推出来。 +- 🔴 **`f_category` 有三种语义**:`base_msg_account` / `base_intg_supplier` = **供应商类别码** + (`SMTP` / `TencentCloud` / …,列表按 `MessageEnum` 翻中文名,`SMTP` 原样保留); + `base_msg_send` / `base_msg_template` / `base_msg_monitor` = **业务分类 id 的 JSON 数组**。 +- 🔴 **创建人 / 修改人列存的是「登录账号」不是 UUID**(仓库既有约定,`docs/contract.md:2092`) + ⇒ 列表要显示名字就得 **JOIN `base_user` ON `f_account`**(`f_id` 兜底)。 +- 🔴 **msgCenter 不做应用隔离**:`base_msg_*` / `base_intg_supplier*` **没有 `f_system_id` 列** + ⇒ `App-Code` 头**不影响**这一族(不是漏做,是官方 DDL 如此)。 +- 🔴 **复制账号不复制 `f_is_default`**(官方 `entity.setIsDefault(...)` 会复制出**两个默认账号**) + ⇒ 本仓**保守不复制**(保留 `setDefault` 不变量),复制件 `f_enabled_mark=0`; + 复制模板的 `f_template_type` 硬编码 `"0"`(官方 `MessageTemplateConfigController.java:583`)。 +- 🔴 **模板复制要抄两张子表**,而**两张子表的列不一样** + (官方是两个实体:`TemplateParamEntity` / `MsgVariableEntity`)⇒ 各写各的显式列, + **禁 `SELECT *`**(`base_msg_variable` 根本没有 `f_field_name` 列)。 +- 🔴 **`GET /api/message/Receive` 与 `GET /api/message/Supplier` 返 ListVO** + (`{list:[…]}`,**不是** `{pagination,list}`)—— 官方就是 ListVO。 +- 🔴 **`POST /api/message/Monitor/{id}/Retry` 的能力判定排在数据判定之前**: + 本仓**永远**发不出去 ⇒ 先报「未接入消息服务商」,比「数据不存在」更说明问题。 +- 🔴 **官方前端 `testConfig` 声明的是动态路径** `${Api.Prefix}/${data.testType}` + (`api/msgCenter/accountConfig.ts:33`)⇒ 静态抽端点器把最后一段记成**路径参数** + ⇒ 尺子 `fe-gap.py` 会报缺口。官方 Java **只有静态端点** + `POST /api/message/Account/testSendMail`,而前端**唯一调用点** + (`src/views/integrationCenter/email/Test.vue:59`)把 `testType` 写死成 `'testSendMail'` + ⇒ 运行期 URL 就是那个静态端点(**已实现**)。 + ⇒ 本仓**加一条同语义别名** `POST /api/message/Account/{id}`(参数名必须是 `{id}`, + 见 §5「批次 20 新增的坑」)⇒ `fe-gap` 的 `msgCenter` 列 **50/50(100%)**。 + +**🔴 官方 Java 多暴露 12 条、官方前端从不调的端点 ⇒ 本期不做**(记在已知限制): +Account 的 `detail/{id}` / `unable/{id}` / `Action/Export` / `Action/Import`、 +Template 的同 4 条、Send 的 `/Selector` / `getInfoByEnCode/{enCode}` / `detail/{id}`、 +Monitor 的 `POST /Monitor`。 + +- 回归测试 `tests/batch20_it.rs`(**6 条**):51 条路径逐条打(防 `matchit` 冲突)、 + 账号 CRUD + 复制 + 设默认 + 删默认必须失败、模板 CRUD(含两张子表)+ 发送配置 CRUD、 + 敏感词 / 接收配置 / 供应商 CRUD(**两个 ListVO 形状**钉住)、 + **7 条诚实失败逐条断言**(`code=400` + `data:null` + msg 含「消息服务商」)、 + 面 B 未登录 `602`。 + --- ## 2. 运行中的现场(断了就按这里重启) @@ -1349,13 +1423,20 @@ xop run --secret GU=git_local_user --secret GP=git_local_pass -- bash -c ' 只导元数据、**不导 Flowable 的 `act_*` 引擎表**。 🔴 官方流程引擎是**独立 HTTP 服务**(`FlowAbleUrl` = `/api/Flow/*`), 本仓没有它 ⇒ 一切「动作类」端点一律 `400` + 人话。 - 16. ⏸️ **暂缓**(用户 2026-11-02 决定):`aiCenter` 75 / `extend` 64 / `msgCenter` 50 / `teamwork` 40。 + 16. ⏸️ **暂缓**(用户 2026-11-02 决定):`aiCenter` 75 / `extend` 64 / `teamwork` 40。 + 🔴 **`msgCenter` 50 已按用户指示做完**(批次 20,见 §1「批次 20」小节)—— + 它**不是**「本仓没这个模块」:官方 `base_msg_*` / `base_intg_supplier*` 表本来就在, + 只是端点没接。**做之前先查表存不存在**,别按「没模块」下结论。 17. ✅ **onlineDev 集成测试已写**(`tests/batch17_it.rs`,**11 passed**)—— `matchit` 同位置参数名冲突这类错静态看不出来(批次 12 踩过)⇒ 新端点族落地后**必须**跑一次集成测试。 18. ✅ **workFlow 集成测试已写**(`tests/batch19_it.rs`,**7 passed**)—— 逐条打一遍 104 条路径防 `matchit` 冲突 + 模板 CRUD 落库 + 评论/委托 + **27 条引擎端点逐条断言「诚实失败」** + 多应用隔离 + 未登录 602。 + 19. ✅ **msgCenter 集成测试已写**(`tests/batch20_it.rs`,**6 passed**)—— + 逐条打一遍 51 条路径防 `matchit` 冲突(**同位置参数名冲突就是靠它抓的**)+ + 账号 / 模板 / 发送配置 / 敏感词 / 接收 / 供应商 CRUD 落库 + + **两个 ListVO 形状**(`Receive` / `Supplier`)+ **7 条诚实失败逐条断言** + 未登录 602。 ### 🔴🔴 批次 12(下一轮优先做)—— 「框架固定包 + 业务模块链接就好」 @@ -2053,6 +2134,47 @@ ENC_BIN="$PWD/target/debug/ssw-platform" bash scripts/perm-smoke-jnpf.sh `RawQuery` / `Path` / `HeaderMap` 是 `FromRequestParts`、必须排在它前面 ⇒ 顺序反了**编译不过**(这条比 `matchit` 冲突友好 ⇒ 编译期就能发现)。 +### 批次 20 新增的坑(msgCenter 51 条) + +- 🔴🔴 **axum/matchit:同一位置不允许两个不同的参数名** —— 本批想给官方前端那条 + **动态路径**(`${Api.Prefix}/${data.testType}`)注册 `POST /api/message/Account/{testType}`, + 结果**启动即 panic**: + `Invalid route "/api/message/Account/{testType}": Insertion failed due to conflict with + previously registered route: /api/message/Account/{id}`。 + 🔴 **静态闸门看不出来、编译也过**(路由冲突是**建 router 时**才炸)⇒ + **只有真把 router 建起来才炸** ⇒ 路由扫描测试(`batch20_it` 的 51 条路径逐条打)必须留着。 + ⇒ **同一位置只留一个参数名**(本批用 `{id}`,段内容其实是前端的 `testType`)。 +- 🔴🔴 **写库助手的三组长度必须一致**(列 / CAST / 值)—— 不一致会把值写进**别的列** + 且**不报错**。本批真踩到:`account_copy` 写了 **25 个列名但只有 24 个 CAST** + ⇒ panic `index out of bounds: the len is 25 but the index is 25`(这条路径此前从没跑过)。 + ⇒ 已给 `insert_row` 加**运行时形状校验**:不一致就**明确失败** + (宁可不写,也不静默写坏数据)。 +- 🔴 **抄子表禁 `SELECT *`** —— 模板的**参数表**与**变量表**是官方两个实体 + (`TemplateParamEntity` / `MsgVariableEntity`),**列不一样** + (`base_msg_variable` **没有** `f_field_name` 列)⇒ 抄错列会**静默写坏数据**。 + 🔴 `check-arch` 的 MEM1(禁 `SELECT *`)会当场把这种写法判红 —— 照做即可。 +- 🔴 **静态抽端点器分不清「动态段」和「路径参数」** —— 官方前端 + ``url: `${Api.Prefix}/${data.testType}` `` 里那最后一段**其实是常量** + (唯一调用点写死 `'testSendMail'`)⇒ 抽端点器记成 `{param}` ⇒ 尺子 `fe-gap.py` 报缺口。 + ⇒ 两种收法:① 加一条**同语义别名**把「声明的路径形状」也接住(本批选的); + ② 在契约/交接里写明「这是抽取器的产物,官方后端只有静态端点」。 + 🔴 别为了让尺子变绿去**改尺子的判定**。 +- 🔴 **创建人 / 修改人 / 删除人列存的是「登录账号」不是 UUID**(仓库既有约定)⇒ + 列表要显示人名得 **JOIN `base_user` ON `f_account`**(`f_id` 兜底), + 直接拿它当 `f_id` 去 JOIN 会**查不到**(结果是空名,不是报错)。 +- 🔴 **官方 DDL 就是明文存密钥**(`f_smtp_password` / `f_secret_key`)且前端要拿回来编辑 + ⇒ 照官方返明文。**「口令不得外泄」那条红线只管 `base_user.f_password`**, + 两者别混(混了就等于把用户口令的口径套到第三方服务商密钥上)。 +- 🔴 **`f_category` 有三种语义**(账号 / 供应商 = 供应商类别码; + 发送配置 / 模板 / 监控 = 业务分类 id 的 JSON 数组)⇒ 同一列在不同表里**读法不同**, + 写反了前端看到的是「分类名列表」或「编码」,不会报错。 +- 🔴 **列表形状有两种**:`GET /api/message/Receive` 与 `GET /api/message/Supplier` 返 + **ListVO**(`{list:[…]}`)⇒ 写成 `{pagination,list}` 前端拿到的 `pagination` 是 `undefined`。 +- 🔴 **能力判定要排在数据判定之前**:`POST /api/message/Monitor/{id}/Retry` —— 本仓**永远** + 发不出去 ⇒ 先报「未接入消息服务商」;先查数据会让用户以为「id 写错了」。 +- 🔴 **官方复制账号会复制出「两个默认账号」**(官方把 `isDefault` 一起复制) + ⇒ 本仓**保守不复制** `f_is_default`(保住 `setDefault` 不变量),并把复制件置为**停用**。 + --- ## 6. 收工前(每一轮都要做) @@ -2069,8 +2191,9 @@ ENC_BIN="$PWD/target/debug/ssw-platform" bash scripts/perm-smoke-jnpf.sh | ssw-platform P2-b 收尾 | `1dcb55af-…` | 已过期(一次性,未删) | P2-b 已完成 ⇒ **可删** | | 每日积分 | `82c41449-…` | 每日 08:00 | 与本仓无关 | -🔴 **2026-11-02 批次 19 收尾时实查:本会话没有挂任何定时任务**(`CronList` = 空)⇒ -**没有下一次自动续跑**。理由:面 B 剩下四族(`aiCenter` 75 / `extend` 64 / -`msgCenter` 50 / `teamwork` 40)是**用户 2026-11-02 明确暂缓**的 +🔴 **2026-11-02 批次 20 收尾时实查:本会话没有挂任何定时任务**(`CronList` = 空)⇒ +**没有下一次自动续跑**。理由:面 B 剩下三族(`aiCenter` 75 / `extend` 64 / +`teamwork` 40)是**用户 2026-11-02 明确暂缓**的 ⇒ **不该自己续跑**(续跑等于推翻用户的暂缓决定)。 -⇒ 若要恢复自动续跑,需**先拿到用户的新指示**(或用户改口「继续做暂缓的那四族」)。 +⇒ 若要恢复自动续跑,需**先拿到用户的新指示**(或用户改口「继续做暂缓的那三族」)。 +(🔴 `msgCenter` 50 是**用户当天单独点名要做的**(「msgCenter 50 去做完吧」)⇒ 批次 20 已做完。) diff --git a/docs/contract.md b/docs/contract.md index d0e26d3..1873bb8 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -437,7 +437,7 @@ SELECT row_to_json(q)::text AS _row FROM () AS q ## 6. 端点全表 > 🔴 **本节是「人读」版;机器可读版在附录 A 的 `[ENDPOINT]` 区段** -> (列:`face` / `method` / `path` / `guard` / `owner`,一行一条端点,**610** 条; +> (列:`face` / `method` / `path` / `guard` / `owner`,一行一条端点,**765** 条; > 外加 `[FACE]` 区段登记各契约面的条数)。 > 由 **`scripts/check-contract.sh`** 把它与**代码里真实注册的路由**逐条对账 > (总数 / 存在性 / 方法 / 归属层 / 守卫,**双向**)⇒ @@ -445,7 +445,7 @@ SELECT row_to_json(q)::text AS _row FROM () AS q > 🔴 **改端点时两处都要改**:本节的散文表 + 附录 A 的 `[ENDPOINT]`。 > > 📊 **本仓对「官方 JNPF 契约面」的覆盖**是另一本账:附录 A 的 **`[OFFICIAL]`** 区段 -> (607 行 = 官方端点全表 + 每个端点的 `status` 四态 + 官方出处 `文件:行号`)⇒ +> (761 行 = 官方端点全表 + 每个端点的 `status` 四态 + 官方出处 `文件:行号`)⇒ > 由 `check-contract.sh` 的 **CC10** 与代码真实路由**双向**对账 ⇒ > 打印「官方端点覆盖 N/M」。官方端点全表的人读版在 `JNPF_SOURCE_AUDIT.md` §4。 @@ -1860,6 +1860,58 @@ B GET /api/workflow/trigger/task 登录 platform B DELETE /api/workflow/trigger/task workFlow.flowMonitor platform B POST /api/workflow/trigger/task/Retry/{id} workFlow.flowMonitor platform +B GET /api/message/Account integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B POST /api/message/Account integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B GET /api/message/Account/{id} integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B PUT /api/message/Account/{id} integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B DELETE /api/message/Account/{id} integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B POST /api/message/Account/{id}/Actions/Copy integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B POST /api/message/Account/testSendMail integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B PUT /api/message/Account/setdefault 登录 platform +B GET /api/message/Send msgCenter.sendConfig platform +B POST /api/message/Send msgCenter.sendConfig platform +B GET /api/message/Send/{id} 登录 platform +B PUT /api/message/Send/{id} msgCenter.sendConfig platform +B DELETE /api/message/Send/{id} msgCenter.sendConfig platform +B POST /api/message/Send/{id}/Actions/Copy msgCenter.sendConfig platform +B POST /api/message/Send/getTestConfig/{id} msgCenter.sendConfig platform +B POST /api/message/Send/testSendConfig msgCenter.sendConfig platform +B GET /api/message/Send/getSendConfigList 登录 platform +B GET /api/message/Template msgCenter.msgTemplate|integrationCenter.sms|integrationCenter.email platform +B POST /api/message/Template msgCenter.msgTemplate platform +B GET /api/message/Template/{id} msgCenter.msgTemplate|integrationCenter.sms|integrationCenter.email platform +B PUT /api/message/Template/{id} msgCenter.msgTemplate platform +B DELETE /api/message/Template/{id} msgCenter.msgTemplate platform +B POST /api/message/Template/{id}/Actions/Copy msgCenter.msgTemplate platform +B POST /api/message/Template/testSendMail msgCenter.msgTemplate platform +B GET /api/message/Sensitive 登录 platform +B POST /api/message/Sensitive 登录 platform +B GET /api/message/Sensitive/{id} 登录 platform +B PUT /api/message/Sensitive/{id} 登录 platform +B DELETE /api/message/Sensitive/{id} 登录 platform +B GET /api/message/Receive 登录 platform +B POST /api/message/Receive 登录 platform +B GET /api/message/Monitor 登录 platform +B GET /api/message/Monitor/detail/{id} msgCenter.msgRecord platform +B DELETE /api/message/Monitor/batchRemove msgCenter.msgRecord platform +B DELETE /api/message/Monitor/empty msgCenter.msgRecord platform +B GET /api/message/Monitor/{id}/RecordList msgCenter.msgRecord platform +B GET /api/message/Monitor/Info 登录 platform +B POST /api/message/Monitor/{id}/Retry 登录 platform +B GET /api/message/Supplier 登录 platform +B POST /api/message/Supplier 登录 platform +B GET /api/message/Supplier/Selector 登录 platform +B GET /api/message/Supplier/{id} 登录 platform +B PUT /api/message/Supplier/{id} 登录 platform +B DELETE /api/message/Supplier/{id} 登录 platform +B GET /api/message/Supplier/TemplateList integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform +B POST /api/message/Supplier/{id}/Actions/Copy 登录 platform +B POST /api/message/Supplier/SyncTemplate 登录 platform +B POST /api/message/Supplier/TestConnect 登录 platform +B PUT /api/message/Supplier/{id}/Actions/State 登录 platform +B GET /api/message/Supplier/{id}/VariableList 登录 platform +B POST /api/message/Account/{id} integrationCenter.sms|integrationCenter.email|integrationCenter.weChatMp|integrationCenter.webhook platform + # 🔴 以下由 `scripts/pack-sync.py` 从 `packs/*` 生成 —— **不许手改** # (下次同步会被覆盖;改包就够) @@ -1883,7 +1935,7 @@ B DELETE /api/asset/DataResource/{id} permission.asset.dataResource asset [FACE] # face 条数 说明 A 28 面 A 专属(+ 2 条共用 ⇒ 面 A 合计 30 条) -B 684 面 B 专属(官方 JNPF 形状;批次 13 新增 Area 7 + Variate 7;批次 14 新增数据中心 29;批次 15 新增系统服务 39;批次 16 新增权限关系 26;批次 17 新增 onlineDev 78 + Report 23;批次 18 新增 core 22;批次 19 新增 workFlow 104) +B 735 面 B 专属(官方 JNPF 形状;批次 13 新增 Area 7 + Variate 7;批次 14 新增数据中心 29;批次 15 新增系统服务 39;批次 16 新增权限关系 26;批次 17 新增 onlineDev 78 + Report 23;批次 18 新增 core 22;批次 19 新增 workFlow 104;批次 20 新增 msgCenter 51(前端 50 + 动态路径别名 1)) AB 2 两面共用(CurrentUser / Authority Data —— 按判别头分流) [OFFICIAL] @@ -2621,6 +2673,57 @@ GET /api/workflow/trigger/task/List implemented TriggerTaskController.java:59 GET /api/workflow/trigger/task implemented TriggerTaskController.java:72 面 B 已落地:流程**元数据**(模板 / 版本 / 节点 / 评论 / 委托 / 监控 / 触发记录)**真落库**到官方 24 张 `workflow_*` 表(DDL 逐字照官方);**引擎动作**(发起 / 审批 / 办理 …)因本仓未接入 Flowable ⇒ **明确业务失败** DELETE /api/workflow/trigger/task implemented TriggerTaskController.java:110 面 B 已落地:流程**元数据**(模板 / 版本 / 节点 / 评论 / 委托 / 监控 / 触发记录)**真落库**到官方 24 张 `workflow_*` 表(DDL 逐字照官方);**引擎动作**(发起 / 审批 / 办理 …)因本仓未接入 Flowable ⇒ **明确业务失败** POST /api/workflow/trigger/task/Retry/{id} partial TriggerTaskController.java:97 本仓未接入流程引擎(Flowable,官方是**独立 HTTP 服务** `FlowAbleUrl`)⇒ **明确业务失败** +GET /api/message/Account implemented AccountController.java:113 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Account implemented AccountController.java:176 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Account/{id} implemented AccountController.java:205 面 B 已落地:`smtpPassword` 等密钥字段**照官方返回明文**(官方 DDL 即明文存、前端要拿回来编辑;与「用户登录口令不得外泄」是两条不同的红线) +PUT /api/message/Account/{id} implemented AccountController.java:255 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +DELETE /api/message/Account/{id} implemented AccountController.java:324 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Account/{id}/Actions/Copy implemented AccountController.java:394 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Account/testSendMail partial AccountController.java:470 本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**(不返假发送结果 / 假模板) +PUT /api/message/Account/setdefault implemented AccountController.java:160 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Send implemented SendMessageConfigController.java:143 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Send implemented SendMessageConfigController.java:304 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Send/{id} implemented SendMessageConfigController.java:443 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +PUT /api/message/Send/{id} implemented SendMessageConfigController.java:545 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +DELETE /api/message/Send/{id} implemented SendMessageConfigController.java:657 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Send/{id}/Actions/Copy implemented SendMessageConfigController.java:757 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Send/getTestConfig/{id} implemented SendMessageConfigController.java:680 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Send/testSendConfig partial SendMessageConfigController.java:719 本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**(不返假发送结果 / 假模板) +GET /api/message/Send/getSendConfigList implemented SendMessageConfigController.java:226 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Template implemented MessageTemplateConfigController.java:117 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Template implemented MessageTemplateConfigController.java:174 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Template/{id} implemented MessageTemplateConfigController.java:250 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +PUT /api/message/Template/{id} implemented MessageTemplateConfigController.java:334 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +DELETE /api/message/Template/{id} implemented MessageTemplateConfigController.java:518 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Template/{id}/Actions/Copy implemented MessageTemplateConfigController.java:569 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Template/testSendMail partial api/msgCenter/msgTemplate.ts:33 本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**(不返假发送结果 / 假模板) +GET /api/message/Sensitive implemented MsgSensitiveController.java:34 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Sensitive implemented MsgSensitiveController.java:42 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Sensitive/{id} implemented MsgSensitiveController.java:49 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +PUT /api/message/Sensitive/{id} implemented MsgSensitiveController.java:63 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +DELETE /api/message/Sensitive/{id} implemented MsgSensitiveController.java:56 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Receive implemented MsgReceiveController.java:29 面 B 已落地:官方返 **ListVO**(`{list:[…]}`,**不是分页**);每条含 `channels` / `configJson`(渠道矩阵)与业务分类的`categoryName` / `subCategoryName` / `topCategoryName` +POST /api/message/Receive implemented MsgReceiveController.java:39 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Monitor implemented MessageMonitorController.java:100 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Monitor/detail/{id} implemented MessageMonitorController.java:222 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +DELETE /api/message/Monitor/batchRemove implemented MessageMonitorController.java:176 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +DELETE /api/message/Monitor/empty implemented MessageMonitorController.java:190 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Monitor/{id}/RecordList implemented MessageMonitorController.java:277 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Monitor/Info implemented MessageMonitorController.java:139 面 B 已落地:`msgTypeInfo.msgTypeList` 官方走 `msgSendType` **字典**⇒ 本仓**无此字典** ⇒ 改用官方 `MessageTypeEnum` 的 8 个消息类型;`noticeInfo` 按官方口径只统计「公告」业务分类(`f_category` 含 `2046494646179336192`) +POST /api/message/Monitor/{id}/Retry partial MessageMonitorController.java:315 本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**(不返假发送结果 / 假模板) +GET /api/message/Supplier implemented IntgSupplierController.java:86 面 B 已落地:`secretKey` **照官方返回明文**(官方 DDL 即明文存);官方 VO 里 `supplierName`/`supplierId`/`smsSignature`/`isDefault`/`content` **没有数据来源**(实体里没这些字段)⇒ 本仓同官方返 null +POST /api/message/Supplier implemented IntgSupplierController.java:94 面 B 已落地:官方在落库前会**真连服务商**做「测试连接」⇒ 本仓**跳过连通性检查**(名称 / 编码 / 密钥重复校验全做,落库照做) +GET /api/message/Supplier/Selector implemented IntgSupplierController.java:193 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Supplier/{id} implemented IntgSupplierController.java:201 面 B 已落地:`secretKey` **照官方返回明文**;`isEditor` = 该供应商**没有模板**(官方:`CollUtil.isEmpty(tplEntities)`) +PUT /api/message/Supplier/{id} implemented IntgSupplierController.java:166 面 B 已落地:同新增 —— 官方先真连服务商做「测试连接」⇒ 本仓**跳过连通性检查**(其余校验全做) +DELETE /api/message/Supplier/{id} implemented IntgSupplierController.java:221 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Supplier/TemplateList implemented IntgSupplierController.java:240 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Supplier/{id}/Actions/Copy implemented IntgSupplierController.java:209 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Supplier/SyncTemplate partial IntgSupplierController.java:260 本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**(不返假发送结果 / 假模板) +POST /api/message/Supplier/TestConnect partial api/msgCenter/supplier.ts:45 本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**(不返假发送结果 / 假模板) +PUT /api/message/Supplier/{id}/Actions/State implemented IntgSupplierController.java:275 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +GET /api/message/Supplier/{id}/VariableList implemented IntgSupplierController.java:266 面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / 监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` 表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP 客户端 ⇒ **明确业务失败** +POST /api/message/Account/{id} partial api/msgCenter/accountConfig.ts:33 官方前端 `testConfig` 的**动态**路径(`${Api.Prefix}/${data.testType}`,`api/msgCenter/accountConfig.ts:33`)的**同语义别名**;运行期 `testType` 写死为 `testSendMail` ⇒ 打到官方静态端点(已实现)。本仓无 HTTP 客户端 ⇒ **明确业务失败**(不返假发送结果) [RULER] # name 期望断言数(尺子**自己**断言的条数;跑出来的条数对不上 ⇒ 失败) diff --git a/docs/known-limitations.md b/docs/known-limitations.md index a29414b..54073f5 100644 --- a/docs/known-limitations.md +++ b/docs/known-limitations.md @@ -90,6 +90,11 @@ | (ai) | **`AuthorizeDataReturnVO.list`(权限树模型)返空数组** —— 只保证 `ids`/`all` 语义正确 | 面 B 规格 §8 B1 | 官方那套树模型(`modelId` + `button`/`column`/`resource`/`form` 子树)本仓不做。**代价**:官方授权弹窗需二次适配(`ids` 可直接用) | | (aj) | **组织 `AsyncList/{id}` 不分页** —— 按父 id 逐层取,`pageSize` = 本层条数 | 面 B 规格 §8 B10 | 官方前端就是靠这个接口**逐层展开**机构树。**代价**:机构极多时无分页保护(本仓机构表本身很小) | | (ak) | **`DELETE /api/permission/Organize/{id}` 不级联** —— 只软删本行 | 面 B 实现 2026-10-31 | 官方删父机构会连带子机构。**代价**:删父后子机构**悬挂**(`f_parent_id` 指向已软删的行),列表里**不会再出现**(`f_delete_mark=0` 过滤)⇒ 表现为「孤儿节点静默消失」。v1 不做递归是**有意**的(避免一次请求删掉整棵子树) | +| (am) | **消息中心 7 条「真连服务商」端点恒明确失败** —— 本仓**没有 HTTP 客户端** ⇒ `Account/testSendMail` / `Account/{id}`(前端动态路径别名) / `Send/testSendConfig` / `Template/testSendMail` / `Monitor/{id}/Retry` / `Supplier/SyncTemplate` / `Supplier/TestConnect` 一律 `code=400` + `data:null` + 人话 | 面 B 实现 2026-11-02(批次 20) | **不返假发送结果、不返假模板、不返假连通性**。代价:官方前端「发送测试 / 测试连接 / 同步模板 / 重发」按钮点下去只会看到失败提示(本仓确实发不出去) | +| (an) | **消息账号 / 供应商的密钥字段照官方返明文**(`smtpPassword` / `secretKey`) | 面 B 实现 2026-11-02(批次 20) | 官方 DDL 就是**明文**存(`base_msg_account.f_smtp_password` / `base_intg_supplier.f_secret_key`)且官方前端**要拿回来编辑** ⇒ 本仓**照官方**。🔴 与「用户登录口令不得外泄」是**两条不同的红线**(那条只管 `base_user.f_password`)。代价:**第三方服务商密钥会出现在响应体与前端内存里** | +| (ao) | **供应商的新增 / 更新跳过「测试连接」** | 面 B 实现 2026-11-02(批次 20) | 官方落库前会**真连服务商**做「测试连接」⇒ 本仓**写库照做**(名称 / 编码 / 密钥重复校验全做),只跳过连通性。代价:**可能落库一个连不通的供应商**(官方会当场拦下) | +| (ap) | **官方 Java 多暴露 12 条、官方前端从不调的 msgCenter 端点,本批不做** | 面 B 实现 2026-11-02(批次 20) | Account 的 `detail/{id}` / `unable/{id}` / `Action/Export` / `Action/Import`、Template 的同 4 条、Send 的 `/Selector` / `getInfoByEnCode/{enCode}` / `detail/{id}`、Monitor 的 `POST /Monitor`。代价:**按官方 Java 直接调的第三方客户端**会拿到 404(官方前端一条都不调) | +| (aq) | **消息中心不做应用隔离** | 面 B 实现 2026-11-02(批次 20) | `base_msg_*` / `base_intg_supplier*` **没有 `f_system_id` 列**(官方 DDL 如此)⇒ `App-Code` 头**不影响**这一族。代价:**同一租户下多个应用的配置项互相可见**(与「多应用 = 同一租户下的多个子系统」口径一致,不是隔离漏洞) | | (al) | ~~**`GET /api/permission/Users` 的 `keyword` 不生效**~~ —— ✅ **2026-10-31 已补齐**:`f_account` / `f_real_name` / `f_mobile_phone` 三列 ILIKE,空关键词**一个参数都不传** | 面 B 实现 2026-10-31 | 🔴 坑:空关键词时若仍把 `like` 塞进参数数组 ⇒ SQL 里没有 `$1`,PG 报「bind message supplies 1 parameters, but prepared statement requires 0」⇒ **必须** `if keyword.is_empty() { Vec::new() }` | ### H.1 🔴 一条**判别规则**(不是限制,是红线) diff --git a/scripts/gen-contract-endpoints.py b/scripts/gen-contract-endpoints.py index 6d6aa50..509d032 100644 --- a/scripts/gen-contract-endpoints.py +++ b/scripts/gen-contract-endpoints.py @@ -395,6 +395,94 @@ REPORT_FRONTEND_LINES = { "GET /api/Report/data/{id}/getQueryList": 106, } +# 🔴 **消息中心族(批次 20)**:官方 `jnpf-message` 的 Controller ⇒ 文件名 + 映射行号。 +# +# 🔴 **范围**:官方前端 `src/api/msgCenter/**` 的**全部 50 个接口**。 +# 官方 Java 还多暴露 12 条前端从不调的(Account 的 `detail/{id}` / `unable/{id}` / +# `Action/Export` / `Action/Import`,Template 的同 4 条,Send 的 `/Selector` / +# `getInfoByEnCode/{enCode}` / `detail/{id}`,Monitor 的 `POST /Monitor`) +# ⇒ **本期不做**(官方前端不需要)⇒ 记在 `HANDOFF.md` 的已知限制里。 +_MSG_CENTER_CONTROLLERS = { + "AccountController.java": { + "GET /api/message/Account": 113, + "PUT /api/message/Account/setdefault": 160, + "POST /api/message/Account": 176, + "GET /api/message/Account/{id}": 205, + "PUT /api/message/Account/{id}": 255, + "DELETE /api/message/Account/{id}": 324, + "POST /api/message/Account/{id}/Actions/Copy": 394, + "POST /api/message/Account/testSendMail": 470, + }, + "SendMessageConfigController.java": { + "GET /api/message/Send": 143, + "GET /api/message/Send/getSendConfigList": 226, + "POST /api/message/Send": 304, + "GET /api/message/Send/{id}": 443, + "PUT /api/message/Send/{id}": 545, + "DELETE /api/message/Send/{id}": 657, + "POST /api/message/Send/getTestConfig/{id}": 680, + "POST /api/message/Send/testSendConfig": 719, + "POST /api/message/Send/{id}/Actions/Copy": 757, + }, + "MessageTemplateConfigController.java": { + "GET /api/message/Template": 117, + "POST /api/message/Template": 174, + "GET /api/message/Template/{id}": 250, + "PUT /api/message/Template/{id}": 334, + "DELETE /api/message/Template/{id}": 518, + "POST /api/message/Template/{id}/Actions/Copy": 569, + }, + "MsgSensitiveController.java": { + "GET /api/message/Sensitive": 34, + "POST /api/message/Sensitive": 42, + "GET /api/message/Sensitive/{id}": 49, + "DELETE /api/message/Sensitive/{id}": 56, + "PUT /api/message/Sensitive/{id}": 63, + }, + "MsgReceiveController.java": { + "GET /api/message/Receive": 29, + "POST /api/message/Receive": 39, + }, + "MessageMonitorController.java": { + "GET /api/message/Monitor": 100, + "GET /api/message/Monitor/Info": 139, + "DELETE /api/message/Monitor/batchRemove": 176, + "DELETE /api/message/Monitor/empty": 190, + "GET /api/message/Monitor/detail/{id}": 222, + "GET /api/message/Monitor/{id}/RecordList": 277, + "POST /api/message/Monitor/{id}/Retry": 315, + }, + "IntgSupplierController.java": { + "GET /api/message/Supplier": 86, + "POST /api/message/Supplier": 94, + "PUT /api/message/Supplier/{id}": 166, + "GET /api/message/Supplier/Selector": 193, + "GET /api/message/Supplier/{id}": 201, + "POST /api/message/Supplier/{id}/Actions/Copy": 209, + "DELETE /api/message/Supplier/{id}": 221, + "GET /api/message/Supplier/TemplateList": 240, + "POST /api/message/Supplier/SyncTemplate": 260, + "GET /api/message/Supplier/{id}/VariableList": 266, + "PUT /api/message/Supplier/{id}/Actions/State": 275, + }, +} + +# 🔴 消息中心族里**官方 Java 没有对应 `@XxxMapping`** 的 3 条 +# (官方前端自己声明了这三个接口,官方 Java 后端没实现)⇒ 出处指官方前端。 +# +# 🔴 第三条 `POST /api/message/Account/{id}` 是**动态路径**: +# 官方前端 `api/msgCenter/accountConfig.ts:33` 写 `${Api.Prefix}/${data.testType}` +# ⇒ 静态抽端点器把最后一段记成路径参数。官方 Java 只有静态端点 +# `POST /api/message/Account/testSendMail`(`AccountController.java:470`), +# 而前端**唯一调用点**(`src/views/integrationCenter/email/Test.vue:59`)把 +# `testType` 写死成 `'testSendMail'` ⇒ 运行期 URL 就是那个静态端点(**已实现**)。 +# 这条别名把「前端声明的路径形状」也接住(行为与静态端点完全一致)。 +_MSG_CENTER_FRONTEND_ONLY = { + "POST /api/message/Template/testSendMail": "api/msgCenter/msgTemplate.ts:33", + "POST /api/message/Supplier/TestConnect": "api/msgCenter/supplier.ts:45", + "POST /api/message/Account/{id}": "api/msgCenter/accountConfig.ts:33", +} + # 🔴 **状态判定**:本仓**诚实失败**(无文件服务 / 无渲染器 / 无数据引擎) # 的端点 ⇒ `partial`(已落地但**形状有偏差**);完全对齐 ⇒ `implemented`。 # 键 = `(method, path)`;值 = (status, note)。 @@ -606,9 +694,75 @@ PARTIAL_NOTES[("GET", "/api/flowForm/Form/getFormById/{id}")] = ( "`workflow_form_relation.f_form_id → f_flow_id` 返流程主键" "(**不返假流程号**)") +# 🔴 ---- 消息中心族(批次 20)---- +# +# 🔴 **6 条「真发消息 / 真连服务商」** ⇒ 本仓**没有 HTTP 客户端** +# ⇒ 一律**明确业务失败**(不返假发送结果、不返假模板)。 +_MSG_CENTER_SEND_PATHS = [ + ("POST", "/api/message/Account/testSendMail"), + ("POST", "/api/message/Send/testSendConfig"), + ("POST", "/api/message/Template/testSendMail"), + ("POST", "/api/message/Monitor/{id}/Retry"), + ("POST", "/api/message/Supplier/SyncTemplate"), + ("POST", "/api/message/Supplier/TestConnect"), +] +for _m, _p in _MSG_CENTER_SEND_PATHS: + PARTIAL_NOTES[(_m, _p)] = ( + "partial", "本仓无 HTTP 客户端(不接任何消息服务商)⇒ **明确业务失败**" + "(不返假发送结果 / 假模板)") + +# 🔴 官方前端 `testConfig` 的**动态路径**别名(`${Api.Prefix}/${data.testType}`): +# 官方 Java 只有静态端点 `/Account/testSendMail`,前端调用点把 `testType` +# 写死成 `'testSendMail'` ⇒ 运行期就是那个静态端点;本条是**同语义别名**。 +PARTIAL_NOTES[("POST", "/api/message/Account/{id}")] = ( + "partial", "官方前端 `testConfig` 的**动态**路径(`${Api.Prefix}/${data.testType}`," + "`api/msgCenter/accountConfig.ts:33`)的**同语义别名**;运行期 " + "`testType` 写死为 `testSendMail` ⇒ 打到官方静态端点(已实现)。" + "本仓无 HTTP 客户端 ⇒ **明确业务失败**(不返假发送结果)") + +# 🔴 供应商的新增 / 更新:官方会先**真连服务商**做「测试连接」⇒ +# 本仓跳过连通性检查(**写库照做**),其余校验(名称 / 编码 / 密钥重复)全做。 +PARTIAL_NOTES[("POST", "/api/message/Supplier")] = ( + "implemented", "面 B 已落地:官方在落库前会**真连服务商**做「测试连接」⇒ " + "本仓**跳过连通性检查**(名称 / 编码 / 密钥重复校验全做," + "落库照做)") +PARTIAL_NOTES[("PUT", "/api/message/Supplier/{id}")] = ( + "implemented", "面 B 已落地:同新增 —— 官方先真连服务商做「测试连接」⇒ " + "本仓**跳过连通性检查**(其余校验全做)") + +# 🔴 消息账号 / 供应商的**密钥字段**:官方 DDL 就是**明文**存 +# (`base_msg_account.f_smtp_password` / `base_intg_supplier.f_secret_key`) +# 且官方前端**要拿回来编辑** ⇒ 本仓**照官方**返回(与「用户登录口令不得外泄」 +# 是两码事 —— 那条只管 `base_user.f_password`)。 +PARTIAL_NOTES[("GET", "/api/message/Account/{id}")] = ( + "implemented", "面 B 已落地:`smtpPassword` 等密钥字段**照官方返回明文**" + "(官方 DDL 即明文存、前端要拿回来编辑;与「用户登录口令不得外泄」" + "是两条不同的红线)") +PARTIAL_NOTES[("GET", "/api/message/Supplier")] = ( + "implemented", "面 B 已落地:`secretKey` **照官方返回明文**(官方 DDL 即明文存);" + "官方 VO 里 `supplierName`/`supplierId`/`smsSignature`/`isDefault`/" + "`content` **没有数据来源**(实体里没这些字段)⇒ 本仓同官方返 null") +PARTIAL_NOTES[("GET", "/api/message/Supplier/{id}")] = ( + "implemented", "面 B 已落地:`secretKey` **照官方返回明文**;`isEditor` = 该供应商" + "**没有模板**(官方:`CollUtil.isEmpty(tplEntities)`)") + +# 🔴 消息审计 `msgTypeInfo.msgTypeList`:官方走 `msgSendType` **字典** +# ⇒ 本仓**没有这个字典** ⇒ 改用官方 `MessageTypeEnum` 的 8 个消息类型。 +PARTIAL_NOTES[("GET", "/api/message/Monitor/Info")] = ( + "implemented", "面 B 已落地:`msgTypeInfo.msgTypeList` 官方走 `msgSendType` **字典**" + "⇒ 本仓**无此字典** ⇒ 改用官方 `MessageTypeEnum` 的 8 个消息类型;" + "`noticeInfo` 按官方口径只统计「公告」业务分类" + "(`f_category` 含 `2046494646179336192`)") + +# 🔴 消息接收配置 `GET /api/message/Receive`:官方返的是 **ListVO**(不是分页)。 +PARTIAL_NOTES[("GET", "/api/message/Receive")] = ( + "implemented", "面 B 已落地:官方返 **ListVO**(`{list:[…]}`,**不是分页**);" + "每条含 `channels` / `configJson`(渠道矩阵)与业务分类的" + "`categoryName` / `subCategoryName` / `topCategoryName`") + # 🔴 **端点顺序**:按官方模块分组,组内按路径排 —— 与 `routes.rs` 的注册顺序对齐 # (⇒ 契约读起来与代码读起来同序 ⇒ 人工 review 不用来回跳)。 -MODULE_ORDER = ["core", "online_dev", "report", "workflow"] +MODULE_ORDER = ["core", "online_dev", "report", "workflow", "msg_center"] # 🔴 **默认 note**(未在 `PARTIAL_NOTES` 里显式标注的端点)。 DEFAULT_NOTES = { @@ -621,6 +775,10 @@ DEFAULT_NOTES = { "workflow": "面 B 已落地:流程**元数据**(模板 / 版本 / 节点 / 评论 / 委托 / " "监控 / 触发记录)**真落库**到官方 24 张 `workflow_*` 表(DDL 逐字照官方);" "**引擎动作**(发起 / 审批 / 办理 …)因本仓未接入 Flowable ⇒ **明确业务失败**", + "msg_center": "面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / " + "监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` " + "表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP " + "客户端 ⇒ **明确业务失败**", } @@ -713,6 +871,19 @@ def official_entry(mod, key, path): status, note = PARTIAL_NOTES.get(key, ("implemented", DEFAULT_NOTES["workflow"])) return src, status, note raise SystemExit("workflow 族没有官方出处可登记:%s %s" % (method, path)) + if mod == "msg_center": + # 🔴 消息中心族(批次 20):官方 `jnpf-message` 的 Controller 优先, + # 官方 Java **没有**映射的 2 条 ⇒ 落到官方前端 `api/msgCenter/**`。 + for ctrl, table in _MSG_CENTER_CONTROLLERS.items(): + if k in table: + src = "%s:%d" % (ctrl, table[k]) + status, note = PARTIAL_NOTES.get(key, ("implemented", DEFAULT_NOTES["msg_center"])) + return src, status, note + src = _MSG_CENTER_FRONTEND_ONLY.get(k) + if src: + status, note = PARTIAL_NOTES.get(key, ("implemented", DEFAULT_NOTES["msg_center"])) + return src, status, note + raise SystemExit("msg_center 族没有官方出处可登记:%s %s" % (method, path)) # onlineDev for ctrl, table in _VISUALDEV_CONTROLLERS.items(): if k in table: diff --git a/src/backend/src/platform/compat/mod.rs b/src/backend/src/platform/compat/mod.rs index 43faa4c..897b710 100644 --- a/src/backend/src/platform/compat/mod.rs +++ b/src/backend/src/platform/compat/mod.rs @@ -12,6 +12,7 @@ //! | `core` | `api/core/**` | `/api/oauth/*` 等 | //! | `online_dev` | `api/onlineDev/**` | `/api/onlineDev/*`、`/api/Report/*` | //! | `work_flow` | `api/workFlow/**` | `/api/workflow/*` | +//! | `msg_center` | `api/msgCenter/**` | `/api/message/*` | //! //! 🔴 **`helper` 不是官方模块**:它是契约面的**公共底座**(导入 / 通用工具 / //! 判别头 / 守卫 / 共享常量 / 菜单与用户信息构造),被多个官方模块共用。 @@ -25,3 +26,4 @@ pub mod core; pub mod online_dev; pub mod report; pub mod workflow; +pub mod msg_center; diff --git a/src/backend/src/platform/compat/msg_center.rs b/src/backend/src/platform/compat/msg_center.rs new file mode 100644 index 0000000..e38a55b --- /dev/null +++ b/src/backend/src/platform/compat/msg_center.rs @@ -0,0 +1,4411 @@ +//! msgCenter —— 官方 **消息中心**(`/api/message/*`)端点集(50 条)。 +//! +//! 🔴 **本仓的范围**:官方 `jnpf-message` 模块 + 官方前端 `api/msgCenter/**` 的 +//! **50 个调用点**(`accountConfig.ts` 8 + `sendConfig.ts` 9 + `msgTemplate.ts` 7 +//! + `msgSecurity.ts` 5 + `receiveConfig.ts` 2 + `msgMonitor.ts` 7 + `supplier.ts` 12)。 +//! 官方 Java **另有 12 条前端从不调的端点**(导出 / 导入 / `detail` / `unable` …) +//! ⇒ 本批**不做**(见 `HANDOFF.md` 的「批次 20」已知限制)。 +//! +//! 🔴 **本仓没有 HTTP 客户端** ⇒ **六个「要真发消息 / 要连服务商」的端点一律 +//! 明确业务失败**(`code=400` + 可读原因;**绝不返假发送结果**): +//! `POST /api/message/Account/testSendMail` / `POST /api/message/Send/testSendConfig` +//! / `POST /api/message/Template/testSendMail` / `POST /api/message/Supplier/TestConnect` +//! / `POST /api/message/Supplier/SyncTemplate` / `POST /api/message/Monitor/{id}/Retry`。 +//! +//! 🔴 **`f_category` 有三套语义**(最容易做错的地方 ⇒ 三套解析器,不能混): +//! | 表 | 存什么 | 怎么读 | +//! |---|---|---| +//! | `base_msg_account` | **供应商类别码**(`SMTP` / `TencentCloud` / …) | `MessageEnum` 查中文名(`SMTP` 保留原样) | +//! | `base_intg_supplier` | **供应商类别码**(同上) | 原样返回 | +//! | `base_msg_send` / `base_msg_template` / `base_msg_monitor` | **业务类别 id 的 JSON 数组串**(`["2046494646179336192"]`) | 解析成 id 数组,再查 `base_business_category` 换名字 | +//! +//! 🔴 **`f_creator_user_id` 存的是「登录账号」**(本仓约定;官方存的是 userId) +//! ⇒ 取创建人姓名一律 `JOIN base_user ON f_account = f_creator_user_id`。 +//! +//! 🔴 **口令类字段照官方返回**(`smtpPassword` / `secretKey`):官方 DDL 就是**明文**列, +//! 官方前端编辑既有配置时**必须**回填它们 ⇒ 照官方返回;这与「用户登录口令不得外泄」 +//! (只针对 `base_user.f_password`)**是两回事**。 +//! +//! 🔴 **写路径的三条硬律**(与契约面其余模块同一套): +//! 1. 列名只来自常量白名单(请求里的键**永不**进 SQL 文本); +//! 2. 只 SET body 里真出现的键; +//! 3. 审计列用 SQL 自己的 `now()`,**不占参数位**。 + +use axum::body::Bytes; +use axum::extract::{Path, RawQuery, State}; +use axum::http::HeaderMap; +use axum::Json; +use serde_json::{json, Map, Value}; +use std::collections::HashMap; + +use crate::platform::auth::require_login_face_b; +use crate::platform::crud::value_to_text; +use crate::platform::envelope::{code, fail, ok, ActionResult}; +use crate::platform::ids::new_uuid; +use crate::platform::state::AppState; + +use super::helper::{ + db_error, guard, guard_any, id_list_of, list_vo, page_list, params_of, parse_body, + placeholder, qv, text_field, Paging, +}; + +// ---------------------------------------------------------------- 点权限编码 + +/// 🔴 官方 `SendMessageConfigController` 的 `@SaCheckPermission("msgCenter.sendConfig")`。 +pub(super) const EN_MSG_SEND_CONFIG: &str = "msgCenter.sendConfig"; + +/// 🔴 官方 `MessageTemplateConfigController` 的 `@SaCheckPermission("msgCenter.msgTemplate")`。 +pub(super) const EN_MSG_TEMPLATE: &str = "msgCenter.msgTemplate"; + +/// 🔴 官方 `MessageMonitorController` 的 `@SaCheckPermission("msgCenter.msgRecord")`。 +pub(super) const EN_MSG_RECORD: &str = "msgCenter.msgRecord"; + +/// 🔴 官方 `AccountController` 的 `@SaCheckPermission({"integrationCenter.sms", …})`。 +pub(super) const EN_INTEGRATION_SMS: &str = "integrationCenter.sms"; +pub(super) const EN_INTEGRATION_EMAIL: &str = "integrationCenter.email"; +pub(super) const EN_INTEGRATION_WECHAT_MP: &str = "integrationCenter.weChatMp"; +pub(super) const EN_INTEGRATION_WEBHOOK: &str = "integrationCenter.webhook"; + +// ---------------------------------------------------------------- 官方枚举(照抄,不自创) + +/// 🔴 官方 `MessageTypeEnum`(`code` → `message`)。 +const MESSAGE_TYPES: [(&str, &str); 8] = [ + ("1", "站内信"), + ("2", "邮件"), + ("3", "短信"), + ("4", "钉钉"), + ("5", "企业微信"), + ("6", "群机器人"), + ("7", "微信公众号"), + ("8", "飞书"), +]; + +/// 🔴 官方 `MessageEnum`(供应商类别 `code` → `categoryName`)。 +const SUPPLIER_CATEGORIES: [(&str, &str); 7] = [ + ("AlibabaCloud", "阿里云"), + ("TencentCloud", "腾讯云"), + ("SMTP", "自建邮箱"), + ("DingTalk", "钉钉"), + ("Feishu", "飞书"), + ("WeWork", "企业微信"), + ("WeMP", "微信公众号"), +]; + +/// 🔴 官方 `BusinessCategoryEnum.NOTICE` 的 `enCode` = `announce` ⇒ 官方 `base_business_category` +/// 里 `f_en_code = 'announce'` 的那一行 id(本仓种子里的固定字面量 id)。 +const NOTICE_CATEGORY_ID: &str = "2046494646179336192"; + +/// 🔴 官方 `MsgCode` 文案(写端点的 `msg` 前端会直接 toast 出来 ⇒ 照抄)。 +const MSG_CREATED: &str = "新建成功"; +const MSG_UPDATED: &str = "更新成功"; +const MSG_DELETED: &str = "删除成功"; +const MSG_COPIED: &str = "复制成功"; +const MSG_OPERATED: &str = "操作成功"; +const MSG_SAVED: &str = "保存成功"; + +/// 🔴 官方 `MsgCode` 的失败文案。 +const MSG_DUP_ENCODE: &str = "编码不能重复"; +const MSG_DATA_NOT_FOUND: &str = "操作失败,数据不存在"; +const MSG_COPY_FAILED: &str = "复制失败,数据不存在"; +const MSG_COPY_LIMIT: &str = "已到达该模板复制上限,请复制源模板"; +const MSG_DEFAULT_CANNOT_DELETE: &str = "默认数据无法删除"; +const MSG_SUPPLIER_RELATED: &str = "供应商被关联引用,不允许被禁用"; +const MSG_SUPPLIER_RELATED_DELETE: &str = "供应商被关联引用,不允许被删除"; +const MSG_NO_TEMPLATE: &str = "配置模板无数据,无法测试"; +const MSG_DUP_SENSITIVE: &str = "敏感词内容已存在"; +const MSG_DISABLE_CANNOT_DEFAULT: &str = "禁用配置无法设为默认"; + +// ---------------------------------------------------------------- 「能力不存在」的统一口径 + +/// 🔴 **要真连服务商 / 真发消息**的端点 —— 明确业务失败(不返假发送结果)。 +fn unsupported_provider(what: &str) -> Json { + fail( + code::FAIL, + format!("本仓未接入消息服务商(无 HTTP 客户端),不支持{what}"), + ) +} + +/// 成功但**带官方文案**的响应(`data` 为 null)。 +fn ok_msg(msg: &str) -> Json { + Json(ActionResult { + code: code::SUCCESS, + msg: msg.to_string(), + data: Value::Null, + }) +} + +// ---------------------------------------------------------------- 通用小工具 + +/// body ⇒ 白名单内的 `(列, CAST, 值)`;**只收 body 里真出现的键**。 +fn write_fields( + obj: &Map, + whitelist: &[(&'static str, &'static str, &'static str)], +) -> Vec<(&'static str, &'static str, Option)> { + let mut out = Vec::new(); + for (json_key, column, cast) in whitelist { + if obj.contains_key(*json_key) { + out.push((*column, *cast, value_to_text(obj.get(*json_key)))); + } + } + out +} + +/// 解析 JSON body ⇒ 对象(**不是对象 ⇒ 400**)。 +fn body_obj(body: &Bytes) -> Result, Json> { + match parse_body(body) { + Ok(Value::Object(o)) => Ok(o), + Ok(_) => Err(fail(code::FAIL, "请求参数格式错误")), + Err(resp) => Err(resp), + } +} + +/// 分页跑批:count 与 list **共用同一组前缀参数**(分页参数追加在末尾)。 +async fn paged_query( + state: &AppState, + select_cols: &str, + from_sql: &str, + where_body: &str, + order_by: &str, + mut values: Vec>, + page: &Paging, + ctx: &str, +) -> Result<(i64, Vec), Json> { + let count_sql = format!("SELECT count(*)::bigint AS \"c\" FROM {from_sql} WHERE {where_body}"); + let total = match state.db.query_json_params(&count_sql, ¶ms_of(&values)).await { + Ok(rows) => rows + .into_iter() + .next() + .and_then(|r| r["c"].as_i64()) + .unwrap_or(0), + Err(e) => return Err(db_error(e, &format!("{ctx}总数查询"))), + }; + + values.push(Some(page.page_size.to_string())); + values.push(Some(page.offset.to_string())); + let p_limit = values.len() - 1; + let p_offset = values.len(); + let sql = format!( + "SELECT {select_cols} FROM {from_sql} WHERE {where_body} {order_by} \ + LIMIT ${p_limit}::text::integer OFFSET ${p_offset}::text::integer" + ); + let rows = match state.db.query_json_params(&sql, ¶ms_of(&values)).await { + Ok(rows) => rows, + Err(e) => return Err(db_error(e, &format!("{ctx}查询"))), + }; + Ok((total, rows)) +} + +/// 插入一行:列名只来自白名单;审计列用 `now()`(**不占参数位**)。 +async fn insert_row( + state: &AppState, + table: &str, + columns: &[&str], + casts: &[&str], + values: &[Option], + creator: &str, + ctx: &str, +) -> Result<(), Json> { + // 🔴 **三组长度必须一致** —— 不一致说明调用方写错了列白名单(列 / CAST / 值错位), + // 错位会把值写进**别的列**且**不报错**。宁可明确失败,也不静默写坏数据。 + if columns.len() != casts.len() || columns.len() != values.len() { + return Err(fail( + code::FAIL, + format!( + "内部错误:写入形状不一致(列 {} / 类型 {} / 值 {},{ctx})", + columns.len(), + casts.len(), + values.len() + ), + )); + } + let mut cols: Vec<&str> = columns.to_vec(); + let mut cas: Vec<&str> = casts.to_vec(); + let mut vals: Vec> = values.to_vec(); + cols.push("f_creator_user_id"); + cas.push(""); + vals.push(Some(creator.to_string())); + cols.push("f_creator_time"); + let mut marks: Vec = (0..vals.len()) + .map(|i| placeholder(i + 1, cas[i])) + .collect(); + marks.push("now()".to_string()); + let sql = format!( + "INSERT INTO {table} ({}) VALUES ({})", + cols.join(", "), + marks.join(", ") + ); + match state.db.exec_params(&sql, ¶ms_of(&vals)).await { + Ok(_) => Ok(()), + Err(e) => Err(db_error(e, ctx)), + } +} + +/// 改一行:只 SET body 里真出现的键 + 审计列(`now()` 不占参数位)。 +async fn update_row( + state: &AppState, + table: &str, + id: &str, + sets: &[(&'static str, &'static str, Option)], + modifier: &str, + ctx: &str, +) -> Result<(), Json> { + if sets.is_empty() { + return Ok(()); + } + let mut parts: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + for (column, cast, value) in sets { + values.push(value.clone()); + parts.push(format!("{column} = {}", placeholder(values.len(), cast))); + } + values.push(Some(modifier.to_string())); + let p_user = values.len(); + parts.push("f_last_modify_time = now()".to_string()); + parts.push(format!("f_last_modify_user_id = ${p_user}::text")); + values.push(Some(id.to_string())); + let p_id = values.len(); + let sql = format!( + "UPDATE {table} SET {} WHERE f_id = ${p_id}::text AND COALESCE(f_delete_mark, 0) = 0", + parts.join(", ") + ); + match state.db.exec_params(&sql, ¶ms_of(&values)).await { + Ok(_) => Ok(()), + Err(e) => Err(db_error(e, ctx)), + } +} + +/// 软删除一行(官方 `f_delete_mark = 1` 口径)。 +async fn soft_delete( + state: &AppState, + table: &str, + id: &str, + deleter: &str, + ctx: &str, +) -> Result<(), Json> { + let sql = format!( + "UPDATE {table} SET f_delete_mark = 1, f_delete_time = now(), \ + f_delete_user_id = $1::text WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0" + ); + let values = vec![Some(deleter.to_string()), Some(id.to_string())]; + match state.db.exec_params(&sql, ¶ms_of(&values)).await { + Ok(_) => Ok(()), + Err(e) => Err(db_error(e, ctx)), + } +} + +/// 查一行(`{"…": …}` 形状)。 +async fn fetch_one( + state: &AppState, + sql: &str, + values: &[Option], + ctx: &str, +) -> Result, Json> { + match state.db.query_json_params(sql, ¶ms_of(values)).await { + Ok(rows) => Ok(rows.into_iter().next()), + Err(e) => Err(db_error(e, ctx)), + } +} + +/// 查多行。 +async fn fetch_all( + state: &AppState, + sql: &str, + values: &[Option], + ctx: &str, +) -> Result, Json> { + match state.db.query_json_params(sql, ¶ms_of(values)).await { + Ok(rows) => Ok(rows), + Err(e) => Err(db_error(e, ctx)), + } +} + +/// 取一行里的字符串字段。 +fn sv(row: &Value, key: &str) -> String { + match row.get(key) { + Some(Value::String(s)) => s.clone(), + Some(Value::Null) | None => String::new(), + Some(other) => other.to_string(), + } +} + +/// 取一行里的整数字段。 +fn iv(row: &Value, key: &str) -> Option { + row.get(key).and_then(|v| match v { + Value::Number(n) => n.as_i64(), + Value::String(s) => s.trim().parse::().ok(), + _ => None, + }) +} + +/// 官方 `MessageTypeEnum` 的中文名(认不出来就原样返回 code)。 +fn message_type_name(code: &str) -> String { + for (c, name) in MESSAGE_TYPES.iter() { + if *c == code { + return name.to_string(); + } + } + code.to_string() +} + +/// 官方 `MessageEnum` 的中文名(`SMTP` 保留原样 —— 官方 `AccountController.list` 就这么干)。 +fn supplier_category_name(code: &str) -> String { + if code == "SMTP" { + return "SMTP".to_string(); + } + for (c, name) in SUPPLIER_CATEGORIES.iter() { + if *c == code { + return name.to_string(); + } + } + code.to_string() +} + +/// 🔴 **业务类别 id 数组串**(`base_msg_send` / `base_msg_template` / `base_msg_monitor` 的 +/// `f_category` 存的是 `JsonUtil.getObjectToString(list)` ⇒ `["2046494646179336192"]`)。 +fn parse_category_ids(raw: Option<&str>) -> Vec { + let text = match raw { + Some(t) => t.trim(), + None => return Vec::new(), + }; + if text.is_empty() { + return Vec::new(); + } + if text.starts_with('[') { + if let Ok(Value::Array(items)) = serde_json::from_str::(text) { + return items + .iter() + .filter_map(|v| match v { + Value::String(s) if !s.is_empty() => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + }) + .collect(); + } + } + text.split(',') + .map(|s| s.trim().trim_matches('"').to_string()) + .filter(|s| !s.is_empty()) + .collect() +} + +/// 业务类别 id 数组 ⇒ 官方显示名(`-` 连接,官方 `joining("-")`)。 +fn join_category_names(ids: &[String], map: &HashMap) -> String { + ids.iter() + .filter_map(|id| map.get(id).map(|(full, _)| full.clone())) + .collect::>() + .join("-") +} + +/// 业务类别(`base_business_category`)⇒ `id → (full_name, parent_id)`。 +async fn business_category_map( + state: &AppState, +) -> Result, Json> { + let sql = "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_parent_id AS \"parentId\" \ + FROM base_business_category \ + WHERE COALESCE(f_enabled_mark, 1) = 1 AND COALESCE(f_delete_mark, 0) = 0"; + let rows = fetch_all(state, sql, &[], "业务类别查询").await?; + let mut map = HashMap::new(); + for row in rows { + let id = sv(&row, "id"); + if id.is_empty() { + continue; + } + let full = sv(&row, "fullName"); + let parent = { + let p = sv(&row, "parentId"); + if p.is_empty() { + "-1".to_string() + } else { + p + } + }; + map.insert(id, (full, parent)); + } + Ok(map) +} + +/// 官方 `RandomUtil` 风格的 5 位后缀(复制用)。 +fn copy_suffix() -> String { + new_uuid()[..5].to_string() +} + +/// 时间参数归一(官方有的端点用 epoch 毫秒、有的用 `yyyy-MM-dd HH:mm:ss`)⇒ +/// 统一成能喂给 `::text::timestamp` 的串。 +fn normalize_time(raw: &str) -> Option { + let t = raw.trim(); + if t.is_empty() { + return None; + } + if let Ok(ms) = t.parse::() { + return chrono::DateTime::from_timestamp_millis(ms) + .map(|d| d.with_timezone(&chrono::Local).format("%Y-%m-%d %H:%M:%S").to_string()); + } + if t.len() == 10 { + return Some(format!("{t} 00:00:00")); + } + if let Some(head) = t.get(..19) { + return Some(head.to_string()); + } + None +} + +/// 官方 `MessageTypeEnum` 去掉「群机器人」后的**默认接收渠道矩阵**。 +fn default_channels() -> Vec { + MESSAGE_TYPES + .iter() + .filter(|(code, _)| *code != "6") + .map(|(code, name)| { + json!({ + "fullName": name, + "enCode": code, + "isCheck": true, + "isLock": *code == "1", + }) + }) + .collect() +} + +/// 解析已存的渠道配置(`base_msg_receive.f_config_json` 是一段 JSON 数组串)。 +fn parse_channels(raw: Option<&str>) -> Vec { + let text = match raw { + Some(t) => t.trim(), + None => return Vec::new(), + }; + if text.is_empty() { + return Vec::new(); + } + match serde_json::from_str::(text) { + Ok(Value::Array(items)) => items + .into_iter() + .filter(|v| v.is_object()) + .collect::>(), + _ => Vec::new(), + } +} + +// ================================================================ 账号配置(8 条) +// +// 🔴 官方 `AccountController`(`@RequestMapping("/api/message/Account")`)。 +// 守卫:`@SaCheckPermission({"integrationCenter.sms","integrationCenter.email", +// "integrationCenter.weChatMp","integrationCenter.webhook"}, mode=OR)`; +// `PUT /setdefault` 官方**没有**点权限 ⇒ 只要登录。 + +/// 🔴 官方 `AccountConfigCrModel` ⇒ 列白名单。 +const ACCOUNT_WRITE_FIELDS: &[(&str, &str, &str)] = &[ + ("category", "f_category", ""), + ("fullName", "f_full_name", ""), + ("enCode", "f_en_code", ""), + ("endPoint", "f_end_point", ""), + ("supplierId", "f_supplier_id", ""), + ("addressName", "f_address_name", ""), + ("smtpServer", "f_smtp_server", ""), + ("smtpPort", "f_smtp_port", "::integer"), + ("sslLink", "f_ssl_link", "::integer"), + ("smtpUser", "f_smtp_user", ""), + ("smtpPassword", "f_smtp_password", ""), + ("messageType", "f_message_type", ""), + ("token", "f_token", ""), + ("aesKey", "f_aes_key", ""), + ("region", "f_region", ""), + ("sdkAppId", "f_sdk_app_id", ""), + ("webhookAddress", "f_webhook_address", ""), + ("approveType", "f_approve_type", "::integer"), + ("sortCode", "f_sort_code", "::bigint"), + ("description", "f_description", ""), + ("enabledMark", "f_enabled_mark", "::integer"), + ("smsSignature", "f_sms_signature", ""), +]; + +const ACCOUNT_LIST_COLUMNS: &str = "a.f_id AS \"id\", a.f_full_name AS \"fullName\", \ + a.f_category AS \"category\", a.f_en_code AS \"enCode\", a.f_address_name AS \"addressorName\", \ + a.f_smtp_user AS \"smtpUser\", a.f_sms_signature AS \"smsSignature\", \ + COALESCE(a.f_sort_code, 0) AS \"sortCode\", COALESCE(a.f_enabled_mark, 0) AS \"enabledMark\", \ + (EXTRACT(EPOCH FROM a.f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + a.f_creator_user_id AS \"creatorUserId\", \ + (EXTRACT(EPOCH FROM a.f_last_modify_time) * 1000)::bigint AS \"lastModifyTime\", \ + COALESCE(u.f_real_name, '') || '/' || COALESCE(u.f_account, '') AS \"creatorUser\", \ + COALESCE(a.f_is_default, 0) AS \"isDefault\", a.f_supplier_id AS \"supplierId\", \ + s.f_full_name AS \"supplierFullName\""; + +const ACCOUNT_FROM: &str = "base_msg_account a \ + LEFT JOIN base_user u ON u.f_id = COALESCE( \ + (SELECT u2.f_id FROM base_user u2 WHERE u2.f_account = a.f_creator_user_id LIMIT 1), \ + a.f_creator_user_id) \ + LEFT JOIN base_intg_supplier s ON s.f_id = a.f_supplier_id"; + +/// 🔴 官方 `AccountConfigListVO` 的 17 个字段(顺序照官方 VO)。 +fn shape_account_row(row: &Value) -> Value { + let supplier_full = sv(row, "supplierFullName"); + let full_name = if supplier_full.is_empty() { + sv(row, "fullName") + } else { + supplier_full + }; + json!({ + "id": sv(row, "id"), + "fullName": full_name, + "category": supplier_category_name(&sv(row, "category")), + "type": Value::Null, + "enCode": sv(row, "enCode"), + "addressorName": sv(row, "addressorName"), + "smtpUser": sv(row, "smtpUser"), + "supplierName": Value::Null, + "smsSignature": sv(row, "smsSignature"), + "webhookType": Value::Null, + "sortCode": iv(row, "sortCode"), + "enabledMark": iv(row, "enabledMark").map(|v| v.to_string()).unwrap_or_default(), + "creatorTime": iv(row, "creatorTime"), + "creatorUserId": sv(row, "creatorUserId"), + "lastModifyTime": iv(row, "lastModifyTime"), + "creatorUser": sv(row, "creatorUser"), + "isDefault": iv(row, "isDefault"), + }) +} + +/// `GET /api/message/Account` —— 账号配置列表。 +/// +/// 官方 `AccountController.java:113`(`@SaCheckPermission({…}, mode=OR)` @109)。 +pub async fn account_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let message_type = qv(&raw, "messageType"); + let category = qv(&raw, "category"); + let enabled_mark = qv(&raw, "enabledMark"); + + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "AND (a.f_full_name ILIKE ${next}::text OR a.f_en_code ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !message_type.is_empty() { + filters.push(format!("AND a.f_message_type = ${next}::text")); + values.push(Some(message_type)); + next += 1; + } + if !category.is_empty() { + filters.push(format!("AND a.f_category = ${next}::text")); + values.push(Some(category)); + next += 1; + } + if !enabled_mark.is_empty() { + filters.push(format!("AND a.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + } + let where_body = format!( + "COALESCE(a.f_delete_mark, 0) = 0{}", + if filters.is_empty() { + String::new() + } else { + format!(" {}", filters.join(" ")) + } + ); + match paged_query( + &state, + ACCOUNT_LIST_COLUMNS, + ACCOUNT_FROM, + &where_body, + "ORDER BY COALESCE(a.f_sort_code, 0) ASC, a.f_creator_time DESC", + values, + &page, + "账号配置列表", + ) + .await + { + Ok((total, rows)) => { + let list: Vec = rows.iter().map(shape_account_row).collect(); + ok(page_list(page.current_page, page.page_size, total, list)) + } + Err(resp) => resp, + } +} + +/// `POST /api/message/Account` —— 新建账号配置。 +/// +/// 官方 `AccountController.java:176`(编码重复 ⇒ `MsgCode.EXIST002`)。 +pub async fn account_create( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let full_name = text_field(&obj, "fullName").unwrap_or_default(); + if full_name.is_empty() { + return fail(code::FAIL, "名称不能为空"); + } + let en_code = text_field(&obj, "enCode").unwrap_or_default(); + let category = text_field(&obj, "category").unwrap_or_default(); + if !en_code.is_empty() { + let dup = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_account \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_en_code = $1::text \ + AND ($2::text = '' OR f_category = $2::text) LIMIT 1", + &[Some(en_code.clone()), Some(category.clone())], + "账号配置查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup.is_some() { + return fail(code::FAIL, MSG_DUP_ENCODE); + } + } + + let new_id = new_uuid(); + let mut columns: Vec<&str> = vec!["f_id", "f_tenant_id"]; + let mut casts: Vec<&str> = vec!["", ""]; + let mut values: Vec> = vec![Some(new_id), Some("0".to_string())]; + for (column, cast, value) in write_fields(&obj, ACCOUNT_WRITE_FIELDS) { + columns.push(column); + casts.push(cast); + values.push(value); + } + columns.push("f_delete_mark"); + casts.push("::integer"); + values.push(Some("0".to_string())); + columns.push("f_is_default"); + casts.push("::integer"); + values.push(Some("0".to_string())); + if let Err(resp) = insert_row( + &state, + "base_msg_account", + &columns, + &casts, + &values, + &user.account, + "新建账号配置", + ) + .await + { + return resp; + } + ok_msg(MSG_CREATED) +} + +/// `GET /api/message/Account/{id}` —— 账号配置详情。 +/// +/// 官方 `AccountController.java:205`(`isEditor` = 供应商模板还没被消息模板引用时为 true)。 +pub async fn account_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + return resp; + } + let row = match fetch_one( + &state, + "SELECT a.f_id AS \"id\", a.f_full_name AS \"fullName\", a.f_en_code AS \"enCode\", \ + a.f_address_name AS \"addressName\", a.f_smtp_server AS \"smtpServer\", \ + a.f_smtp_port AS \"smtpPort\", a.f_ssl_link AS \"sslLink\", a.f_smtp_user AS \"smtpUser\", \ + a.f_smtp_password AS \"smtpPassword\", a.f_sms_signature AS \"smsSignature\", \ + a.f_end_point AS \"endpoint\", a.f_sdk_app_id AS \"sdkAppId\", a.f_webhook_address AS \"webhookAddress\", \ + a.f_approve_type AS \"approveType\", a.f_sort_code AS \"sortCode\", \ + a.f_enabled_mark AS \"enabledMark\", a.f_description AS \"description\", \ + a.f_supplier_id AS \"supplierId\", a.f_region AS \"region\", a.f_category AS \"category\", \ + a.f_token AS \"token\", a.f_aes_key AS \"aesKey\", a.f_message_type AS \"messageType\", \ + s.f_full_name AS \"supplierFullName\" \ + FROM base_msg_account a LEFT JOIN base_intg_supplier s ON s.f_id = a.f_supplier_id \ + WHERE a.f_id = $1::text AND COALESCE(a.f_delete_mark, 0) = 0", + &[Some(id.clone())], + "账号配置详情", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + + // 🔴 官方 `isEditor`:该账号挂了供应商模板、且这些模板已被消息模板引用 ⇒ 不可编辑。 + let supplier_id = sv(&row, "supplierId"); + let message_type = sv(&row, "messageType"); + let mut is_editor = true; + if !supplier_id.is_empty() { + let used = match fetch_one( + &state, + "SELECT t.f_id AS \"id\" FROM base_msg_template t \ + WHERE COALESCE(t.f_delete_mark, 0) = 0 AND t.f_template_id IN ( \ + SELECT st.f_id FROM base_intg_supplier_tpl st \ + WHERE COALESCE(st.f_delete_mark, 0) = 0 AND st.f_supplier_id = $1::text \ + AND ($2::text = '' OR st.f_message_type = $2::text)) LIMIT 1", + &[Some(supplier_id.clone()), Some(message_type.clone())], + "账号配置模板引用查询", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + is_editor = used.is_none(); + } + + let supplier_full = sv(&row, "supplierFullName"); + let full_name = if supplier_full.is_empty() { + sv(&row, "fullName") + } else { + supplier_full + }; + ok(json!({ + "id": sv(&row, "id"), + "fullName": full_name, + "type": Value::Null, + "enCode": sv(&row, "enCode"), + "addressName": sv(&row, "addressName"), + "smtpServer": sv(&row, "smtpServer"), + "smtpPort": iv(&row, "smtpPort"), + "sslLink": iv(&row, "sslLink"), + "smtpUser": sv(&row, "smtpUser"), + "smtpPassword": sv(&row, "smtpPassword"), + "channel": Value::Null, + "smsSignature": sv(&row, "smsSignature"), + "appId": Value::Null, + "appSecret": Value::Null, + "endpoint": sv(&row, "endpoint"), + "sdkAppId": sv(&row, "sdkAppId"), + "appKey": Value::Null, + "zoneName": Value::Null, + "zoneParam": Value::Null, + "enterpriseId": Value::Null, + "agentId": Value::Null, + "webhookType": Value::Null, + "webhookAddress": sv(&row, "webhookAddress"), + "approveType": iv(&row, "approveType"), + "bearer": Value::Null, + "userName": Value::Null, + "password": Value::Null, + "sortCode": iv(&row, "sortCode"), + "enabledMark": iv(&row, "enabledMark"), + "description": sv(&row, "description"), + "supplierId": supplier_id, + "region": sv(&row, "region"), + "category": sv(&row, "category"), + "token": sv(&row, "token"), + "aesKey": sv(&row, "aesKey"), + "isEditor": is_editor, + })) +} + +/// `PUT /api/message/Account/{id}` —— 更新账号配置。 +pub async fn account_update( + State(state): State, + headers: HeaderMap, + Path(id): Path, + body: Bytes, +) -> Json { + let user = match guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_account \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "账号配置存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + if let Err(resp) = update_row( + &state, + "base_msg_account", + &id, + &write_fields(&obj, ACCOUNT_WRITE_FIELDS), + &user.account, + "更新账号配置", + ) + .await + { + return resp; + } + ok_msg(MSG_UPDATED) +} + +/// `DELETE /api/message/Account/{id}` —— 删除账号配置(默认配置不许删 ⇒ `MsgCode.FA062`)。 +pub async fn account_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + Ok(u) => u, + Err(resp) => return resp, + }; + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", COALESCE(f_is_default, 0) AS \"isDefault\" FROM base_msg_account \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "账号配置删除前查询", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + if iv(&row, "isDefault").unwrap_or(0) == 1 { + return fail(code::FAIL, MSG_DEFAULT_CANNOT_DELETE); + } + if let Err(resp) = soft_delete(&state, "base_msg_account", &id, &user.account, "删除账号配置").await + { + return resp; + } + ok_msg(MSG_DELETED) +} + +/// `POST /api/message/Account/{id}/Actions/Copy` —— 复制账号配置。 +/// +/// 官方 `AccountController.java:394`(`fullName + ".副本" + 5 位` / `enCode + 5 位` / 复制件禁用)。 +pub async fn account_copy( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + Ok(u) => u, + Err(resp) => return resp, + }; + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_category AS \"category\", f_end_point AS \"endPoint\", f_supplier_id AS \"supplierId\", \ + f_address_name AS \"addressName\", f_smtp_server AS \"smtpServer\", f_smtp_port AS \"smtpPort\", \ + f_ssl_link AS \"sslLink\", f_smtp_user AS \"smtpUser\", f_smtp_password AS \"smtpPassword\", \ + f_message_type AS \"messageType\", f_token AS \"token\", f_aes_key AS \"aesKey\", \ + f_region AS \"region\", f_sdk_app_id AS \"sdkAppId\", f_webhook_address AS \"webhookAddress\", \ + f_approve_type AS \"approveType\", f_sort_code AS \"sortCode\", f_description AS \"description\", \ + f_sms_signature AS \"smsSignature\" \ + FROM base_msg_account WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "账号配置复制源", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_COPY_FAILED), + }; + let suffix = copy_suffix(); + let full_name = format!("{}.副本{}", sv(&row, "fullName"), suffix); + let en_code = format!("{}{}", sv(&row, "enCode"), suffix); + if en_code.len() > 50 || full_name.len() > 50 { + return fail(code::FAIL, MSG_COPY_LIMIT); + } + let new_id = new_uuid(); + let values = vec![ + Some(new_id), + Some("0".to_string()), + Some(full_name), + Some(en_code), + Some(sv(&row, "category")), + Some(sv(&row, "endPoint")), + Some(sv(&row, "supplierId")), + Some(sv(&row, "addressName")), + Some(sv(&row, "smtpServer")), + iv(&row, "smtpPort").map(|v| v.to_string()), + iv(&row, "sslLink").map(|v| v.to_string()), + Some(sv(&row, "smtpUser")), + Some(sv(&row, "smtpPassword")), + Some(sv(&row, "messageType")), + Some(sv(&row, "token")), + Some(sv(&row, "aesKey")), + Some(sv(&row, "region")), + Some(sv(&row, "sdkAppId")), + Some(sv(&row, "webhookAddress")), + iv(&row, "approveType").map(|v| v.to_string()), + iv(&row, "sortCode").map(|v| v.to_string()), + Some(sv(&row, "description")), + Some("0".to_string()), + Some(sv(&row, "smsSignature")), + // 🔴 官方复制件会**连 `f_is_default` 一起复制**(= 同一消息类型出现两个默认)。 + // 本仓取更保守口径:复制件一律**不是默认**(保 `setDefault` 的「一类型一默认」不变量)。 + Some("0".to_string()), + ]; + let columns = [ + "f_id", + "f_tenant_id", + "f_full_name", + "f_en_code", + "f_category", + "f_end_point", + "f_supplier_id", + "f_address_name", + "f_smtp_server", + "f_smtp_port", + "f_ssl_link", + "f_smtp_user", + "f_smtp_password", + "f_message_type", + "f_token", + "f_aes_key", + "f_region", + "f_sdk_app_id", + "f_webhook_address", + "f_approve_type", + "f_sort_code", + "f_description", + "f_enabled_mark", + "f_sms_signature", + "f_is_default", + ]; + let casts = [ + // f_id, f_tenant_id, f_full_name, f_en_code, f_category, f_end_point, + // f_supplier_id, f_address_name, f_smtp_server + "", "", "", "", "", "", "", "", "", + // f_smtp_port, f_ssl_link + "::integer", "::integer", + // f_smtp_user, f_smtp_password, f_message_type, f_token, f_aes_key, f_region, + // f_sdk_app_id, f_webhook_address + "", "", "", "", "", "", "", "", + // f_approve_type, f_sort_code, f_description, f_enabled_mark + "::integer", "::bigint", "", "::integer", + // f_sms_signature, f_is_default + "", "::integer", + ]; + if let Err(resp) = insert_row( + &state, + "base_msg_account", + &columns, + &casts, + &values, + &user.account, + "复制账号配置", + ) + .await + { + return resp; + } + ok_msg(MSG_COPIED) +} + +/// `PUT /api/message/Account/setdefault` —— 设为默认(官方只要登录)。 +/// +/// 🔴 官方 `AccountServiceImpl.setDefault`:先把**同消息类型**的所有配置 `f_is_default` 清零, +/// 再把目标置 1;目标本身是禁用状态 ⇒ 失败。 +pub async fn account_set_default( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let id = text_field(&obj, "id").unwrap_or_default(); + if id.is_empty() { + return fail(code::FAIL, "请求参数格式错误"); + } + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_message_type AS \"messageType\", \ + COALESCE(f_enabled_mark, 0) AS \"enabledMark\" FROM base_msg_account \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "账号配置默认查询", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + if iv(&row, "enabledMark").unwrap_or(0) == 0 { + return fail(code::FAIL, MSG_DISABLE_CANNOT_DEFAULT); + } + let message_type = sv(&row, "messageType"); + let clear_sql = "UPDATE base_msg_account SET f_is_default = 0, f_last_modify_time = now() \ + WHERE COALESCE(f_delete_mark, 0) = 0 \ + AND ($1::text = '' OR f_message_type = $1::text)"; + if let Err(e) = state + .db + .exec_params(clear_sql, ¶ms_of(&[Some(message_type)])) + .await + { + return db_error(e, "清除默认账号配置"); + } + let set_sql = "UPDATE base_msg_account SET f_is_default = 1, f_last_modify_time = now() \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0"; + if let Err(e) = state.db.exec_params(set_sql, ¶ms_of(&[Some(id)])).await { + return db_error(e, "设置默认账号配置"); + } + ok_msg(MSG_OPERATED) +} + +/// `POST /api/message/Account/testSendMail` —— 测试发邮件。 +/// +/// 🔴 官方 `AccountController.java:470` ⇒ **真发邮件**(要连服务商)⇒ 本仓明确业务失败。 +pub async fn account_test_send( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + return resp; + } + let _ = body; + unsupported_provider("测试发送邮件") +} + +/// `POST /api/message/Account/{id}` —— 官方前端「测试配置」的**动态**路径(别名)。 +/// +/// 🔴 官方前端 `api/msgCenter/accountConfig.ts:33` 写的是 +/// ``url: `${Api.Prefix}/${data.testType}` `` ⇒ **最后一段是运行期拼出来的**。 +/// 官方 Java **只有静态端点** `POST /api/message/Account/testSendMail` +/// (`AccountController.java:470`),而前端**唯一调用点** +/// (`src/views/integrationCenter/email/Test.vue:59`)把 `testType` 写死成 +/// `'testSendMail'` ⇒ 运行期 URL 就等于那个静态端点(**已实现**)。 +/// +/// 🔴 **为什么还要这条别名**:静态抽端点器把 `${data.testType}` 记成**路径参数** +/// (`/api/message/Account/{param}`)⇒ 尺子 `fe-gap.py` 会把这条报成缺口。 +/// 本路由用**同一个语义**(诚实失败)把它接住 ⇒ 前端「声明的路径」也通。 +/// 两条路由的差别只有路径形状,**行为完全一致**(都明确业务失败,不返假发送结果)。 +/// +/// 🔴 路由里的参数名是 `{id}`(不是 `{testType}`):axum/matchit **同一位置不允许 +/// 两个不同的参数名**,而 `{id}` 已被 `POST /api/message/Account/{id}/Actions/Copy` +/// 占用 ⇒ 这里传的其实是前端的 **testType**(运行期恒为 `testSendMail`)。 +pub async fn account_test_send_by_type( + State(state): State, + headers: HeaderMap, + Path(test_type): Path, + body: Bytes, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + return resp; + } + let _ = body; + unsupported_provider(&format!("测试发送邮件({test_type})")) +} + +// ================================================================ 消息发送配置(9 条) +// +// 🔴 官方 `SendMessageConfigController`(`@RequestMapping("/api/message/Send")`)。 +// 写操作守卫 `@SaCheckPermission("msgCenter.sendConfig")`; +// `GET /{id}` 与 `GET /getSendConfigList` 官方**没有**点权限 ⇒ 只要登录。 + +/// 🔴 官方 `SendMessageConfigForm` ⇒ 列白名单(`category` 单独处理,是 id 数组)。 +const SEND_WRITE_FIELDS: &[(&str, &str, &str)] = &[ + ("fullName", "f_full_name", ""), + ("enCode", "f_en_code", ""), + ("templateType", "f_template_type", ""), + ("sendType", "f_send_type", "::integer"), + ("description", "f_description", ""), + ("enabledMark", "f_enabled_mark", "::integer"), + ("sortCode", "f_sort_code", "::bigint"), +]; + +const SEND_LIST_COLUMNS: &str = "s.f_id AS \"id\", s.f_full_name AS \"fullName\", \ + s.f_en_code AS \"enCode\", s.f_template_type AS \"templateType\", \ + s.f_category AS \"category\", s.f_send_type AS \"sendType\", \ + COALESCE(s.f_sort_code, 0) AS \"sortCode\", COALESCE(s.f_enabled_mark, 0) AS \"enabledMark\", \ + s.f_creator_user_id AS \"creatorUserId\", s.f_last_modify_user_id AS \"lastModifyUserId\", \ + (EXTRACT(EPOCH FROM s.f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + (EXTRACT(EPOCH FROM s.f_last_modify_time) * 1000)::bigint AS \"lastModifyTime\", \ + COALESCE(u.f_real_name, '') || '/' || COALESCE(u.f_account, '') AS \"creatorUser\""; + +const SEND_FROM: &str = "base_msg_send s \ + LEFT JOIN base_user u ON u.f_id = COALESCE( \ + (SELECT u2.f_id FROM base_user u2 WHERE u2.f_account = s.f_creator_user_id LIMIT 1), \ + s.f_creator_user_id)"; + +/// 官方 `SendConfigTemplateModel`(发送配置下的模板子表)。 +async fn send_template_models( + state: &AppState, + config_id: &str, + only_enabled: bool, +) -> Result, Json> { + let sql = "SELECT st.f_id AS \"id\", st.f_send_config_id AS \"sendConfigId\", \ + st.f_message_type AS \"messageType\", st.f_template_id AS \"templateId\", \ + st.f_description AS \"description\", COALESCE(st.f_enabled_mark, 0) AS \"enabledMark\", \ + t.f_full_name AS \"msgTemplateName\" \ + FROM base_msg_send_template st \ + LEFT JOIN base_msg_template t ON t.f_id = st.f_template_id \ + WHERE COALESCE(st.f_delete_mark, 0) = 0 AND st.f_send_config_id = $1::text \ + AND ($2::text = '' OR COALESCE(st.f_enabled_mark, 0) = $2::text::integer) \ + ORDER BY st.f_message_type ASC"; + let filter = if only_enabled { "1" } else { "" }; + let rows = fetch_all( + state, + sql, + &[Some(config_id.to_string()), Some(filter.to_string())], + "发送配置模板子表查询", + ) + .await?; + let mut out = Vec::new(); + for row in rows { + let template_id = sv(&row, "templateId"); + let params = template_params(state, &template_id).await?; + out.push(json!({ + "id": sv(&row, "id"), + "sendConfigId": sv(&row, "sendConfigId"), + "messageType": message_type_name(&sv(&row, "messageType")), + "templateId": template_id, + "accountConfigId": Value::Null, + "toUser": Value::Null, + "paramJson": params, + "msgTemplateName": sv(&row, "msgTemplateName"), + "description": sv(&row, "description"), + "enabledMark": iv(&row, "enabledMark"), + })); + } + Ok(out) +} + +/// 消息模板的参数表(`base_msg_template_param`)⇒ 官方 `TemplateParamModel` 形状。 +async fn template_params( + state: &AppState, + template_id: &str, +) -> Result, Json> { + if template_id.is_empty() { + return Ok(Vec::new()); + } + let sql = "SELECT f_field AS \"field\", f_field_name AS \"fieldName\" \ + FROM base_msg_template_param \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_template_id = $1::text \ + ORDER BY f_field ASC"; + let rows = fetch_all(state, sql, &[Some(template_id.to_string())], "模板参数查询").await?; + Ok(rows + .iter() + .map(|r| json!({"field": sv(r, "field"), "fieldName": sv(r, "fieldName")})) + .collect()) +} + +/// `GET /api/message/Send` —— 消息发送配置列表。 +/// +/// 官方 `SendMessageConfigController.java:143`(`@SaCheckPermission("msgCenter.sendConfig")`)。 +pub async fn send_config_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let category = qv(&raw, "category"); + let enabled_mark = qv(&raw, "enabledMark"); + let template_type = qv(&raw, "templateType"); + + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "AND (s.f_full_name ILIKE ${next}::text OR s.f_en_code ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !category.is_empty() { + // 🔴 官方 `f_category` 存的是 **id 数组的 JSON 串** ⇒ 用 `LIKE` 命中。 + filters.push(format!("AND s.f_category LIKE ${next}::text")); + values.push(Some(format!("%{category}%"))); + next += 1; + } + if !template_type.is_empty() { + filters.push(format!("AND s.f_template_type = ${next}::text")); + values.push(Some(template_type)); + next += 1; + } + if !enabled_mark.is_empty() { + filters.push(format!("AND s.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + } + let where_body = format!( + "COALESCE(s.f_delete_mark, 0) = 0{}", + if filters.is_empty() { + String::new() + } else { + format!(" {}", filters.join(" ")) + } + ); + let (total, rows) = match paged_query( + &state, + SEND_LIST_COLUMNS, + SEND_FROM, + &where_body, + "ORDER BY COALESCE(s.f_sort_code, 0) ASC, s.f_creator_time DESC", + values, + &page, + "消息发送配置列表", + ) + .await + { + Ok(v) => v, + Err(resp) => return resp, + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let mut list = Vec::new(); + for row in rows { + let id = sv(&row, "id"); + let templates = match send_template_models(&state, &id, false).await { + Ok(t) => t, + Err(resp) => return resp, + }; + // 🔴 官方 `messageType` = 子表里出现过的消息类型(中文名 + code)。 + let mut types: Vec = Vec::new(); + for t in &templates { + let name = sv(t, "messageType"); + let en = MESSAGE_TYPES + .iter() + .find(|(c, _)| *c == name) + .map(|(c, _)| *c) + .unwrap_or(""); + let already = types + .iter() + .any(|v| v.get("type").and_then(|x| x.as_str()).unwrap_or("") == en); + if !already && !en.is_empty() { + types.push(json!({"fullName": name, "type": en})); + } + } + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + list.push(json!({ + "id": id, + "sendConfigTemplateList": templates, + "fullName": sv(&row, "fullName"), + "enCode": sv(&row, "enCode"), + "messageType": types, + "templateType": sv(&row, "templateType"), + "messageSource": Value::Null, + "sortCode": iv(&row, "sortCode"), + "enabledMark": iv(&row, "enabledMark").map(|v| v.to_string()).unwrap_or_default(), + "creatorUserId": sv(&row, "creatorUserId"), + "creatorTime": iv(&row, "creatorTime"), + "lastModifyUserId": sv(&row, "lastModifyUserId"), + "lastModifyTime": iv(&row, "lastModifyTime"), + "creatorUser": sv(&row, "creatorUser"), + "category": join_category_names(&cat_ids, &cat_map), + "sendType": iv(&row, "sendType"), + })); + } + ok(page_list(page.current_page, page.page_size, total, list)) +} + +/// `POST /api/message/Send` —— 新建消息发送配置。 +pub async fn send_config_create( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let full_name = text_field(&obj, "fullName").unwrap_or_default(); + if full_name.is_empty() { + return fail(code::FAIL, "名称不能为空"); + } + let new_id = new_uuid(); + let cat_ids = id_list_of(&obj, "category"); + let mut columns: Vec<&str> = vec!["f_id", "f_tenant_id"]; + let mut casts: Vec<&str> = vec!["", ""]; + let mut values: Vec> = vec![Some(new_id.clone()), Some("0".to_string())]; + for (column, cast, value) in write_fields(&obj, SEND_WRITE_FIELDS) { + columns.push(column); + casts.push(cast); + values.push(value); + } + columns.push("f_category"); + casts.push(""); + values.push(Some( + serde_json::to_string(&cat_ids).unwrap_or_else(|_| "[]".to_string()), + )); + columns.push("f_delete_mark"); + casts.push("::integer"); + values.push(Some("0".to_string())); + if let Err(resp) = insert_row( + &state, + "base_msg_send", + &columns, + &casts, + &values, + &user.account, + "新建消息发送配置", + ) + .await + { + return resp; + } + if let Err(resp) = insert_send_templates(&state, &new_id, &obj, &user.account).await { + return resp; + } + ok_msg(MSG_CREATED) +} + +/// 把 body 里的 `sendConfigTemplateList` 写进 `base_msg_send_template`。 +async fn insert_send_templates( + state: &AppState, + config_id: &str, + obj: &Map, + creator: &str, +) -> Result<(), Json> { + let items = match obj.get("sendConfigTemplateList") { + Some(Value::Array(items)) => items.clone(), + _ => return Ok(()), + }; + for item in items { + let tpl = match item.as_object() { + Some(o) => o.clone(), + None => continue, + }; + let columns = [ + "f_id", + "f_tenant_id", + "f_send_config_id", + "f_message_type", + "f_template_id", + "f_description", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(config_id.to_string()), + text_field(&tpl, "messageType"), + text_field(&tpl, "templateId"), + text_field(&tpl, "description"), + Some( + tpl.get("enabledMark") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .unwrap_or(1) + .to_string(), + ), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "::integer", "::integer"]; + insert_row( + state, + "base_msg_send_template", + &columns, + &casts, + &values, + creator, + "新建发送配置模板", + ) + .await?; + } + Ok(()) +} + +/// `GET /api/message/Send/{id}` —— 消息发送配置详情(官方只要登录)。 +pub async fn send_config_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_template_type AS \"templateType\", f_category AS \"category\", f_send_type AS \"sendType\", \ + COALESCE(f_sort_code, 0) AS \"sortCode\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\", \ + f_description AS \"description\" FROM base_msg_send \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息发送配置详情", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let templates = match send_template_models(&state, &id, false).await { + Ok(t) => t, + Err(resp) => return resp, + }; + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + ok(json!({ + "id": sv(&row, "id"), + "fullName": sv(&row, "fullName"), + "enCode": sv(&row, "enCode"), + "templateType": sv(&row, "templateType"), + "messageSource": Value::Null, + "messageSourceName": Value::Null, + "sortCode": iv(&row, "sortCode"), + "enabledMark": iv(&row, "enabledMark").map(|v| v.to_string()).unwrap_or_default(), + "description": sv(&row, "description"), + "sendConfigTemplateList": templates, + "category": cat_ids, + "categoryName": join_category_names(&cat_ids, &cat_map), + "sendType": iv(&row, "sendType"), + })) +} + +/// `PUT /api/message/Send/{id}` —— 更新消息发送配置。 +pub async fn send_config_update( + State(state): State, + headers: HeaderMap, + Path(id): Path, + body: Bytes, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_send \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息发送配置存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + let mut sets = write_fields(&obj, SEND_WRITE_FIELDS); + if obj.contains_key("category") { + let cat_ids = id_list_of(&obj, "category"); + sets.push(( + "f_category", + "", + Some(serde_json::to_string(&cat_ids).unwrap_or_else(|_| "[]".to_string())), + )); + } + if let Err(resp) = update_row( + &state, + "base_msg_send", + &id, + &sets, + &user.account, + "更新消息发送配置", + ) + .await + { + return resp; + } + if obj.contains_key("sendConfigTemplateList") { + // 🔴 官方:子表「先删后增」。 + let sql = "UPDATE base_msg_send_template SET f_delete_mark = 1, f_delete_time = now(), \ + f_delete_user_id = $1::text \ + WHERE f_send_config_id = $2::text AND COALESCE(f_delete_mark, 0) = 0"; + if let Err(e) = state + .db + .exec_params(sql, ¶ms_of(&[Some(user.account.clone()), Some(id.clone())])) + .await + { + return db_error(e, "清空发送配置模板"); + } + if let Err(resp) = insert_send_templates(&state, &id, &obj, &user.account).await { + return resp; + } + } + ok_msg(MSG_UPDATED) +} + +/// `DELETE /api/message/Send/{id}` —— 删除消息发送配置(连带子表)。 +pub async fn send_config_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_send \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息发送配置存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + if let Err(resp) = soft_delete(&state, "base_msg_send", &id, &user.account, "删除消息发送配置").await + { + return resp; + } + let sql = "UPDATE base_msg_send_template SET f_delete_mark = 1, f_delete_time = now(), \ + f_delete_user_id = $1::text \ + WHERE f_send_config_id = $2::text AND COALESCE(f_delete_mark, 0) = 0"; + if let Err(e) = state + .db + .exec_params(sql, ¶ms_of(&[Some(user.account), Some(id)])) + .await + { + return db_error(e, "删除发送配置模板"); + } + ok_msg(MSG_DELETED) +} + +/// `POST /api/message/Send/{id}/Actions/Copy` —— 复制消息发送配置(连子表)。 +pub async fn send_config_copy( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_template_type AS \"templateType\", f_category AS \"category\", f_send_type AS \"sendType\", \ + COALESCE(f_sort_code, 0) AS \"sortCode\", f_description AS \"description\" \ + FROM base_msg_send WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息发送配置复制源", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_COPY_FAILED), + }; + let suffix = copy_suffix(); + let full_name = format!("{}.副本{}", sv(&row, "fullName"), suffix); + let en_code = format!("{}{}", sv(&row, "enCode"), suffix); + if en_code.len() > 50 || full_name.len() > 50 { + return fail(code::FAIL, MSG_COPY_LIMIT); + } + let new_id = new_uuid(); + let columns = [ + "f_id", + "f_tenant_id", + "f_full_name", + "f_en_code", + "f_template_type", + "f_category", + "f_send_type", + "f_sort_code", + "f_description", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_id.clone()), + Some("0".to_string()), + Some(full_name), + Some(en_code), + Some("0".to_string()), + Some(sv(&row, "category")), + iv(&row, "sendType").map(|v| v.to_string()), + iv(&row, "sortCode").map(|v| v.to_string()), + Some(sv(&row, "description")), + Some("0".to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "::integer", "::bigint", "", "::integer", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_msg_send", + &columns, + &casts, + &values, + &user.account, + "复制消息发送配置", + ) + .await + { + return resp; + } + // 🔴 官方:子表一起复制。 + let sql = "SELECT f_message_type AS \"messageType\", f_template_id AS \"templateId\", \ + f_description AS \"description\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \ + FROM base_msg_send_template \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_send_config_id = $1::text"; + let rows = match fetch_all(&state, sql, &[Some(id.clone())], "发送配置复制子表").await { + Ok(v) => v, + Err(resp) => return resp, + }; + for r in rows { + let columns = [ + "f_id", + "f_tenant_id", + "f_send_config_id", + "f_message_type", + "f_template_id", + "f_description", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(new_id.clone()), + Some(sv(&r, "messageType")), + Some(sv(&r, "templateId")), + Some(sv(&r, "description")), + iv(&r, "enabledMark").map(|v| v.to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "::integer", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_msg_send_template", + &columns, + &casts, + &values, + &user.account, + "复制发送配置模板", + ) + .await + { + return resp; + } + } + ok_msg(MSG_COPIED) +} + +/// `POST /api/message/Send/getTestConfig/{id}` —— 取发送配置下的模板(**裸数组**)。 +/// +/// 官方 `SendMessageConfigController.java:680`(没有模板 ⇒ `MsgCode.MSERR121`)。 +pub async fn send_config_test_config( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + return resp; + } + let models = match send_template_models(&state, &id, false).await { + Ok(m) => m, + Err(resp) => return resp, + }; + if models.is_empty() { + return fail(code::FAIL, MSG_NO_TEMPLATE); + } + ok(Value::Array(models)) +} + +/// `POST /api/message/Send/testSendConfig` —— 测试消息发送配置。 +/// +/// 🔴 官方 `SendMessageConfigController.java:719` ⇒ **真发消息** ⇒ 本仓明确业务失败。 +pub async fn send_config_test_send( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_MSG_SEND_CONFIG).await { + return resp; + } + let _ = body; + unsupported_provider("测试消息发送配置") +} + +/// `GET /api/message/Send/getSendConfigList` —— 发送配置下拉框(官方只要登录)。 +pub async fn send_config_select_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let category = qv(&raw, "category"); + // 🔴 官方:`enabledMark` 缺省是 "1"(只看启用的)。 + let enabled_mark = { + let v = qv(&raw, "enabledMark"); + if v.is_empty() { + "1".to_string() + } else { + v + } + }; + + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "AND (s.f_full_name ILIKE ${next}::text OR s.f_en_code ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !category.is_empty() { + filters.push(format!("AND s.f_category LIKE ${next}::text")); + values.push(Some(format!("%{category}%"))); + next += 1; + } + filters.push(format!("AND s.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + + let where_body = format!( + "COALESCE(s.f_delete_mark, 0) = 0 {}", + filters.join(" ") + ); + let (total, rows) = match paged_query( + &state, + SEND_LIST_COLUMNS, + SEND_FROM, + &where_body, + "ORDER BY COALESCE(s.f_sort_code, 0) ASC, s.f_creator_time DESC", + values, + &page, + "消息发送配置下拉框", + ) + .await + { + Ok(v) => v, + Err(resp) => return resp, + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let mut list = Vec::new(); + for row in rows { + let id = sv(&row, "id"); + // 🔴 官方:下拉框只取**启用**的模板子表。 + let templates = match send_template_models(&state, &id, true).await { + Ok(t) => t, + Err(resp) => return resp, + }; + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + list.push(json!({ + "id": id, + "fullName": sv(&row, "fullName"), + "enCode": sv(&row, "enCode"), + "templateJson": templates, + "category": join_category_names(&cat_ids, &cat_map).replace('-', "/"), + })); + } + ok(page_list(page.current_page, page.page_size, total, list)) +} + +// ================================================================ 消息模板(7 条) +// +// 🔴 官方 `MessageTemplateConfigController`(`@RequestMapping("/api/message/Template")`)。 +// 读守卫 `@SaCheckPermission({"msgCenter.msgTemplate","integrationCenter.sms", +// "integrationCenter.email"}, mode=OR)`;写守卫只要 `msgCenter.msgTemplate`。 + +/// 🔴 官方 `MessageTemplateConfigForm` ⇒ 列白名单(`category` 单独处理)。 +const TEMPLATE_WRITE_FIELDS: &[(&str, &str, &str)] = &[ + ("fullName", "f_full_name", ""), + ("enCode", "f_en_code", ""), + ("templateType", "f_template_type", ""), + ("messageType", "f_message_type", ""), + ("wxSkip", "f_wx_skip", ""), + ("xcxAppId", "f_xcx_app_id", ""), + ("title", "f_title", ""), + ("content", "f_content", ""), + ("templateId", "f_template_id", ""), + ("description", "f_description", ""), + ("enabledMark", "f_enabled_mark", "::integer"), + ("sortCode", "f_sort_code", "::bigint"), + ("emailType", "f_email_type", "::integer"), +]; + +const TEMPLATE_LIST_COLUMNS: &str = "t.f_id AS \"id\", t.f_full_name AS \"fullName\", \ + t.f_en_code AS \"enCode\", t.f_template_type AS \"templateType\", t.f_category AS \"category\", \ + t.f_message_type AS \"messageType\", COALESCE(t.f_sort_code, 0) AS \"sortCode\", \ + COALESCE(t.f_enabled_mark, 0) AS \"enabledMark\", \ + (EXTRACT(EPOCH FROM t.f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + t.f_creator_user_id AS \"creatorUserId\", \ + (EXTRACT(EPOCH FROM t.f_last_modify_time) * 1000)::bigint AS \"lastModifyTime\", \ + COALESCE(u.f_real_name, '') || '/' || COALESCE(u.f_account, '') AS \"creatorUser\""; + +const TEMPLATE_FROM: &str = "base_msg_template t \ + LEFT JOIN base_user u ON u.f_id = COALESCE( \ + (SELECT u2.f_id FROM base_user u2 WHERE u2.f_account = t.f_creator_user_id LIMIT 1), \ + t.f_creator_user_id)"; + +/// 官方 `MsgVariableEntity`(模板变量表 `base_msg_variable`)。 +async fn template_variables( + state: &AppState, + template_id: &str, + wrap: bool, +) -> Result, Json> { + if template_id.is_empty() { + return Ok(Vec::new()); + } + let sql = "SELECT f_id AS \"id\", f_template_id AS \"templateId\", f_field_id AS \"fieldId\", \ + f_variable AS \"variable\", f_field AS \"field\", COALESCE(f_is_title, 0) AS \"isTitle\", \ + COALESCE(f_enabled_mark, 1) AS \"enabledMark\" \ + FROM base_msg_variable \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_template_id = $1::text ORDER BY f_id ASC"; + let rows = fetch_all(state, sql, &[Some(template_id.to_string())], "模板变量查询").await?; + Ok(rows + .iter() + .map(|r| { + let variable = sv(r, "variable"); + let variable = if wrap && !variable.starts_with("${") && !variable.is_empty() { + format!("${{{variable}}}") + } else { + variable + }; + json!({ + "id": sv(r, "id"), + "templateId": sv(r, "templateId"), + "fieldId": sv(r, "fieldId"), + "variable": variable, + "field": sv(r, "field"), + "isTitle": iv(r, "isTitle"), + "enabledMark": iv(r, "enabledMark"), + }) + }) + .collect()) +} + +/// `GET /api/message/Template` —— 消息模板列表。 +/// +/// 官方 `MessageTemplateConfigController.java:117`(`@SaCheckPermission({…}, mode=OR)`)。 +pub async fn msg_template_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[EN_MSG_TEMPLATE, EN_INTEGRATION_SMS, EN_INTEGRATION_EMAIL], + ) + .await + { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let message_type = qv(&raw, "messageType"); + let category = qv(&raw, "category"); + let enabled_mark = qv(&raw, "enabledMark"); + + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "AND (t.f_full_name ILIKE ${next}::text OR t.f_en_code ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !message_type.is_empty() { + filters.push(format!("AND t.f_message_type = ${next}::text")); + values.push(Some(message_type)); + next += 1; + } + if !category.is_empty() { + filters.push(format!("AND t.f_category LIKE ${next}::text")); + values.push(Some(format!("%{category}%"))); + next += 1; + } + if !enabled_mark.is_empty() { + filters.push(format!("AND t.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + } + let where_body = format!( + "COALESCE(t.f_delete_mark, 0) = 0{}", + if filters.is_empty() { + String::new() + } else { + format!(" {}", filters.join(" ")) + } + ); + let (total, rows) = match paged_query( + &state, + TEMPLATE_LIST_COLUMNS, + TEMPLATE_FROM, + &where_body, + "ORDER BY COALESCE(t.f_sort_code, 0) ASC, t.f_creator_time DESC", + values, + &page, + "消息模板列表", + ) + .await + { + Ok(v) => v, + Err(resp) => return resp, + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let mut list = Vec::new(); + for row in rows { + let id = sv(&row, "id"); + let params = match template_params(&state, &id).await { + Ok(p) => p, + Err(resp) => return resp, + }; + let vars = match template_variables(&state, &id, false).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + list.push(json!({ + "id": id, + "templateParamList": params, + "smsFieldList": vars, + "fullName": sv(&row, "fullName"), + "enCode": sv(&row, "enCode"), + "templateType": sv(&row, "templateType"), + "category": join_category_names(&cat_ids, &cat_map), + "messageType": message_type_name(&sv(&row, "messageType")), + "sortCode": iv(&row, "sortCode"), + "enabledMark": iv(&row, "enabledMark"), + "creatorTime": iv(&row, "creatorTime"), + "creatorUserId": sv(&row, "creatorUserId"), + "lastModifyTime": iv(&row, "lastModifyTime"), + "creatorUser": sv(&row, "creatorUser"), + })); + } + ok(page_list(page.current_page, page.page_size, total, list)) +} + +/// `POST /api/message/Template` —— 新建消息模板。 +pub async fn msg_template_create( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_TEMPLATE).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let full_name = text_field(&obj, "fullName").unwrap_or_default(); + if full_name.is_empty() { + return fail(code::FAIL, "名称不能为空"); + } + let new_id = new_uuid(); + let cat_ids = id_list_of(&obj, "category"); + let mut columns: Vec<&str> = vec!["f_id", "f_tenant_id"]; + let mut casts: Vec<&str> = vec!["", ""]; + let mut values: Vec> = vec![Some(new_id.clone()), Some("0".to_string())]; + for (column, cast, value) in write_fields(&obj, TEMPLATE_WRITE_FIELDS) { + columns.push(column); + casts.push(cast); + values.push(value); + } + columns.push("f_category"); + casts.push(""); + values.push(Some( + serde_json::to_string(&cat_ids).unwrap_or_else(|_| "[]".to_string()), + )); + columns.push("f_delete_mark"); + casts.push("::integer"); + values.push(Some("0".to_string())); + if let Err(resp) = insert_row( + &state, + "base_msg_template", + &columns, + &casts, + &values, + &user.account, + "新建消息模板", + ) + .await + { + return resp; + } + if let Err(resp) = insert_template_children(&state, &new_id, &obj, &user.account).await { + return resp; + } + ok_msg(MSG_CREATED) +} + +/// 把 body 里的 `templateParamList` / `msgVariableEntityList` 写进子表。 +async fn insert_template_children( + state: &AppState, + template_id: &str, + obj: &Map, + creator: &str, +) -> Result<(), Json> { + if let Some(Value::Array(items)) = obj.get("templateParamList") { + for item in items { + let p = match item.as_object() { + Some(o) => o.clone(), + None => continue, + }; + let columns = [ + "f_id", + "f_tenant_id", + "f_template_id", + "f_field", + "f_field_name", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(template_id.to_string()), + text_field(&p, "field"), + text_field(&p, "fieldName"), + Some("1".to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "::integer", "::integer"]; + insert_row( + state, + "base_msg_template_param", + &columns, + &casts, + &values, + creator, + "新建模板参数", + ) + .await?; + } + } + let vars = obj + .get("msgVariableEntityList") + .or_else(|| obj.get("variableList")) + .cloned(); + if let Some(Value::Array(items)) = vars { + for item in items { + let v = match item.as_object() { + Some(o) => o.clone(), + None => continue, + }; + let columns = [ + "f_id", + "f_tenant_id", + "f_template_id", + "f_field_id", + "f_variable", + "f_field", + "f_is_title", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(template_id.to_string()), + text_field(&v, "fieldId"), + text_field(&v, "variable"), + text_field(&v, "field"), + v.get("isTitle") + .and_then(|x| x.as_i64().or_else(|| x.as_str()?.trim().parse().ok())) + .map(|x| x.to_string()), + Some("1".to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "::integer", "::integer", "::integer"]; + insert_row(state, "base_msg_variable", &columns, &casts, &values, creator, "新建模板变量") + .await?; + } + } + Ok(()) +} + +/// `GET /api/message/Template/{id}` —— 消息模板详情。 +/// +/// 官方 `MessageTemplateConfigController.java:250`。 +pub async fn msg_template_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[EN_MSG_TEMPLATE, EN_INTEGRATION_SMS, EN_INTEGRATION_EMAIL], + ) + .await + { + return resp; + } + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_template_type AS \"templateType\", f_category AS \"category\", f_message_type AS \"messageType\", \ + COALESCE(f_sort_code, 0) AS \"sortCode\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\", \ + f_description AS \"description\", f_title AS \"title\", f_content AS \"content\", \ + f_template_id AS \"templateId\", f_wx_skip AS \"wxSkip\", f_xcx_app_id AS \"xcxAppId\", \ + f_email_type AS \"emailType\", \ + (EXTRACT(EPOCH FROM f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + f_creator_user_id AS \"creatorUserId\", \ + (EXTRACT(EPOCH FROM f_last_modify_time) * 1000)::bigint AS \"lastModifyTime\", \ + f_last_modify_user_id AS \"lastModifyUserId\" \ + FROM base_msg_template WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息模板详情", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let params = match template_params(&state, &id).await { + Ok(p) => p, + Err(resp) => return resp, + }; + let vars = match template_variables(&state, &id, false).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let wrapped = match template_variables(&state, &id, true).await { + Ok(v) => v, + Err(resp) => return resp, + }; + // 🔴 官方 `templateName` = `f_template_id` 指向的**供应商模板**名字。 + let template_name = match fetch_one( + &state, + "SELECT f_full_name AS \"fullName\" FROM base_intg_supplier_tpl WHERE f_id = $1::text", + &[Some(sv(&row, "templateId"))], + "供应商模板查询", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + // 🔴 官方 `disabled` = 该模板已被**发送配置**引用 ⇒ 不可删。 + let used = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_send_template \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_template_id = $1::text LIMIT 1", + &[Some(id.clone())], + "模板引用查询", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + ok(json!({ + "id": sv(&row, "id"), + "fullName": sv(&row, "fullName"), + "enCode": sv(&row, "enCode"), + "templateType": sv(&row, "templateType"), + "category": cat_ids, + "messageType": message_type_name(&sv(&row, "messageType")), + "sortCode": iv(&row, "sortCode"), + "enabledMark": iv(&row, "enabledMark"), + "description": sv(&row, "description"), + "title": sv(&row, "title"), + "content": sv(&row, "content"), + "templateCode": Value::Null, + "wxSkip": sv(&row, "wxSkip"), + "xcxAppId": sv(&row, "xcxAppId"), + "creatorTime": iv(&row, "creatorTime"), + "creatorUserId": sv(&row, "creatorUserId"), + "lastModifyTime": iv(&row, "lastModifyTime"), + "lastModifyUserId": sv(&row, "lastModifyUserId"), + "templateParamList": params, + "msgVariableEntityList": vars, + "emailType": iv(&row, "emailType"), + "templateName": template_name.map(|r| sv(&r, "fullName")).unwrap_or_default(), + "templateId": sv(&row, "templateId"), + "categoryName": join_category_names(&cat_ids, &cat_map), + "variableList": wrapped, + "disabled": used.is_some(), + })) +} + +/// `PUT /api/message/Template/{id}` —— 更新消息模板。 +pub async fn msg_template_update( + State(state): State, + headers: HeaderMap, + Path(id): Path, + body: Bytes, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_TEMPLATE).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_template \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息模板存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + let mut sets = write_fields(&obj, TEMPLATE_WRITE_FIELDS); + if obj.contains_key("category") { + let cat_ids = id_list_of(&obj, "category"); + sets.push(( + "f_category", + "", + Some(serde_json::to_string(&cat_ids).unwrap_or_else(|_| "[]".to_string())), + )); + } + if let Err(resp) = update_row( + &state, + "base_msg_template", + &id, + &sets, + &user.account, + "更新消息模板", + ) + .await + { + return resp; + } + if obj.contains_key("templateParamList") || obj.contains_key("msgVariableEntityList") { + for table in ["base_msg_template_param", "base_msg_variable"] { + let sql = format!( + "UPDATE {table} SET f_delete_mark = 1, f_delete_time = now(), \ + f_delete_user_id = $1::text \ + WHERE f_template_id = $2::text AND COALESCE(f_delete_mark, 0) = 0" + ); + if let Err(e) = state + .db + .exec_params(&sql, ¶ms_of(&[Some(user.account.clone()), Some(id.clone())])) + .await + { + return db_error(e, "清空模板子表"); + } + } + if let Err(resp) = insert_template_children(&state, &id, &obj, &user.account).await { + return resp; + } + } + ok_msg(MSG_UPDATED) +} + +/// `DELETE /api/message/Template/{id}` —— 删除消息模板。 +pub async fn msg_template_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_TEMPLATE).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_template \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息模板存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + if let Err(resp) = soft_delete(&state, "base_msg_template", &id, &user.account, "删除消息模板").await { + return resp; + } + ok_msg(MSG_DELETED) +} + +/// `POST /api/message/Template/{id}/Actions/Copy` —— 复制消息模板。 +pub async fn msg_template_copy( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_TEMPLATE).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_template_type AS \"templateType\", f_category AS \"category\", f_message_type AS \"messageType\", \ + COALESCE(f_sort_code, 0) AS \"sortCode\", f_description AS \"description\", \ + f_title AS \"title\", f_content AS \"content\", f_template_id AS \"templateId\", \ + f_wx_skip AS \"wxSkip\", f_xcx_app_id AS \"xcxAppId\", f_email_type AS \"emailType\" \ + FROM base_msg_template WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息模板复制源", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_COPY_FAILED), + }; + let suffix = copy_suffix(); + let full_name = format!("{}.副本{}", sv(&row, "fullName"), suffix); + let en_code = format!("{}{}", sv(&row, "enCode"), suffix); + if en_code.len() > 50 || full_name.len() > 50 { + return fail(code::FAIL, MSG_COPY_LIMIT); + } + let new_id = new_uuid(); + let columns = [ + "f_id", + "f_tenant_id", + "f_full_name", + "f_en_code", + "f_template_type", + "f_category", + "f_message_type", + "f_title", + "f_content", + "f_template_id", + "f_description", + "f_enabled_mark", + "f_sort_code", + "f_wx_skip", + "f_xcx_app_id", + "f_email_type", + "f_delete_mark", + ]; + let values = vec![ + Some(new_id.clone()), + Some("0".to_string()), + Some(full_name), + Some(en_code), + // 🔴 官方复制件把 `templateType` 置成 `"0"`(`MessageTemplateConfigController.java:583`)。 + Some("0".to_string()), + Some(sv(&row, "category")), + Some(sv(&row, "messageType")), + Some(sv(&row, "title")), + Some(sv(&row, "content")), + Some(sv(&row, "templateId")), + Some(sv(&row, "description")), + Some("0".to_string()), + iv(&row, "sortCode").map(|v| v.to_string()), + Some(sv(&row, "wxSkip")), + Some(sv(&row, "xcxAppId")), + iv(&row, "emailType").map(|v| v.to_string()), + Some("0".to_string()), + ]; + let casts = [ + "", "", "", "", "", "", "", "", "", "", "", "::integer", "::bigint", "", "", "::integer", + "::integer", + ]; + if let Err(resp) = insert_row( + &state, + "base_msg_template", + &columns, + &casts, + &values, + &user.account, + "复制消息模板", + ) + .await + { + return resp; + } + // 🔴 官方:子表(参数 / 变量)一起复制。 + // 🔴 两张子表**列不一样**(官方是两个实体:`TemplateParamEntity` / `MsgVariableEntity`), + // 所以各写各的显式列 —— 禁 `SELECT *`(列名会随官方 DDL 漂移,且撑内存)。 + let param_rows = match fetch_all( + &state, + "SELECT f_field AS \"field\", f_field_name AS \"fieldName\", \ + COALESCE(f_enabled_mark, 0) AS \"enabledMark\" FROM base_msg_template_param \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_template_id = $1::text", + &[Some(id.clone())], + "模板参数复制源", + ) + .await { + Ok(v) => v, + Err(resp) => return resp, + }; + for r in param_rows { + let columns = [ + "f_id", + "f_tenant_id", + "f_template_id", + "f_field", + "f_field_name", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(new_id.clone()), + Some(sv(&r, "field")), + Some(sv(&r, "fieldName")), + iv(&r, "enabledMark").map(|v| v.to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "::integer", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_msg_template_param", + &columns, + &casts, + &values, + &user.account, + "复制模板参数", + ) + .await + { + return resp; + } + } + let var_rows = match fetch_all( + &state, + "SELECT f_field_id AS \"fieldId\", f_variable AS \"variable\", f_field AS \"field\", \ + COALESCE(f_is_title, 0) AS \"isTitle\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \ + FROM base_msg_variable WHERE COALESCE(f_delete_mark, 0) = 0 AND f_template_id = $1::text", + &[Some(id.clone())], + "模板变量复制源", + ) + .await { + Ok(v) => v, + Err(resp) => return resp, + }; + for r in var_rows { + let columns = [ + "f_id", + "f_tenant_id", + "f_template_id", + "f_field_id", + "f_variable", + "f_field", + "f_is_title", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(new_id.clone()), + Some(sv(&r, "fieldId")), + Some(sv(&r, "variable")), + Some(sv(&r, "field")), + iv(&r, "isTitle").map(|v| v.to_string()), + iv(&r, "enabledMark").map(|v| v.to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "::integer", "::integer", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_msg_variable", + &columns, + &casts, + &values, + &user.account, + "复制模板变量", + ) + .await + { + return resp; + } + } + ok_msg(MSG_COPIED) +} + +/// `POST /api/message/Template/testSendMail` —— 模板测试发邮件。 +/// +/// 🔴 **官方前端有、官方 Java 没有**(`api/msgCenter/msgTemplate.ts:33`)⇒ 真发邮件 ⇒ 明确业务失败。 +pub async fn msg_template_test_send( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_MSG_TEMPLATE).await { + return resp; + } + let _ = body; + unsupported_provider("测试发送邮件") +} + +// ================================================================ 消息安全(敏感词,5 条) +// +// 🔴 官方 `MsgSensitiveController` —— **一个 `@SaCheckPermission` 都没有** ⇒ 全部只要登录。 + +const SENSITIVE_WRITE_FIELDS: &[(&str, &str, &str)] = &[ + ("sensitiveWord", "f_sensitive_word", ""), + ("replaceText", "f_replace_text", ""), + ("enabledMark", "f_enabled_mark", "::integer"), + ("sortCode", "f_sort_code", "::bigint"), + ("description", "f_description", ""), +]; + +/// `GET /api/message/Sensitive` —— 敏感词列表。 +pub async fn sensitive_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let enabled_mark = qv(&raw, "enabledMark"); + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!("AND s.f_sensitive_word ILIKE ${next}::text")); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !enabled_mark.is_empty() { + filters.push(format!("AND s.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + } + let where_body = format!( + "COALESCE(s.f_delete_mark, 0) = 0{}", + if filters.is_empty() { + String::new() + } else { + format!(" {}", filters.join(" ")) + } + ); + let cols = "s.f_id AS \"id\", s.f_sensitive_word AS \"sensitiveWord\", \ + s.f_replace_text AS \"replaceText\", \ + (EXTRACT(EPOCH FROM s.f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + COALESCE(s.f_sort_code, 0) AS \"sortCode\", \ + COALESCE(s.f_enabled_mark, 0) AS \"enabledMark\", s.f_description AS \"description\""; + match paged_query( + &state, + cols, + "base_msg_sensitive s", + &where_body, + "ORDER BY COALESCE(s.f_sort_code, 0) ASC, s.f_creator_time DESC", + values, + &page, + "敏感词列表", + ) + .await + { + Ok((total, rows)) => ok(page_list(page.current_page, page.page_size, total, rows)), + Err(resp) => resp, + } +} + +/// `POST /api/message/Sensitive` —— 新增敏感词。 +pub async fn sensitive_create( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let word = text_field(&obj, "sensitiveWord").unwrap_or_default(); + if word.is_empty() { + return fail(code::FAIL, "敏感词内容不能为空"); + } + let dup = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_sensitive \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_sensitive_word = $1::text LIMIT 1", + &[Some(word.clone())], + "敏感词查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup.is_some() { + return fail(code::FAIL, MSG_DUP_SENSITIVE); + } + let columns = [ + "f_id", + "f_tenant_id", + "f_sensitive_word", + "f_replace_text", + "f_enabled_mark", + "f_sort_code", + "f_description", + "f_delete_mark", + ]; + let mut values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(word), + text_field(&obj, "replaceText"), + obj.get("enabledMark") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .map(|v| v.to_string()), + obj.get("sortCode") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .map(|v| v.to_string()), + text_field(&obj, "description"), + Some("0".to_string()), + ]; + if values[4].is_none() { + values[4] = Some("1".to_string()); + } + let casts = ["", "", "", "", "::integer", "::bigint", "", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_msg_sensitive", + &columns, + &casts, + &values, + &user.account, + "新增敏感词", + ) + .await + { + return resp; + } + ok_msg(MSG_OPERATED) +} + +/// `GET /api/message/Sensitive/{id}` —— 敏感词详情。 +pub async fn sensitive_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_sensitive_word AS \"sensitiveWord\", f_replace_text AS \"replaceText\", \ + (EXTRACT(EPOCH FROM f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + COALESCE(f_sort_code, 0) AS \"sortCode\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\", \ + f_description AS \"description\" FROM base_msg_sensitive \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "敏感词详情", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + match row { + Some(r) => ok(r), + None => fail(code::FAIL, MSG_DATA_NOT_FOUND), + } +} + +/// `PUT /api/message/Sensitive/{id}` —— 更新敏感词。 +pub async fn sensitive_update( + State(state): State, + headers: HeaderMap, + Path(id): Path, + body: Bytes, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_sensitive \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "敏感词存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + if let Err(resp) = update_row( + &state, + "base_msg_sensitive", + &id, + &write_fields(&obj, SENSITIVE_WRITE_FIELDS), + &user.account, + "更新敏感词", + ) + .await + { + return resp; + } + ok_msg(MSG_OPERATED) +} + +/// `DELETE /api/message/Sensitive/{id}` —— 删除敏感词。 +pub async fn sensitive_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_msg_sensitive \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "敏感词存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, MSG_DATA_NOT_FOUND); + } + if let Err(resp) = soft_delete(&state, "base_msg_sensitive", &id, &user.account, "删除敏感词").await { + return resp; + } + ok_msg(MSG_DELETED) +} + +// ================================================================ 消息接收配置(2 条) +// +// 🔴 官方 `MsgReceiveController` —— 无 `@SaCheckPermission` ⇒ 只要登录。 +// 🔴 官方 `GET /api/message/Receive` 返回的是 **ListVO**(`{list:[…]}`),不是 PageListVO。 + +/// `GET /api/message/Receive` —— 消息接收配置列表。 +pub async fn receive_list( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let rows = match fetch_all( + &state, + "SELECT f_id AS \"id\", f_type AS \"type\", f_category AS \"category\", \ + f_config_json AS \"configJson\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \ + FROM base_msg_receive WHERE COALESCE(f_delete_mark, 0) = 0 ORDER BY f_id ASC", + &[], + "消息接收配置列表", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let defaults = default_channels(); + let mut list = Vec::new(); + for row in rows { + let category = sv(&row, "category"); + let (category_name, parent_id) = cat_map.get(&category).cloned().unwrap_or_default(); + // 🔴 官方口径:`topCategoryName` = 业务分类树的**根**,`subCategoryName` = 根的直接子。 + let (top_name, sub_name) = category_tree_names(&category, &cat_map); + let channels = parse_channels(Some(&sv(&row, "configJson"))); + let channels = if channels.is_empty() { + defaults.clone() + } else { + channels + }; + list.push(json!({ + "id": sv(&row, "id"), + "category": category, + "categoryName": category_name, + "channels": channels, + "configJson": channels, + "enabledMark": iv(&row, "enabledMark"), + "subCategoryName": sub_name, + "topCategoryName": top_name, + "type": iv(&row, "type"), + })); + let _ = parent_id; + } + ok(list_vo(list)) +} + +/// 业务分类树上的「根 / 根的子」名字。 +fn category_tree_names( + category: &str, + cat_map: &HashMap, +) -> (String, String) { + let mut node = category.to_string(); + let mut top = node.clone(); + let mut sub = String::new(); + // 最多向上走 8 层,防环。 + for _ in 0..8 { + let parent = match cat_map.get(&node) { + Some((_, p)) if !p.is_empty() && p != "0" => p.clone(), + _ => break, + }; + top = parent.clone(); + sub = node.clone(); + node = parent; + } + let top_name = cat_map.get(&top).map(|(n, _)| n.clone()).unwrap_or_default(); + let sub_name = cat_map + .get(&sub) + .map(|(n, _)| n.clone()) + .unwrap_or_else(|| top_name.clone()); + (top_name, sub_name) +} + +/// `POST /api/message/Receive` —— 保存消息接收配置。 +pub async fn receive_save( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let msg_type = obj + .get("type") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .unwrap_or(1); + let items = match obj.get("receiveList") { + Some(Value::Array(a)) => a.clone(), + _ => Vec::new(), + }; + for item in items { + let io = match item.as_object() { + Some(o) => o.clone(), + None => continue, + }; + let category = text_field(&io, "category") + .or_else(|| text_field(&io, "id")) + .unwrap_or_default(); + let channels = io + .get("channels") + .or_else(|| io.get("configJson")) + .or_else(|| io.get("channelList")) + .cloned() + .unwrap_or(Value::Null); + // 🔴 官方 `saveByIds`:按类型**先删后插**。 + let del = "DELETE FROM base_msg_receive WHERE f_type = $1::text::integer \ + AND COALESCE(f_delete_mark, 0) = 0 \ + AND COALESCE(f_category, '') = $2::text"; + if let Err(e) = state + .db + .exec_params(&del, ¶ms_of(&[Some(msg_type.to_string()), Some(category.clone())])) + .await + { + return db_error(e, "清空消息接收配置"); + } + let enabled = io + .get("enabledMark") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .unwrap_or(1); + if let Value::Array(chs) = &channels { + for ch in chs { + let co = match ch.as_object() { + Some(o) => o.clone(), + None => continue, + }; + let cfg = serde_json::to_string(&Value::Object(co.clone())) + .unwrap_or_else(|_| "{}".to_string()); + let columns = [ + "f_id", + "f_tenant_id", + "f_type", + "f_category", + "f_config_json", + "f_enabled_mark", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(msg_type.to_string()), + Some(category.clone()), + Some(cfg), + Some(enabled.to_string()), + Some("0".to_string()), + ]; + let casts = ["", "", "::integer", "", "", "::integer", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_msg_receive", + &columns, + &casts, + &values, + &user.account, + "保存消息接收配置", + ) + .await + { + return resp; + } + } + } + } + ok_msg(MSG_SAVED) +} + +// ================================================================ 消息监控(7 条) +// +// 🔴 官方 `MessageMonitorController` —— 列表/详情/重试只要登录; +// 删除类(batchRemove / empty / detail / RecordList)要 `msgCenter.msgRecord`。 + +/// `GET /api/message/Monitor` —— 消息监控列表。 +pub async fn monitor_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let message_type = qv(&raw, "messageType"); + let category = qv(&raw, "category"); + let status = qv(&raw, "status"); + let start_time = qv(&raw, "startTime"); + let end_time = qv(&raw, "endTime"); + + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "AND (m.f_title ILIKE ${next}::text OR m.f_description ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !message_type.is_empty() { + filters.push(format!("AND m.f_message_type = ${next}::text")); + values.push(Some(message_type)); + next += 1; + } + if !category.is_empty() { + filters.push(format!("AND m.f_category LIKE ${next}::text")); + values.push(Some(format!("%{category}%"))); + next += 1; + } + if !status.is_empty() { + filters.push(format!("AND m.f_status = ${next}::text::integer")); + values.push(Some(status)); + next += 1; + } + if !start_time.is_empty() { + filters.push(format!("AND m.f_send_time >= ${next}::text::timestamp")); + values.push(normalize_time(&start_time)); + next += 1; + } + if !end_time.is_empty() { + filters.push(format!("AND m.f_send_time <= ${next}::text::timestamp")); + values.push(normalize_time(&end_time)); + } + let where_body = format!( + "COALESCE(m.f_delete_mark, 0) = 0{}", + if filters.is_empty() { + String::new() + } else { + format!(" {}", filters.join(" ")) + } + ); + let cols = "m.f_id AS \"id\", m.f_message_type AS \"messageType\", m.f_send_time AS \"sendTime\", \ + m.f_title AS \"title\", m.f_category AS \"category\", m.f_send_type AS \"sendType\", \ + m.f_status AS \"status\", m.f_creator_user_id AS \"sendUser\""; + match paged_query( + &state, + cols, + "base_msg_monitor m", + &where_body, + "ORDER BY m.f_send_time DESC", + values, + &page, + "消息监控列表", + ) + .await + { + Ok((total, rows)) => { + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let mut list = Vec::new(); + for row in rows { + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + list.push(json!({ + "id": sv(&row, "id"), + "messageType": message_type_name(&sv(&row, "messageType")), + "sendTime": sv(&row, "sendTime"), + "title": sv(&row, "title"), + "category": join_category_names(&cat_ids, &cat_map), + "sendType": sv(&row, "sendType"), + "status": iv(&row, "status"), + "sendUser": sv(&row, "sendUser"), + })); + } + ok(page_list(page.current_page, page.page_size, total, list)) + } + Err(resp) => resp, + } +} + +/// `GET /api/message/Monitor/detail/{id}` —— 消息监控详情(含已读/未读)。 +pub async fn monitor_detail( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_MSG_RECORD).await { + return resp; + } + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_message_type AS \"messageType\", f_send_time AS \"sendTime\", \ + f_title AS \"title\", f_category AS \"category\", f_send_type AS \"sendType\", \ + f_status AS \"status\", f_retry_json AS \"retryJson\", f_creator_user_id AS \"sendUser\" \ + FROM base_msg_monitor WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "消息监控详情", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + let cat_map = match business_category_map(&state).await { + Ok(m) => m, + Err(resp) => return resp, + }; + let cat_ids = parse_category_ids(Some(&sv(&row, "category"))); + // 🔴 官方 `readInfo` = 该监控下的站内信分「已读 / 未读」两份名单。 + let read_rows = match fetch_all( + &state, + "SELECT f_id AS \"id\", f_title AS \"title\", f_user_id AS \"userId\", f_is_read AS \"isRead\", \ + f_read_time AS \"readTime\", f_read_count AS \"readCount\" \ + FROM base_message WHERE f_monitor_id = $1::text AND COALESCE(f_is_read, 0) = 1 \ + ORDER BY f_read_time DESC", + &[Some(id.clone())], + "已读名单", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let unread_rows = match fetch_all( + &state, + "SELECT f_id AS \"id\", f_title AS \"title\", f_user_id AS \"userId\", f_is_read AS \"isRead\", \ + f_read_time AS \"readTime\", f_read_count AS \"readCount\" \ + FROM base_message WHERE f_monitor_id = $1::text AND COALESCE(f_is_read, 0) = 0 \ + ORDER BY f_creator_time DESC", + &[Some(id.clone())], + "未读名单", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + ok(json!({ + "id": sv(&row, "id"), + "messageType": message_type_name(&sv(&row, "messageType")), + "sendTime": sv(&row, "sendTime"), + "title": sv(&row, "title"), + "category": join_category_names(&cat_ids, &cat_map), + "sendType": sv(&row, "sendType"), + "status": iv(&row, "status"), + "sendUser": sv(&row, "sendUser"), + "retryJson": sv(&row, "retryJson"), + "readInfo": { + "readList": read_rows, + "unReadList": unread_rows, + }, + })) +} + +/// `DELETE /api/message/Monitor/batchRemove` —— 批量删除监控记录。 +pub async fn monitor_batch_remove( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_RECORD).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let ids = id_list_of(&obj, "ids"); + if ids.is_empty() { + return fail(code::FAIL, "请选择要删除的记录"); + } + for id in &ids { + if let Err(resp) = soft_delete( + &state, + "base_msg_monitor", + id, + &user.account, + "批量删除消息监控", + ) + .await + { + return resp; + } + } + ok_msg(MSG_DELETED) +} + +/// `DELETE /api/message/Monitor/empty` —— 清空消息监控。 +pub async fn monitor_empty( + State(state): State, + headers: HeaderMap, +) -> Json { + let user = match guard(&state, &headers, EN_MSG_RECORD).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let sql = "UPDATE base_msg_monitor SET f_delete_mark = 1, f_delete_time = now(), \ + f_delete_user_id = $1::text WHERE COALESCE(f_delete_mark, 0) = 0"; + if let Err(e) = state + .db + .exec_params(&sql, ¶ms_of(&[Some(user.account.clone())])) + .await + { + return db_error(e, "清空消息监控"); + } + ok_msg(MSG_OPERATED) +} + +/// `GET /api/message/Monitor/{id}/RecordList` —— 某次发送的记录列表。 +pub async fn monitor_record_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, + raw: RawQuery, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_MSG_RECORD).await { + return resp; + } + let page = Paging::of(&raw); + let status = qv(&raw, "status"); + let mut filters: Vec = vec!["COALESCE(r.f_delete_mark, 0) = 0".to_string()]; + let mut values: Vec> = vec![Some(id.clone())]; + if !status.is_empty() { + filters.push("r.f_status = $2::text::integer".to_string()); + values.push(Some(status)); + } + let cols = "r.f_id AS \"id\", r.f_monitor_id AS \"monitorId\", r.f_status AS \"status\", \ + r.f_send_time AS \"sendTime\", r.f_description AS \"description\", \ + r.f_receive_user AS \"receiveUser\""; + match paged_query( + &state, + cols, + "base_msg_record r", + &filters.join(" AND "), + "ORDER BY r.f_send_time DESC", + values, + &page, + "消息发送记录列表", + ) + .await + { + Ok((total, rows)) => ok(page_list(page.current_page, page.page_size, total, rows)), + Err(resp) => resp, + } +} + +/// `GET /api/message/Monitor/Info` —— 消息发送统计。 +/// +/// 🔴 官方 `MessageMonitorServiceImpl.getDataByDay`。 +pub async fn monitor_info( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let start_raw = qv(&raw, "startTime"); + let end_raw = qv(&raw, "endTime"); + let (start_ts, end_ts) = monitor_range(&start_raw, &end_raw); + let start = normalize_epoch(start_ts); + let end = normalize_epoch(end_ts); + let sql = "SELECT f_status AS \"status\", f_message_type AS \"messageType\", \ + TO_CHAR(f_send_time, 'YYYYMMDD') AS \"day\", \ + f_category AS \"category\" \ + FROM base_msg_monitor \ + WHERE COALESCE(f_delete_mark, 0) = 0 \ + AND f_send_time >= $1::text::timestamp AND f_send_time < $2::text::timestamp"; + let rows = match fetch_all( + &state, + sql, + &[Some(start.clone()), Some(end.clone())], + "消息发送统计", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let mut total = 0i64; + let mut success = 0i64; + let mut fail = 0i64; + let mut sending = 0i64; + let mut notice_success = 0i64; + let mut notice_fail = 0i64; + let mut notice_sending = 0i64; + let mut by_type: HashMap> = HashMap::new(); + let mut by_day: Vec = Vec::new(); + for row in &rows { + total += 1; + let status = iv(row, "status").unwrap_or(0); + let day = sv(row, "day"); + let mtype = sv(row, "messageType"); + let is_notice = sv(row, "category").contains(NOTICE_CATEGORY_ID); + match status { + 0 => { + success += 1; + if is_notice { + notice_success += 1; + } + } + 1 => { + fail += 1; + if is_notice { + notice_fail += 1; + } + } + _ => { + sending += 1; + if is_notice { + notice_sending += 1; + } + } + } + *by_type + .entry(mtype) + .or_default() + .entry(day.clone()) + .or_insert(0) += 1; + if !by_day.contains(&day) { + by_day.push(day); + } + } + by_day.sort(); + // 🔴 官方:日期序列取 start~end(含端点),缺的日子补 0。 + let date_list = date_series(start_ts, end_ts); + let mut msg_type_list = Vec::new(); + for (code, name) in MESSAGE_TYPES.iter() { + let per_day = by_type.get(*code); + let data: Vec = date_list + .iter() + .map(|d| per_day.and_then(|m| m.get(d)).copied().unwrap_or(0)) + .collect(); + msg_type_list.push(json!({ "name": name, "data": data })); + } + let rate = if total > 0 { + (success as f64 * 10000.0 / total as f64).round() / 100.0 + } else { + 0.0 + }; + ok(json!({ + "msgSuccessRate": rate, + "sendFail": fail, + "sendSuccess": success, + "sending": sending, + "noticeInfo": { + "sendFail": notice_fail, + "sendSuccess": notice_success, + "sending": notice_sending, + }, + "msgTypeInfo": { + "dateList": date_list, + "msgTypeList": msg_type_list, + }, + })) +} + +/// 监控统计区间:缺省「近 30 天(含今天)」。 +fn monitor_range(start_raw: &str, end_raw: &str) -> (i64, i64) { + let now = chrono::Utc::now().timestamp_millis(); + let day = 86_400_000i64; + let default_start = now - day * 30; + let default_end = now + day; + let start = parse_epoch(start_raw).unwrap_or(default_start); + let end = parse_epoch(end_raw).unwrap_or(default_end); + if end <= start { + (start, start + day) + } else { + (start, end) + } +} + +/// 解析成 epoch 毫秒:纯数字当毫秒,`YYYY-MM-DD` / `YYYY-MM-DD HH:mm:ss` 当本地时间。 +fn parse_epoch(raw: &str) -> Option { + if raw.is_empty() { + return None; + } + if raw.chars().all(|c| c.is_ascii_digit()) { + return raw.parse::().ok(); + } + chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%d %H:%M:%S") + .ok() + .or_else(|| { + chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d") + .ok() + .and_then(|d| d.and_hms_opt(0, 0, 0)) + }) + .map(|dt| dt.and_utc().timestamp_millis()) +} + +/// epoch 毫秒 ⇒ `YYYY-MM-DD HH:mm:ss`(UTC)。 +fn normalize_epoch(ts: i64) -> String { + chrono::DateTime::from_timestamp_millis(ts) + .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()) + .unwrap_or_else(|| "1970-01-01 00:00:00".to_string()) +} + +/// 官方口径:start~end 之间的每一天(`yyyyMMdd`)。 +fn date_series(start_ts: i64, end_ts: i64) -> Vec { + let day = 86_400_000i64; + let mut out = Vec::new(); + let mut cur = start_ts; + let mut guard_count = 0; + while cur < end_ts && guard_count < 400 { + if let Some(dt) = chrono::DateTime::from_timestamp_millis(cur) { + out.push(dt.format("%Y%m%d").to_string()); + } + cur += day; + guard_count += 1; + } + out +} + +/// `POST /api/message/Monitor/{id}/Retry` —— 重发失败的消息。 +/// +/// 🔴 真发消息 ⇒ 本仓无 HTTP 客户端 ⇒ 明确业务失败。 +pub async fn monitor_retry( + State(state): State, + headers: HeaderMap, + Path(_id): Path, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let _ = body; + // 🔴 **能力判定排在数据判定之前** —— 本仓**永远**发不出去,重发对任何 id 都不可用; + // 先报「未接入消息服务商」,比「数据不存在」更能说明问题(后者会让人以为是 id 写错)。 + unsupported_provider("重发消息") +} + +// ================================================================ 消息供应商(12 条) +// +// 🔴 官方 `IntgSupplierController` —— 除 `/TemplateList` 外**全部只要登录**。 +// 🔴 官方 `add` / `put` 都会先**真连服务商**做「测试连接」⇒ 本仓无 HTTP 客户端 ⇒ +// 跳过连通性检查(写库照做),在契约台账里如实标 partial。 + +const MSG_SUPPLIER_DUP_NAME: &str = "名称重复"; +const MSG_SUPPLIER_DUP_CODE: &str = "编码重复"; +const MSG_SUPPLIER_COPY_FAILED: &str = "复制失败"; +const MSG_SUPPLIER_SECRET_EXISTS: &str = "创建失败,系统中已存在相同的供应商密钥凭证"; +const MSG_SUPPLIER_SECRET_ACTIVATED: &str = "启用失败,系统中已存在相同的供应商密钥凭证"; + +/// 官方 `SupplierEnum`:消息类型 ⇒ 允许的供应商类别。 +fn supplier_categories_for(message_type: &str) -> Vec<&'static str> { + match message_type { + "2" | "3" => vec!["TencentCloud", "AlibabaCloud"], + "4" => vec!["DingTalk"], + "5" => vec!["WeWork"], + "6" => vec!["TencentCloud", "AlibabaCloud", "Feishu"], + "7" => vec!["WeMP"], + "8" => vec!["Feishu"], + _ => Vec::new(), + } +} + +/// 供应商是否被引用(消息账号引用 或 供应商模板引用)。 +async fn supplier_is_related(state: &AppState, supplier_id: &str) -> Result> { + let acc = fetch_one( + state, + "SELECT f_id AS \"id\" FROM base_msg_account \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_supplier_id = $1::text LIMIT 1", + &[Some(supplier_id.to_string())], + "供应商账号引用查询", + ) + .await?; + if acc.is_some() { + return Ok(true); + } + let tpl = fetch_one( + state, + "SELECT f_id AS \"id\" FROM base_intg_supplier_tpl \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_supplier_id = $1::text LIMIT 1", + &[Some(supplier_id.to_string())], + "供应商模板引用查询", + ) + .await?; + Ok(tpl.is_some()) +} + +/// `GET /api/message/Supplier` —— 供应商列表。 +pub async fn supplier_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let keyword = qv(&raw, "keyword"); + let category = qv(&raw, "category"); + let enabled_mark = qv(&raw, "enabledMark"); + let mut filters: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "AND (s.f_full_name ILIKE ${next}::text OR s.f_en_code ILIKE ${next}::text \ + OR s.f_secret_id ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !category.is_empty() { + filters.push(format!("AND s.f_category = ${next}::text")); + values.push(Some(category)); + next += 1; + } + if !enabled_mark.is_empty() { + filters.push(format!("AND s.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + } + let where_body = format!( + "COALESCE(s.f_delete_mark, 0) = 0{}", + if filters.is_empty() { + String::new() + } else { + format!(" {}", filters.join(" ")) + } + ); + let cols = "s.f_id AS \"id\", s.f_en_code AS \"enCode\", s.f_full_name AS \"fullName\", \ + s.f_category AS \"category\", s.f_secret_id AS \"secretId\", s.f_secret_key AS \"secretKey\", \ + COALESCE(s.f_enabled_mark, 0) AS \"enabledMark\", COALESCE(s.f_sort_code, 0) AS \"sortCode\""; + match fetch_all( + &state, + &format!( + "SELECT {cols} FROM base_intg_supplier s WHERE {where_body} \ + ORDER BY COALESCE(s.f_sort_code, 0) ASC, s.f_creator_time DESC" + ), + &values, + "供应商列表", + ) + .await + { + Ok(rows) => { + let mut list = Vec::new(); + for row in rows { + let cat = sv(&row, "category"); + list.push(json!({ + "id": sv(&row, "id"), + "enCode": sv(&row, "enCode"), + "fullName": sv(&row, "fullName"), + "category": cat, + "secretId": sv(&row, "secretId"), + "secretKey": sv(&row, "secretKey"), + "supplierName": supplier_category_name(&cat), + "supplierId": Value::Null, + "enabledMark": iv(&row, "enabledMark"), + "sortCode": iv(&row, "sortCode"), + "smsSignature": Value::Null, + "isDefault": Value::Null, + "content": Value::Null, + })); + } + ok(list_vo(list)) + } + Err(resp) => resp, + } +} + +/// `POST /api/message/Supplier` —— 新增供应商。 +pub async fn supplier_create( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let full_name = text_field(&obj, "fullName").unwrap_or_default(); + let en_code = text_field(&obj, "enCode").unwrap_or_default(); + let secret_id = text_field(&obj, "secretId").unwrap_or_default(); + let secret_key = text_field(&obj, "secretKey").unwrap_or_default(); + if full_name.is_empty() || en_code.is_empty() { + return fail(code::FAIL, "名称与编码不能为空"); + } + let dup_name = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_full_name = $1::text LIMIT 1", + &[Some(full_name.clone())], + "供应商名称查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup_name.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_DUP_NAME); + } + let dup_code = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_en_code = $1::text LIMIT 1", + &[Some(en_code.clone())], + "供应商编码查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup_code.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_DUP_CODE); + } + let dup_secret = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_secret_id = $1::text \ + AND f_secret_key = $2::text LIMIT 1", + &[Some(secret_id.clone()), Some(secret_key.clone())], + "供应商密钥查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup_secret.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_SECRET_EXISTS); + } + let columns = [ + "f_id", + "f_tenant_id", + "f_full_name", + "f_en_code", + "f_category", + "f_secret_id", + "f_secret_key", + "f_sort_code", + "f_enabled_mark", + "f_description", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(full_name), + Some(en_code), + text_field(&obj, "category"), + Some(secret_id), + Some(secret_key), + obj.get("sortCode") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .map(|v| v.to_string()), + obj.get("enabledMark") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .map(|v| v.to_string()), + text_field(&obj, "description"), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "", "::bigint", "::integer", "", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_intg_supplier", + &columns, + &casts, + &values, + &user.account, + "新增供应商", + ) + .await + { + return resp; + } + ok_msg(MSG_CREATED) +} + +/// `GET /api/message/Supplier/Selector` —— 供应商下拉框。 +pub async fn supplier_selector( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let message_type = qv(&raw, "messageType"); + if message_type.is_empty() { + return fail(code::FAIL, "messageType 不能为空"); + } + let allowed = supplier_categories_for(&message_type); + let mut filters = vec!["COALESCE(s.f_delete_mark, 0) = 0".to_string()]; + let values: Vec> = Vec::new(); + if !allowed.is_empty() { + let list = allowed + .iter() + .map(|c| format!("'{}'", c)) + .collect::>() + .join(", "); + filters.push(format!("s.f_category IN ({list})")); + } + filters.push("COALESCE(s.f_enabled_mark, 0) = 1".to_string()); + // 🔴 官方:已被**同类型消息账号**引用的供应商不再出现在下拉里。 + let used = match fetch_all( + &state, + "SELECT DISTINCT f_supplier_id AS \"supplierId\" FROM base_msg_account \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_message_type = $1::text \ + AND COALESCE(f_supplier_id, '') <> ''", + &[Some(message_type.clone())], + "已被引用的供应商", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let used_ids: Vec = used.iter().map(|r| sv(r, "supplierId")).collect(); + match fetch_all( + &state, + &format!( + "SELECT s.f_id AS \"id\", s.f_en_code AS \"enCode\", s.f_full_name AS \"fullName\", \ + s.f_category AS \"category\" FROM base_intg_supplier s WHERE {} \ + ORDER BY COALESCE(s.f_sort_code, 0) ASC", + filters.join(" AND ") + ), + &values, + "供应商下拉列表", + ) + .await + { + Ok(rows) => { + let list: Vec = rows + .iter() + .filter(|r| !used_ids.contains(&sv(r, "id"))) + .map(|r| { + json!({ + "id": sv(r, "id"), + "enCode": sv(r, "enCode"), + "fullName": sv(r, "fullName"), + "category": sv(r, "category"), + }) + }) + .collect(); + ok(list_vo(list)) + } + Err(resp) => resp, + } +} + +/// `GET /api/message/Supplier/{id}` —— 供应商详情。 +pub async fn supplier_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_en_code AS \"enCode\", f_full_name AS \"fullName\", \ + f_category AS \"category\", f_secret_id AS \"secretId\", f_secret_key AS \"secretKey\", \ + f_description AS \"description\", COALESCE(f_sort_code, 0) AS \"sortCode\", \ + COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \ + FROM base_intg_supplier WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "供应商详情", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + // 🔴 官方 `isEditor`:该供应商**没有模板** ⇒ 可编辑(模板由服务商同步进来)。 + let tpl_count = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier_tpl \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_supplier_id = $1::text LIMIT 1", + &[Some(id.clone())], + "供应商模板数", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + ok(json!({ + "id": sv(&row, "id"), + "enCode": sv(&row, "enCode"), + "fullName": sv(&row, "fullName"), + "category": sv(&row, "category"), + "secretId": sv(&row, "secretId"), + "secretKey": sv(&row, "secretKey"), + "description": sv(&row, "description"), + "sortCode": iv(&row, "sortCode"), + "enabledMark": iv(&row, "enabledMark"), + "isEditor": tpl_count.is_none(), + })) +} + +/// `PUT /api/message/Supplier/{id}` —— 更新供应商。 +pub async fn supplier_update( + State(state): State, + headers: HeaderMap, + Path(id): Path, + body: Bytes, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let cur = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_secret_id AS \"secretId\", f_secret_key AS \"secretKey\", \ + COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \ + FROM base_intg_supplier WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "供应商存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let cur = match cur { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + let full_name = text_field(&obj, "fullName").unwrap_or_default(); + let en_code = text_field(&obj, "enCode").unwrap_or_default(); + let secret_id = text_field(&obj, "secretId").unwrap_or_default(); + let secret_key = text_field(&obj, "secretKey").unwrap_or_default(); + let dup_name = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_full_name = $1::text AND f_id <> $2::text \ + LIMIT 1", + &[Some(full_name.clone()), Some(id.clone())], + "供应商名称查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup_name.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_DUP_NAME); + } + let dup_code = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_en_code = $1::text AND f_id <> $2::text \ + LIMIT 1", + &[Some(en_code.clone()), Some(id.clone())], + "供应商编码查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup_code.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_DUP_CODE); + } + // 🔴 官方 `checkSecret` / `isActivated`:目标本身**已启用** ⇒ 两道检查都跳过。 + let cur_enabled = iv(&cur, "enabledMark").unwrap_or(0) == 1; + if !cur_enabled { + let dup_secret = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_secret_id = $1::text \ + AND f_secret_key = $2::text AND f_id <> $3::text LIMIT 1", + &[Some(secret_id.clone()), Some(secret_key.clone()), Some(id.clone())], + "供应商密钥查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if dup_secret.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_SECRET_EXISTS); + } + let activated = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_secret_id = $1::text \ + AND f_secret_key = $2::text AND f_id <> $3::text \ + AND COALESCE(f_enabled_mark, 0) = 1 LIMIT 1", + &[Some(secret_id.clone()), Some(secret_key.clone()), Some(id.clone())], + "供应商密钥启用查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if activated.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_SECRET_ACTIVATED); + } + } + let sets = write_fields( + &obj, + &[ + ("fullName", "f_full_name", ""), + ("enCode", "f_en_code", ""), + ("category", "f_category", ""), + ("secretId", "f_secret_id", ""), + ("secretKey", "f_secret_key", ""), + ("description", "f_description", ""), + ("enabledMark", "f_enabled_mark", "::integer"), + ("sortCode", "f_sort_code", "::bigint"), + ], + ); + if let Err(resp) = update_row( + &state, + "base_intg_supplier", + &id, + &sets, + &user.account, + "更新供应商", + ) + .await + { + return resp; + } + ok_msg(MSG_UPDATED) +} + +/// `DELETE /api/message/Supplier/{id}` —— 删除供应商。 +pub async fn supplier_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let exists = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "供应商存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if exists.is_none() { + return fail(code::FAIL, "删除失败,数据不存在"); + } + let related = match supplier_is_related(&state, &id).await { + Ok(r) => r, + Err(resp) => return resp, + }; + if related { + return fail(code::FAIL, MSG_SUPPLIER_RELATED_DELETE); + } + if let Err(resp) = soft_delete(&state, "base_intg_supplier", &id, &user.account, "删除供应商").await { + return resp; + } + ok_msg(MSG_DELETED) +} + +/// `GET /api/message/Supplier/TemplateList` —— 供应商模板列表。 +pub async fn supplier_template_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = guard_any( + &state, + &headers, + &[ + EN_INTEGRATION_SMS, + EN_INTEGRATION_EMAIL, + EN_INTEGRATION_WECHAT_MP, + EN_INTEGRATION_WEBHOOK, + ], + ) + .await + { + return resp; + } + let page = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let message_type = qv(&raw, "messageType"); + let category = qv(&raw, "category"); + let enabled_mark = qv(&raw, "enabledMark"); + let mut filters: Vec = vec!["COALESCE(t.f_delete_mark, 0) = 0".to_string()]; + let mut values: Vec> = Vec::new(); + let mut next = 1usize; + if !keyword.is_empty() { + filters.push(format!( + "(t.f_en_code ILIKE ${next}::text OR t.f_full_name ILIKE ${next}::text \ + OR t.f_sms_signature ILIKE ${next}::text OR s.f_full_name ILIKE ${next}::text)" + )); + values.push(Some(format!("%{keyword}%"))); + next += 1; + } + if !message_type.is_empty() && message_type != "1" { + filters.push(format!("t.f_message_type = ${next}::text")); + values.push(Some(message_type)); + next += 1; + } + if !category.is_empty() { + filters.push(format!("s.f_category = ${next}::text")); + values.push(Some(category)); + next += 1; + } + if !enabled_mark.is_empty() { + filters.push(format!("t.f_enabled_mark = ${next}::text::integer")); + values.push(Some(enabled_mark)); + } + let where_body = filters.join(" AND "); + let cols = "t.f_id AS \"id\", t.f_en_code AS \"enCode\", t.f_full_name AS \"fullName\", \ + t.f_message_type AS \"messageType\", t.f_supplier_id AS \"supplierId\", \ + t.f_content AS \"content\", t.f_sms_signature AS \"smsSignature\", \ + COALESCE(t.f_enabled_mark, 0) AS \"enabledMark\", COALESCE(t.f_sort_code, 0) AS \"sortCode\", \ + s.f_full_name AS \"supplierName\""; + let from = "base_intg_supplier_tpl t LEFT JOIN base_intg_supplier s ON s.f_id = t.f_supplier_id"; + match paged_query( + &state, + cols, + from, + &where_body, + "ORDER BY COALESCE(t.f_sort_code, 0) ASC, t.f_creator_time DESC", + values, + &page, + "供应商模板列表", + ) + .await + { + Ok((total, rows)) => { + let mut list = Vec::new(); + for row in rows { + let cat = sv(&row, "category"); + list.push(json!({ + "id": sv(&row, "id"), + "enCode": sv(&row, "enCode"), + "fullName": sv(&row, "fullName"), + "category": cat, + "secretId": Value::Null, + "secretKey": Value::Null, + "supplierName": sv(&row, "supplierName"), + "supplierId": sv(&row, "supplierId"), + "enabledMark": iv(&row, "enabledMark"), + "sortCode": iv(&row, "sortCode"), + "smsSignature": sv(&row, "smsSignature"), + "isDefault": Value::Null, + "content": sv(&row, "content"), + "messageType": sv(&row, "messageType"), + })); + } + ok(page_list(page.current_page, page.page_size, total, list)) + } + Err(resp) => resp, + } +} + +/// `POST /api/message/Supplier/{id}/Actions/Copy` —— 复制供应商。 +pub async fn supplier_copy( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_en_code AS \"enCode\", f_full_name AS \"fullName\", \ + f_category AS \"category\", f_secret_id AS \"secretId\", f_secret_key AS \"secretKey\", \ + f_description AS \"description\", COALESCE(f_sort_code, 0) AS \"sortCode\" \ + FROM base_intg_supplier WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "供应商复制源", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_SUPPLIER_COPY_FAILED), + }; + let suffix = copy_suffix(); + let full_name = format!("{}.副本{}", sv(&row, "fullName"), suffix); + let en_code = format!("{}{}", sv(&row, "enCode"), suffix); + if full_name.len() > 50 || en_code.len() > 50 { + return fail(code::FAIL, MSG_COPY_LIMIT); + } + let columns = [ + "f_id", + "f_tenant_id", + "f_full_name", + "f_en_code", + "f_category", + "f_secret_id", + "f_secret_key", + "f_sort_code", + "f_enabled_mark", + "f_description", + "f_delete_mark", + ]; + let values = vec![ + Some(new_uuid()), + Some("0".to_string()), + Some(full_name), + Some(en_code), + Some(sv(&row, "category")), + Some(sv(&row, "secretId")), + Some(sv(&row, "secretKey")), + iv(&row, "sortCode").map(|v| v.to_string()), + Some("0".to_string()), + Some(sv(&row, "description")), + Some("0".to_string()), + ]; + let casts = ["", "", "", "", "", "", "", "::bigint", "::integer", "", "::integer"]; + if let Err(resp) = insert_row( + &state, + "base_intg_supplier", + &columns, + &casts, + &values, + &user.account, + "复制供应商", + ) + .await + { + return resp; + } + ok_msg(MSG_COPIED) +} + +/// `POST /api/message/Supplier/SyncTemplate` —— 从服务商同步模板。 +/// +/// 🔴 真连服务商 ⇒ 本仓无 HTTP 客户端 ⇒ 明确业务失败。 +pub async fn supplier_sync_template( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let _ = body; + unsupported_provider("同步供应商模板") +} + +/// `POST /api/message/Supplier/TestConnect` —— 供应商连通性测试。 +/// +/// 🔴 **官方前端有、官方 Java 没有**(`api/msgCenter/supplier.ts:45`)⇒ 真连服务商 ⇒ 明确业务失败。 +pub async fn supplier_test_connect( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let _ = body; + unsupported_provider("测试供应商连接") +} + +/// `PUT /api/message/Supplier/{id}/Actions/State` —— 改供应商启用状态。 +/// +/// 🔴 官方语义:请求体带的是**当前** `enabledMark`,服务端**取反**落库。 +pub async fn supplier_state( + State(state): State, + headers: HeaderMap, + Path(id): Path, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match body_obj(&body) { + Ok(o) => o, + Err(resp) => return resp, + }; + let row = match fetch_one( + &state, + "SELECT f_id AS \"id\", f_secret_id AS \"secretId\", f_secret_key AS \"secretKey\", \ + COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \ + FROM base_intg_supplier WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[Some(id.clone())], + "供应商存在性", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + let current = iv(&row, "enabledMark").unwrap_or(0); + let requested = obj + .get("enabledMark") + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + .unwrap_or(current); + if requested == 1 { + // 🔴 官方:当前是「启用」⇒ 本次操作是**禁用** ⇒ 被引用则拦。 + let related = match supplier_is_related(&state, &id).await { + Ok(r) => r, + Err(resp) => return resp, + }; + if related { + return fail(code::FAIL, MSG_SUPPLIER_RELATED); + } + } else { + // 🔴 官方:当前是「禁用」⇒ 本次操作是**启用** ⇒ 同一密钥已被别的**启用**供应商占用则拦。 + let activated = match fetch_one( + &state, + "SELECT f_id AS \"id\" FROM base_intg_supplier \ + WHERE COALESCE(f_delete_mark, 0) = 0 AND f_secret_id = $1::text \ + AND f_secret_key = $2::text AND f_id <> $3::text \ + AND COALESCE(f_enabled_mark, 0) = 1 LIMIT 1", + &[ + Some(sv(&row, "secretId")), + Some(sv(&row, "secretKey")), + Some(id.clone()), + ], + "供应商密钥启用查重", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if activated.is_some() { + return fail(code::FAIL, MSG_SUPPLIER_SECRET_ACTIVATED); + } + } + let next_mark = if requested == 1 { 0 } else { 1 }; + let sql = "UPDATE base_intg_supplier SET f_enabled_mark = $1::text::integer, \ + f_last_modify_time = now() WHERE f_id = $2::text"; + if let Err(e) = state + .db + .exec_params( + sql, + ¶ms_of(&[Some(next_mark.to_string()), Some(id.clone())]), + ) + .await + { + return db_error(e, "修改供应商状态"); + } + ok_msg(MSG_OPERATED) +} + +/// `GET /api/message/Supplier/{id}/VariableList` —— 供应商模板的变量列表。 +/// +/// 🔴 官方 `parseVariable(id)`:**`id` 是供应商模板 id**(不是供应商 id)。 +pub async fn supplier_variable_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let row = match fetch_one( + &state, + "SELECT t.f_content AS \"content\", t.f_supplier_id AS \"supplierId\", \ + s.f_category AS \"category\" FROM base_intg_supplier_tpl t \ + LEFT JOIN base_intg_supplier s ON s.f_id = t.f_supplier_id \ + WHERE t.f_id = $1::text AND COALESCE(t.f_delete_mark, 0) = 0", + &[Some(id.clone())], + "供应商模板内容", + ).await { + Ok(v) => v, + Err(resp) => return resp, + }; + let row = match row { + Some(r) => r, + None => return fail(code::FAIL, MSG_DATA_NOT_FOUND), + }; + let content = sv(&row, "content"); + let category = sv(&row, "category"); + let variables = parse_template_variables(&content, &category); + ok(list_vo(variables.into_iter().map(Value::String).collect())) +} + +/// 🔴 官方 `IntgSupplierTplServiceImpl.parseVariable`: +/// 阿里云 `${x}` / 腾讯云 `{x}` / 公众号 `{{x}}`。 +/// 🔴 本仓**没有 regex crate** ⇒ 手写扫描。 +fn parse_template_variables(content: &str, category: &str) -> Vec { + let bytes: Vec = content.chars().collect(); + let mut out: Vec = Vec::new(); + let mut i = 0usize; + while i < bytes.len() { + let c = bytes[i]; + let (open, close, wrap) = match category { + "AlibabaCloud" => ('$', '}', "${"), + "TencentCloud" => ('{', '}', "{"), + "WeMP" => ('{', '}', "{"), + _ => { + // 其它类别官方不解析 ⇒ 空列表。 + return out; + } + }; + if c != open { + i += 1; + continue; + } + if category == "AlibabaCloud" { + // `${x}`:必须紧跟一个 `{`。 + if i + 1 >= bytes.len() || bytes[i + 1] != '{' { + i += 1; + continue; + } + } + let start = i + if category == "AlibabaCloud" { 2 } else { 1 }; + let mut j = start; + while j < bytes.len() && bytes[j] != close { + j += 1; + } + if j >= bytes.len() { + break; + } + let name: String = bytes[start..j].iter().collect(); + if !name.is_empty() { + let wrapped = format!("{wrap}{name}{close}"); + if !out.contains(&wrapped) { + out.push(wrapped); + } + } + i = j + 1; + } + out +} diff --git a/src/backend/src/routes.rs b/src/backend/src/routes.rs index 5b0cb52..aa43e2e 100644 --- a/src/backend/src/routes.rs +++ b/src/backend/src/routes.rs @@ -1697,6 +1697,138 @@ pub fn build_router(state: AppState) -> axum::Router { .route("/api/workflow/trigger/task", get(compat::workflow::workflow_trigger_task_list)) .route("/api/workflow/trigger/task", delete(compat::workflow::workflow_trigger_delete)) .route("/api/workflow/trigger/task/Retry/{id}", post(compat::workflow::workflow_trigger_retry)) + // 🔴 **消息中心(msgCenter)50 条** —— 官方前端 `src/api/msgCenter/**` 的全部接口。 + // 与上面的 `compat::message`(站内信 / 公告)**不是**一族,路径不重叠。 + .route("/api/message/Account", get(compat::msg_center::account_list)) + .route("/api/message/Account", post(compat::msg_center::account_create)) + .route("/api/message/Account/{id}", get(compat::msg_center::account_info)) + .route("/api/message/Account/{id}", put(compat::msg_center::account_update)) + .route("/api/message/Account/{id}", delete(compat::msg_center::account_delete)) + .route( + "/api/message/Account/{id}/Actions/Copy", + post(compat::msg_center::account_copy), + ) + .route( + "/api/message/Account/testSendMail", + post(compat::msg_center::account_test_send), + ) + // 🔴 官方前端 `testConfig` 声明的是**动态**路径 `${Api.Prefix}/${data.testType}` + // (`api/msgCenter/accountConfig.ts:33`)⇒ 这条别名把「声明的路径」也接住。 + // 静态段 `testSendMail` 优先级更高(matchit 静态 > 参数)⇒ 官方前端那条 + // 实际打的是静态端点;两条行为一致(都明确业务失败)。 + // 🔴 **参数名必须是 `{id}`**:axum/matchit **同一位置不允许两个不同的参数名** + // (`{id}` 已被上面的 Copy 路由占用 ⇒ 注册 `{testType}` 会直接 panic: + // "Insertion failed due to conflict with previously registered route")。 + .route( + "/api/message/Account/{id}", + post(compat::msg_center::account_test_send_by_type), + ) + .route( + "/api/message/Account/setdefault", + put(compat::msg_center::account_set_default), + ) + .route("/api/message/Send", get(compat::msg_center::send_config_list)) + .route("/api/message/Send", post(compat::msg_center::send_config_create)) + .route("/api/message/Send/{id}", get(compat::msg_center::send_config_info)) + .route("/api/message/Send/{id}", put(compat::msg_center::send_config_update)) + .route("/api/message/Send/{id}", delete(compat::msg_center::send_config_delete)) + .route( + "/api/message/Send/{id}/Actions/Copy", + post(compat::msg_center::send_config_copy), + ) + .route( + "/api/message/Send/getTestConfig/{id}", + post(compat::msg_center::send_config_test_config), + ) + .route( + "/api/message/Send/testSendConfig", + post(compat::msg_center::send_config_test_send), + ) + .route( + "/api/message/Send/getSendConfigList", + get(compat::msg_center::send_config_select_list), + ) + .route("/api/message/Template", get(compat::msg_center::msg_template_list)) + .route("/api/message/Template", post(compat::msg_center::msg_template_create)) + .route("/api/message/Template/{id}", get(compat::msg_center::msg_template_info)) + .route("/api/message/Template/{id}", put(compat::msg_center::msg_template_update)) + .route( + "/api/message/Template/{id}", + delete(compat::msg_center::msg_template_delete), + ) + .route( + "/api/message/Template/{id}/Actions/Copy", + post(compat::msg_center::msg_template_copy), + ) + .route( + "/api/message/Template/testSendMail", + post(compat::msg_center::msg_template_test_send), + ) + .route("/api/message/Sensitive", get(compat::msg_center::sensitive_list)) + .route("/api/message/Sensitive", post(compat::msg_center::sensitive_create)) + .route("/api/message/Sensitive/{id}", get(compat::msg_center::sensitive_info)) + .route("/api/message/Sensitive/{id}", put(compat::msg_center::sensitive_update)) + .route( + "/api/message/Sensitive/{id}", + delete(compat::msg_center::sensitive_delete), + ) + .route("/api/message/Receive", get(compat::msg_center::receive_list)) + .route("/api/message/Receive", post(compat::msg_center::receive_save)) + .route("/api/message/Monitor", get(compat::msg_center::monitor_list)) + .route( + "/api/message/Monitor/detail/{id}", + get(compat::msg_center::monitor_detail), + ) + .route( + "/api/message/Monitor/batchRemove", + delete(compat::msg_center::monitor_batch_remove), + ) + .route("/api/message/Monitor/empty", delete(compat::msg_center::monitor_empty)) + .route( + "/api/message/Monitor/{id}/RecordList", + get(compat::msg_center::monitor_record_list), + ) + .route("/api/message/Monitor/Info", get(compat::msg_center::monitor_info)) + .route( + "/api/message/Monitor/{id}/Retry", + post(compat::msg_center::monitor_retry), + ) + .route("/api/message/Supplier", get(compat::msg_center::supplier_list)) + .route("/api/message/Supplier", post(compat::msg_center::supplier_create)) + .route( + "/api/message/Supplier/Selector", + get(compat::msg_center::supplier_selector), + ) + .route("/api/message/Supplier/{id}", get(compat::msg_center::supplier_info)) + .route("/api/message/Supplier/{id}", put(compat::msg_center::supplier_update)) + .route( + "/api/message/Supplier/{id}", + delete(compat::msg_center::supplier_delete), + ) + .route( + "/api/message/Supplier/TemplateList", + get(compat::msg_center::supplier_template_list), + ) + .route( + "/api/message/Supplier/{id}/Actions/Copy", + post(compat::msg_center::supplier_copy), + ) + .route( + "/api/message/Supplier/SyncTemplate", + post(compat::msg_center::supplier_sync_template), + ) + .route( + "/api/message/Supplier/TestConnect", + post(compat::msg_center::supplier_test_connect), + ) + .route( + "/api/message/Supplier/{id}/Actions/State", + put(compat::msg_center::supplier_state), + ) + .route( + "/api/message/Supplier/{id}/VariableList", + get(compat::msg_center::supplier_variable_list), + ) .merge(crate::bootstrap::pack_router_or_empty()); // 🔴 **仅测试构建**存在的「故意 panic」端点 —— 用来钉住 catch-all 中间件 diff --git a/src/backend/tests/batch20_it.rs b/src/backend/tests/batch20_it.rs new file mode 100644 index 0000000..8d4e3fd --- /dev/null +++ b/src/backend/tests/batch20_it.rs @@ -0,0 +1,899 @@ +//! 批次 20 —— **msgCenter 族 50 条**的集成测试。 +//! +//! 🔴 **本批的形状分三类**(与 `platform/compat/msg_center.rs` 的口径一致): +//! ① **本地可自洽的元数据**(账号配置 / 发送配置 / 消息模板 / 敏感词 / +//! 接收配置 / 监控记录 / 供应商)⇒ **真落库**到官方 `base_msg_*` / +//! `base_intg_supplier*` 表(DDL 逐字照官方); +//! ② **要真连服务商**(测试发送 / 重发 / 同步模板 / 测试连接)⇒ **明确业务失败** +//! (本仓**无 HTTP 客户端**)—— **绝不返假发送结果、假模板**; +//! ③ **官方 Java 有、官方前端没有**的 12 条 ⇒ **不实现**(记在 HANDOFF 的已知限制里)。 +//! +//! 🔴 **三类断言**: +//! ① **路由存在**(50 条逐条打一遍)—— 防 axum 的 `matchit` 参数名冲突 +//! (同位置不能有两个参数名 ⇒ **启动即 panic**,静态闸门看不出来、编译也过); +//! ② **真实现**的**精确形状**(CRUD 闭环 + `PageListVO` / `ListVO` 的区别); +//! ③ **能力缺失**端点的**诚实失败**(`code=400` + `data:null` + 人话)。 + +use std::path::PathBuf; +use std::sync::Arc; + +use serde_json::{json, Value}; +use ssw_platform::platform::db::Db; +use ssw_platform::platform::seed::first_seed; +use ssw_platform::platform::session::{SessionStore, TicketStore}; +use ssw_platform::platform::state::AppState; +use ssw_platform::routes::build_app; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::sync::{Mutex, OnceCell}; + +static DB: OnceCell = OnceCell::const_new(); +static LOCK: Mutex<()> = Mutex::const_new(()); + +async fn db() -> &'static Db { + DB.get_or_init(|| async { + let db = Db::open_temp().await.expect("打开 pglite 临时库失败"); + ssw_platform::bootstrap::ensure_schema_all(&db) + .await + .expect("ensure_schema_all 失败"); + ssw_platform::bootstrap::ensure_base(&db) + .await + .expect("ensure_base 失败"); + first_seed(&db, "123456").await.expect("first_seed 失败"); + db + }) + .await +} + +async fn serve(state: AppState) -> u16 { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("绑定失败"); + let port = listener.local_addr().expect("取本地地址失败").port(); + let server = tokio::spawn(async move { + let _ = axum::serve(listener, build_app(state)).await; + }); + tokio::task::yield_now().await; + std::mem::forget(server); + port +} + +fn new_state(db: &Db) -> AppState { + AppState { + config: Arc::new(ssw_platform::platform::config::Config::from_env(PathBuf::from( + "/tmp/ssw-platform-batch20-it", + ))), + db: Arc::new(db.clone()), + sessions: Arc::new(SessionStore::default()), + tickets: Arc::new(TicketStore::default()), + } +} + +/// 面 B 请求(`Vue-Version: 3` + `App-Code: mainSystem`)。 +async fn call(port: u16, method: &str, path: &str, token: &str, body: Option<&str>) -> Value { + let mut stream = TcpStream::connect(("127.0.0.1", port)) + .await + .expect("连接失败"); + let payload = body.unwrap_or(""); + let req = format!( + "{method} {path} HTTP/1.1\r\n\ + Host: 127.0.0.1\r\n\ + Vue-Version: 3\r\n\ + App-Code: mainSystem\r\n\ + Authorization: {token}\r\n\ + Content-Type: application/json\r\n\ + Content-Length: {}\r\n\ + Connection: close\r\n\r\n{payload}", + payload.len() + ); + stream + .write_all(req.as_bytes()) + .await + .expect("写请求失败"); + let mut buf = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(15), + stream.read_to_end(&mut buf), + ) + .await + .expect("读响应超时") + .expect("读响应失败"); + let text = String::from_utf8_lossy(&buf).to_string(); + let (_, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔"); + serde_json::from_str(body.trim()).unwrap_or(Value::Null) +} + +async fn login(port: u16) -> String { + let enc = ssw_platform::platform::cipher::encrypt_password("123456"); + let payload = format!("account=admin&password={enc}"); + let mut stream = TcpStream::connect(("127.0.0.1", port)) + .await + .expect("连接失败"); + let req = format!( + "POST /api/oauth/Login HTTP/1.1\r\n\ + Host: 127.0.0.1\r\n\ + Vue-Version: 3\r\n\ + App-Code: mainSystem\r\n\ + Content-Type: application/x-www-form-urlencoded\r\n\ + Content-Length: {}\r\n\ + Connection: close\r\n\r\n{payload}", + payload.len() + ); + stream + .write_all(req.as_bytes()) + .await + .expect("写请求失败"); + let mut buf = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(15), + stream.read_to_end(&mut buf), + ) + .await + .expect("读响应超时") + .expect("读响应失败"); + let text = String::from_utf8_lossy(&buf).to_string(); + let (_, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔"); + let v: Value = serde_json::from_str(body.trim()).unwrap_or(Value::Null); + v["data"]["token"] + .as_str() + .expect("登录必须返 token") + .to_string() +} + +async fn boot() -> (u16, String) { + let state = new_state(db().await); + let port = serve(state).await; + let token = login(port).await; + (port, token) +} + +/// 从 `PageListVO` / `ListVO` 里按 `enCode` 找一条。 +fn find_by_en_code(list: &Value, en_code: &str) -> Option { + list["list"] + .as_array()? + .iter() + .find(|r| r["enCode"].as_str() == Some(en_code)) + .cloned() +} + +/// 🔴 **50 条端点逐条打一遍** —— 判据「不是 404 / 405」。 +/// +/// 🔴 **为什么必须有这条测试**:axum 的 `matchit` 在**同一位置有两个参数名** +/// (如 `/api/message/Account/{id}` 与 `/api/message/Account/{accountId}`)时会 +/// **启动即 panic** —— 静态闸门看不出来、编译也过,只有真把 router 建起来才炸。 +#[tokio::test] +async fn msg_center_all_50_endpoints_are_registered_without_matchit_conflict() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + let cases: Vec<(&str, &str)> = vec![ + // ---- 账号配置(8 条)---- + ("GET", "/api/message/Account"), + ("POST", "/api/message/Account"), + ("GET", "/api/message/Account/{id}"), + ("PUT", "/api/message/Account/{id}"), + ("DELETE", "/api/message/Account/{id}"), + ("POST", "/api/message/Account/{id}/Actions/Copy"), + ("POST", "/api/message/Account/testSendMail"), + ("PUT", "/api/message/Account/setdefault"), + // ---- 消息发送配置(9 条)---- + ("GET", "/api/message/Send"), + ("POST", "/api/message/Send"), + ("GET", "/api/message/Send/{id}"), + ("PUT", "/api/message/Send/{id}"), + ("DELETE", "/api/message/Send/{id}"), + ("POST", "/api/message/Send/{id}/Actions/Copy"), + ("POST", "/api/message/Send/getTestConfig/{id}"), + ("POST", "/api/message/Send/testSendConfig"), + ("GET", "/api/message/Send/getSendConfigList"), + // ---- 消息模板(7 条)---- + ("GET", "/api/message/Template"), + ("POST", "/api/message/Template"), + ("GET", "/api/message/Template/{id}"), + ("PUT", "/api/message/Template/{id}"), + ("DELETE", "/api/message/Template/{id}"), + ("POST", "/api/message/Template/{id}/Actions/Copy"), + ("POST", "/api/message/Template/testSendMail"), + // ---- 消息安全(5 条)---- + ("GET", "/api/message/Sensitive"), + ("POST", "/api/message/Sensitive"), + ("GET", "/api/message/Sensitive/{id}"), + ("PUT", "/api/message/Sensitive/{id}"), + ("DELETE", "/api/message/Sensitive/{id}"), + // ---- 消息接收(2 条)---- + ("GET", "/api/message/Receive"), + ("POST", "/api/message/Receive"), + // ---- 消息监控(7 条)---- + ("GET", "/api/message/Monitor"), + ("GET", "/api/message/Monitor/Info"), + ("DELETE", "/api/message/Monitor/batchRemove"), + ("DELETE", "/api/message/Monitor/empty"), + ("GET", "/api/message/Monitor/detail/{id}"), + ("GET", "/api/message/Monitor/{id}/RecordList"), + ("POST", "/api/message/Monitor/{id}/Retry"), + // ---- 消息供应商(12 条)---- + ("GET", "/api/message/Supplier"), + ("POST", "/api/message/Supplier"), + ("GET", "/api/message/Supplier/Selector"), + ("GET", "/api/message/Supplier/{id}"), + ("PUT", "/api/message/Supplier/{id}"), + ("DELETE", "/api/message/Supplier/{id}"), + ("GET", "/api/message/Supplier/TemplateList"), + ("POST", "/api/message/Supplier/{id}/Actions/Copy"), + ("POST", "/api/message/Supplier/SyncTemplate"), + ("POST", "/api/message/Supplier/TestConnect"), + ("PUT", "/api/message/Supplier/{id}/Actions/State"), + ("GET", "/api/message/Supplier/{id}/VariableList"), + ]; + assert_eq!(cases.len(), 50, "本批就是 50 条"); + + let probe = "b20_probe_no_such_id"; + for (method, raw_path) in cases { + let path = raw_path.replace("{id}", probe); + let res = call(port, method, &path, &token, Some("{}")).await; + let code = res["code"].as_i64().unwrap_or(-1); + assert!( + code != 404 && code != 405, + "`{method} {raw_path}` 必须已注册(404/405 说明路由没接上),实际 code={code}:{:?}", + res + ); + } + + // 🔴 官方前端 `testConfig` 声明的**动态**路径别名(`${Api.Prefix}/${data.testType}`) + // 也必须已注册(官方前端那条静态路径被静态段优先 ⇒ 别名只在别的段名上生效)。 + let alias = call( + port, + "POST", + "/api/message/Account/probe-test-type", + &token, + Some("{}"), + ) + .await; + let alias_code = alias["code"].as_i64().unwrap_or(-1); + assert!( + alias_code != 404 && alias_code != 405, + "动态路径别名必须已注册,实际 code={alias_code}:{alias:?}" + ); +} + +/// 🔴 **账号配置 CRUD 闭环**(真落库 `base_msg_account`)。 +/// +/// 断言官方 `AccountConfigListVO`(17 字段)的形状要点: +/// - `GET /api/message/Account` ⇒ `data` 是 **PageListVO**(`{pagination,list}`); +/// - `category` 是**中文名**(官方 `MessageEnum.getByCode(category).getCategoryName()`), +/// `SMTP` 例外(官方原样保留); +/// - `enabledMark` 是**字符串**(官方 VO 里就是 `String`)。 +#[tokio::test] +async fn account_crud_round_trip_matches_official_list_vo() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + // ---- 新建 ---- + let created = call( + port, + "POST", + "/api/message/Account", + &token, + Some( + &json!({ + "fullName": "批次20短信账号", + "category": "TencentCloud", + "enCode": "b20_acc_probe", + "messageType": "3", + "addressName": "探针发件人", + "smtpServer": "smtp.example.com", + "smtpPort": 465, + "smtpUser": "probe@example.com", + "smtpPassword": "probe-secret", + "enabledMark": 1 + }) + .to_string(), + ), + ) + .await; + assert_eq!(created["code"], 200, "新建账号配置必须成功:{created:?}"); + assert_eq!(created["msg"], "新建成功", "官方文案:{created:?}"); + assert!(created["data"].is_null(), "官方写端点不返数据:{created:?}"); + + // ---- 列表(PageListVO)---- + let listed = call( + port, + "GET", + "/api/message/Account?keyword=b20_acc_probe", + &token, + None, + ) + .await; + assert_eq!(listed["code"], 200, "{listed:?}"); + assert!( + listed["data"]["pagination"]["currentPage"].as_i64() == Some(1), + "必须是 PageListVO(带 pagination):{listed:?}" + ); + assert!( + listed["data"]["pagination"]["total"].as_i64().unwrap_or(0) >= 1, + "列表必须有数据:{listed:?}" + ); + let row = find_by_en_code(&listed["data"], "b20_acc_probe").expect("列表里必须有刚建的账号"); + let id = row["id"].as_str().expect("id 必须是字符串").to_string(); + // 🔴 官方:`category` 走 `MessageEnum.getByCode(...).getCategoryName()` ⇒ 中文名。 + assert_eq!(row["category"], "腾讯云", "category 必须是官方中文名:{row:?}"); + // 🔴 官方 VO 里 `enabledMark` 是 `String`。 + assert!( + row["enabledMark"].is_string(), + "enabledMark 必须是字符串(官方 VO 是 String):{row:?}" + ); + // 🔴 官方 VO 里 `type` / `supplierName` / `webhookType` 三个字段**没有来源** ⇒ null。 + assert!(row["type"].is_null(), "type 应为 null:{row:?}"); + assert!(row["supplierName"].is_null(), "supplierName 应为 null:{row:?}"); + assert!(row["webhookType"].is_null(), "webhookType 应为 null:{row:?}"); + // 🔴 17 个字段一个不少。 + for key in [ + "id", + "fullName", + "category", + "type", + "enCode", + "addressorName", + "smtpUser", + "supplierName", + "smsSignature", + "webhookType", + "sortCode", + "enabledMark", + "creatorTime", + "creatorUserId", + "lastModifyTime", + "creatorUser", + "isDefault", + ] { + assert!(row.get(key).is_some(), "官方 AccountConfigListVO 少了字段 `{key}`:{row:?}"); + } + + // ---- 详情 ---- + let info = call(port, "GET", &format!("/api/message/Account/{id}"), &token, None).await; + assert_eq!(info["code"], 200, "{info:?}"); + assert_eq!(info["data"]["enCode"], "b20_acc_probe", "{info:?}"); + assert_eq!(info["data"]["smtpServer"], "smtp.example.com", "{info:?}"); + assert_eq!(info["data"]["smtpUser"], "probe@example.com", "{info:?}"); + assert!(info["data"]["isEditor"].is_boolean(), "官方有 isEditor:{info:?}"); + + // ---- 更新 ---- + let updated = call( + port, + "PUT", + &format!("/api/message/Account/{id}"), + &token, + Some(&json!({"fullName": "批次20短信账号改"}).to_string()), + ) + .await; + assert_eq!(updated["code"], 200, "{updated:?}"); + assert_eq!(updated["msg"], "更新成功", "{updated:?}"); + let info2 = call(port, "GET", &format!("/api/message/Account/{id}"), &token, None).await; + assert_eq!(info2["data"]["fullName"], "批次20短信账号改", "{info2:?}"); + + // ---- 复制(官方:`.副本` + 5 位、复制件禁用)---- + let copied = call( + port, + "POST", + &format!("/api/message/Account/{id}/Actions/Copy"), + &token, + None, + ) + .await; + assert_eq!(copied["code"], 200, "{copied:?}"); + assert_eq!(copied["msg"], "复制成功", "{copied:?}"); + let listed2 = call(port, "GET", "/api/message/Account", &token, None).await; + let copy_row = listed2["data"]["list"] + .as_array() + .expect("list 必须是数组") + .iter() + .find(|r| { + r["enCode"] + .as_str() + .map(|c| c.starts_with("b20_acc_probe") && c != "b20_acc_probe") + .unwrap_or(false) + }) + .cloned() + .expect("列表里必须有复制件"); + let copy_id = copy_row["id"].as_str().expect("id").to_string(); + assert_eq!( + copy_row["enabledMark"], "0", + "官方复制件一律禁用:{copy_row:?}" + ); + + // ---- 设为默认(官方:一类型一默认;禁用件不许设默认)---- + let set_default = call( + port, + "PUT", + "/api/message/Account/setdefault", + &token, + Some(&json!({"id": id}).to_string()), + ) + .await; + assert_eq!(set_default["code"], 200, "{set_default:?}"); + assert_eq!(set_default["msg"], "操作成功", "{set_default:?}"); + + let listed3 = call(port, "GET", "/api/message/Account", &token, None).await; + let row3 = find_by_en_code(&listed3["data"], "b20_acc_probe").expect("列表里必须有原账号"); + assert_eq!(row3["isDefault"], 1, "设默认后 isDefault 应为 1:{row3:?}"); + + // 🔴 官方 `FA062`:默认数据不许删。 + let del_default = call(port, "DELETE", &format!("/api/message/Account/{id}"), &token, None).await; + assert_eq!(del_default["code"], 400, "默认账号不许删:{del_default:?}"); + assert_eq!(del_default["msg"], "默认数据无法删除", "{del_default:?}"); + + // ---- 删除(复制件)---- + let deleted = call( + port, + "DELETE", + &format!("/api/message/Account/{copy_id}"), + &token, + None, + ) + .await; + assert_eq!(deleted["code"], 200, "{deleted:?}"); + assert_eq!(deleted["msg"], "删除成功", "{deleted:?}"); + + let listed4 = call(port, "GET", "/api/message/Account", &token, None).await; + assert!( + find_by_en_code(&listed4["data"], "b20_acc_probe").is_some(), + "原账号还在:{listed4:?}" + ); + assert!( + listed4["data"]["list"] + .as_array() + .unwrap() + .iter() + .all(|r| r["id"] != copy_id.as_str()), + "复制件应已软删:{listed4:?}" + ); +} + +/// 🔴 **消息模板 / 发送配置 CRUD 闭环**(真落库 `base_msg_template` / `base_msg_send`)。 +#[tokio::test] +async fn template_and_send_config_crud_round_trip() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + // ---- 消息模板 ---- + let tpl = call( + port, + "POST", + "/api/message/Template", + &token, + Some( + &json!({ + "fullName": "批次20模板", + "enCode": "b20_tpl_probe", + "templateType": 1, + "messageType": "3", + "content": "你好 ${name}", + "enabledMark": 1, + "templateParamList": [{"field": "name", "fieldName": "姓名"}], + "msgVariableEntityList": [ + {"fieldId": "f1", "variable": "name", "field": "name", "isTitle": 0} + ] + }) + .to_string(), + ), + ) + .await; + assert_eq!(tpl["code"], 200, "新建模板必须成功:{tpl:?}"); + assert_eq!(tpl["msg"], "新建成功", "{tpl:?}"); + + let tpls = call(port, "GET", "/api/message/Template", &token, None).await; + assert_eq!(tpls["code"], 200, "{tpls:?}"); + assert!( + tpls["data"]["pagination"]["total"].as_i64().unwrap_or(0) >= 1, + "模板列表必须是 PageListVO:{tpls:?}" + ); + let tpl_row = find_by_en_code(&tpls["data"], "b20_tpl_probe").expect("列表里必须有刚建的模板"); + let tpl_id = tpl_row["id"].as_str().expect("id").to_string(); + // 🔴 官方 VO:`messageType` 是**中文名**(`MessageTypeEnum.getByMessage`)。 + assert_eq!(tpl_row["messageType"], "短信", "{tpl_row:?}"); + // 🔴 子表(参数 / 变量)随模板一起落库。 + assert_eq!( + tpl_row["templateParamList"].as_array().map(|a| a.len()), + Some(1), + "模板参数子表必须落库:{tpl_row:?}" + ); + assert_eq!( + tpl_row["smsFieldList"].as_array().map(|a| a.len()), + Some(1), + "模板变量子表必须落库:{tpl_row:?}" + ); + + let tpl_info = call( + port, + "GET", + &format!("/api/message/Template/{tpl_id}"), + &token, + None, + ) + .await; + assert_eq!(tpl_info["code"], 200, "{tpl_info:?}"); + assert_eq!(tpl_info["data"]["enCode"], "b20_tpl_probe", "{tpl_info:?}"); + + // ---- 复制模板(官方:连子表一起复制)---- + let tpl_copy = call( + port, + "POST", + &format!("/api/message/Template/{tpl_id}/Actions/Copy"), + &token, + None, + ) + .await; + assert_eq!(tpl_copy["code"], 200, "{tpl_copy:?}"); + assert_eq!(tpl_copy["msg"], "复制成功", "{tpl_copy:?}"); + + let tpls2 = call(port, "GET", "/api/message/Template", &token, None).await; + let copy_row = tpls2["data"]["list"] + .as_array() + .expect("list 必须是数组") + .iter() + .find(|r| { + r["enCode"] + .as_str() + .map(|c| c.starts_with("b20_tpl_probe") && c != "b20_tpl_probe") + .unwrap_or(false) + }) + .cloned() + .expect("列表里必须有模板副本"); + let copy_id = copy_row["id"].as_str().expect("id").to_string(); + // 🔴 官方复制件:`enabledMark=0`、`templateType="0"`。 + assert_eq!(copy_row["enabledMark"], 0, "模板副本必须禁用:{copy_row:?}"); + // 🔴 子表也要跟着复制(两张子表列不同 ⇒ 这条钉住「别用同一套列」)。 + assert_eq!( + copy_row["templateParamList"].as_array().map(|a| a.len()), + Some(1), + "模板副本必须带上参数子表:{copy_row:?}" + ); + assert_eq!( + copy_row["smsFieldList"].as_array().map(|a| a.len()), + Some(1), + "模板副本必须带上变量子表:{copy_row:?}" + ); + + let tpl_del = call( + port, + "DELETE", + &format!("/api/message/Template/{copy_id}"), + &token, + None, + ) + .await; + assert_eq!(tpl_del["code"], 200, "{tpl_del:?}"); + assert_eq!(tpl_del["msg"], "删除成功", "{tpl_del:?}"); + + // ---- 消息发送配置 ---- + let send = call( + port, + "POST", + "/api/message/Send", + &token, + Some( + &json!({ + "fullName": "批次20发送配置", + "enCode": "b20_send_probe", + "templateType": 1, + "sendType": 1, + "enabledMark": 1 + }) + .to_string(), + ), + ) + .await; + assert_eq!(send["code"], 200, "新建发送配置必须成功:{send:?}"); + + let sends = call(port, "GET", "/api/message/Send", &token, None).await; + assert_eq!(sends["code"], 200, "{sends:?}"); + let send_row = find_by_en_code(&sends["data"], "b20_send_probe").expect("列表里必须有刚建的发送配置"); + let send_id = send_row["id"].as_str().expect("id").to_string(); + // 🔴 官方 VO:`enabledMark` 是字符串。 + assert!(send_row["enabledMark"].is_string(), "{send_row:?}"); + + let send_sel = call( + port, + "GET", + "/api/message/Send/getSendConfigList?keyword=b20_send_probe", + &token, + None, + ) + .await; + assert_eq!(send_sel["code"], 200, "{send_sel:?}"); + + let send_del = call( + port, + "DELETE", + &format!("/api/message/Send/{send_id}"), + &token, + None, + ) + .await; + assert_eq!(send_del["code"], 200, "{send_del:?}"); +} + +/// 🔴 **敏感词 / 接收配置 / 供应商 CRUD 闭环** —— 重点是 **`ListVO` vs `PageListVO`**。 +/// +/// 🔴 官方口径: +/// - `GET /api/message/Receive` ⇒ **`ListVO`**(只有 `list`,**没有** `pagination`)—— +/// 官方 `MsgReceiveController.java:29`; +/// - `GET /api/message/Supplier` ⇒ **`ListVO`**(官方 `IntgSupplierController.java:86`)。 +#[tokio::test] +async fn sensitive_receive_supplier_round_trip_and_list_vo_shapes() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + // ---- 敏感词 ---- + let sens = call( + port, + "POST", + "/api/message/Sensitive", + &token, + Some( + &json!({ + "sensitiveWord": "批次20敏感词", + "replaceText": "***", + "enabledMark": 1 + }) + .to_string(), + ), + ) + .await; + assert_eq!(sens["code"], 200, "新建敏感词必须成功:{sens:?}"); + + let sens_list = call(port, "GET", "/api/message/Sensitive", &token, None).await; + assert_eq!(sens_list["code"], 200, "{sens_list:?}"); + assert!( + sens_list["data"]["pagination"]["total"].as_i64().unwrap_or(0) >= 1, + "敏感词列表是 PageListVO:{sens_list:?}" + ); + let sens_row = sens_list["data"]["list"] + .as_array() + .unwrap() + .iter() + .find(|r| r["sensitiveWord"] == "批次20敏感词") + .cloned() + .expect("列表里必须有刚建的敏感词"); + let sens_id = sens_row["id"].as_str().expect("id").to_string(); + + let sens_upd = call( + port, + "PUT", + &format!("/api/message/Sensitive/{sens_id}"), + &token, + Some(&json!({"replaceText": "###"}).to_string()), + ) + .await; + assert_eq!(sens_upd["code"], 200, "{sens_upd:?}"); + + let sens_del = call( + port, + "DELETE", + &format!("/api/message/Sensitive/{sens_id}"), + &token, + None, + ) + .await; + assert_eq!(sens_del["code"], 200, "{sens_del:?}"); + assert_eq!(sens_del["msg"], "删除成功", "{sens_del:?}"); + + // ---- 接收配置(ListVO!)---- + let recv = call(port, "GET", "/api/message/Receive", &token, None).await; + assert_eq!(recv["code"], 200, "{recv:?}"); + assert!( + recv["data"]["list"].is_array(), + "官方 Receive 返回 ListVO(只有 list):{recv:?}" + ); + assert!( + recv["data"]["pagination"].is_null(), + "官方 Receive **不是** PageListVO(不得有 pagination):{recv:?}" + ); + + let recv_save = call( + port, + "POST", + "/api/message/Receive", + &token, + Some( + &json!({ + "type": 1, + "receiveList": [ + { + "category": "2046494646179336192", + "enabledMark": 1, + "channels": [{"name": "system", "value": "system"}] + } + ] + }) + .to_string(), + ), + ) + .await; + assert_eq!(recv_save["code"], 200, "{recv_save:?}"); + + let recv2 = call(port, "GET", "/api/message/Receive", &token, None).await; + assert_eq!(recv2["code"], 200, "{recv2:?}"); + assert!( + recv2["data"]["list"].as_array().unwrap().len() >= 1, + "保存后接收配置列表必须有数据:{recv2:?}" + ); + assert!( + recv2["data"]["pagination"].is_null(), + "官方 Receive 返回 ListVO(不得有 pagination):{recv2:?}" + ); + + // ---- 供应商(ListVO!)---- + let sup = call( + port, + "POST", + "/api/message/Supplier", + &token, + Some( + &json!({ + "fullName": "批次20供应商", + "enCode": "b20_sup_probe", + "category": "TencentCloud", + "secretId": "AKIDprobe", + "secretKey": "probe-secret-key", + "enabledMark": 1 + }) + .to_string(), + ), + ) + .await; + assert_eq!(sup["code"], 200, "新建供应商必须成功:{sup:?}"); + assert_eq!(sup["msg"], "新建成功", "{sup:?}"); + + let sup_list = call(port, "GET", "/api/message/Supplier", &token, None).await; + assert_eq!(sup_list["code"], 200, "{sup_list:?}"); + assert!( + sup_list["data"]["list"].is_array(), + "官方 Supplier 返回 ListVO:{sup_list:?}" + ); + assert!( + sup_list["data"]["pagination"].is_null(), + "官方 Supplier **不是** PageListVO(不得有 pagination):{sup_list:?}" + ); + let sup_row = find_by_en_code(&sup_list["data"], "b20_sup_probe").expect("列表里必须有刚建的供应商"); + let sup_id = sup_row["id"].as_str().expect("id").to_string(); + + // 🔴 官方 `IntgSupplierListVo` 里没有来源的字段 ⇒ null。 + assert!(sup_row["supplierId"].is_null(), "{sup_row:?}"); + assert!(sup_row["smsSignature"].is_null(), "{sup_row:?}"); + assert!(sup_row["isDefault"].is_null(), "{sup_row:?}"); + assert!(sup_row["content"].is_null(), "{sup_row:?}"); + + // ---- 供应商详情 / 更新 ---- + let sup_info = call( + port, + "GET", + &format!("/api/message/Supplier/{sup_id}"), + &token, + None, + ) + .await; + assert_eq!(sup_info["code"], 200, "{sup_info:?}"); + assert_eq!(sup_info["data"]["enCode"], "b20_sup_probe", "{sup_info:?}"); + + let sup_upd = call( + port, + "PUT", + &format!("/api/message/Supplier/{sup_id}"), + &token, + Some( + &json!({ + "fullName": "批次20供应商改", + "enCode": "b20_sup_probe", + "category": "TencentCloud", + "secretId": "AKIDprobe", + "secretKey": "probe-secret-key" + }) + .to_string(), + ), + ) + .await; + assert_eq!(sup_upd["code"], 200, "{sup_upd:?}"); + assert_eq!(sup_upd["msg"], "更新成功", "{sup_upd:?}"); + + // ---- 启停切换(官方:请求体带**当前**状态,服务端取反)---- + let st = call( + port, + "PUT", + &format!("/api/message/Supplier/{sup_id}/Actions/State"), + &token, + Some(&json!({"enabledMark": 1}).to_string()), + ) + .await; + assert_eq!(st["code"], 200, "{st:?}"); + assert_eq!(st["msg"], "操作成功", "{st:?}"); + let sup_list2 = call(port, "GET", "/api/message/Supplier", &token, None).await; + let sup_row2 = find_by_en_code(&sup_list2["data"], "b20_sup_probe").expect("供应商还在"); + assert_eq!( + sup_row2["enabledMark"], 0, + "当前是启用 ⇒ 本次操作是禁用:{sup_row2:?}" + ); + + // ---- 复制 ---- + let sup_copy = call( + port, + "POST", + &format!("/api/message/Supplier/{sup_id}/Actions/Copy"), + &token, + None, + ) + .await; + assert_eq!(sup_copy["code"], 200, "{sup_copy:?}"); + assert_eq!(sup_copy["msg"], "复制成功", "{sup_copy:?}"); + + // ---- 删除 ---- + let sup_del = call( + port, + "DELETE", + &format!("/api/message/Supplier/{sup_id}"), + &token, + None, + ) + .await; + assert_eq!(sup_del["code"], 200, "{sup_del:?}"); + assert_eq!(sup_del["msg"], "删除成功", "{sup_del:?}"); +} + +/// 🔴 **能力缺失 ⇒ 明确业务失败**(不返假发送结果 / 假模板)。 +/// +/// 本仓**没有 HTTP 客户端** ⇒ 真连服务商的动作一律 `code=400` + `data:null` + 人话。 +#[tokio::test] +async fn provider_dependent_endpoints_fail_honestly() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + let cases: Vec<(&str, &str)> = vec![ + ("POST", "/api/message/Account/testSendMail"), + // 🔴 前端 `testConfig` 的**动态**路径别名(`${Api.Prefix}/${data.testType}`): + // 这里用一个**非 `testSendMail`** 的段 ⇒ 命中的就是那条动态别名路由 + // (静态段优先级更高 ⇒ `testSendMail` 那条走的是官方静态端点)。 + ("POST", "/api/message/Account/probe-test-type"), + ("POST", "/api/message/Send/testSendConfig"), + ("POST", "/api/message/Template/testSendMail"), + ("POST", "/api/message/Monitor/probe-monitor/Retry"), + ("POST", "/api/message/Supplier/SyncTemplate"), + ("POST", "/api/message/Supplier/TestConnect"), + ]; + + for (method, path) in cases { + let res = call(port, method, path, &token, Some("{}")).await; + assert_eq!( + res["code"], 400, + "`{method} {path}` 必须明确业务失败(不是 200 假成功):{res:?}" + ); + assert!( + res["data"].is_null(), + "`{method} {path}` 失败时 data 必须是 null:{res:?}" + ); + let msg = res["msg"].as_str().unwrap_or_default(); + assert!( + !msg.is_empty() && msg.contains("消息服务商"), + "`{method} {path}` 的 msg 必须说清「未接入消息服务商」:{res:?}" + ); + } +} + +/// 🔴 **面 B 未登录 ⇒ `code=602`**(不是 600 —— 官方前端只对 601/602 清 token)。 +#[tokio::test] +async fn face_b_unauthenticated_returns_602() { + let _g = LOCK.lock().await; + let (port, _token) = boot().await; + + for (method, path) in [ + ("GET", "/api/message/Account"), + ("GET", "/api/message/Sensitive"), + ("GET", "/api/message/Receive"), + ("GET", "/api/message/Supplier"), + ] { + let res = call(port, method, path, "", None).await; + assert_eq!( + res["code"], 602, + "`{method} {path}` 未登录必须是 602:{res:?}" + ); + } +}