diff --git a/.workbuddy/memory/2026-11-03.md b/.workbuddy/memory/2026-11-03.md new file mode 100644 index 0000000..0b03dc6 --- /dev/null +++ b/.workbuddy/memory/2026-11-03.md @@ -0,0 +1,13 @@ +# 2026-11-03 + +### 00:00–01:55 批次 21–23:官方前端最后 183 条端点(900/900) + +- **三批**:aiCenter 75 / extend 64 / teamwork 40,另收尾 4 条(Dataset/Selector、DatasetLog、saveInterfaceList、ShortLink `{id}/Config`)。 +- **实现方式**:新增 `platform/compat/res.rs` 通用资源引擎(`Res{table,fields,keyword,order,scope}` → list/info/create/update/delete),约 150 条是薄封装;业务动作手写(版本、复制、分享、回收站、切片/召回、日程)。 +- **表**:AI 用既有官方 `base_ai_*`;新增 `ext_*` 18 张(extend 15 + teamwork 3)。 +- 🔴 **踩坑 1**:`main.rs::whitelist_self_check` 会把 `ext_*` 判成「孤儿 DDL」⇒ 启动失败。正确做法是在 `sspf_store::db` 加 `EXTEND_TABLES`/`TEAMWORK_TABLES` 常量(与 REPORT/WORKFLOW 同机制)并在闸门里放行;`db.rs` 的两条表数断言也要同步。 +- 🔴 **踩坑 2**:`docs/contract.md` 的 `[ENDPOINT]` 是 **pack-sync 生成物** ⇒ 手改后必须跑 `python3 scripts/pack-sync.py`,否则 verify 第一步红。`[OFFICIAL]` 是手写台账,脚本不碰。 +- 🔴 **踩坑 3**:官方前端有**两个** ShortLink 配置函数(`getConfig/{id}` 与 `{id}/Config`)⇒ 两条路由都要留,不能只改一条。 +- **诚实失败(21 条)**:LLM 推理 / 供应商连通性 / MCP 同步 / SMTP / IMAP / Excel 导入导出 / 文件上传打包预览 —— 一律 400 + 人话(见 known-limitations §I)。 +- **数字**:契约 948 条;官方台账 934/940(742/192/6);fe-gap **900/900(100%)**;test **673 passed**;verify --smoke 14 步全绿;723 探针 0 404/405/500;OPTIONS 948 全 405。 +- **测试**:新增 `tests/ext_batches_it.rs` 6 条(路由存在 / AI 召回 / 诚实失败 / extend / teamwork / 未登录 602)。 diff --git a/HANDOFF.md b/HANDOFF.md index 0491fc9..ef37495 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1,6 +1,6 @@ # HANDOFF —— 交给下一个 session 的现场交接 -> 更新于 2026-11-02(面 B **批次 19 收尾** —— workFlow 104 条), +> 更新于 2026-11-03(面 B **批次 21–23** —— aiCenter 75 + extend 64 + teamwork 40), > 底部保留 2026-11-01 19:00 的「批次 12 方向决策」与 > **20:10 的「前端 MVP 用 React 模板、除了认证其它都留给集成阶段」**。**开工先读这一页** > (尤其 **§0-bis 的「下一轮的优先级改了」**),再读 `CLAUDE.md`(硬约定), @@ -32,7 +32,7 @@ ## 0-0-bis. 2026-11-02 23:40 MCP 扩面:26 → 52 个业务工具 -参考 dacli 的命令面,把 MCP 从「26 个工具」扩到 **49 个**(4 元工具不变,仍是分层加载): +参考 dacli 的命令面,把 MCP 从「26 个工具」扩到 **52 个**(4 元工具不变,仍是分层加载): | 域 | 新增 | |---|---| @@ -53,6 +53,35 @@ --- +## 0-0-ter. 2026-11-03 批次 21–23:官方前端端点补到 **900/900** + +按 `scripts/fe-gap.py` 的缺口表,把最后三族做完(另收尾 4 条零散缺口): + +| 批 | 族 | 条数 | 落地 | +|---|---|---|---| +| 21 | `aiCenter` | 75 | 智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史 **真落库**(官方 `base_ai_*` 表);文档切片 + 关键词召回真做 | +| 22 | `extend` | 64 | CRM / 销售订单 / 员工 / 甘特 / 控件示例 / 邮件 / 大数据 **真落库**(新增 `ext_*` 15 张) | +| 23 | `teamwork` | 40 | 文件**元数据**(目录 / 移动 / 复制 / 分享 / 回收站 / 标签 / 空间)+ 日程 **真落库**(`ext_document*` 3 张 + 官方 `base_schedule`) | +| 收尾 | systemData / onlineDev | 4 | `Dataset/Selector`、`DatasetLog/{id}`(如实空分页)、`InterfaceOauth/saveInterfaceList`、`ShortLink/{id}/Config`(与旧 `getConfig/{id}` 同 handler) | + +🔴 **实现方式**:新增 `src/backend/src/platform/compat/res.rs` **通用资源引擎** +(`Res{table, fields, keyword, order, scope}` ⇒ list / info / create / update / delete), +三族里约 150 条是薄封装;有业务语义的动作(版本、复制、分享、回收站、切片/召回、日程)手写。 + +🔴 **新增表的登记**:`ext_*` 18 张既不是 `base_*` 平台表、也不是业务包表 ⇒ +在 `sspf_store::db::{EXTEND_TABLES, TEAMWORK_TABLES}` 登记,并在 `main.rs` 的 +**孤儿 DDL 闸门**里放行(与 `REPORT_TABLES` / `WORKFLOW_TABLES` 同一套机制)。 + +🔴 **诚实失败**(见 `docs/known-limitations.md` §I):LLM 推理、供应商连通性、MCP 同步、 +SMTP/IMAP、Excel 导入导出、文件上传/打包/预览 —— 一律 `400` + 人话,**不返假成功**。 + +⇒ 复验:`cargo test --workspace` **673 passed / 0 failed**;`verify.sh --smoke` **14 步全绿**; +723 条端点探针 **0 个 404/405/500**;OPTIONS **948 条全 405**; +`check-contract` PASS=10(契约 948 条 / 官方台账覆盖 **934/940**,implemented 742 / partial 192 / absent 6); +`fe-gap` **900/900(100%)**。 + +--- + ## 0. ⚠️ 修正上一版口径(很重要) 上一版说「跑 pnpm 必须 `dangerouslyDisableSandbox`」。**这条不完整**:真正拦住 fs 的是 @@ -397,21 +426,26 @@ React 模板的加模块成本 = **改/加 8 个文件、15~20 分钟**(`HOWTO --- -## 1. 一句话现状(2026-11-02 批次 20 —— msgCenter 全族 50 条收尾) +## 1. 一句话现状(2026-11-03 批次 21–23 —— aiCenter / extend / teamwork 收尾) **📌 当前数字(以此为准,下面各批的「当时数字」仅存档)**: -- 契约端点 **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**(**667 passed**;主 lib 105; - `batch19_it` **7**、`batch20_it` **6**、`verify_fixes_it` **7**、`mcp_tools_it` **6**)。 -- 十二道闸门全绿;`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%)**。 +- 契约端点 **948 条**(面 A 28 + 面 B **918** + 两面共用 2);`tables` → **171** + (`schema.sql` **170** 张 + 业务包 1 张;平台表 `BASE_TABLES` **123** + + `WORKFLOW_TABLES` **24** + `REPORT_TABLES` **2** + 内嵌业务表 3 + + `EXTEND_TABLES` **15** + `TEAMWORK_TABLES` **3**)。 +- `cargo test --offline --workspace` = **全绿 0 failed**(**673 passed**;主 lib 105; + `batch19_it` **7**、`batch20_it` **6**、`verify_fixes_it` **7**、`mcp_tools_it` **6**、 + `ext_batches_it` **6**)。 +- 闸门全绿;`check-contract` `PASS=10 FAIL=0`,官方端点覆盖 **934/940** + (implemented 742 / partial 192 / absent 6;oos 1 单列)。 +- `python3 scripts/fe-gap.py`:合计 **900 / 900(100%)** —— **`aiCenter` 75/75、 + `extend` 64/64、`teamwork` 40/40、`msgCenter` 50/50、`workFlow` 104/104、 + `core` 27/27、`system` 196/196、`permission` 137/137 全部 100%; + `systemData` 106/106、`onlineDev` 101/101**。 +- 🔴 **批次 21–23 把官方前端的最后 183 条缺口做完了**(179 + 收尾 4): + 见 §0-0-ter 与 `docs/known-limitations.md` §I。真落库 158 条、诚实失败 21 条 + (LLM / SMTP / IMAP / MCP / 文件服务 / Excel 一律 `400` + 人话)。 - 🔴 **批次 20 把 msgCenter 做完了**(用户 2026-11-02 指示「msgCenter 50 去做完吧」): 官方前端 `src/api/msgCenter/**` 的**全部 50 个接口** ⇒ 落 **51 条面 B 端点** (50 条前端接口 + 1 条**动态路径别名**,见下),新增 `platform/compat/msg_center.rs`。 diff --git a/crates/sspf-store/src/db.rs b/crates/sspf-store/src/db.rs index 8355f1c..3dcfc45 100644 --- a/crates/sspf-store/src/db.rs +++ b/crates/sspf-store/src/db.rs @@ -114,7 +114,43 @@ pub const WORKFLOW_TABLES: [&str; 24] = [ "workflow_version", ]; -/// `PGLITE_DIR=memory://` 的临时库标记(与 `config::TEMP_DIR_MARKER` 同值)。 +/// 🔴 **extend 示例模块的表**(官方 `/api/extend/**` 契约面的落库载体)。 +/// +/// 🔴 官方 `jnpf-extend` 的示例业务表在官方 DDL 里叫 `ext_*`;本仓照这个名字建, +/// 不改成 `base_*`(改了就和官方对不上,集成期要多一层映射)。 +/// 它们**不是**平台表、也**不是**业务包表(没有 spec)⇒ 与 `REPORT_TABLES` / +/// `WORKFLOW_TABLES` 同性质:**契约面的固定装置**。 +/// +/// 🔴 金额 / 业务日期列用 TEXT(示例页只展示):本仓的绑定参数是 `$N::text`, +/// 进 NUMERIC/TIMESTAMP 列会报类型错;审计列仍是 TIMESTAMP。 +pub const EXTEND_TABLES: [&str; 15] = [ + "ext_big_data", + "ext_customer", + "ext_goods_classify", + "ext_goods", + "ext_crm_order", + "ext_crm_order_entry", + "ext_crm_collection_plan", + "ext_email", + "ext_email_config", + "ext_employee", + "ext_project", + "ext_project_task", + "ext_table_example", + "ext_sale_product", + "ext_sale_product_entry", +]; + +/// 🔴 **teamwork 的表**(官方 `jnpf-file` 的文档 / 空间 + 分享关系)。 +/// +/// 与 [`EXTEND_TABLES`] 同性质:契约面固定装置,不是平台表、不是业务包表。 +pub const TEAMWORK_TABLES: [&str; 3] = [ + "ext_document", + "ext_document_space", + "ext_document_share", +]; + +/// `PGLITE_DIR=memory://` 的临时库标记(与 `config::TEMP_DIR_MARKER` 同值)。/// `PGLITE_DIR=memory://` 的临时库标记(与 `config::TEMP_DIR_MARKER` 同值)。 const TEMP_DIR_MARKER: &str = "memory://"; // PostgreSQL 内建类型 OID(`scalar_text` 按列类型分派时只需这几个)。 @@ -1304,10 +1340,13 @@ mod tests { let mut expected = EMBEDDED_BUSINESS_TABLES.to_vec(); expected.extend_from_slice(&REPORT_TABLES); expected.extend_from_slice(&WORKFLOW_TABLES); + expected.extend_from_slice(&EXTEND_TABLES); + expected.extend_from_slice(&TEAMWORK_TABLES); expected.sort(); assert_eq!( business_names, expected, - "schema.sql 里的非平台表必须恰好是面 A 内嵌的 3 张 + 报表元数据 2 张 + 流程元数据 24 张(业务包表住 packs/)" + "schema.sql 里的非平台表必须恰好是面 A 内嵌 3 + 报表元数据 2 + 流程元数据 24 \ + + extend 示例 15 + teamwork 3(业务包表住 packs/)" ); // 🔴 与 main.rs 的 BASE_TABLES 对账的另一半在那边(孤儿 DDL 闸门)。 @@ -1340,12 +1379,16 @@ mod tests { BASE_TABLE_COUNT + EMBEDDED_BUSINESS_TABLES.len() + REPORT_TABLES.len() - + WORKFLOW_TABLES.len(), + + WORKFLOW_TABLES.len() + + EXTEND_TABLES.len() + + TEAMWORK_TABLES.len(), "ddl_tables 应解析出 {} 张表({} 平台 + {} 面 A 内嵌业务 + {} 报表元数据 + {} 流程元数据)", BASE_TABLE_COUNT + EMBEDDED_BUSINESS_TABLES.len() + REPORT_TABLES.len() - + WORKFLOW_TABLES.len(), + + WORKFLOW_TABLES.len() + + EXTEND_TABLES.len() + + TEAMWORK_TABLES.len(), BASE_TABLE_COUNT, EMBEDDED_BUSINESS_TABLES.len(), REPORT_TABLES.len(), diff --git a/docs/contract.md b/docs/contract.md index 27611b6..640c7a9 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1677,7 +1677,7 @@ B GET /api/visualdev/share/Selector 登录 platform B POST /api/visualdev/ocr 登录 platform B GET /api/visualdev/ShortLink/{id} onlineDev.formDesign platform B PUT /api/visualdev/ShortLink onlineDev.formDesign platform -B GET /api/visualdev/ShortLink/getConfig/{id} 登录 platform +B GET /api/visualdev/ShortLink/{id}/Config 登录 platform B POST /api/visualdev/ShortLink/checkPwd 登录 platform B GET /api/visualdev/ShortLink/Config 登录 platform B POST /api/visualdev/ShortLink/{id}/ListLink 登录 platform @@ -1912,6 +1912,190 @@ 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 +B GET /api/ai/Agent 登录 platform +B POST /api/ai/Agent 登录 platform +B GET /api/ai/Agent/Selector 登录 platform +B POST /api/ai/Agent/Save 登录 platform +B GET /api/ai/Agent/Info/{id} 登录 platform +B POST /api/ai/Agent/Info/{id} 登录 platform +B DELETE /api/ai/Agent/Info/{id} 登录 platform +B GET /api/ai/Agent/Version/{id} 登录 platform +B GET /api/ai/Agent/{id} 登录 platform +B PUT /api/ai/Agent/{id} 登录 platform +B DELETE /api/ai/Agent/{id} 登录 platform +B POST /api/ai/Agent/{id}/Actions/Copy 登录 platform +B GET /api/ai/AiSupplier 登录 platform +B POST /api/ai/AiSupplier 登录 platform +B GET /api/ai/AiSupplier/Selector 登录 platform +B POST /api/ai/AiSupplier/checkAi 登录 platform +B GET /api/ai/AiSupplier/{id} 登录 platform +B PUT /api/ai/AiSupplier/{id} 登录 platform +B DELETE /api/ai/AiSupplier/{id} 登录 platform +B POST /api/ai/Chat/Send 登录 platform +B POST /api/ai/Chat/Translate 登录 platform +B POST /api/ai/Chat/Optimize 登录 platform +B GET /api/ai/Chat/Close/{id} 登录 platform +B GET /api/ai/Chat/history/list 登录 platform +B DELETE /api/ai/Chat/history/cleanAll 登录 platform +B GET /api/ai/Chat/history/get/{id} 登录 platform +B PUT /api/ai/Chat/history/update/{id} 登录 platform +B DELETE /api/ai/Chat/history/delete/{id} 登录 platform +B GET /api/ai/Document 登录 platform +B POST /api/ai/Document 登录 platform +B GET /api/ai/Document/{id} 登录 platform +B PUT /api/ai/Document/{id} 登录 platform +B DELETE /api/ai/Document/{id} 登录 platform +B GET /api/ai/Document/{id}/getText 登录 platform +B POST /api/ai/Document/{id}/section 登录 platform +B POST /api/ai/Document/{id}/study 登录 platform +B GET /api/ai/Knowledge 登录 platform +B POST /api/ai/Knowledge 登录 platform +B GET /api/ai/Knowledge/Selector 登录 platform +B POST /api/ai/Knowledge/getListByIds 登录 platform +B GET /api/ai/Knowledge/Relation/{id} 登录 platform +B GET /api/ai/Knowledge/{id} 登录 platform +B PUT /api/ai/Knowledge/{id} 登录 platform +B DELETE /api/ai/Knowledge/{id} 登录 platform +B POST /api/ai/Knowledge/{id}/Test 登录 platform +B GET /api/ai/Mcp 登录 platform +B POST /api/ai/Mcp 登录 platform +B GET /api/ai/Mcp/Selector 登录 platform +B GET /api/ai/Mcp/Sync/{id} 登录 platform +B POST /api/ai/Mcp/getListByIds 登录 platform +B GET /api/ai/Mcp/{id} 登录 platform +B PUT /api/ai/Mcp/{id} 登录 platform +B DELETE /api/ai/Mcp/{id} 登录 platform +B GET /api/ai/Model 登录 platform +B GET /api/ai/Model/{id} 登录 platform +B PUT /api/ai/Model/{id} 登录 platform +B GET /api/ai/Prompt 登录 platform +B POST /api/ai/Prompt 登录 platform +B GET /api/ai/Prompt/{id} 登录 platform +B PUT /api/ai/Prompt/{id} 登录 platform +B DELETE /api/ai/Prompt/{id} 登录 platform +B GET /api/ai/Serve 登录 platform +B POST /api/ai/Serve 登录 platform +B GET /api/ai/Serve/Selector 登录 platform +B GET /api/ai/Serve/{id} 登录 platform +B PUT /api/ai/Serve/{id} 登录 platform +B DELETE /api/ai/Serve/{id} 登录 platform +B GET /api/ai/Skills 登录 platform +B POST /api/ai/Skills/getListByIds 登录 platform +B GET /api/ai/Skills/{id} 登录 platform +B GET /api/ai/Tool 登录 platform +B POST /api/ai/Tool/getListByIds 登录 platform +B GET /api/ai/Tool/{id} 登录 platform +B POST /api/ai/visualdev 登录 platform +B POST /api/ai/workflow 登录 platform +B GET /api/extend/BigData 登录 platform +B POST /api/extend/BigData 登录 platform +B GET /api/extend/CrmOrder 登录 platform +B GET /api/extend/CrmOrder/Customer 登录 platform +B GET /api/extend/CrmOrder/Goods 登录 platform +B GET /api/extend/CrmOrder/OrderEntry/{id}/Items 登录 platform +B DELETE /api/extend/CrmOrder/{id} 登录 platform +B GET /api/extend/CrmOrder/{id}/CollectionPlan 登录 platform +B GET /api/extend/DocumentPreview 登录 platform +B GET /api/extend/DocumentPreview/{id}/Preview 登录 platform +B GET /api/extend/Email 登录 platform +B POST /api/extend/Email 登录 platform +B POST /api/extend/Email/Actions/SaveDraft 登录 platform +B GET /api/extend/Email/Config 登录 platform +B PUT /api/extend/Email/Config 登录 platform +B POST /api/extend/Email/Config/Actions/CheckMail 登录 platform +B POST /api/extend/Email/Receive 登录 platform +B GET /api/extend/Email/{id} 登录 platform +B DELETE /api/extend/Email/{id} 登录 platform +B PUT /api/extend/Email/{id}/Actions/Read 登录 platform +B PUT /api/extend/Email/{id}/Actions/Unread 登录 platform +B PUT /api/extend/Email/{id}/Actions/Star 登录 platform +B PUT /api/extend/Email/{id}/Actions/Unstar 登录 platform +B GET /api/extend/Employee 登录 platform +B GET /api/extend/Employee/ExportData 登录 platform +B POST /api/extend/Employee/ImportData 登录 platform +B GET /api/extend/Employee/ImportPreview 登录 platform +B GET /api/extend/Employee/TemplateDownload 登录 platform +B DELETE /api/extend/Employee/{id} 登录 platform +B GET /api/extend/ProjectGantt 登录 platform +B POST /api/extend/ProjectGantt 登录 platform +B POST /api/extend/ProjectGantt/Task 登录 platform +B GET /api/extend/ProjectGantt/Task/{id} 登录 platform +B PUT /api/extend/ProjectGantt/Task/{id} 登录 platform +B GET /api/extend/ProjectGantt/{id} 登录 platform +B PUT /api/extend/ProjectGantt/{id} 登录 platform +B DELETE /api/extend/ProjectGantt/{id} 登录 platform +B GET /api/extend/ProjectGantt/{id}/Task 登录 platform +B GET /api/extend/ProjectGantt/{id}/Task/Selector/{taskId} 登录 platform +B GET /api/extend/TableExample 登录 platform +B POST /api/extend/TableExample 登录 platform +B GET /api/extend/TableExample/All 登录 platform +B GET /api/extend/TableExample/CityList/{id} 登录 platform +B GET /api/extend/TableExample/ControlSample/{id} 登录 platform +B GET /api/extend/TableExample/IndustryList 登录 platform +B PUT /api/extend/TableExample/UpdateSign/{id} 登录 platform +B GET /api/extend/TableExample/{id} 登录 platform +B PUT /api/extend/TableExample/{id} 登录 platform +B DELETE /api/extend/TableExample/{id} 登录 platform +B GET /api/extend/TableExample/{id}/Actions/Postil 登录 platform +B PUT /api/extend/TableExample/{id}/Actions/RowsEdit 登录 platform +B POST /api/extend/TableExample/{id}/Postil 登录 platform +B DELETE /api/extend/TableExample/{id}/Postil/{index} 登录 platform +B GET /api/extend/saleOrder/Classify 登录 platform +B GET /api/extend/saleOrder/Customer 登录 platform +B GET /api/extend/saleOrder/Goods 登录 platform +B GET /api/extend/saleOrder/Goods/Selector 登录 platform +B GET /api/extend/saleOrder/Goods/getGoodList 登录 platform +B GET /api/extend/saleOrder/Product 登录 platform +B POST /api/extend/saleOrder/Product 登录 platform +B GET /api/extend/saleOrder/Product/ProductEntry/{id} 登录 platform +B GET /api/extend/saleOrder/Product/{id} 登录 platform +B PUT /api/extend/saleOrder/Product/{id} 登录 platform +B DELETE /api/extend/saleOrder/Product/{id} 登录 platform +B GET /api/file/Document 登录 platform +B POST /api/file/Document 登录 platform +B GET /api/file/Document/list 登录 platform +B PUT /api/file/Document/tag 登录 platform +B POST /api/file/Document/BatchDelete 登录 platform +B POST /api/file/Document/FolderTree 登录 platform +B GET /api/file/Document/Detail 登录 platform +B PUT /api/file/Document/Actions/MoveTo/{toId} 登录 platform +B POST /api/file/Document/Actions/Copy/{toId} 登录 platform +B POST /api/file/Document/Actions/Share 登录 platform +B POST /api/file/Document/Actions/CancelShare 登录 platform +B POST /api/file/Document/Actions/ShareAdjustment/{id} 登录 platform +B GET /api/file/Document/Share 登录 platform +B GET /api/file/Document/ShareTome 登录 platform +B GET /api/file/Document/ShareUser/{id} 登录 platform +B GET /api/file/Document/Trash 登录 platform +B POST /api/file/Document/Trash 登录 platform +B POST /api/file/Document/Trash/Actions/Recovery 登录 platform +B POST /api/file/Document/PackDownload 登录 platform +B POST /api/file/Document/merge 登录 platform +B POST /api/file/Document/UploadBlob 登录 platform +B GET /api/file/Document/getIcon 登录 platform +B GET /api/file/Document/recent 登录 platform +B GET /api/file/Document/{id} 登录 platform +B PUT /api/file/Document/{id} 登录 platform +B GET /api/file/DocumentSpace 登录 platform +B POST /api/file/DocumentSpace 登录 platform +B POST /api/file/DocumentSpace/MoveOut 登录 platform +B POST /api/file/DocumentSpace/Release 登录 platform +B GET /api/file/DocumentSpace/Selector 登录 platform +B GET /api/file/DocumentSpace/getDocumentList 登录 platform +B GET /api/file/DocumentSpace/{id} 登录 platform +B PUT /api/file/DocumentSpace/{id} 登录 platform +B DELETE /api/file/DocumentSpace/{id} 登录 platform +B GET /api/system/Schedule 登录 platform +B POST /api/system/Schedule 登录 platform +B GET /api/system/Schedule/detail 登录 platform +B GET /api/system/Schedule/{id} 登录 platform +B PUT /api/system/Schedule/{id}/{kind} 登录 platform +B DELETE /api/system/Schedule/{id}/{kind} 登录 platform +B GET /api/system/Dataset/Selector dataCenter.dataset platform +B GET /api/system/DatasetLog/{id} dataCenter.dataset platform +B POST /api/system/InterfaceOauth/saveInterfaceList integrationCenter.openApi platform +B GET /api/visualdev/ShortLink/getConfig/{id} 登录 platform + # 🔴 以下由 `scripts/pack-sync.py` 从 `packs/*` 生成 —— **不许手改** # (下次同步会被覆盖;改包就够) @@ -1935,7 +2119,7 @@ B DELETE /api/asset/DataResource/{id} permission.asset.dataResource asset [FACE] # face 条数 说明 A 28 面 A 专属(+ 2 条共用 ⇒ 面 A 合计 30 条) -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)) +B 918 面 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);批次 21–23 新增 aiCenter 75 + extend 64 + teamwork 40 + 收尾 4) AB 2 两面共用(CurrentUser / Authority Data —— 按判别头分流) [OFFICIAL] @@ -2416,9 +2600,9 @@ GET /api/system/Tag/{id}/Actions/Export partial TagController.java:169 同上: # 三者同时成立 ⇒ 前端历史遗留的死声明,不是本仓缺口。 # 记 `oos`(不进覆盖分母)而非 `absent`:它们压根不是官方端点,算进分母会让覆盖率说谎。 # 它们仍会被 `scripts/fe-gap.py` 报成缺口(那把尺子只比「前端声明了什么」)—— 已知且有意。 -GET /api/system/Dataset/Selector oos DataSetController.java:82 死声明:`dataset.ts:76 getDatasetSelector` 无人调用;`DataSetController` 只有 `/getList`(那是 `getDatasetSelectorList` 的端点)⇒ 不实现 -GET /api/system/DatasetLog/{id} oos DataSetController.java:82 死声明:`dataset.ts:40 getDataSetLog` 无人调用;全仓 Java **没有任何** `DatasetLog` 映射(`InterfaceOauth/dataInterfaceLog/{id}` 是另一个端点)⇒ 不实现 -POST /api/system/InterfaceOauth/saveInterfaceList oos InterfaceOauthController.java:74 死声明:`openApi.ts:32 saveInterfaceList` 无人调用;该控制器只有读的 `getInterfaceList`,保存走 `POST /api/system/InterfaceOauth` 本身 ⇒ 不实现 +GET /api/system/Dataset/Selector implemented api/systemData/dataset.ts:77 面 B 已落地:数据集下拉(id / fullName / enCode / type) +GET /api/system/DatasetLog/{id} partial api/systemData/dataset.ts:41 本仓不落数据集执行日志 ⇒ **如实返回空分页**(不编造记录) +POST /api/system/InterfaceOauth/saveInterfaceList implemented api/systemData/openApi.ts:33 面 B 已落地:写 `f_data_interface_ids`(官方前端暂无消费点) # ---- 权限关系(批次 16):角色绑定 / 在线用户 / 自定义范围 / 工作详情 / 导入导出 ---- GET /api/permission/RoleRelation partial RoleRelationController.java:80 面 B 已落地:按 `type` 三分支(user 补岗位/组织名;organize/position 给树路径)。**`gender` 返原码**:本仓没种子化 `SEX_TYPE` 字典,不做翻译。用户的 `position` 由 `base_user.f_position_id`(逗号分隔)反查 `base_position.f_full_name` —— 官方是查 `base_user_relation`,但本仓的岗位**只**落在 `f_position_id`(同 `GetPosition`) POST /api/permission/RoleRelation implemented RoleRelationController.java:153 面 B 已落地:空 ids / 角色不存在 / 停用用户过滤 / 已绑定跳过 / 超管不能添加 / 三态返回(`部分成功`)逐条对齐;绑完**把用户踢下线**(官方 `delCurUser`)。🔴 `f_object_type` **全小写**(`user`/`organize`/`position`,官方 `PermissionConst` 逐字):授权引擎只认小写,写成首字母大写会**绑定成功但权限永不生效** @@ -2493,7 +2677,7 @@ GET /api/visualdev/share/Selector implemented SystemShareController.java:87 面 POST /api/visualdev/ocr partial OcrController.java:48 本仓无 OCR 服务 ⇒ **明确业务失败** GET /api/visualdev/ShortLink/{id} implemented VisualdevShortLinkController.java:101 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 PUT /api/visualdev/ShortLink implemented VisualdevShortLinkController.java:139 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 -GET /api/visualdev/ShortLink/getConfig/{id} implemented VisualdevShortLinkController.java:229 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 +GET /api/visualdev/ShortLink/{id}/Config implemented VisualdevShortLinkController.java:229 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 POST /api/visualdev/ShortLink/checkPwd implemented VisualdevShortLinkController.java:244 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 GET /api/visualdev/ShortLink/Config implemented VisualdevShortLinkController.java:263 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 POST /api/visualdev/ShortLink/{id}/ListLink implemented VisualdevShortLinkController.java:292 面 B 已落地:按官方 `jnpf-visualdev` 的 Controller 形状实现 @@ -2724,6 +2908,186 @@ POST /api/message/Supplier/TestConnect partial api/msgCenter/supplier.ts:45 本 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 客户端 ⇒ **明确业务失败**(不返假发送结果) +GET /api/ai/Agent implemented api/aiCenter/aiAgent.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Agent implemented api/aiCenter/aiAgent.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Agent/Selector implemented api/aiCenter/aiAgent.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Agent/Save implemented api/aiCenter/aiAgent.ts:37 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Agent/Info/{id} implemented api/aiCenter/aiAgent.ts:41 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Agent/Info/{id} implemented api/aiCenter/aiAgent.ts:53 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Agent/Info/{id} implemented api/aiCenter/aiAgent.ts:49 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Agent/Version/{id} implemented api/aiCenter/aiAgent.ts:45 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Agent/{id} implemented api/aiCenter/aiAgent.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Agent/{id} implemented api/aiCenter/aiAgent.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Agent/{id} implemented api/aiCenter/aiAgent.ts:29 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Agent/{id}/Actions/Copy implemented api/aiCenter/aiAgent.ts:33 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/AiSupplier implemented api/aiCenter/aiModel.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/AiSupplier implemented api/aiCenter/aiModel.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/AiSupplier/Selector implemented api/aiCenter/aiModel.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/AiSupplier/checkAi partial api/aiCenter/aiModel.ts:33 本仓无 HTTP 客户端 ⇒ 无法连供应商,明确业务失败 +GET /api/ai/AiSupplier/{id} implemented api/aiCenter/aiModel.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/AiSupplier/{id} implemented api/aiCenter/aiModel.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/AiSupplier/{id} implemented api/aiCenter/aiModel.ts:29 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Chat/Send partial api/aiCenter/aiChat.ts:9 本仓无 HTTP 客户端 ⇒ 无法调 LLM,明确业务失败(元数据管理可用) +POST /api/ai/Chat/Translate partial api/aiCenter/aiChat.ts:19 本仓无 LLM 推理服务 ⇒ 明确业务失败 +POST /api/ai/Chat/Optimize partial api/aiCenter/aiChat.ts:47 本仓无 LLM 推理服务 ⇒ 明确业务失败 +GET /api/ai/Chat/Close/{id} implemented api/aiCenter/aiChat.ts:23 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Chat/history/list implemented api/aiCenter/aiChat.ts:27 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Chat/history/cleanAll implemented api/aiCenter/aiChat.ts:43 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Chat/history/get/{id} implemented api/aiCenter/aiChat.ts:31 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Chat/history/update/{id} implemented api/aiCenter/aiChat.ts:35 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Chat/history/delete/{id} implemented api/aiCenter/aiChat.ts:39 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Document implemented api/aiCenter/aiDocument.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Document implemented api/aiCenter/aiDocument.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Document/{id} implemented api/aiCenter/aiDocument.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Document/{id} implemented api/aiCenter/aiDocument.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Document/{id} implemented api/aiCenter/aiDocument.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Document/{id}/getText implemented api/aiCenter/aiDocument.ts:37 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Document/{id}/section partial api/aiCenter/aiDocument.ts:29 本地按行切片(真做);无向量化 +POST /api/ai/Document/{id}/study partial api/aiCenter/aiDocument.ts:33 本地切片 + 落 f_state(真做);无向量库,召回走关键词 +GET /api/ai/Knowledge implemented api/aiCenter/aiKnowledge.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Knowledge implemented api/aiCenter/aiKnowledge.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Knowledge/Selector implemented api/aiCenter/aiKnowledge.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Knowledge/getListByIds implemented api/aiCenter/aiKnowledge.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Knowledge/Relation/{id} implemented api/aiCenter/aiKnowledge.ts:41 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Knowledge/{id} implemented api/aiCenter/aiKnowledge.ts:29 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Knowledge/{id} implemented api/aiCenter/aiKnowledge.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Knowledge/{id} implemented api/aiCenter/aiKnowledge.ts:33 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Knowledge/{id}/Test partial api/aiCenter/aiKnowledge.ts:37 关键词召回(真做,score=命中词占比);无向量相似度 +GET /api/ai/Mcp implemented api/aiCenter/aiMcp.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Mcp implemented api/aiCenter/aiMcp.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Mcp/Selector implemented api/aiCenter/aiMcp.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Mcp/Sync/{id} partial api/aiCenter/aiMcp.ts:37 本仓无 HTTP/stdio 客户端 ⇒ 无法连 MCP 服务,明确业务失败 +POST /api/ai/Mcp/getListByIds implemented api/aiCenter/aiMcp.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Mcp/{id} implemented api/aiCenter/aiMcp.ts:29 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Mcp/{id} implemented api/aiCenter/aiMcp.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Mcp/{id} implemented api/aiCenter/aiMcp.ts:33 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Model implemented api/aiCenter/aiModelConfig.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Model/{id} implemented api/aiCenter/aiModelConfig.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Model/{id} implemented api/aiCenter/aiModelConfig.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Prompt implemented api/aiCenter/aiPrompt.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Prompt implemented api/aiCenter/aiPrompt.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Prompt/{id} implemented api/aiCenter/aiPrompt.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Prompt/{id} implemented api/aiCenter/aiPrompt.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Prompt/{id} implemented api/aiCenter/aiPrompt.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Serve implemented api/aiCenter/aiAgentService.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Serve implemented api/aiCenter/aiAgentService.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Serve/Selector implemented api/aiCenter/aiAgentService.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Serve/{id} implemented api/aiCenter/aiAgentService.ts:25 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +PUT /api/ai/Serve/{id} implemented api/aiCenter/aiAgentService.ts:21 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +DELETE /api/ai/Serve/{id} implemented api/aiCenter/aiAgentService.ts:29 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Skills implemented api/aiCenter/aiSkills.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Skills/getListByIds implemented api/aiCenter/aiSkills.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Skills/{id} implemented api/aiCenter/aiSkills.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Tool implemented api/aiCenter/aiTool.ts:9 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/Tool/getListByIds implemented api/aiCenter/aiTool.ts:13 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +GET /api/ai/Tool/{id} implemented api/aiCenter/aiTool.ts:17 面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败 +POST /api/ai/visualdev partial api/aiCenter/aiChat.ts:52 本仓无 LLM ⇒ 不生成表单;传 id 时按 id 查已有表单 +POST /api/ai/workflow partial api/aiCenter/aiChat.ts:56 本仓无 LLM ⇒ 不生成流程;传 id 时按 id 查已有模板 +GET /api/extend/BigData implemented api/extend/bigData.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/BigData implemented api/extend/bigData.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/CrmOrder implemented api/extend/order.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/CrmOrder/Customer implemented api/extend/order.ts:25 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/CrmOrder/Goods implemented api/extend/order.ts:29 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/CrmOrder/OrderEntry/{id}/Items implemented api/extend/order.ts:17 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +DELETE /api/extend/CrmOrder/{id} implemented api/extend/order.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/CrmOrder/{id}/CollectionPlan implemented api/extend/order.ts:21 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/DocumentPreview implemented api/extend/documentPreview.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/DocumentPreview/{id}/Preview partial api/extend/documentPreview.ts:13 本仓无 onlyoffice / 文件服务 ⇒ 明确业务失败 +GET /api/extend/Email implemented api/extend/email.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/Email partial api/extend/email.ts:25 本仓无 SMTP ⇒ 不发信;草稿走 SaveDraft 真存 +POST /api/extend/Email/Actions/SaveDraft implemented api/extend/email.ts:29 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/Email/Config implemented api/extend/email.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/Email/Config implemented api/extend/email.ts:17 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/Email/Config/Actions/CheckMail partial api/extend/email.ts:21 本仓无 SMTP/IMAP 客户端 ⇒ 明确业务失败 +POST /api/extend/Email/Receive partial api/extend/email.ts:57 本仓无 IMAP 客户端 ⇒ 明确业务失败 +GET /api/extend/Email/{id} implemented api/extend/email.ts:33 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +DELETE /api/extend/Email/{id} implemented api/extend/email.ts:37 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/Email/{id}/Actions/Read implemented api/extend/email.ts:41 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/Email/{id}/Actions/Unread implemented api/extend/email.ts:45 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/Email/{id}/Actions/Star implemented api/extend/email.ts:49 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/Email/{id}/Actions/Unstar implemented api/extend/email.ts:53 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/Employee implemented api/extend/employee.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/Employee/ExportData partial api/extend/employee.ts:17 本仓无文件服务与 Excel 库 ⇒ 明确业务失败 +POST /api/extend/Employee/ImportData partial api/extend/employee.ts:25 本仓无文件服务与 Excel 库 ⇒ 明确业务失败 +GET /api/extend/Employee/ImportPreview partial api/extend/employee.ts:29 本仓无文件服务与 Excel 库 ⇒ 明确业务失败 +GET /api/extend/Employee/TemplateDownload partial api/extend/employee.ts:21 本仓无文件服务 ⇒ 明确业务失败 +DELETE /api/extend/Employee/{id} implemented api/extend/employee.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/ProjectGantt implemented api/extend/projectGantt.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/ProjectGantt implemented api/extend/projectGantt.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/ProjectGantt/Task implemented api/extend/projectGantt.ts:41 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/ProjectGantt/Task/{id} implemented api/extend/projectGantt.ts:37 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/ProjectGantt/Task/{id} implemented api/extend/projectGantt.ts:45 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/ProjectGantt/{id} implemented api/extend/projectGantt.ts:25 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/ProjectGantt/{id} implemented api/extend/projectGantt.ts:17 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +DELETE /api/extend/ProjectGantt/{id} implemented api/extend/projectGantt.ts:21 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/ProjectGantt/{id}/Task implemented api/extend/projectGantt.ts:29 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/ProjectGantt/{id}/Task/Selector/{taskId} implemented api/extend/projectGantt.ts:33 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample implemented api/extend/table.ts:29 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/TableExample implemented api/extend/table.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample/All implemented api/extend/table.ts:33 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample/CityList/{id} implemented api/extend/table.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample/ControlSample/{id} implemented api/extend/table.ts:61 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample/IndustryList implemented api/extend/table.ts:21 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/TableExample/UpdateSign/{id} implemented api/extend/table.ts:57 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample/{id} implemented api/extend/table.ts:25 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/TableExample/{id} implemented api/extend/table.ts:53 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +DELETE /api/extend/TableExample/{id} implemented api/extend/table.ts:17 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/TableExample/{id}/Actions/Postil implemented api/extend/table.ts:41 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/TableExample/{id}/Actions/RowsEdit implemented api/extend/table.ts:37 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/TableExample/{id}/Postil implemented api/extend/table.ts:45 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +DELETE /api/extend/TableExample/{id}/Postil/{index} implemented api/extend/table.ts:49 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Classify implemented api/extend/saleOrder.ts:33 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Customer implemented api/extend/saleOrder.ts:29 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Goods implemented api/extend/saleOrder.ts:37 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Goods/Selector implemented api/extend/saleOrder.ts:49 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Goods/getGoodList implemented api/extend/saleOrder.ts:41 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Product implemented api/extend/saleOrder.ts:9 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +POST /api/extend/saleOrder/Product implemented api/extend/saleOrder.ts:17 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Product/ProductEntry/{id} implemented api/extend/saleOrder.ts:45 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/extend/saleOrder/Product/{id} implemented api/extend/saleOrder.ts:13 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +PUT /api/extend/saleOrder/Product/{id} implemented api/extend/saleOrder.ts:21 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +DELETE /api/extend/saleOrder/Product/{id} implemented api/extend/saleOrder.ts:25 面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败 +GET /api/file/Document implemented api/teamwork/document.ts:11 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document implemented api/teamwork/document.ts:19 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/list implemented api/teamwork/document.ts:15 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +PUT /api/file/Document/tag implemented api/teamwork/document.ts:23 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/BatchDelete implemented api/teamwork/document.ts:31 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/FolderTree implemented api/teamwork/document.ts:35 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/Detail implemented api/teamwork/document.ts:43 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +PUT /api/file/Document/Actions/MoveTo/{toId} implemented api/teamwork/document.ts:47 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/Actions/Copy/{toId} implemented api/teamwork/document.ts:51 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/Actions/Share implemented api/teamwork/document.ts:59 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/Actions/CancelShare implemented api/teamwork/document.ts:55 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/Actions/ShareAdjustment/{id} implemented api/teamwork/document.ts:63 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/Share implemented api/teamwork/document.ts:67 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/ShareTome implemented api/teamwork/document.ts:75 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/ShareUser/{id} implemented api/teamwork/document.ts:79 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/Trash implemented api/teamwork/document.ts:83 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/Trash implemented api/teamwork/document.ts:87 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/Trash/Actions/Recovery implemented api/teamwork/document.ts:91 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/Document/PackDownload partial api/teamwork/document.ts:95 本仓无文件服务 ⇒ 明确业务失败 +POST /api/file/Document/merge partial api/teamwork/document.ts:99 本仓无文件服务 ⇒ 分片合并明确失败 +POST /api/file/Document/UploadBlob partial api/teamwork/document.ts:103 本仓无文件服务 ⇒ 只支持元数据,上传明确失败 +GET /api/file/Document/getIcon implemented api/teamwork/document.ts:107 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/recent implemented api/teamwork/document.ts:71 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/Document/{id} implemented api/teamwork/document.ts:39 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +PUT /api/file/Document/{id} implemented api/teamwork/document.ts:27 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/DocumentSpace implemented api/teamwork/documentSpace.ts:9 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/DocumentSpace implemented api/teamwork/documentSpace.ts:25 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/DocumentSpace/MoveOut implemented api/teamwork/documentSpace.ts:41 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/file/DocumentSpace/Release implemented api/teamwork/documentSpace.ts:37 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/DocumentSpace/Selector implemented api/teamwork/documentSpace.ts:17 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/DocumentSpace/getDocumentList implemented api/teamwork/documentSpace.ts:13 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/file/DocumentSpace/{id} implemented api/teamwork/documentSpace.ts:33 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +PUT /api/file/DocumentSpace/{id} implemented api/teamwork/documentSpace.ts:29 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +DELETE /api/file/DocumentSpace/{id} implemented api/teamwork/documentSpace.ts:21 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/system/Schedule implemented api/teamwork/schedule.ts:9 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +POST /api/system/Schedule implemented api/teamwork/schedule.ts:13 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/system/Schedule/detail implemented api/teamwork/schedule.ts:29 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/system/Schedule/{id} implemented api/teamwork/schedule.ts:25 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +PUT /api/system/Schedule/{id}/{kind} implemented api/teamwork/schedule.ts:17 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +DELETE /api/system/Schedule/{id}/{kind} implemented api/teamwork/schedule.ts:21 面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败 +GET /api/visualdev/ShortLink/getConfig/{id} implemented api/onlineDev/shortLink.ts:17 面 B 已落地:外链配置(与 `{id}/Config` 同一 handler;官方前端两个函数都在用) [RULER] # name 期望断言数(尺子**自己**断言的条数;跑出来的条数对不上 ⇒ 失败) diff --git a/docs/known-limitations.md b/docs/known-limitations.md index 54073f5..bb9ee5b 100644 --- a/docs/known-limitations.md +++ b/docs/known-limitations.md @@ -110,3 +110,20 @@ 而本仓前端 `src/frontend/src/api/request.ts` **也发**前两个(与官方同款)⇒ **只有 `Vue-Version` 是本仓前端唯一不发的**。 🔴 **本仓前端禁止发 `Vue-Version`**(发了 ⇒ 面 A 请求被误判成面 B ⇒ 契约整体错位)。 🔴 `scripts/check-module.sh` 的「全局红线」段**静态钉住两侧**:前端**禁发**该头 + 面 B 尺子**必带**该头。 + +## I. AI 中心 / extend 示例 / teamwork(批次 21–23,2026-11-03) + +> 这三族把官方前端 `src/api/**` 的**最后 179 条**端点补齐(`fe-gap` 从 717/900 → **900/900**)。 +> 口径与批次 20 一致:**能本地自洽的真落库,需要外部能力的如实失败**。 + +| # | 限制 | 为什么接受 / 代价 | +|---|---|---| +| (ar) | **AI 中心没有 LLM 推理能力**:`Chat/Send` / `Translate` / `Optimize` / `AiSupplier/checkAi` / `Mcp/Sync` 一律 `code=400` + 人话 | 本仓 `src/backend/Cargo.toml` **没有 HTTP 客户端**(无 reqwest / hyper client)。假装流式返回一段文本 = 骗前端。代价:AI 中心页面只能做**元数据管理**,对话/翻译/连通性检查用不了 | +| (as) | **知识库召回是关键词匹配,不是向量检索**:`Document/{id}/study` 本地按行切片(≤800 字)并落 `f_state=1`;`Knowledge/{id}/Test` 用 ILIKE 命中的词数占比当 `score` | 本仓没有向量库 / embedding 服务。**真做了切片与召回**(不是空壳),但语义召回质量不如向量检索。代价:同义词、跨语言召回会漏 | +| (at) | **AI 中心的守卫只到「登录」**:官方是 `@SaCheckPermission("aiCenter.*")`,本仓没有 AI 菜单/权限点种子 | 如实降级(`require_login_face_b`)。代价:**任何登录用户都能改 AI 配置**(dev 环境可接受;集成期补菜单种子后改回 `guard(...)` 即可) | +| (au) | **供应商密钥不下发**:列表/详情的 `credential` 恒空串,只给 `credentialConfigured` 布尔 | 官方会把密钥原样返给前端编辑;但本仓守卫只到登录 ⇒ 不能把密钥发给任何登录用户。代价:编辑供应商时**必须重新输入密钥**(留空=不改,更新逻辑已处理) | +| (av) | **extend 的邮件 / 导入导出 / 预览不可用**:`POST Email`(发信)、`Email/Receive`、`Email/Config/Actions/CheckMail`、`Employee/{ExportData,ImportData,ImportPreview,TemplateDownload}`、`DocumentPreview/{id}/Preview` 一律 400 | 没有 SMTP/IMAP 客户端、没有 Excel 库、没有文件服务。草稿(`SaveDraft`)与邮箱配置**真落库**。代价:这些示例页的「发送/导出」按钮只会提示失败 | +| (aw) | **extend 的金额 / 业务日期列是 TEXT** | 本仓的 SQL 绑定参数是 `$N::text`(进 NUMERIC/TIMESTAMP 列需逐列 cast)⇒ 示例页只做展示,用 TEXT 换实现简单。代价:**不能直接用 SQL 做金额汇总/日期比较**(报表要用需先 cast) | +| (ax) | **`TableExample/CityList/{id}` 依赖 `base_province`**,本仓**没有行政区划种子** ⇒ 恒空列表 | 不编造城市数据。代价:控件示例的「城市」下拉为空(`IndustryList` 是官方同款静态选项,有值) | +| (ay) | **teamwork 只存文件元数据,不存字节**:`UploadBlob` / `PackDownload` / `merge` 一律 400;文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 / 空间**真落库** | 本仓没有对象存储 / onlyoffice / 分片合并。代价:页面上传文件会失败,但目录与分享体系可用 | +| (az) | **日程只落库,不推送提醒**:`base_schedule` 的 `reminderTime` / `sendConfigId` 原样存,**没有调度器真发提醒** | 本仓的 `scheduletask` 只登记任务、不执行;IM/邮件通道也没有。代价:日程到点不会通知 | diff --git a/scripts/gen-contract-endpoints.py b/scripts/gen-contract-endpoints.py index 509d032..2acd723 100644 --- a/scripts/gen-contract-endpoints.py +++ b/scripts/gen-contract-endpoints.py @@ -25,6 +25,7 @@ """ import importlib.util +import json import os import re import sys @@ -762,7 +763,15 @@ PARTIAL_NOTES[("GET", "/api/message/Receive")] = ( # 🔴 **端点顺序**:按官方模块分组,组内按路径排 —— 与 `routes.rs` 的注册顺序对齐 # (⇒ 契约读起来与代码读起来同序 ⇒ 人工 review 不用来回跳)。 -MODULE_ORDER = ["core", "online_dev", "report", "workflow", "msg_center"] +MODULE_ORDER = ["core", "online_dev", "report", "workflow", "msg_center", + "ai", "extend", "teamwork"] + +# 🔴 **批次 21–23**:AI 中心 / extend 示例 / teamwork(文件 + 日程)三族。 +# 官方出处直接取官方前端 `api//**:行号`(与 `scripts/fe-gap.py` 同一份扫描结果), +# 因为这三族在官方 Java 里分散在 `jnpf-ai-v3` / `jnpf-extend` / `jnpf-file` / +# `jnpf-system` 四个模块,逐条对 Java 行号收益不大、且更容易漂。 +_EXT_SOURCES = json.load( + open(os.path.join(HERE, "official-ext-sources.json"), encoding="utf-8")) # 🔴 **默认 note**(未在 `PARTIAL_NOTES` 里显式标注的端点)。 DEFAULT_NOTES = { @@ -775,6 +784,13 @@ DEFAULT_NOTES = { "workflow": "面 B 已落地:流程**元数据**(模板 / 版本 / 节点 / 评论 / 委托 / " "监控 / 触发记录)**真落库**到官方 24 张 `workflow_*` 表(DDL 逐字照官方);" "**引擎动作**(发起 / 审批 / 办理 …)因本仓未接入 Flowable ⇒ **明确业务失败**", + "ai": "面 B 已落地:AI 中心元数据(智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / " + "提示词 / 服务 / 技能 / 工具 / 会话历史)真落库到官方 `base_ai_*` 表;" + "**调模型推理 / 供应商连通性检查 / MCP 工具同步**因本仓无 HTTP 客户端明确失败", + "extend": "面 B 已落地:官方示例模块真落库到 `ext_*` 15 张表;" + "需要 SMTP/IMAP、文件服务、Excel 引擎的动作明确失败", + "teamwork": "面 B 已落地:文件**元数据**(文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / " + "最近 / 标签 / 空间)与日程真落库;上传 / 打包下载 / 分片合并因本仓无文件服务明确失败", "msg_center": "面 B 已落地:消息中心(账号 / 发送配置 / 模板 / 敏感词 / 接收配置 / " "监控 / 供应商)**真落库**到官方 `base_msg_*` + `base_intg_supplier*` " "表(DDL 逐字照官方);**真发消息 / 真连服务商**的动作因本仓无 HTTP " @@ -829,9 +845,63 @@ def build_rows(modules): return ep_rows, off_rows +# ---- 批次 21–23:三族的「部分落地」说明(诚实的降级点)---- +PARTIAL_NOTES.update({ + ("POST", "/api/ai/Chat/Send"): ( + "partial", "本仓无 HTTP 客户端 ⇒ 无法调 LLM,明确业务失败(元数据管理可用)"), + ("POST", "/api/ai/Chat/Translate"): ( + "partial", "本仓无 LLM 推理服务 ⇒ 明确业务失败"), + ("POST", "/api/ai/Chat/Optimize"): ( + "partial", "本仓无 LLM 推理服务 ⇒ 明确业务失败"), + ("POST", "/api/ai/AiSupplier/checkAi"): ( + "partial", "本仓无 HTTP 客户端 ⇒ 无法连供应商,明确业务失败"), + ("GET", "/api/ai/Mcp/Sync/{id}"): ( + "partial", "本仓无 HTTP/stdio 客户端 ⇒ 无法连 MCP 服务,明确业务失败"), + ("POST", "/api/ai/visualdev"): ( + "partial", "本仓无 LLM ⇒ 不生成表单;传 id 时按 id 查已有表单"), + ("POST", "/api/ai/workflow"): ( + "partial", "本仓无 LLM ⇒ 不生成流程;传 id 时按 id 查已有模板"), + ("POST", "/api/ai/Document/{id}/section"): ( + "partial", "本地按行切片(真做);无向量化"), + ("POST", "/api/ai/Document/{id}/study"): ( + "partial", "本地切片 + 落 f_state(真做);无向量库,召回走关键词"), + ("POST", "/api/ai/Knowledge/{id}/Test"): ( + "partial", "关键词召回(真做,score=命中词占比);无向量相似度"), + ("POST", "/api/extend/Email"): ( + "partial", "本仓无 SMTP ⇒ 不发信;草稿走 SaveDraft 真存"), + ("POST", "/api/extend/Email/Config/Actions/CheckMail"): ( + "partial", "本仓无 SMTP/IMAP 客户端 ⇒ 明确业务失败"), + ("POST", "/api/extend/Email/Receive"): ( + "partial", "本仓无 IMAP 客户端 ⇒ 明确业务失败"), + ("GET", "/api/extend/Employee/ExportData"): ( + "partial", "本仓无文件服务与 Excel 库 ⇒ 明确业务失败"), + ("POST", "/api/extend/Employee/ImportData"): ( + "partial", "本仓无文件服务与 Excel 库 ⇒ 明确业务失败"), + ("GET", "/api/extend/Employee/ImportPreview"): ( + "partial", "本仓无文件服务与 Excel 库 ⇒ 明确业务失败"), + ("GET", "/api/extend/Employee/TemplateDownload"): ( + "partial", "本仓无文件服务 ⇒ 明确业务失败"), + ("GET", "/api/extend/DocumentPreview/{id}/Preview"): ( + "partial", "本仓无 onlyoffice / 文件服务 ⇒ 明确业务失败"), + ("POST", "/api/file/Document/UploadBlob"): ( + "partial", "本仓无文件服务 ⇒ 只支持元数据,上传明确失败"), + ("POST", "/api/file/Document/PackDownload"): ( + "partial", "本仓无文件服务 ⇒ 明确业务失败"), + ("POST", "/api/file/Document/merge"): ( + "partial", "本仓无文件服务 ⇒ 分片合并明确失败"), +}) + + def official_entry(mod, key, path): """⇒ (src, status, note) —— 官方出处 + 落地状态 + 偏差说明。""" method = key[0] + if mod in ("ai", "extend", "teamwork"): + table = _EXT_SOURCES.get(mod) or {} + src = table.get("%s %s" % (method, norm_path(path))) + if not src: + raise SystemExit("三族没有官方出处可登记:%s %s" % (mod, path)) + status, note = PARTIAL_NOTES.get(key, ("implemented", DEFAULT_NOTES[mod])) + return src, status, note if mod == "report": line = REPORT_FRONTEND_LINES.get("%s %s" % (method, path)) src = "%s:%d" % (REPORT_SRC, line) if line else REPORT_SRC diff --git a/scripts/official-ext-sources.json b/scripts/official-ext-sources.json new file mode 100644 index 0000000..d75dae3 --- /dev/null +++ b/scripts/official-ext-sources.json @@ -0,0 +1,187 @@ +{ + "ai": { + "DELETE /api/ai/Agent/Info/{}": "api/aiCenter/aiAgent.ts:49", + "DELETE /api/ai/Agent/{}": "api/aiCenter/aiAgent.ts:29", + "DELETE /api/ai/AiSupplier/{}": "api/aiCenter/aiModel.ts:29", + "DELETE /api/ai/Chat/history/cleanAll": "api/aiCenter/aiChat.ts:43", + "DELETE /api/ai/Chat/history/delete/{}": "api/aiCenter/aiChat.ts:39", + "DELETE /api/ai/Document/{}": "api/aiCenter/aiDocument.ts:25", + "DELETE /api/ai/Knowledge/{}": "api/aiCenter/aiKnowledge.ts:33", + "DELETE /api/ai/Mcp/{}": "api/aiCenter/aiMcp.ts:33", + "DELETE /api/ai/Prompt/{}": "api/aiCenter/aiPrompt.ts:25", + "DELETE /api/ai/Serve/{}": "api/aiCenter/aiAgentService.ts:29", + "GET /api/ai/Agent": "api/aiCenter/aiAgent.ts:9", + "GET /api/ai/Agent/Info/{}": "api/aiCenter/aiAgent.ts:41", + "GET /api/ai/Agent/Selector": "api/aiCenter/aiAgent.ts:13", + "GET /api/ai/Agent/Version/{}": "api/aiCenter/aiAgent.ts:45", + "GET /api/ai/Agent/{}": "api/aiCenter/aiAgent.ts:25", + "GET /api/ai/AiSupplier": "api/aiCenter/aiModel.ts:9", + "GET /api/ai/AiSupplier/Selector": "api/aiCenter/aiModel.ts:13", + "GET /api/ai/AiSupplier/{}": "api/aiCenter/aiModel.ts:25", + "GET /api/ai/Chat/Close/{}": "api/aiCenter/aiChat.ts:23", + "GET /api/ai/Chat/history/get/{}": "api/aiCenter/aiChat.ts:31", + "GET /api/ai/Chat/history/list": "api/aiCenter/aiChat.ts:27", + "GET /api/ai/Document": "api/aiCenter/aiDocument.ts:9", + "GET /api/ai/Document/{}": "api/aiCenter/aiDocument.ts:21", + "GET /api/ai/Document/{}/getText": "api/aiCenter/aiDocument.ts:37", + "GET /api/ai/Knowledge": "api/aiCenter/aiKnowledge.ts:9", + "GET /api/ai/Knowledge/Relation/{}": "api/aiCenter/aiKnowledge.ts:41", + "GET /api/ai/Knowledge/Selector": "api/aiCenter/aiKnowledge.ts:13", + "GET /api/ai/Knowledge/{}": "api/aiCenter/aiKnowledge.ts:29", + "GET /api/ai/Mcp": "api/aiCenter/aiMcp.ts:9", + "GET /api/ai/Mcp/Selector": "api/aiCenter/aiMcp.ts:13", + "GET /api/ai/Mcp/Sync/{}": "api/aiCenter/aiMcp.ts:37", + "GET /api/ai/Mcp/{}": "api/aiCenter/aiMcp.ts:29", + "GET /api/ai/Model": "api/aiCenter/aiModelConfig.ts:9", + "GET /api/ai/Model/{}": "api/aiCenter/aiModelConfig.ts:17", + "GET /api/ai/Prompt": "api/aiCenter/aiPrompt.ts:9", + "GET /api/ai/Prompt/{}": "api/aiCenter/aiPrompt.ts:21", + "GET /api/ai/Serve": "api/aiCenter/aiAgentService.ts:9", + "GET /api/ai/Serve/Selector": "api/aiCenter/aiAgentService.ts:13", + "GET /api/ai/Serve/{}": "api/aiCenter/aiAgentService.ts:25", + "GET /api/ai/Skills": "api/aiCenter/aiSkills.ts:9", + "GET /api/ai/Skills/{}": "api/aiCenter/aiSkills.ts:17", + "GET /api/ai/Tool": "api/aiCenter/aiTool.ts:9", + "GET /api/ai/Tool/{}": "api/aiCenter/aiTool.ts:17", + "POST /api/ai/Agent": "api/aiCenter/aiAgent.ts:17", + "POST /api/ai/Agent/Info/{}": "api/aiCenter/aiAgent.ts:53", + "POST /api/ai/Agent/Save": "api/aiCenter/aiAgent.ts:37", + "POST /api/ai/Agent/{}/Actions/Copy": "api/aiCenter/aiAgent.ts:33", + "POST /api/ai/AiSupplier": "api/aiCenter/aiModel.ts:17", + "POST /api/ai/AiSupplier/checkAi": "api/aiCenter/aiModel.ts:33", + "POST /api/ai/Chat/Optimize": "api/aiCenter/aiChat.ts:47", + "POST /api/ai/Chat/Send": "api/aiCenter/aiChat.ts:9", + "POST /api/ai/Chat/Translate": "api/aiCenter/aiChat.ts:19", + "POST /api/ai/Document": "api/aiCenter/aiDocument.ts:13", + "POST /api/ai/Document/{}/section": "api/aiCenter/aiDocument.ts:29", + "POST /api/ai/Document/{}/study": "api/aiCenter/aiDocument.ts:33", + "POST /api/ai/Knowledge": "api/aiCenter/aiKnowledge.ts:21", + "POST /api/ai/Knowledge/getListByIds": "api/aiCenter/aiKnowledge.ts:17", + "POST /api/ai/Knowledge/{}/Test": "api/aiCenter/aiKnowledge.ts:37", + "POST /api/ai/Mcp": "api/aiCenter/aiMcp.ts:21", + "POST /api/ai/Mcp/getListByIds": "api/aiCenter/aiMcp.ts:17", + "POST /api/ai/Prompt": "api/aiCenter/aiPrompt.ts:13", + "POST /api/ai/Serve": "api/aiCenter/aiAgentService.ts:17", + "POST /api/ai/Skills/getListByIds": "api/aiCenter/aiSkills.ts:13", + "POST /api/ai/Tool/getListByIds": "api/aiCenter/aiTool.ts:13", + "POST /api/ai/visualdev": "api/aiCenter/aiChat.ts:52", + "POST /api/ai/workflow": "api/aiCenter/aiChat.ts:56", + "PUT /api/ai/Agent/{}": "api/aiCenter/aiAgent.ts:21", + "PUT /api/ai/AiSupplier/{}": "api/aiCenter/aiModel.ts:21", + "PUT /api/ai/Chat/history/update/{}": "api/aiCenter/aiChat.ts:35", + "PUT /api/ai/Document/{}": "api/aiCenter/aiDocument.ts:17", + "PUT /api/ai/Knowledge/{}": "api/aiCenter/aiKnowledge.ts:25", + "PUT /api/ai/Mcp/{}": "api/aiCenter/aiMcp.ts:25", + "PUT /api/ai/Model/{}": "api/aiCenter/aiModelConfig.ts:13", + "PUT /api/ai/Prompt/{}": "api/aiCenter/aiPrompt.ts:17", + "PUT /api/ai/Serve/{}": "api/aiCenter/aiAgentService.ts:21" + }, + "extend": { + "DELETE /api/extend/CrmOrder/{}": "api/extend/order.ts:13", + "DELETE /api/extend/Email/{}": "api/extend/email.ts:37", + "DELETE /api/extend/Employee/{}": "api/extend/employee.ts:13", + "DELETE /api/extend/ProjectGantt/{}": "api/extend/projectGantt.ts:21", + "DELETE /api/extend/TableExample/{}": "api/extend/table.ts:17", + "DELETE /api/extend/TableExample/{}/Postil/{}": "api/extend/table.ts:49", + "DELETE /api/extend/saleOrder/Product/{}": "api/extend/saleOrder.ts:25", + "GET /api/extend/BigData": "api/extend/bigData.ts:9", + "GET /api/extend/CrmOrder": "api/extend/order.ts:9", + "GET /api/extend/CrmOrder/Customer": "api/extend/order.ts:25", + "GET /api/extend/CrmOrder/Goods": "api/extend/order.ts:29", + "GET /api/extend/CrmOrder/OrderEntry/{}/Items": "api/extend/order.ts:17", + "GET /api/extend/CrmOrder/{}/CollectionPlan": "api/extend/order.ts:21", + "GET /api/extend/DocumentPreview": "api/extend/documentPreview.ts:9", + "GET /api/extend/DocumentPreview/{}/Preview": "api/extend/documentPreview.ts:13", + "GET /api/extend/Email": "api/extend/email.ts:9", + "GET /api/extend/Email/Config": "api/extend/email.ts:13", + "GET /api/extend/Email/{}": "api/extend/email.ts:33", + "GET /api/extend/Employee": "api/extend/employee.ts:9", + "GET /api/extend/Employee/ExportData": "api/extend/employee.ts:17", + "GET /api/extend/Employee/ImportPreview": "api/extend/employee.ts:29", + "GET /api/extend/Employee/TemplateDownload": "api/extend/employee.ts:21", + "GET /api/extend/ProjectGantt": "api/extend/projectGantt.ts:9", + "GET /api/extend/ProjectGantt/Task/{}": "api/extend/projectGantt.ts:37", + "GET /api/extend/ProjectGantt/{}": "api/extend/projectGantt.ts:25", + "GET /api/extend/ProjectGantt/{}/Task": "api/extend/projectGantt.ts:29", + "GET /api/extend/ProjectGantt/{}/Task/Selector/{}": "api/extend/projectGantt.ts:33", + "GET /api/extend/TableExample": "api/extend/table.ts:29", + "GET /api/extend/TableExample/All": "api/extend/table.ts:33", + "GET /api/extend/TableExample/CityList/{}": "api/extend/table.ts:9", + "GET /api/extend/TableExample/ControlSample/{}": "api/extend/table.ts:61", + "GET /api/extend/TableExample/IndustryList": "api/extend/table.ts:21", + "GET /api/extend/TableExample/{}": "api/extend/table.ts:25", + "GET /api/extend/TableExample/{}/Actions/Postil": "api/extend/table.ts:41", + "GET /api/extend/saleOrder/Classify": "api/extend/saleOrder.ts:33", + "GET /api/extend/saleOrder/Customer": "api/extend/saleOrder.ts:29", + "GET /api/extend/saleOrder/Goods": "api/extend/saleOrder.ts:37", + "GET /api/extend/saleOrder/Goods/Selector": "api/extend/saleOrder.ts:49", + "GET /api/extend/saleOrder/Goods/getGoodList": "api/extend/saleOrder.ts:41", + "GET /api/extend/saleOrder/Product": "api/extend/saleOrder.ts:9", + "GET /api/extend/saleOrder/Product/ProductEntry/{}": "api/extend/saleOrder.ts:45", + "GET /api/extend/saleOrder/Product/{}": "api/extend/saleOrder.ts:13", + "POST /api/extend/BigData": "api/extend/bigData.ts:13", + "POST /api/extend/Email": "api/extend/email.ts:25", + "POST /api/extend/Email/Actions/SaveDraft": "api/extend/email.ts:29", + "POST /api/extend/Email/Config/Actions/CheckMail": "api/extend/email.ts:21", + "POST /api/extend/Email/Receive": "api/extend/email.ts:57", + "POST /api/extend/Employee/ImportData": "api/extend/employee.ts:25", + "POST /api/extend/ProjectGantt": "api/extend/projectGantt.ts:13", + "POST /api/extend/ProjectGantt/Task": "api/extend/projectGantt.ts:41", + "POST /api/extend/TableExample": "api/extend/table.ts:13", + "POST /api/extend/TableExample/{}/Postil": "api/extend/table.ts:45", + "POST /api/extend/saleOrder/Product": "api/extend/saleOrder.ts:17", + "PUT /api/extend/Email/Config": "api/extend/email.ts:17", + "PUT /api/extend/Email/{}/Actions/Read": "api/extend/email.ts:41", + "PUT /api/extend/Email/{}/Actions/Star": "api/extend/email.ts:49", + "PUT /api/extend/Email/{}/Actions/Unread": "api/extend/email.ts:45", + "PUT /api/extend/Email/{}/Actions/Unstar": "api/extend/email.ts:53", + "PUT /api/extend/ProjectGantt/Task/{}": "api/extend/projectGantt.ts:45", + "PUT /api/extend/ProjectGantt/{}": "api/extend/projectGantt.ts:17", + "PUT /api/extend/TableExample/UpdateSign/{}": "api/extend/table.ts:57", + "PUT /api/extend/TableExample/{}": "api/extend/table.ts:53", + "PUT /api/extend/TableExample/{}/Actions/RowsEdit": "api/extend/table.ts:37", + "PUT /api/extend/saleOrder/Product/{}": "api/extend/saleOrder.ts:21" + }, + "teamwork": { + "DELETE /api/file/DocumentSpace/{}": "api/teamwork/documentSpace.ts:21", + "DELETE /api/system/Schedule/{}/{}": "api/teamwork/schedule.ts:21", + "GET /api/file/Document": "api/teamwork/document.ts:11", + "GET /api/file/Document/Detail": "api/teamwork/document.ts:43", + "GET /api/file/Document/Share": "api/teamwork/document.ts:67", + "GET /api/file/Document/ShareTome": "api/teamwork/document.ts:75", + "GET /api/file/Document/ShareUser/{}": "api/teamwork/document.ts:79", + "GET /api/file/Document/Trash": "api/teamwork/document.ts:83", + "GET /api/file/Document/getIcon": "api/teamwork/document.ts:107", + "GET /api/file/Document/list": "api/teamwork/document.ts:15", + "GET /api/file/Document/recent": "api/teamwork/document.ts:71", + "GET /api/file/Document/{}": "api/teamwork/document.ts:39", + "GET /api/file/DocumentSpace": "api/teamwork/documentSpace.ts:9", + "GET /api/file/DocumentSpace/Selector": "api/teamwork/documentSpace.ts:17", + "GET /api/file/DocumentSpace/getDocumentList": "api/teamwork/documentSpace.ts:13", + "GET /api/file/DocumentSpace/{}": "api/teamwork/documentSpace.ts:33", + "GET /api/system/Schedule": "api/teamwork/schedule.ts:9", + "GET /api/system/Schedule/detail": "api/teamwork/schedule.ts:29", + "GET /api/system/Schedule/{}": "api/teamwork/schedule.ts:25", + "POST /api/file/Document": "api/teamwork/document.ts:19", + "POST /api/file/Document/Actions/CancelShare": "api/teamwork/document.ts:55", + "POST /api/file/Document/Actions/Copy/{}": "api/teamwork/document.ts:51", + "POST /api/file/Document/Actions/Share": "api/teamwork/document.ts:59", + "POST /api/file/Document/Actions/ShareAdjustment/{}": "api/teamwork/document.ts:63", + "POST /api/file/Document/BatchDelete": "api/teamwork/document.ts:31", + "POST /api/file/Document/FolderTree": "api/teamwork/document.ts:35", + "POST /api/file/Document/PackDownload": "api/teamwork/document.ts:95", + "POST /api/file/Document/Trash": "api/teamwork/document.ts:87", + "POST /api/file/Document/Trash/Actions/Recovery": "api/teamwork/document.ts:91", + "POST /api/file/Document/UploadBlob": "api/teamwork/document.ts:103", + "POST /api/file/Document/merge": "api/teamwork/document.ts:99", + "POST /api/file/DocumentSpace": "api/teamwork/documentSpace.ts:25", + "POST /api/file/DocumentSpace/MoveOut": "api/teamwork/documentSpace.ts:41", + "POST /api/file/DocumentSpace/Release": "api/teamwork/documentSpace.ts:37", + "POST /api/system/Schedule": "api/teamwork/schedule.ts:13", + "PUT /api/file/Document/Actions/MoveTo/{}": "api/teamwork/document.ts:47", + "PUT /api/file/Document/tag": "api/teamwork/document.ts:23", + "PUT /api/file/Document/{}": "api/teamwork/document.ts:27", + "PUT /api/file/DocumentSpace/{}": "api/teamwork/documentSpace.ts:29", + "PUT /api/system/Schedule/{}/{}": "api/teamwork/schedule.ts:17" + } +} \ No newline at end of file diff --git a/src/backend/db/schema.sql b/src/backend/db/schema.sql index 699c27d..73cc4d1 100644 --- a/src/backend/db/schema.sql +++ b/src/backend/db/schema.sql @@ -3627,3 +3627,409 @@ CREATE TABLE workflow_version ( CREATE INDEX IF NOT EXISTS i_wlu_ftid ON workflow_launch_user(f_task_id); CREATE INDEX IF NOT EXISTS i_wo_fni ON workflow_operator(f_node_id); CREATE INDEX IF NOT EXISTS i_wr_fti ON workflow_record(f_task_id); + +-- ============================================================ 批次 22:extend 示例模块 +-- 🔴 官方 `jnpf-extend` 的示例业务表(Demo / CRM / 邮件 / 员工 / 甘特 / 控件示例 / 销售订单)。 +-- 🔴 金额与业务日期一律 **TEXT**:示例页只做展示,避免 numeric/timestamp 的绑定类型 +-- 转换(本仓 `$N::text` 参数进 NUMERIC 列会报错)。审计列仍用 TIMESTAMP。 + +CREATE TABLE ext_big_data ( + f_id VARCHAR(50) NOT NULL, + f_full_name VARCHAR(200), + f_remark TEXT, + f_num INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_customer ( + f_id VARCHAR(50) NOT NULL, + f_customer_name VARCHAR(200), + f_contact VARCHAR(100), + f_phone VARCHAR(50), + f_address VARCHAR(500), + f_industry VARCHAR(100), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_goods_classify ( + f_id VARCHAR(50) NOT NULL, + f_full_name VARCHAR(200), + f_parent_id VARCHAR(50), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_goods ( + f_id VARCHAR(50) NOT NULL, + f_goods_name VARCHAR(200), + f_classify_id VARCHAR(50), + f_price VARCHAR(50), + f_stock INTEGER, + f_unit VARCHAR(50), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_crm_order ( + f_id VARCHAR(50) NOT NULL, + f_order_no VARCHAR(100), + f_customer_id VARCHAR(50), + f_customer_name VARCHAR(200), + f_order_date VARCHAR(50), + f_total VARCHAR(50), + f_status INTEGER, + f_remark TEXT, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_crm_order_entry ( + f_id VARCHAR(50) NOT NULL, + f_order_id VARCHAR(50), + f_goods_id VARCHAR(50), + f_goods_name VARCHAR(200), + f_qty INTEGER, + f_price VARCHAR(50), + f_amount VARCHAR(50), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_crm_collection_plan ( + f_id VARCHAR(50) NOT NULL, + f_order_id VARCHAR(50), + f_plan_date VARCHAR(50), + f_amount VARCHAR(50), + f_status INTEGER, + f_remark TEXT, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_email ( + f_id VARCHAR(50) NOT NULL, + f_subject VARCHAR(500), + f_body TEXT, + f_sender VARCHAR(200), + f_receiver VARCHAR(2000), + f_mail_type INTEGER, + f_is_read INTEGER, + f_is_star INTEGER, + f_send_time VARCHAR(50), + f_attachments TEXT, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_email_config ( + f_id VARCHAR(50) NOT NULL, + f_email VARCHAR(200), + f_password VARCHAR(500), + f_smtp_host VARCHAR(200), + f_smtp_port INTEGER, + f_imap_host VARCHAR(200), + f_imap_port INTEGER, + f_ssl INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_employee ( + f_id VARCHAR(50) NOT NULL, + f_employee_no VARCHAR(50), + f_full_name VARCHAR(200), + f_gender INTEGER, + f_dept VARCHAR(200), + f_position VARCHAR(200), + f_phone VARCHAR(50), + f_email VARCHAR(200), + f_entry_date VARCHAR(50), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_project ( + f_id VARCHAR(50) NOT NULL, + f_project_name VARCHAR(200), + f_manager VARCHAR(100), + f_start_date VARCHAR(50), + f_end_date VARCHAR(50), + f_status INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_project_task ( + f_id VARCHAR(50) NOT NULL, + f_project_id VARCHAR(50), + f_parent_id VARCHAR(50), + f_task_name VARCHAR(200), + f_start_date VARCHAR(50), + f_end_date VARCHAR(50), + f_progress INTEGER, + f_assignee VARCHAR(100), + f_status INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_table_example ( + f_id VARCHAR(50) NOT NULL, + f_full_name VARCHAR(200), + f_type INTEGER, + f_industry VARCHAR(100), + f_city VARCHAR(200), + f_sign VARCHAR(100), + f_rows_json TEXT, + f_postil_json TEXT, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_sale_product ( + f_id VARCHAR(50) NOT NULL, + f_order_no VARCHAR(100), + f_customer_id VARCHAR(50), + f_customer_name VARCHAR(200), + f_order_date VARCHAR(50), + f_total VARCHAR(50), + f_status INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_sale_product_entry ( + f_id VARCHAR(50) NOT NULL, + f_order_id VARCHAR(50), + f_goods_id VARCHAR(50), + f_goods_name VARCHAR(200), + f_qty INTEGER, + f_price VARCHAR(50), + f_amount VARCHAR(50), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +-- ============================================================ 批次 23:teamwork(文件 / 日程) +-- 🔴 官方 `jnpf-file` 的 `DocumentController` / `DocumentSpaceController` 两张表 + 分享关系表。 +-- 🔴 **文件字节不落库也不落盘**(本仓没有 onlyoffice / 对象存储):只存元数据; +-- 上传 / 打包下载 / 合并分片如实失败,见 `compat/teamwork.rs` 模块头。 + +CREATE TABLE ext_document ( + f_id VARCHAR(50) NOT NULL, + f_parent_id VARCHAR(50), + f_space_id VARCHAR(50), + f_type INTEGER, + f_full_name VARCHAR(500), + f_file_path VARCHAR(2000), + f_file_size VARCHAR(50), + f_file_extension VARCHAR(50), + f_read_count INTEGER, + f_is_share INTEGER, + f_share_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_uploader_url VARCHAR(2000), + f_tag_id VARCHAR(50), + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_document_space ( + f_id VARCHAR(50) NOT NULL, + f_type INTEGER, + f_full_name VARCHAR(200), + f_download_authority INTEGER, + f_upload_authority INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); + +CREATE TABLE ext_document_share ( + f_id VARCHAR(50) NOT NULL, + f_document_id VARCHAR(50), + f_user_id VARCHAR(50), + f_share_type INTEGER, + f_description VARCHAR(500), + f_enabled_mark INTEGER, + f_sort_code BIGINT, + f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_creator_user_id VARCHAR(50), + f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_last_modify_user_id VARCHAR(50), + f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE, + f_delete_user_id VARCHAR(50), + f_delete_mark INTEGER, + f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL, + PRIMARY KEY (f_id, f_tenant_id) +); diff --git a/src/backend/src/main.rs b/src/backend/src/main.rs index 2112bd4..758c6b5 100644 --- a/src/backend/src/main.rs +++ b/src/backend/src/main.rs @@ -899,12 +899,20 @@ fn whitelist_self_check() -> Result<(), String> { // 清单真源在 `sspf_store::db::WORKFLOW_TABLES`。 let workflow_tables = ssw_platform::platform::db::WORKFLOW_TABLES; + // 🔴 **extend 示例 / teamwork 文件**(批次 22–23):官方 `jnpf-extend` 与 + // `jnpf-file` 的落库载体,既不是 `base_*` 平台表、也不是业务 spec 表。 + // 清单真源在 `sspf_store::db::{EXTEND_TABLES, TEAMWORK_TABLES}`。 + let extend_tables = ssw_platform::platform::db::EXTEND_TABLES; + let teamwork_tables = ssw_platform::platform::db::TEAMWORK_TABLES; + for table in &ddl_tables { if !BASE_TABLES.contains(&table.as_str()) && !spec_tables.contains(&table.as_str()) && !pack_tables.contains(&table.as_str()) && !report_tables.contains(&table.as_str()) && !workflow_tables.contains(&table.as_str()) + && !extend_tables.contains(&table.as_str()) + && !teamwork_tables.contains(&table.as_str()) { return Err(format!( "schema.sql 里的表 {table} 既不是 base_* 表、也没有对应的业务 spec(孤儿 DDL?)" diff --git a/src/backend/src/platform/compat/ai.rs b/src/backend/src/platform/compat/ai.rs new file mode 100644 index 0000000..7c6b926 --- /dev/null +++ b/src/backend/src/platform/compat/ai.rs @@ -0,0 +1,1837 @@ +//! ai —— 官方面 B 的 **AI 中心**端点集(`/api/ai/*`,75 条)。 +//! +//! 真源:官方 `jnpf-ai-v3` Controller + 官方前端 `src/api/aiCenter/**`。 +//! +//! 🔴 **本模块只做「能真做」的部分**: +//! | 能力 | 本仓状态 | +//! |---|---| +//! | 智能体 / 供应商 / 模型 / 知识库 / 文档 / MCP / 提示词 / 服务 / 技能 / 工具 | **真落库**到官方 `base_ai_*` 表 | +//! | 会话历史 | **真落库**(`base_ai_agent_history`) | +//! | 文档切片 / 关键词召回 | **真做**(本地切分 + ILIKE,无向量库) | +//! | 调模型推理 / 供应商连通性检查 / MCP 工具同步 | **明确业务失败**(本仓无 HTTP 客户端) | +//! +//! 🔴 **守卫**:官方每条都是 `@SaCheckPermission("aiCenter.*")`,但本仓**没有** +//! AI 中心的菜单与权限点种子 ⇒ 用「登录」守卫(`require_login_face_b`)。 +//! 这是**如实降级**,不是遗漏;集成期补菜单种子后改回 `guard(...)` 即可。 + +use axum::body::Bytes; +use axum::extract::{Path, RawQuery, State}; +use axum::http::HeaderMap; +use axum::Json; +use serde_json::{json, Map, Value}; + +use crate::platform::auth::require_login_face_b; +use crate::platform::envelope::{code, fail, ok, ActionResult}; +use crate::platform::state::AppState; + +use super::helper::{db_error, params_of, parse_body, qv}; +use super::res::{self, i, j, t, Res}; + +// ================================================================ 资源声明 + +const AGENT: Res = Res { + table: "base_ai_agent", + fields: &[ + t("fullName", "f_full_name"), + t("icon", "f_icon"), + t("iconBackground", "f_icon_background"), + i("type", "f_type"), + i("state", "f_state"), + t("versionId", "f_version_id"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const SUPPLIER: Res = Res { + table: "base_ai_supplier", + fields: &[ + t("fullName", "f_full_name"), + t("enCode", "f_en_code"), + t("url", "f_url"), + t("credential", "f_credential"), + t("icon", "f_icon"), + t("backgroundColor", "f_background_color"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name", "f_en_code"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const MODEL: Res = Res { + table: "base_ai_model", + fields: &[ + t("supplierId", "f_supplier_id"), + t("fullName", "f_full_name"), + t("model", "f_model"), + t("type", "f_type"), + t("vectorTableName", "f_vector_table_name"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name", "f_model"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const PROMPT: Res = Res { + table: "base_ai_agent_prompt", + fields: &[ + t("fullName", "f_full_name"), + t("callWord", "f_call_word"), + i("type", "f_type"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name", "f_call_word"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const KNOWLEDGE: Res = Res { + table: "base_ai_knowledge", + fields: &[ + t("modelId", "f_model_id"), + t("supplierId", "f_supplier_id"), + t("fullName", "f_full_name"), + t("icon", "f_icon"), + t("iconBackground", "f_icon_background"), + i("way", "f_way"), + j("wayJson", "f_way_json"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const DOCUMENT: Res = Res { + table: "base_ai_document", + fields: &[ + t("knowledgeId", "f_knowledge_id"), + t("fullName", "f_full_name"), + t("fileSize", "f_file_size"), + t("filePath", "f_file_path"), + t("url", "f_url"), + i("num", "f_num"), + i("way", "f_way"), + j("wayJson", "f_way_json"), + i("type", "f_type"), + i("state", "f_state"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const MCP: Res = Res { + table: "base_ai_mcp", + fields: &[ + t("fullName", "f_full_name"), + t("icon", "f_icon"), + i("mcpType", "f_mcp_type"), + j("mcpJson", "f_mcp_json"), + i("num", "f_num"), + i("state", "f_state"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const SERVE: Res = Res { + table: "base_ai_serve", + fields: &[ + t("agentId", "f_agent_id"), + t("enCode", "f_en_code"), + t("fullName", "f_full_name"), + i("type", "f_type"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name", "f_en_code"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const SKILLS: Res = Res { + table: "base_ai_skills", + fields: &[ + t("fullName", "f_full_name"), + t("enCode", "f_en_code"), + t("icon", "f_icon"), + j("skillsJson", "f_skills_json"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name", "f_en_code"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const TOOL: Res = Res { + table: "base_ai_tool", + fields: &[ + t("fullName", "f_full_name"), + t("enCode", "f_en_code"), + t("icon", "f_icon"), + j("toolJson", "f_tool_json"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + i("enabledMark", "f_enabled_mark"), + ], + keyword: &["f_full_name", "f_en_code"], + order: "COALESCE(f_sort_code, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const VERSION: Res = Res { + table: "base_ai_agent_version", + fields: &[ + t("agentId", "f_agent_id"), + t("modelId", "f_model_id"), + t("version", "f_version"), + j("configJson", "f_config_json"), + j("chartJson", "f_chart_json"), + j("knowledgeJson", "f_knowledge_json"), + j("skillJson", "f_skill_json"), + t("callWord", "f_call_word"), + i("state", "f_status"), + t("description", "f_description"), + i("sortCode", "f_sort_code"), + ], + keyword: &["f_version"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + + +/// 列表/详情里**不下发** `f_credential`(供应商密钥)。 +/// +/// 🔴 官方列表也会把 credential 带出去,但那是「同一后台管理员可见」的假设; +/// 本仓没有 AI 菜单权限点(守卫只到「登录」)⇒ **不能把密钥发给任何登录用户**。 +fn mask_supplier(mut row: Value) -> Value { + if let Some(obj) = row.as_object_mut() { + if obj.contains_key("credential") { + let configured = obj + .get("credential") + .and_then(Value::as_str) + .map(|s| !s.trim().is_empty()) + .unwrap_or(false); + obj.insert("credential".into(), Value::String(String::new())); + obj.insert("credentialConfigured".into(), Value::Bool(configured)); + } + } + row +} + +fn mask_suppliers(v: Value) -> Value { + match v { + Value::Array(items) => Value::Array(items.into_iter().map(mask_supplier).collect()), + Value::Object(mut o) => { + if let Some(list) = o.get_mut("list") { + let taken = std::mem::replace(list, Value::Null); + *list = mask_suppliers(taken); + } else { + return mask_supplier(Value::Object(o)); + } + Value::Object(o) + } + other => other, + } +} + +// ================================================================ Agent + +pub async fn agent_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![ + res::filter(&raw, "type", "f_type"), + res::filter(&raw, "state", "f_state"), + ]; + res::list_json(&state, &AGENT, &raw, filters).await +} + +pub async fn agent_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &AGENT).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "智能体下拉"), + } +} + +pub async fn agent_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, + }; + res::create_json(&state, &AGENT, &body, &user.account).await +} + +pub async fn agent_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &AGENT, &id).await +} + +pub async fn agent_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, + }; + res::update_json(&state, &AGENT, &id, &body, &user.account).await +} + +pub async fn agent_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + // 智能体删除时把它的版本一起软删(否则版本表留孤儿行)。 + if let Err(e) = state + .db + .exec_params( + "UPDATE base_ai_agent_version SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_agent_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + return db_error(e, "删除智能体版本"); + } + res::delete_json(&state, &AGENT, &id).await +} + +/// `POST /api/ai/Agent/{id}/Actions/Copy` —— 复制智能体(含最新版本)。 +pub async fn agent_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 Some(src) = (match res::get(&state.db, &AGENT, &id).await { + Ok(v) => v, + Err(e) => return db_error(e, "智能体查询"), + }) else { + return fail(code::FAIL, "智能体不存在"); + }; + let mut obj: Map = src.as_object().cloned().unwrap_or_default(); + obj.remove("id"); + obj.remove("versionId"); + let name = obj + .get("fullName") + .and_then(Value::as_str) + .unwrap_or("智能体") + .to_string(); + obj.insert("fullName".into(), json!(format!("{name}副本"))); + obj.insert("state".into(), json!(0)); + + let new_id = match res::create(&state.db, &AGENT, &obj, &user.account).await { + Ok(v) => v, + Err(e) => return db_error(e, "复制智能体"), + }; + + // 复制它最新的一个版本(没有版本也允许,前端会新建)。 + if let Ok(rows) = state + .db + .query_json_params( + "SELECT f_id AS \"id\" FROM base_ai_agent_version \ + WHERE f_agent_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_creator_time DESC NULLS LAST LIMIT 1", + &[&id.trim()], + ) + .await + { + if let Some(vid) = rows.first().and_then(|r| r.get("id")).and_then(Value::as_str) { + if let Ok(Some(v)) = res::get(&state.db, &VERSION, vid).await { + let mut vo: Map = v.as_object().cloned().unwrap_or_default(); + vo.remove("id"); + vo.insert("agentId".into(), json!(new_id)); + vo.insert("state".into(), json!(0)); + if let Ok(nv) = res::create(&state.db, &VERSION, &vo, &user.account).await { + let _ = state + .db + .exec_params( + "UPDATE base_ai_agent SET f_version_id = $1::text WHERE f_id = $2::text", + &[&nv, &new_id], + ) + .await; + } + } + } + } + ok(json!({ "id": new_id })) +} + +/// `POST /api/ai/Agent/Save` —— 保存智能体**版本**(新建或更新)。 +pub async fn agent_save_version( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let agent_id = obj + .get("agentId") + .and_then(Value::as_str) + .map(str::trim) + .unwrap_or_default() + .to_string(); + if agent_id.is_empty() { + return fail(code::FAIL, "智能体 id 不能为空"); + } + let existed = match res::get(&state.db, &AGENT, &agent_id).await { + Ok(Some(v)) => v, + Ok(None) => return fail(code::FAIL, "智能体不存在"), + Err(e) => return db_error(e, "智能体查询"), + }; + + let version_id = obj + .get("id") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); + + let vid = match version_id { + Some(vid) => match res::update(&state.db, &VERSION, &vid, &obj, &user.account).await { + Ok(true) => vid, + Ok(false) => return fail(code::FAIL, "版本不存在"), + Err(e) => return db_error(e, "更新版本"), + }, + None => { + let mut vo = obj.clone(); + vo.remove("id"); + let seq = state + .db + .query_json_params( + "SELECT COUNT(*)::bigint AS \"n\" FROM base_ai_agent_version \ + WHERE f_agent_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&agent_id], + ) + .await + .ok() + .and_then(|rows| rows.first().and_then(|r| r.get("n")).and_then(Value::as_i64)) + .unwrap_or(0) + + 1; + vo.insert("version".into(), json!(format!("V{seq}"))); + vo.insert("state".into(), json!(1)); + match res::create(&state.db, &VERSION, &vo, &user.account).await { + Ok(v) => v, + Err(e) => return db_error(e, "新建版本"), + } + } + }; + + // 版本落定后回写智能体的 versionId + state=1(与官方「保存即发布草稿」一致)。 + if let Err(e) = state + .db + .exec_params( + "UPDATE base_ai_agent SET f_version_id = $1::text, f_state = 1, \ + f_last_modify_time = now(), f_last_modify_user_id = $2::text WHERE f_id = $3::text", + &[&vid, &user.account, &agent_id], + ) + .await + { + return db_error(e, "回写智能体版本"); + } + let _ = existed; + ok(json!({ "id": vid, "agentId": agent_id })) +} + +pub async fn agent_version_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &VERSION, &id).await +} + +pub async fn agent_version_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_agent_id AS \"agentId\", f_model_id AS \"modelId\", \ + f_version AS \"version\", f_config_json AS \"configJson\", \ + f_chart_json AS \"chartJson\", f_knowledge_json AS \"knowledgeJson\", \ + f_skill_json AS \"skillJson\", f_call_word AS \"callWord\", \ + COALESCE(f_status, 0)::bigint AS \"state\", \ + (EXTRACT(EPOCH FROM f_creator_time) * 1000)::bigint AS \"creatorTime\" \ + FROM base_ai_agent_version \ + WHERE f_agent_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_creator_time DESC NULLS LAST", + &[&id.trim()], + ) + .await + { + // 前端把 `res.data` 当**数组**用(`state.versionList = res.data || []`)。 + Ok(rows) => ok(json!(rows)), + Err(e) => db_error(e, "版本列表"), + } +} + +pub async fn agent_version_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &VERSION, &id).await +} + +/// `POST /api/ai/Agent/Info/{id}` —— 复制版本。 +pub async fn agent_version_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 Some(src) = (match res::get(&state.db, &VERSION, &id).await { + Ok(v) => v, + Err(e) => return db_error(e, "版本查询"), + }) else { + return fail(code::FAIL, "版本不存在"); + }; + let mut obj: Map = src.as_object().cloned().unwrap_or_default(); + obj.remove("id"); + let old = obj + .get("version") + .and_then(Value::as_str) + .unwrap_or("V0") + .to_string(); + obj.insert("version".into(), json!(format!("{old}.copy"))); + obj.insert("state".into(), json!(0)); + match res::create(&state.db, &VERSION, &obj, &user.account).await { + Ok(v) => ok(json!({ "id": v })), + Err(e) => db_error(e, "复制版本"), + } +} + +// ================================================================ AiSupplier + +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 Json(mut body) = res::list_json(&state, &SUPPLIER, &raw, vec![]).await; + body.data = mask_suppliers(body.data); + Json(body) +} + +pub async fn supplier_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &SUPPLIER).await { + Ok(list) => ok(super::helper::list_vo( + list.into_iter().map(mask_supplier).collect(), + )), + Err(e) => db_error(e, "供应商下拉"), + } +} + +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, + }; + res::create_json(&state, &SUPPLIER, &body, &user.account).await +} + +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 Json(mut body) = res::info_json(&state, &SUPPLIER, &id).await; + body.data = mask_suppliers(body.data); + Json(body) +} + +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, + }; + res::update_json(&state, &SUPPLIER, &id, &body, &user.account).await +} + +pub async fn supplier_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &SUPPLIER, &id).await +} + +/// `POST /api/ai/AiSupplier/checkAi` —— 连通性检查。 +/// +/// 🔴 **本仓无 HTTP 客户端**(`src/backend/Cargo.toml` 没有 reqwest)⇒ 明确失败。 +/// 不返「成功」:前端会据此把供应商标成「可用」,那是假信号。 +pub async fn supplier_check( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓未接入 HTTP 客户端:无法向供应商发起连通性检查(集成期补)", + ) +} + +// ================================================================ Model + +pub async fn model_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![res::filter(&raw, "supplierId", "f_supplier_id")]; + res::list_json(&state, &MODEL, &raw, filters).await +} + +pub async fn model_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &MODEL, &id).await +} + +pub async fn model_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, + }; + res::update_json(&state, &MODEL, &id, &body, &user.account).await +} + +// ================================================================ Prompt + +pub async fn prompt_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![res::filter(&raw, "type", "f_type")]; + res::list_json(&state, &PROMPT, &raw, filters).await +} + +pub async fn prompt_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, + }; + res::create_json(&state, &PROMPT, &body, &user.account).await +} + +pub async fn prompt_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &PROMPT, &id).await +} + +pub async fn prompt_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, + }; + res::update_json(&state, &PROMPT, &id, &body, &user.account).await +} + +pub async fn prompt_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &PROMPT, &id).await +} + +// ================================================================ Knowledge + +pub async fn knowledge_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &KNOWLEDGE, &raw, vec![]).await +} + +pub async fn knowledge_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &KNOWLEDGE).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "知识库下拉"), + } +} + +pub async fn knowledge_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, + }; + res::create_json(&state, &KNOWLEDGE, &body, &user.account).await +} + +pub async fn knowledge_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &KNOWLEDGE, &id).await +} + +pub async fn knowledge_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, + }; + res::update_json(&state, &KNOWLEDGE, &id, &body, &user.account).await +} + +pub async fn knowledge_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + // 知识库删除时把文档一起软删。 + if let Err(e) = state + .db + .exec_params( + "UPDATE base_ai_document SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_knowledge_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + return db_error(e, "删除知识库文档"); + } + res::delete_json(&state, &KNOWLEDGE, &id).await +} + +/// `POST /api/ai/Knowledge/getListByIds` —— 按 id 批量取(智能体绑定回显)。 +pub async fn knowledge_by_ids( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let ids = match ids_of(&body) { + Ok(v) => v, + Err(resp) => return resp, + }; + match res::by_ids(&state.db, &KNOWLEDGE, &ids).await { + Ok(list) => ok(json!(list)), + Err(e) => db_error(e, "按 id 查知识库"), + } +} + +/// `GET /api/ai/Knowledge/Relation/{id}` —— 哪些智能体绑了这个知识库。 +pub async fn knowledge_relation( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT a.f_id AS \"id\", a.f_full_name AS \"fullName\", a.f_icon AS \"icon\" \ + FROM base_ai_agent a JOIN base_ai_agent_version v ON v.f_agent_id = a.f_id \ + WHERE COALESCE(a.f_delete_mark, 0) = 0 AND COALESCE(v.f_delete_mark, 0) = 0 \ + AND COALESCE(v.f_knowledge_json, '') ILIKE $1::text \ + GROUP BY a.f_id, a.f_full_name, a.f_icon ORDER BY a.f_full_name ASC", + &[&format!("%{id}%")], + ) + .await + { + Ok(list) => ok(json!(list)), + Err(e) => db_error(e, "知识库关联查询"), + } +} + +/// `POST /api/ai/Knowledge/{id}/Test` —— 召回测试。 +/// +/// 🔴 本仓**无向量库** ⇒ 用**关键词匹配**(文档正文/文件名 ILIKE),返回带命中片段的 +/// 真实结果;`score` 是命中词数占比(不是向量相似度,字段名沿用官方)。 +pub async fn knowledge_test( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let question = ["question", "keyword", "text", "content"] + .iter() + .find_map(|k| obj.get(*k).and_then(Value::as_str)) + .unwrap_or_default() + .trim() + .to_string(); + if question.is_empty() { + return fail(code::FAIL, "召回内容不能为空"); + } + let docs = match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", \ + COALESCE(f_way_json, '') AS \"content\" \ + FROM base_ai_document \ + WHERE f_knowledge_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_creator_time DESC NULLS LAST LIMIT 200", + &[&id.trim()], + ) + .await + { + Ok(v) => v, + Err(e) => return db_error(e, "召回查询"), + }; + let words: Vec = question + .split_whitespace() + .filter(|w| !w.is_empty()) + .map(|w| w.to_lowercase()) + .collect(); + let mut hits: Vec = Vec::new(); + for doc in docs { + let text = doc + .get("content") + .and_then(Value::as_str) + .unwrap_or_default() + .to_lowercase(); + let name = doc + .get("fullName") + .and_then(Value::as_str) + .unwrap_or_default() + .to_lowercase(); + let hit = words + .iter() + .filter(|w| text.contains(w.as_str()) || name.contains(w.as_str())) + .count(); + if hit == 0 { + continue; + } + let score = if words.is_empty() { + 0.0 + } else { + hit as f64 / words.len() as f64 + }; + let snippet = snippet_of( + doc.get("content").and_then(Value::as_str).unwrap_or_default(), + &words, + ); + hits.push(json!({ + "id": doc.get("id").cloned().unwrap_or(Value::Null), + "fullName": doc.get("fullName").cloned().unwrap_or(Value::Null), + "content": snippet, + "score": (score * 100.0).round() / 100.0, + })); + } + hits.sort_by(|a, b| { + b.get("score") + .and_then(Value::as_f64) + .unwrap_or(0.0) + .partial_cmp(&a.get("score").and_then(Value::as_f64).unwrap_or(0.0)) + .unwrap_or(std::cmp::Ordering::Equal) + }); + ok(json!({ "list": hits, "total": hits.len() })) +} + +/// 取命中词周围的一段文本(最多 200 字符)。 +fn snippet_of(text: &str, words: &[String]) -> String { + if text.is_empty() { + return String::new(); + } + let lower = text.to_lowercase(); + for w in words { + if let Some(pos) = lower.find(w.as_str()) { + let start = text[..pos].char_indices().rev().nth(60).map(|(i, _)| i).unwrap_or(0); + let tail: String = text[start..].chars().take(200).collect(); + return tail; + } + } + text.chars().take(200).collect() +} + +// ================================================================ Document + +pub async fn document_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![ + res::filter(&raw, "knowledgeId", "f_knowledge_id"), + res::filter(&raw, "state", "f_state"), + ]; + res::list_json(&state, &DOCUMENT, &raw, filters).await +} + +pub async fn document_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, + }; + res::create_json(&state, &DOCUMENT, &body, &user.account).await +} + +pub async fn document_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &DOCUMENT, &id).await +} + +pub async fn document_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, + }; + res::update_json(&state, &DOCUMENT, &id, &body, &user.account).await +} + +pub async fn document_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &DOCUMENT, &id).await +} + +/// `GET /api/ai/Document/{id}/getText` —— 取正文(存在 `f_way_json.content` 里)。 +pub async fn document_text( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let Some(row) = (match res::get(&state.db, &DOCUMENT, &id).await { + Ok(v) => v, + Err(e) => return db_error(e, "文档查询"), + }) else { + return fail(code::FAIL, "文档不存在"); + }; + let raw = row + .get("wayJson") + .and_then(Value::as_str) + .unwrap_or_default(); + let text = serde_json::from_str::(raw) + .ok() + .and_then(|v| { + v.get("content") + .or_else(|| v.get("text")) + .and_then(Value::as_str) + .map(str::to_string) + }) + .unwrap_or_default(); + ok(json!({ "text": text, "length": text.chars().count() })) +} + +/// `POST /api/ai/Document/{id}/section` —— 文档切片。 +/// +/// 🔴 **真做**:按空行/换行切成段,写回 `f_num`(片数);不产生向量。 +pub async fn document_section( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let text = obj + .get("text") + .or_else(|| obj.get("content")) + .and_then(Value::as_str) + .unwrap_or_default(); + let sections = split_sections(text); + let count = sections.len() as i64; + let mut payload = Map::new(); + payload.insert("text".into(), json!(text)); + payload.insert("sections".into(), json!(sections)); + if let Err(e) = state + .db + .exec_params( + "UPDATE base_ai_document SET f_num = $1::text::integer, f_way_json = $2::text, \ + f_last_modify_time = now(), f_last_modify_user_id = $3::text \ + WHERE f_id = $4::text AND COALESCE(f_delete_mark, 0) = 0", + &[ + &count.to_string(), + &Value::Object(payload.clone()).to_string(), + &user.account, + &id.trim(), + ], + ) + .await + { + return db_error(e, "文档切片"); + } + ok(json!({ "id": id, "num": count, "sections": payload["sections"].clone() })) +} + +/// `POST /api/ai/Document/{id}/study` —— 学习(本地切分 + 落 `f_state=1`)。 +pub async fn document_study( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let text = obj + .get("text") + .or_else(|| obj.get("content")) + .and_then(Value::as_str) + .unwrap_or_default(); + let sections = split_sections(text); + let payload = json!({ "text": text, "sections": sections, "engine": "local-keyword" }); + if let Err(e) = state + .db + .exec_params( + "UPDATE base_ai_document SET f_state = 1, f_num = $1::text::integer, \ + f_way_json = $2::text, f_last_modify_time = now(), \ + f_last_modify_user_id = $3::text \ + WHERE f_id = $4::text AND COALESCE(f_delete_mark, 0) = 0", + &[ + §ions.len().to_string(), + &payload.to_string(), + &user.account, + &id.trim(), + ], + ) + .await + { + return db_error(e, "文档学习"); + } + ok(json!({ + "id": id, + "num": sections.len(), + "engine": "local-keyword", + "msg": "已按关键词索引(本仓无向量库)", + })) +} + +/// 按空行 / 单换行切片;空文本 ⇒ 空。过长段落按 800 字符再切。 +fn split_sections(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for block in text.split('\n') { + let trimmed = block.trim(); + if trimmed.is_empty() { + continue; + } + if trimmed.chars().count() <= 800 { + out.push(trimmed.to_string()); + continue; + } + let mut buf = String::new(); + for ch in trimmed.chars() { + buf.push(ch); + if buf.chars().count() >= 800 { + out.push(std::mem::take(&mut buf)); + } + } + if !buf.trim().is_empty() { + out.push(buf); + } + } + out +} + +// ================================================================ Mcp + +pub async fn mcp_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &MCP, &raw, vec![]).await +} + +pub async fn mcp_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &MCP).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "MCP 下拉"), + } +} + +pub async fn mcp_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, + }; + res::create_json(&state, &MCP, &body, &user.account).await +} + +pub async fn mcp_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &MCP, &id).await +} + +pub async fn mcp_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, + }; + res::update_json(&state, &MCP, &id, &body, &user.account).await +} + +pub async fn mcp_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + if let Err(e) = state + .db + .exec_params( + "UPDATE base_ai_mcp_tool SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_mcp_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + return db_error(e, "删除 MCP 工具"); + } + res::delete_json(&state, &MCP, &id).await +} + +pub async fn mcp_by_ids( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let ids = match ids_of(&body) { + Ok(v) => v, + Err(resp) => return resp, + }; + match res::by_ids(&state.db, &MCP, &ids).await { + Ok(list) => ok(json!(list)), + Err(e) => db_error(e, "按 id 查 MCP"), + } +} + +/// `GET /api/ai/Mcp/Sync/{id}` —— 同步 MCP 工具清单。 +/// +/// 🔴 需要**主动连 MCP 服务**(HTTP/stdio)⇒ 本仓无 HTTP 客户端,明确失败。 +pub async fn mcp_sync( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::get(&state.db, &MCP, &id).await { + Ok(Some(_)) => {} + Ok(None) => return fail(code::FAIL, "MCP 不存在"), + Err(e) => return db_error(e, "MCP 查询"), + } + fail( + code::FAIL, + "本仓未接入 HTTP/stdio 客户端:无法连接 MCP 服务同步工具(集成期补)", + ) +} + +pub async fn mcp_tool_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_mcp_id AS \"mcpId\", f_full_name AS \"fullName\", \ + f_en_code AS \"enCode\", f_tool_json AS \"toolJson\", \ + f_description AS \"description\" \ + FROM base_ai_mcp_tool \ + WHERE f_mcp_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_full_name ASC", + &[&id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "MCP 工具列表"), + } +} + +// ================================================================ Serve + +pub async fn serve_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![res::filter(&raw, "agentId", "f_agent_id")]; + res::list_json(&state, &SERVE, &raw, filters).await +} + +pub async fn serve_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &SERVE).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "服务下拉"), + } +} + +pub async fn serve_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, + }; + res::create_json(&state, &SERVE, &body, &user.account).await +} + +pub async fn serve_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &SERVE, &id).await +} + +pub async fn serve_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, + }; + res::update_json(&state, &SERVE, &id, &body, &user.account).await +} + +pub async fn serve_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &SERVE, &id).await +} + +// ================================================================ Skills / Tool + +pub async fn skills_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &SKILLS, &raw, vec![]).await +} + +pub async fn skills_by_ids( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let ids = match ids_of(&body) { + Ok(v) => v, + Err(resp) => return resp, + }; + match res::by_ids(&state.db, &SKILLS, &ids).await { + Ok(list) => ok(json!(list)), + Err(e) => db_error(e, "按 id 查技能"), + } +} + +pub async fn skills_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &SKILLS, &id).await +} + +pub async fn tool_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &TOOL, &raw, vec![]).await +} + +pub async fn tool_by_ids( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let ids = match ids_of(&body) { + Ok(v) => v, + Err(resp) => return resp, + }; + match res::by_ids(&state.db, &TOOL, &ids).await { + Ok(list) => ok(json!(list)), + Err(e) => db_error(e, "按 id 查工具"), + } +} + +pub async fn tool_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &TOOL, &id).await +} + +// ================================================================ Chat + +/// `POST /api/ai/Chat/Send` —— 流式对话。 +/// +/// 🔴 **明确失败**:本仓没有 LLM 供应商配置表?有(`base_ai_supplier`),但**没有 +/// HTTP 客户端**,发不出请求。假装返回一段文本等于骗前端。 +/// 前端是 `responseType: 'stream'`,`fail` 返回的是普通 JSON —— vben 的 fetch +/// 适配器会把它当流读完并报「请求失败」,不会崩页面。 +pub async fn chat_send( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓未接入 LLM 推理服务:无法发起对话(AI 中心的元数据管理可用)", + ) +} + +pub async fn chat_translate( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail(code::FAIL, "本仓未接入 LLM 推理服务:无法翻译") +} + +pub async fn chat_optimize( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail(code::FAIL, "本仓未接入 LLM 推理服务:无法优化提示词") +} + +/// `GET /api/ai/Chat/Close/{id}` —— 终止流(幂等)。 +pub async fn chat_close( + State(state): State, + headers: HeaderMap, + Path(_id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + ok(Value::Null) +} + +/// `GET /api/ai/Chat/history/list` —— 会话列表(**裸数组**,前端 `res.data` 直接用)。 +pub async fn chat_history_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let keyword = qv(&raw, "keyword"); + let mut values: Vec> = vec![Some(user.account.clone())]; + let mut cond = String::from("COALESCE(f_delete_mark, 0) = 0 AND f_creator_user_id = $1::text"); + if !keyword.trim().is_empty() { + values.push(Some(format!("%{}%", keyword.trim()))); + cond.push_str(&format!( + " AND COALESCE(f_question_text, '') ILIKE $2::text" + )); + } + let sql = format!( + "SELECT f_chat_id AS \"id\", MIN(f_question_text) AS \"fullName\", \ + MAX(f_creator_time) AS \"lastTime\", COUNT(*)::bigint AS \"num\" \ + FROM base_ai_agent_history WHERE {cond} \ + GROUP BY f_chat_id ORDER BY MAX(f_creator_time) DESC NULLS LAST LIMIT 200" + ); + match state.db.query_json_params(&sql, ¶ms_of(&values)).await { + Ok(rows) => ok(json!(rows)), + Err(e) => db_error(e, "会话列表"), + } +} + +/// `GET /api/ai/Chat/history/get/{id}` —— 某个会话的全部消息(裸数组)。 +pub async fn chat_history_get( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_chat_id AS \"chatId\", f_question_text AS \"questionText\", \ + f_content AS \"content\", COALESCE(f_type, 0)::bigint AS \"type\", \ + f_knowledge_json AS \"knowledgeJson\", f_mcp_json AS \"mcpJson\", \ + f_tool_json AS \"toolJson\", f_skills_json AS \"skillsJson\", \ + (EXTRACT(EPOCH FROM f_creator_time) * 1000)::bigint AS \"creatorTime\" \ + FROM base_ai_agent_history \ + WHERE f_chat_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_creator_time ASC NULLS FIRST", + &[&id.trim()], + ) + .await + { + Ok(rows) => ok(json!(rows)), + Err(e) => db_error(e, "会话记录"), + } +} + +pub async fn chat_history_update( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let mut sets: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + for (key, col) in [("questionText", "f_question_text"), ("content", "f_content")] { + if let Some(v) = obj.get(key).and_then(Value::as_str) { + values.push(Some(v.to_string())); + sets.push(format!("{col} = ${}::text", values.len())); + } + } + if sets.is_empty() { + return fail(code::FAIL, "没有需要更新的字段"); + } + values.push(Some(id.trim().to_string())); + let id_at = values.len(); + let sql = format!( + "UPDATE base_ai_agent_history SET {}, f_last_modify_time = now() WHERE f_id = ${id_at}::text", + sets.join(", ") + ); + match state.db.exec_params(&sql, ¶ms_of(&values)).await { + Ok(_) => ok(json!({ "id": id })), + Err(e) => db_error(e, "更新会话记录"), + } +} + +pub async fn chat_history_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .exec_params( + "UPDATE base_ai_agent_history SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_chat_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + Ok(_) => ok(Value::Null), + Err(e) => db_error(e, "删除会话"), + } +} + +pub async fn chat_history_clean( + State(state): State, + headers: HeaderMap, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + match state + .db + .exec_params( + "UPDATE base_ai_agent_history SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_creator_user_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&user.account], + ) + .await + { + Ok(_) => ok(Value::Null), + Err(e) => db_error(e, "清空会话"), + } +} + +// ================================================================ 旧版 AI 建表单 / 流程 + +/// `POST /api/ai/visualdev` —— 老版「AI 生成表单」。 +/// +/// 本仓不做生成(没有 LLM);但**查询已有表单**是有意义的:返回表单定义, +/// 前端可以据此回填。没有 id 时如实失败。 +pub async fn ai_visualdev( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let Some(id) = obj + .get("id") + .or_else(|| obj.get("formId")) + .and_then(Value::as_str) + else { + return fail(code::FAIL, "本仓未接入 LLM:无法生成表单(可传 id 查已有表单)"); + }; + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_form_data AS \"formData\", f_column_data AS \"columnData\", \ + f_tables_data AS \"tablesData\" \ + FROM base_visual_dev WHERE f_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + &[&id.trim()], + ) + .await + { + Ok(rows) if !rows.is_empty() => ok(rows[0].clone()), + Ok(_) => fail(code::FAIL, "表单不存在"), + Err(e) => db_error(e, "表单查询"), + } +} + +/// `POST /api/ai/workflow` —— 老版「AI 生成流程」(同上,只支持按 id 查)。 +pub async fn ai_workflow( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let Some(id) = obj + .get("id") + .or_else(|| obj.get("templateId")) + .and_then(Value::as_str) + else { + return fail(code::FAIL, "本仓未接入 LLM:无法生成流程(可传 id 查已有模板)"); + }; + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \ + f_form_id AS \"formId\", COALESCE(f_type, 0)::bigint AS \"type\" \ + FROM workflow_template WHERE f_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + &[&id.trim()], + ) + .await + { + Ok(rows) if !rows.is_empty() => ok(rows[0].clone()), + Ok(_) => fail(code::FAIL, "流程模板不存在"), + Err(e) => db_error(e, "流程模板查询"), + } +} + +// ================================================================ 小工具 + +/// body 里的 `ids`(也接受 `idList`)。 +fn ids_of(body: &Bytes) -> Result, Json> { + let obj = match parse_body(body) { + Ok(Value::Object(o)) => o, + Ok(_) => return Err(fail(code::FAIL, "请求参数格式错误")), + Err(resp) => return Err(resp), + }; + let ids = obj + .get("ids") + .or_else(|| obj.get("idList")) + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect::>() + }) + .unwrap_or_default(); + Ok(ids) +} diff --git a/src/backend/src/platform/compat/extend.rs b/src/backend/src/platform/compat/extend.rs new file mode 100644 index 0000000..2aa8e1a --- /dev/null +++ b/src/backend/src/platform/compat/extend.rs @@ -0,0 +1,1465 @@ +//! extend —— 官方面 B 的**示例模块**端点集(`/api/extend/*`,64 条)。 +//! +//! 真源:官方 `jnpf-extend` Controller + 官方前端 `src/api/extend/**`。 +//! +//! 🔴 **这些是官方「示例/演示」页面**(CRM、销售订单、员工导入、甘特图、控件示例、 +//! 邮件)。本仓把它们**当真表做**(`ext_*` 15 张表),因为页面要能点、要能存。 +//! 唯一不做的是**需要外部通道**的动作: +//! | 动作 | 原因 | +//! |---|---| +//! | 发邮件 / 收邮件 / 检查邮箱 | 没有 SMTP/IMAP 客户端 | +//! | 员工导入 / 导出 / 模板下载 | 没有文件服务与 Excel 库 | +//! | 文档预览 | 没有文件服务 | +//! +//! 🔴 守卫:官方 `@SaCheckPermission("extend.*")`,本仓无对应菜单种子 ⇒ 登录即可。 + +use axum::body::Bytes; +use axum::extract::{Path, RawQuery, State}; +use axum::http::HeaderMap; +use axum::Json; +use serde_json::{json, Value}; + +use crate::platform::auth::require_login_face_b; +use crate::platform::envelope::{code, fail, ok, ActionResult}; +use crate::platform::state::AppState; + +use super::helper::{db_error, params_of, parse_body, qv, Paging}; +use super::res::{self, i, j, t, Res}; + +// ================================================================ 资源声明 + +const BIG_DATA: Res = Res { + table: "ext_big_data", + fields: &[ + t("fullName", "f_full_name"), + t("remark", "f_remark"), + i("num", "f_num"), + ], + keyword: &["f_full_name", "f_remark"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const CUSTOMER: Res = Res { + table: "ext_customer", + fields: &[ + t("customerName", "f_customer_name"), + t("contact", "f_contact"), + t("phone", "f_phone"), + t("address", "f_address"), + t("industry", "f_industry"), + ], + keyword: &["f_customer_name", "f_contact", "f_phone"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const CLASSIFY: Res = Res { + table: "ext_goods_classify", + fields: &[ + t("fullName", "f_full_name"), + t("parentId", "f_parent_id"), + ], + keyword: &["f_full_name"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const GOODS: Res = Res { + table: "ext_goods", + fields: &[ + t("goodsName", "f_goods_name"), + t("classifyId", "f_classify_id"), + t("price", "f_price"), + i("stock", "f_stock"), + t("unit", "f_unit"), + ], + keyword: &["f_goods_name"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const CRM_ORDER: Res = Res { + table: "ext_crm_order", + fields: &[ + t("orderNo", "f_order_no"), + t("customerId", "f_customer_id"), + t("customerName", "f_customer_name"), + t("orderDate", "f_order_date"), + t("total", "f_total"), + i("status", "f_status"), + t("remark", "f_remark"), + ], + keyword: &["f_order_no", "f_customer_name"], + order: "f_order_date DESC NULLS LAST", + scope: "", +}; + + +const EMAIL: Res = Res { + table: "ext_email", + fields: &[ + t("subject", "f_subject"), + t("body", "f_body"), + t("sender", "f_sender"), + t("receiver", "f_receiver"), + i("mailType", "f_mail_type"), + i("isRead", "f_is_read"), + i("isStar", "f_is_star"), + t("sendTime", "f_send_time"), + j("attachments", "f_attachments"), + ], + keyword: &["f_subject", "f_sender", "f_receiver"], + order: "COALESCE(f_send_time, '') DESC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const EMAIL_CONFIG: Res = Res { + table: "ext_email_config", + fields: &[ + t("email", "f_email"), + t("password", "f_password"), + t("smtpHost", "f_smtp_host"), + i("smtpPort", "f_smtp_port"), + t("imapHost", "f_imap_host"), + i("imapPort", "f_imap_port"), + i("ssl", "f_ssl"), + ], + keyword: &["f_email"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const EMPLOYEE: Res = Res { + table: "ext_employee", + fields: &[ + t("employeeNo", "f_employee_no"), + t("fullName", "f_full_name"), + i("gender", "f_gender"), + t("dept", "f_dept"), + t("position", "f_position"), + t("phone", "f_phone"), + t("email", "f_email"), + t("entryDate", "f_entry_date"), + ], + keyword: &["f_employee_no", "f_full_name", "f_dept"], + order: "f_employee_no ASC NULLS LAST", + scope: "", +}; + +const PROJECT: Res = Res { + table: "ext_project", + fields: &[ + t("projectName", "f_project_name"), + t("manager", "f_manager"), + t("startDate", "f_start_date"), + t("endDate", "f_end_date"), + i("status", "f_status"), + ], + keyword: &["f_project_name", "f_manager"], + order: "f_start_date DESC NULLS LAST", + scope: "", +}; + +const PROJECT_TASK: Res = Res { + table: "ext_project_task", + fields: &[ + t("projectId", "f_project_id"), + t("parentId", "f_parent_id"), + t("taskName", "f_task_name"), + t("startDate", "f_start_date"), + t("endDate", "f_end_date"), + i("progress", "f_progress"), + t("assignee", "f_assignee"), + i("status", "f_status"), + ], + keyword: &["f_task_name", "f_assignee"], + order: "f_start_date ASC NULLS LAST", + scope: "", +}; + +const TABLE_EXAMPLE: Res = Res { + table: "ext_table_example", + fields: &[ + t("fullName", "f_full_name"), + i("type", "f_type"), + t("industry", "f_industry"), + t("city", "f_city"), + t("sign", "f_sign"), + j("rowsJson", "f_rows_json"), + j("postilJson", "f_postil_json"), + ], + keyword: &["f_full_name", "f_industry", "f_city"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +const SALE_ORDER: Res = Res { + table: "ext_sale_product", + fields: &[ + t("orderNo", "f_order_no"), + t("customerId", "f_customer_id"), + t("customerName", "f_customer_name"), + t("orderDate", "f_order_date"), + t("total", "f_total"), + i("status", "f_status"), + ], + keyword: &["f_order_no", "f_customer_name"], + order: "f_order_date DESC NULLS LAST", + scope: "", +}; + +const SALE_ENTRY: Res = Res { + table: "ext_sale_product_entry", + fields: &[ + t("orderId", "f_order_id"), + t("goodsId", "f_goods_id"), + t("goodsName", "f_goods_name"), + i("qty", "f_qty"), + t("price", "f_price"), + t("amount", "f_amount"), + ], + keyword: &["f_goods_name"], + order: "f_creator_time ASC NULLS FIRST", + scope: "", +}; + +// ================================================================ BigData + +pub async fn big_data_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &BIG_DATA, &raw, vec![]).await +} + +/// `POST /api/extend/BigData` —— 前端**不带 body**(`createBigData()`), +/// 所以空 body 必须当成 `{}`,不能按「非法 JSON」拒。 +pub async fn big_data_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 = if body.is_empty() { + serde_json::Map::new() + } else { + match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + } + }; + match res::create(&state.db, &BIG_DATA, &obj, &user.account).await { + Ok(id) => ok(json!({ "id": id })), + Err(e) => db_error(e, "新增"), + } +} + +// ================================================================ CRM + +pub async fn crm_order_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![res::filter(&raw, "status", "f_status")]; + res::list_json(&state, &CRM_ORDER, &raw, filters).await +} + +pub async fn crm_customer_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &CUSTOMER, &raw, vec![]).await +} + +pub async fn crm_goods_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &GOODS, &raw, vec![]).await +} + +pub async fn crm_order_entries( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_order_id AS \"orderId\", f_goods_id AS \"goodsId\", \ + f_goods_name AS \"goodsName\", COALESCE(f_qty, 0)::bigint AS \"qty\", \ + f_price AS \"price\", f_amount AS \"amount\" \ + FROM ext_crm_order_entry WHERE f_order_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 ORDER BY f_creator_time ASC NULLS FIRST", + &[&id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "订单明细"), + } +} + +pub async fn crm_order_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_crm_order_entry SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_order_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + return db_error(e, "删除订单明细"); + } + res::delete_json(&state, &CRM_ORDER, &id).await +} + +pub async fn crm_order_plans( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_order_id AS \"orderId\", f_plan_date AS \"planDate\", \ + f_amount AS \"amount\", COALESCE(f_status, 0)::bigint AS \"status\", \ + f_remark AS \"remark\" \ + FROM ext_crm_collection_plan WHERE f_order_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 ORDER BY f_plan_date ASC NULLS LAST", + &[&id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "回款计划"), + } +} + +// ================================================================ DocumentPreview + +/// `GET /api/extend/DocumentPreview` —— 可预览文件清单(来自 `base_file`)。 +pub async fn document_preview_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let paging = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let mut values: Vec> = Vec::new(); + let mut cond = String::from("COALESCE(f_delete_mark, 0) = 0"); + if !keyword.trim().is_empty() { + values.push(Some(format!("%{}%", keyword.trim()))); + cond.push_str(" AND COALESCE(f_file_name, '') ILIKE $1::text"); + } + let total = state + .db + .query_json_params( + &format!("SELECT COUNT(*)::bigint AS \"total\" FROM base_file WHERE {cond}"), + ¶ms_of(&values), + ) + .await + .ok() + .and_then(|r| r.first().and_then(|v| v.get("total")).and_then(Value::as_i64)) + .unwrap_or(0); + values.push(Some(paging.page_size.to_string())); + let limit_at = values.len(); + values.push(Some(paging.offset.to_string())); + let offset_at = values.len(); + match state + .db + .query_json_params( + &format!( + "SELECT f_id AS \"id\", f_file_name AS \"fullName\", f_url AS \"url\", \ + COALESCE(f_type, 0)::bigint AS \"type\" \ + FROM base_file WHERE {cond} ORDER BY f_creator_time DESC NULLS LAST \ + LIMIT ${limit_at}::text::integer OFFSET ${offset_at}::text::integer" + ), + ¶ms_of(&values), + ) + .await + { + Ok(rows) => ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )), + Err(e) => db_error(e, "预览清单"), + } +} + +/// `GET /api/extend/DocumentPreview/{id}/Preview` —— 返回预览地址。 +/// +/// 🔴 本仓**没有文件服务**(无 `jnpf-file` 的 onlyoffice 预览)⇒ 明确失败。 +pub async fn document_preview( + State(state): State, + headers: HeaderMap, + Path(_id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓没有文件预览服务(onlyoffice):无法生成预览地址", + ) +} + +// ================================================================ Email + +pub async fn email_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![ + res::filter(&raw, "mailType", "f_mail_type"), + res::filter(&raw, "isRead", "f_is_read"), + res::filter(&raw, "isStar", "f_is_star"), + ]; + res::list_json(&state, &EMAIL, &raw, filters).await +} + +/// `POST /api/extend/Email` —— 发信。 +/// +/// 🔴 没有 SMTP ⇒ **不落「已发送」假记录**,明确失败。草稿走 `SaveDraft`(真存)。 +pub async fn email_send( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓未接入 SMTP:无法发信(草稿可以保存,收信需要 IMAP)", + ) +} + +pub async fn email_save_draft( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let mut obj = obj; + obj.insert("mailType".into(), json!(3)); + match res::create(&state.db, &EMAIL, &obj, &user.account).await { + Ok(id) => ok(json!({ "id": id })), + Err(e) => db_error(e, "保存草稿"), + } +} + +/// `GET /api/extend/Email/Config` —— 读邮箱配置(**口令不下发**)。 +pub async fn email_config_get( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let row = state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_email AS \"email\", f_smtp_host AS \"smtpHost\", \ + COALESCE(f_smtp_port, 0)::bigint AS \"smtpPort\", \ + f_imap_host AS \"imapHost\", COALESCE(f_imap_port, 0)::bigint AS \"imapPort\", \ + COALESCE(f_ssl, 0)::bigint AS \"ssl\", \ + COALESCE(f_password, '') AS \"password\" \ + FROM ext_email_config WHERE COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_creator_time ASC NULLS FIRST LIMIT 1", + &[], + ) + .await; + match row { + Ok(rows) => { + let mut out = rows.into_iter().next().unwrap_or_else(|| { + json!({ + "id": "email-config", "email": "", "smtpHost": "", "smtpPort": 465, + "imapHost": "", "imapPort": 993, "ssl": 1 + }) + }); + if let Some(o) = out.as_object_mut() { + let configured = o + .get("password") + .and_then(Value::as_str) + .map(|s| !s.is_empty()) + .unwrap_or(false); + o.insert("password".into(), Value::String(String::new())); + o.insert("passwordConfigured".into(), Value::Bool(configured)); + } + ok(out) + } + Err(e) => db_error(e, "邮箱配置"), + } +} + +/// `PUT /api/extend/Email/Config` —— 保存(单行 upsert;空口令不覆盖原值)。 +pub async fn email_config_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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let existing = state + .db + .query_json_params( + "SELECT f_id AS \"id\" FROM ext_email_config \ + WHERE COALESCE(f_delete_mark, 0) = 0 ORDER BY f_creator_time ASC NULLS FIRST LIMIT 1", + &[], + ) + .await + .unwrap_or_default(); + match existing.first().and_then(|r| r.get("id")).and_then(Value::as_str) { + Some(id) => { + let mut o = obj; + if o.get("password") + .and_then(Value::as_str) + .map(|s| s.trim().is_empty()) + .unwrap_or(true) + { + o.remove("password"); + } + match res::update(&state.db, &EMAIL_CONFIG, id, &o, &user.account).await { + Ok(true) => ok(json!({ "id": id })), + Ok(false) => fail(code::FAIL, "邮箱配置不存在"), + Err(e) => db_error(e, "保存邮箱配置"), + } + } + None => { + let mut o = obj; + o.insert("id".into(), json!("email-config")); + match res::create(&state.db, &EMAIL_CONFIG, &o, &user.account).await { + Ok(id) => ok(json!({ "id": id })), + Err(e) => db_error(e, "新建邮箱配置"), + } + } + } +} + +pub async fn email_check( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓未接入 SMTP/IMAP 客户端:无法检查邮箱连通性", + ) +} + +pub async fn email_receive( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail(code::FAIL, "本仓未接入 IMAP 客户端:无法收信") +} + +pub async fn email_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &EMAIL, &id).await +} + +pub async fn email_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &EMAIL, &id).await +} + +/// 读/未读/星标/取消星标共用一个实现(列 + 值由调用方给)。 +async fn set_email_flag( + state: &AppState, + id: &str, + col: &str, + value: i64, +) -> Json { + let sql = format!( + "UPDATE ext_email SET {col} = $1::text::integer, f_last_modify_time = now() \ + WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0" + ); + match state + .db + .exec_params(&sql, &[&value.to_string(), &id.trim()]) + .await + { + Ok(_) => ok(Value::Null), + Err(e) => db_error(e, "更新邮件状态"), + } +} + +pub async fn email_read( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + set_email_flag(&state, &id, "f_is_read", 1).await +} + +pub async fn email_unread( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + set_email_flag(&state, &id, "f_is_read", 0).await +} + +pub async fn email_star( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + set_email_flag(&state, &id, "f_is_star", 1).await +} + +pub async fn email_unstar( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + set_email_flag(&state, &id, "f_is_star", 0).await +} + +// ================================================================ Employee + +pub async fn employee_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &EMPLOYEE, &raw, vec![]).await +} + +pub async fn employee_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &EMPLOYEE, &id).await +} + +/// 导出 / 模板 / 导入 / 预览 —— 4 条都需要**文件服务 + Excel 库** ⇒ 明确失败。 +pub async fn export_unsupported( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓没有文件服务与 Excel 库:导出 / 导入 / 模板下载不可用", + ) +} + +// ================================================================ ProjectGantt + +pub async fn project_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &PROJECT, &raw, vec![]).await +} + +pub async fn project_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, + }; + res::create_json(&state, &PROJECT, &body, &user.account).await +} + +pub async fn project_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &PROJECT, &id).await +} + +pub async fn project_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, + }; + res::update_json(&state, &PROJECT, &id, &body, &user.account).await +} + +pub async fn project_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_project_task SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_project_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + return db_error(e, "删除项目任务"); + } + res::delete_json(&state, &PROJECT, &id).await +} + +pub async fn project_task_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let paging = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let mut values: Vec> = vec![Some(id.trim().to_string())]; + let mut cond = String::from( + "f_project_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + ); + if !keyword.trim().is_empty() { + values.push(Some(format!("%{}%", keyword.trim()))); + cond.push_str(" AND COALESCE(f_task_name, '') ILIKE $2::text"); + } + let total = state + .db + .query_json_params( + &format!("SELECT COUNT(*)::bigint AS \"total\" FROM ext_project_task WHERE {cond}"), + ¶ms_of(&values), + ) + .await + .ok() + .and_then(|r| r.first().and_then(|v| v.get("total")).and_then(Value::as_i64)) + .unwrap_or(0); + values.push(Some(paging.page_size.to_string())); + let limit_at = values.len(); + values.push(Some(paging.offset.to_string())); + let offset_at = values.len(); + match state + .db + .query_json_params( + &format!( + "SELECT f_id AS \"id\", f_project_id AS \"projectId\", \ + f_parent_id AS \"parentId\", f_task_name AS \"taskName\", \ + f_start_date AS \"startDate\", f_end_date AS \"endDate\", \ + COALESCE(f_progress, 0)::bigint AS \"progress\", \ + f_assignee AS \"assignee\", COALESCE(f_status, 0)::bigint AS \"status\" \ + FROM ext_project_task WHERE {cond} \ + ORDER BY f_start_date ASC NULLS LAST \ + LIMIT ${limit_at}::text::integer OFFSET ${offset_at}::text::integer" + ), + ¶ms_of(&values), + ) + .await + { + Ok(rows) => ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )), + Err(e) => db_error(e, "任务列表"), + } +} + +/// `GET /api/extend/ProjectGantt/{id}/Task/Selector/{taskId}` —— 父任务候选 +/// (排除自己,避免把自己挂成自己的父级)。 +pub async fn project_task_selector( + State(state): State, + headers: HeaderMap, + Path((id, task_id)): Path<(String, String)>, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_task_name AS \"fullName\", f_parent_id AS \"parentId\" \ + FROM ext_project_task WHERE f_project_id = $1::text AND f_id <> $2::text \ + AND COALESCE(f_delete_mark, 0) = 0 ORDER BY f_start_date ASC NULLS LAST", + &[&id.trim(), &task_id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "父任务候选"), + } +} + +pub async fn project_task_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, + }; + res::create_json(&state, &PROJECT_TASK, &body, &user.account).await +} + +pub async fn project_task_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &PROJECT_TASK, &id).await +} + +pub async fn project_task_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, + }; + res::update_json(&state, &PROJECT_TASK, &id, &body, &user.account).await +} + +// ================================================================ TableExample + +pub async fn table_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![res::filter(&raw, "type", "f_type")]; + res::list_json(&state, &TABLE_EXAMPLE, &raw, filters).await +} + +pub async fn table_all( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &TABLE_EXAMPLE).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "控件示例列表"), + } +} + +pub async fn table_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, + }; + res::create_json(&state, &TABLE_EXAMPLE, &body, &user.account).await +} + +pub async fn table_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &TABLE_EXAMPLE, &id).await +} + +pub async fn table_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, + }; + res::update_json(&state, &TABLE_EXAMPLE, &id, &body, &user.account).await +} + +pub async fn table_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::delete_json(&state, &TABLE_EXAMPLE, &id).await +} + +/// `PUT /api/extend/TableExample/UpdateSign/{id}` —— 改「标记」列。 +pub async fn table_update_sign( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let sign = obj + .get("sign") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + match state + .db + .exec_params( + "UPDATE ext_table_example SET f_sign = $1::text, f_last_modify_time = now() \ + WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0", + &[&sign, &id.trim()], + ) + .await + { + Ok(_) => ok(Value::Null), + Err(e) => db_error(e, "更新标记"), + } +} + +/// `PUT /api/extend/TableExample/{id}/Actions/RowsEdit` —— 保存可编辑表格行。 +pub async fn table_rows_edit( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let rows = obj.get("rows").cloned().unwrap_or_else(|| json!([])); + match state + .db + .exec_params( + "UPDATE ext_table_example SET f_rows_json = $1::text, f_last_modify_time = now() \ + WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0", + &[&rows.to_string(), &id.trim()], + ) + .await + { + Ok(_) => ok(Value::Null), + Err(e) => db_error(e, "保存表格行"), + } +} + +/// 读 `f_postil_json`(批注数组);坏 JSON ⇒ 空数组(不 500)。 +fn postils_of(raw: Option<&str>) -> Vec { + raw.and_then(|s| serde_json::from_str::(s).ok()) + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default() +} + +async fn load_postils(state: &AppState, id: &str) -> Result, Json> { + let rows = state + .db + .query_json_params( + "SELECT COALESCE(f_postil_json, '') AS \"raw\" FROM ext_table_example \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + &[&id.trim()], + ) + .await + .map_err(|e| db_error(e, "批注查询"))?; + let Some(row) = rows.first() else { + return Err(fail(code::FAIL, "数据不存在")); + }; + Ok(postils_of(row.get("raw").and_then(Value::as_str))) +} + +async fn save_postils( + state: &AppState, + id: &str, + list: &[Value], +) -> Result<(), Json> { + let text = Value::Array(list.to_vec()).to_string(); + state + .db + .exec_params( + "UPDATE ext_table_example SET f_postil_json = $1::text, f_last_modify_time = now() \ + WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0", + &[&text, &id.trim()], + ) + .await + .map_err(|e| db_error(e, "保存批注"))?; + Ok(()) +} + +pub async fn table_postil_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match load_postils(&state, &id).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(resp) => resp, + } +} + +pub async fn table_postil_add( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let content = obj + .get("content") + .or_else(|| obj.get("text")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + if content.trim().is_empty() { + return fail(code::FAIL, "批注内容不能为空"); + } + let mut list = match load_postils(&state, &id).await { + Ok(v) => v, + Err(resp) => return resp, + }; + list.push(json!({ + "index": list.len() + 1, + "content": content, + "creatorUserId": user.account, + "creatorTime": chrono::Utc::now().timestamp_millis(), + })); + match save_postils(&state, &id, &list).await { + Ok(_) => ok(Value::Null), + Err(resp) => resp, + } +} + +pub async fn table_postil_delete( + State(state): State, + headers: HeaderMap, + Path((id, index)): Path<(String, String)>, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let idx = index.trim().parse::().unwrap_or(0); + if idx == 0 { + return fail(code::FAIL, "批注序号不合法"); + } + let mut list = match load_postils(&state, &id).await { + Ok(v) => v, + Err(resp) => return resp, + }; + if idx > list.len() { + return fail(code::FAIL, "批注不存在"); + } + list.remove(idx - 1); + // 删除后重排 index(前端按 index 删除)。 + for (i, item) in list.iter_mut().enumerate() { + if let Some(o) = item.as_object_mut() { + o.insert("index".into(), json!(i + 1)); + } + } + match save_postils(&state, &id, &list).await { + Ok(_) => ok(Value::Null), + Err(resp) => resp, + } +} + +/// `GET /api/extend/TableExample/CityList/{id}` —— 省下的市(`base_province` 子节点)。 +pub async fn table_city_list( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\" FROM base_province \ + WHERE COALESCE(f_parent_id, '-1') = $1::text AND COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY COALESCE(f_sort_code, 0) ASC, f_full_name ASC", + &[&id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "城市列表"), + } +} + +/// `GET /api/extend/TableExample/IndustryList` —— 行业(**静态选项**,官方也是常量表)。 +pub async fn table_industry_list( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let items = [ + ("1", "互联网"), + ("2", "制造业"), + ("3", "金融"), + ("4", "教育"), + ("5", "医疗"), + ("6", "零售"), + ("7", "建筑"), + ("8", "其他"), + ]; + let list: Vec = items + .iter() + .map(|(id, name)| json!({ "id": id, "fullName": name })) + .collect(); + ok(super::helper::list_vo(list)) +} + +/// `GET /api/extend/TableExample/ControlSample/{id}` —— 按控件类型取示例行。 +pub async fn table_control_sample( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![("f_type", id.trim().to_string())]; + let paging = Paging::of(&RawQuery(None)); + match res::page(&state.db, &TABLE_EXAMPLE, &paging, "", &filters).await { + Ok(v) => ok(v), + Err(e) => db_error(e, "控件示例"), + } +} + +// ================================================================ saleOrder + +pub async fn sale_classify_list( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &CLASSIFY).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "商品分类"), + } +} + +pub async fn sale_customer_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &CUSTOMER, &raw, vec![]).await +} + +pub async fn sale_goods_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &GOODS, &raw, vec![]).await +} + +pub async fn sale_goods_selector( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let paging = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + match res::page(&state.db, &GOODS, &paging, &keyword, &[]).await { + Ok(v) => ok(v), + Err(e) => db_error(e, "商品下拉"), + } +} + +/// `GET /api/extend/saleOrder/Goods/getGoodList?type=` —— 按分类取商品。 +pub async fn sale_goods_by_type( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let classify = qv(&raw, "type"); + let filters = vec![("f_classify_id", classify)]; + let paging = Paging::of(&RawQuery(None)); + match res::page(&state.db, &GOODS, &paging, "", &filters).await { + Ok(v) => ok(v), + Err(e) => db_error(e, "按分类取商品"), + } +} + +pub async fn sale_order_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &SALE_ORDER, &raw, vec![]).await +} + +pub async fn sale_order_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &SALE_ORDER, &id).await +} + +pub async fn sale_order_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, + }; + res::update_json(&state, &SALE_ORDER, &id, &body, &user.account).await +} + +pub async fn sale_order_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_sale_product_entry SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_order_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id.trim()], + ) + .await + { + return db_error(e, "删除订单明细"); + } + res::delete_json(&state, &SALE_ORDER, &id).await +} + +pub async fn sale_order_entries( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_order_id AS \"orderId\", f_goods_id AS \"goodsId\", \ + f_goods_name AS \"goodsName\", COALESCE(f_qty, 0)::bigint AS \"qty\", \ + f_price AS \"price\", f_amount AS \"amount\" \ + FROM ext_sale_product_entry WHERE f_order_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 ORDER BY f_creator_time ASC NULLS FIRST", + &[&id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "销售订单明细"), + } +} + +/// `POST /api/extend/saleOrder/Product` 的明细一起落库(前端提交 `goodsList`)。 +/// +/// 🔴 主表走泛型 CRUD;明细必须**同一事务**里写?pglite 单连接串行 ⇒ 逐条写即可, +/// 中途失败会把主表也软删(下面有补偿),不留「有单无明细」。 +pub async fn sale_order_create_with_entries( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let entries: Vec = obj + .get("goodsList") + .or_else(|| obj.get("productEntry")) + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let mut main = obj.clone(); + main.remove("goodsList"); + main.remove("productEntry"); + let id = match res::create(&state.db, &SALE_ORDER, &main, &user.account).await { + Ok(v) => v, + Err(e) => return db_error(e, "新建销售订单"), + }; + for item in entries { + let Some(mut eo) = item.as_object().cloned() else { + continue; + }; + eo.insert("orderId".into(), json!(id)); + if let Err(e) = res::create(&state.db, &SALE_ENTRY, &eo, &user.account).await { + // 补偿:主表软删,避免「有单无明细」。 + let _ = res::remove(&state.db, &SALE_ORDER, &id).await; + return db_error(e, "新建订单明细"); + } + } + ok(json!({ "id": id })) +} diff --git a/src/backend/src/platform/compat/mod.rs b/src/backend/src/platform/compat/mod.rs index 897b710..4ab4b60 100644 --- a/src/backend/src/platform/compat/mod.rs +++ b/src/backend/src/platform/compat/mod.rs @@ -27,3 +27,7 @@ pub mod online_dev; pub mod report; pub mod workflow; pub mod msg_center; +pub mod ai; +pub mod res; +pub mod extend; +pub mod teamwork; diff --git a/src/backend/src/platform/compat/res.rs b/src/backend/src/platform/compat/res.rs new file mode 100644 index 0000000..67e3b16 --- /dev/null +++ b/src/backend/src/platform/compat/res.rs @@ -0,0 +1,460 @@ +//! res —— 契约面的**通用资源引擎**(批次 21–23 引入)。 +//! +//! 🔴 **为什么存在**:`aiCenter` / `extend` / `teamwork` 三族合计 **179 条**端点, +//! 其中约 150 条是「同一张表的 list / info / create / update / delete」。 +//! 逐条手写 SQL 会让三个模块各膨胀 2000 行,且**改一处漏两处**。 +//! ⇒ 把「表名 + 列映射 + 关键词列 + 排序」声明成 [`Res`],SQL 只在这里生成一次。 +//! +//! 🔴 **边界(不许越)**: +//! - 只管**单表 CRUD**。有业务语义的动作(发布、复制版本、回收站、分享)仍在模块里手写。 +//! - 不认识的 JSON 键**静默忽略**(官方 DTO 与表列名不完全一致,多余键不该 500)。 +//! - 所有值走 `$N` 绑定;表名/列名来自**编译期常量**,不接收用户输入。 +//! - 业务失败恒 HTTP 200 + 信封(由调用方 `ok/fail` 决定)。 +//! +//! 🔴 **几种列的读写口径**: +//! | Kind | 读 | 写 | +//! |---|---|---| +//! | `Text` | 原样 | `$N::text` | +//! | `Int` | `COALESCE(col,0)::bigint` | `$N::text::bigint` | +//! | `Json` | 原样(TEXT 里的 JSON 字符串,前端自己 parse) | 对象/数组先 `to_string()` | + +use axum::body::Bytes; +use axum::extract::RawQuery; +use axum::Json; +use serde_json::{json, Map, Value}; + +use crate::platform::db::{pglite, Db}; +use crate::platform::envelope::{code, fail, ok, ActionResult}; +use crate::platform::ids::new_uuid; +use crate::platform::state::AppState; + +use super::helper::{db_error, params_of, parse_body, qv, Paging}; + +/// 列类型(决定投影与写入的 SQL 形状)。 +#[derive(Clone, Copy)] +pub(super) enum Kind { + Text, + Int, + Json, +} + +/// 一列的映射:JSON 键 ↔ 物理列。 +pub(super) struct Field { + pub json: &'static str, + pub col: &'static str, + pub kind: Kind, +} + +/// `Field` 的简写构造(模块里用 `t("fullName", "f_full_name")` 声明)。 +pub(super) const fn t(json: &'static str, col: &'static str) -> Field { + Field { + json, + col, + kind: Kind::Text, + } +} + +pub(super) const fn i(json: &'static str, col: &'static str) -> Field { + Field { + json, + col, + kind: Kind::Int, + } +} + +pub(super) const fn j(json: &'static str, col: &'static str) -> Field { + Field { + json, + col, + kind: Kind::Json, + } +} + +/// 一张资源的声明。 +pub(super) struct Res { + pub table: &'static str, + pub fields: &'static [Field], + /// 关键词搜索的列(空 = 不支持 keyword)。 + pub keyword: &'static [&'static str], + /// `ORDER BY` 片段(不含 `ORDER BY`)。 + pub order: &'static str, + /// 额外过滤(固定作用域,如 `COALESCE(f_type,1)=1`)。 + pub scope: &'static str, +} + +impl Res { + fn projection(&self) -> String { + // 🔴 `f_id` 必须在投影里:列表页要靠它点「编辑 / 删除」。 + // 业务模块的 `EntitySpec` 也走同一条规则(`crud::projection` 恒带 id)。 + let mut cols = vec!["f_id AS \"id\"".to_string()]; + cols.extend(self.fields.iter().map(|f| match f.kind { + Kind::Text | Kind::Json => format!("{} AS \"{}\"", f.col, f.json), + Kind::Int => format!("COALESCE({},0)::bigint AS \"{}\"", f.col, f.json), + })); + cols.join(", ") + } + + fn order_clause(&self) -> String { + if self.order.is_empty() { + "f_creator_time DESC NULLS LAST".to_string() + } else { + self.order.to_string() + } + } +} + +/// 写参数:JSON 值 ⇒ 绑定值。 +/// +/// 🔴 对象/数组**必须序列化**:`crud::value_to_text` 只认 string/number/bool, +/// 直接传对象会被静默丢弃(MCP 扩面时踩过一次)。 +fn param_of(v: &Value) -> Option { + match v { + Value::Null => None, + Value::String(s) => Some(s.clone()), + Value::Bool(b) => Some(if *b { "1".to_string() } else { "0".to_string() }), + Value::Number(n) => Some(n.to_string()), + other => Some(other.to_string()), + } +} + +fn placeholder(index: usize, kind: Kind) -> String { + match kind { + Kind::Text | Kind::Json => format!("${index}::text"), + Kind::Int => format!("${index}::text::bigint"), + } +} + +/// 拼 `WHERE`:软删 + 固定作用域 + 等值过滤 + 关键词。 +fn where_clause( + res: &Res, + keyword: &str, + filters: &[(&str, String)], + values: &mut Vec>, +) -> String { + let mut conds: Vec = vec!["COALESCE(f_delete_mark, 0) = 0".to_string()]; + if !res.scope.is_empty() { + conds.push(res.scope.to_string()); + } + for (col, val) in filters { + if val.is_empty() { + continue; + } + values.push(Some(val.clone())); + conds.push(format!("CAST({col} AS text) = ${}", values.len())); + } + if !keyword.trim().is_empty() && !res.keyword.is_empty() { + values.push(Some(format!("%{}%", keyword.trim()))); + let at = values.len(); + let ors = res + .keyword + .iter() + .map(|c| format!("COALESCE({c}, '') ILIKE ${at}")) + .collect::>() + .join(" OR "); + conds.push(format!("({ors})")); + } + conds.join(" AND ") +} + +/// 分页查询 ⇒ 官方 `PageListVO`(`{pagination, list}`)。 +pub(super) async fn page( + db: &Db, + res: &Res, + paging: &Paging, + keyword: &str, + filters: &[(&str, String)], +) -> Result { + let mut values: Vec> = Vec::new(); + let where_sql = where_clause(res, keyword, filters, &mut values); + let count_sql = format!( + "SELECT COUNT(*)::bigint AS \"total\" FROM {} WHERE {where_sql}", + res.table + ); + let total = db + .query_json_params(&count_sql, ¶ms_of(&values)) + .await? + .first() + .and_then(|r| r.get("total")) + .and_then(Value::as_i64) + .unwrap_or(0); + + values.push(Some(paging.page_size.to_string())); + let limit_at = values.len(); + values.push(Some(paging.offset.to_string())); + let offset_at = values.len(); + let sql = format!( + "SELECT {} FROM {} WHERE {where_sql} ORDER BY {} \ + LIMIT ${limit_at}::text::integer OFFSET ${offset_at}::text::integer", + res.projection(), + res.table, + res.order_clause() + ); + let rows = db.query_json_params(&sql, ¶ms_of(&values)).await?; + Ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )) +} + +/// 不分页的 `ListVO`。 +pub(super) async fn all(db: &Db, res: &Res) -> Result, pglite::Error> { + let sql = format!( + "SELECT {} FROM {} WHERE COALESCE(f_delete_mark, 0) = 0 {} ORDER BY {}", + res.projection(), + res.table, + if res.scope.is_empty() { + String::new() + } else { + format!("AND {}", res.scope) + }, + res.order_clause() + ); + db.query_json_params(&sql, &[]).await +} + +/// 按 id 取详情(软删的不算)。 +pub(super) async fn get(db: &Db, res: &Res, id: &str) -> Result, pglite::Error> { + let sql = format!( + "SELECT {} FROM {} WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + res.projection(), + res.table + ); + Ok(db + .query_json_params(&sql, &[&id.trim()]) + .await? + .into_iter() + .next()) +} + +/// 新增 ⇒ 新 id。 +pub(super) async fn create( + db: &Db, + res: &Res, + obj: &Map, + user: &str, +) -> Result { + let id = obj + .get("id") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .unwrap_or_else(new_uuid); + + let mut cols: Vec<&'static str> = Vec::new(); + let mut slots: Vec = Vec::new(); + let mut values: Vec> = vec![Some(id.clone())]; + for f in res.fields { + let Some(v) = obj.get(f.json) else { continue }; + let Some(text) = param_of(v) else { continue }; + cols.push(f.col); + values.push(Some(text)); + slots.push(placeholder(values.len(), f.kind)); + } + let col_sql = if cols.is_empty() { + String::new() + } else { + format!(", {}", cols.join(", ")) + }; + let val_sql = if slots.is_empty() { + String::new() + } else { + format!(", {}", slots.join(", ")) + }; + values.push(Some(user.to_string())); + let user_at = values.len(); + let sql = format!( + "INSERT INTO {} (f_id{col_sql}, f_delete_mark, f_tenant_id, f_creator_time, \ + f_creator_user_id) VALUES ($1{val_sql}, 0, '0', now(), ${user_at}::text)", + res.table + ); + db.exec_params(&sql, ¶ms_of(&values)).await?; + Ok(id) +} + +/// 更新(只改 body 里出现的键)⇒ 是否命中。 +pub(super) async fn update( + db: &Db, + res: &Res, + id: &str, + obj: &Map, + user: &str, +) -> Result { + let mut sets: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + for f in res.fields { + let Some(v) = obj.get(f.json) else { continue }; + values.push(param_of(v)); + sets.push(format!("{} = {}", f.col, placeholder(values.len(), f.kind))); + } + if sets.is_empty() { + return Ok(false); + } + values.push(Some(user.to_string())); + let user_at = values.len(); + values.push(Some(id.trim().to_string())); + let id_at = values.len(); + let sql = format!( + "UPDATE {} SET {}, f_last_modify_time = now(), f_last_modify_user_id = ${user_at}::text \ + WHERE f_id = ${id_at}::text AND COALESCE(f_delete_mark, 0) = 0", + res.table, + sets.join(", ") + ); + let before = db + .query_json_params( + &format!( + "SELECT f_id AS \"id\" FROM {} WHERE f_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + res.table + ), + &[&id.trim()], + ) + .await?; + if before.is_empty() { + return Ok(false); + } + db.exec_params(&sql, ¶ms_of(&values)).await?; + Ok(true) +} + +/// 软删。 +pub(super) async fn remove(db: &Db, res: &Res, id: &str) -> Result { + let before = db + .query_json_params( + &format!( + "SELECT f_id AS \"id\" FROM {} WHERE f_id = $1::text \ + AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + res.table + ), + &[&id.trim()], + ) + .await?; + if before.is_empty() { + return Ok(false); + } + db.exec_params( + &format!( + "UPDATE {} SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + res.table + ), + &[&id.trim()], + ) + .await?; + Ok(true) +} + +// ================================================================ handler 包装 +// +// 🔴 守卫**留在 handler 里**(不藏进包装函数):`check-contract` 的 CC6 靠 +// 「handler 体内有 `require_login_face_b(...)`」推导守卫,藏进去就会推不出。 + +/// 列表(分页)—— 把 DB 错误转成信封。 +pub(super) async fn list_json( + state: &AppState, + res: &Res, + raw: &RawQuery, + filters: Vec<(&str, String)>, +) -> Json { + let paging = Paging::of(raw); + let keyword = qv(raw, "keyword"); + match page(&state.db, res, &paging, &keyword, &filters).await { + Ok(v) => ok(v), + Err(e) => db_error(e, "列表查询"), + } +} + +/// 详情。 +pub(super) async fn info_json(state: &AppState, res: &Res, id: &str) -> Json { + match get(&state.db, res, id).await { + Ok(Some(row)) => ok(row), + Ok(None) => fail(code::FAIL, "数据不存在"), + Err(e) => db_error(e, "详情查询"), + } +} + +/// 新增。 +pub(super) async fn create_json( + state: &AppState, + res: &Res, + body: &Bytes, + user: &str, +) -> Json { + let obj = match parse_body(body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + match create(&state.db, res, &obj, user).await { + Ok(id) => ok(json!({ "id": id })), + Err(e) => db_error(e, "新增"), + } +} + +/// 更新。 +pub(super) async fn update_json( + state: &AppState, + res: &Res, + id: &str, + body: &Bytes, + user: &str, +) -> Json { + let obj = match parse_body(body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + if obj + .iter() + .all(|(k, _)| !res.fields.iter().any(|f| f.json == k)) + { + return fail(code::FAIL, "没有需要更新的字段"); + } + match update(&state.db, res, id, &obj, user).await { + Ok(true) => ok(json!({ "id": id })), + Ok(false) => fail(code::FAIL, "数据不存在"), + Err(e) => db_error(e, "更新"), + } +} + +/// 软删。 +pub(super) async fn delete_json(state: &AppState, res: &Res, id: &str) -> Json { + match remove(&state.db, res, id).await { + Ok(true) => ok(Value::Null), + Ok(false) => fail(code::FAIL, "数据不存在"), + Err(e) => db_error(e, "删除"), + } +} + +/// `SELECT ... WHERE IN (...)` 的小工具(`getListByIds` 用)。 +pub(super) async fn by_ids( + db: &Db, + res: &Res, + ids: &[String], +) -> Result, pglite::Error> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let mut values: Vec> = Vec::new(); + let mut slots: Vec = Vec::new(); + for id in ids { + values.push(Some(id.clone())); + slots.push(format!("${}::text", values.len())); + } + let sql = format!( + "SELECT {} FROM {} WHERE f_id IN ({}) AND COALESCE(f_delete_mark, 0) = 0", + res.projection(), + res.table, + slots.join(", ") + ); + db.query_json_params(&sql, ¶ms_of(&values)).await +} + +// 供各模块构造「过滤条件」用(`qv` 在 helper 里)。 +pub(super) fn filter(raw: &RawQuery, key: &str, col: &'static str) -> (&'static str, String) { + (col, qv(raw, key)) +} + + diff --git a/src/backend/src/platform/compat/system.rs b/src/backend/src/platform/compat/system.rs index 92733e4..96ac24b 100644 --- a/src/backend/src/platform/compat/system.rs +++ b/src/backend/src/platform/compat/system.rs @@ -6749,6 +6749,53 @@ pub async fn dataset_list( )) } +/// `GET /api/system/Dataset/Selector` —— 数据集下拉(`ListVO`)。 +/// +/// 🔴 官方 `DatasetController.selector` 只回 `id/fullName/enCode/type` 四列; +/// 弹窗选择控件走的是另一条 `getList`(带 `parameterJson` / `fields`)。 +pub async fn dataset_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_DATASET).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", \ + COALESCE(f_en_code, '') AS \"enCode\", \ + COALESCE(f_type, 0)::bigint AS \"type\" \ + FROM base_data_set WHERE COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY COALESCE(f_sort_code, 0) ASC, f_full_name ASC", + &[], + ) + .await + { + Ok(list) => ok(list_vo(list)), + Err(e) => db_error(e, "数据集下拉"), + } +} + +/// `GET /api/system/DatasetLog/{id}` —— 数据集执行日志。 +/// +/// 🔴 本仓**不落数据集执行日志**(`data 集` 的预览/接口调用没有审计表)⇒ +/// 如实返回**空分页**,而不是编造记录。集成期补 `base_data_set_log` 后 +/// 这里改成真查询即可(契约台账标 `partial`)。 +pub async fn dataset_log( + State(state): State, + headers: HeaderMap, + Path(id): Path, + raw: RawQuery, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_DATASET).await { + return resp; + } + let paging = Paging::of(&raw); + let _ = id; + ok(page_list(paging.current_page, paging.page_size, 0, vec![])) +} + /// `GET /api/system/Dataset/getList` —— 弹窗数据集选择控件(`DataSetSelectVO`)。 /// /// 与列表的差别:① 官方**没有** `@SaCheckPermission`(登录即可); @@ -9397,6 +9444,70 @@ pub async fn interface_oauth_get_interface_list( ok(json!(io_itf_list(&state, &data_interface_ids).await)) } +/// `POST /api/system/InterfaceOauth/saveInterfaceList` —— 保存认证接口清单。 +/// +/// body:`{ id, dataInterfaceIds }`(`dataInterfaceIds` 是逗号分隔字符串, +/// 与 `getInterfaceList` 的入参同一口径;也接受数组形式)。 +pub async fn interface_oauth_save_interface_list( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + let user = match guard(&state, &headers, EN_INTERFACE_OAUTH).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match parse_body(&body) { + Ok(Value::Object(obj)) => obj, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let id = obj + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .trim() + .to_string(); + if id.is_empty() { + return fail(code::FAIL, "接口认证 id 不能为空"); + } + let ids = match obj.get("dataInterfaceIds") { + Some(Value::String(s)) => s.clone(), + Some(Value::Array(arr)) => arr + .iter() + .filter_map(Value::as_str) + .collect::>() + .join(","), + _ => String::new(), + }; + let sql = "UPDATE base_data_interface_oauth SET f_data_interface_ids = $1, \ + f_last_modify_time = now(), f_last_modify_user_id = $2 \ + WHERE f_id = $3 AND COALESCE(f_delete_mark, 0) = 0"; + let exists = match state + .db + .query_json_params( + "SELECT f_id AS \"id\" FROM base_data_interface_oauth \ + WHERE f_id = $1 AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + ¶ms_of(&[Some(id.clone())]), + ) + .await + { + Ok(rows) => !rows.is_empty(), + Err(e) => return db_error(e, "查询接口认证"), + }; + if !exists { + return fail(code::FAIL, "数据不存在"); + } + match state + .db + .exec_params(sql, ¶ms_of(&[Some(ids), Some(user.user_id), Some(id)])) + .await + { + Ok(()) => ok(Value::Null), + Err(e) => db_error(e, "保存接口清单"), + } +} + /// 调用日志列表(按 `appId` 过滤)。 pub async fn interface_oauth_data_interface_log( State(state): State, diff --git a/src/backend/src/platform/compat/teamwork.rs b/src/backend/src/platform/compat/teamwork.rs new file mode 100644 index 0000000..4f63fcc --- /dev/null +++ b/src/backend/src/platform/compat/teamwork.rs @@ -0,0 +1,1344 @@ +//! teamwork —— 官方面 B 的**团队协作**端点集(40 条): +//! 文件(`/api/file/Document` 25)、文件空间(`/api/file/DocumentSpace` 9)、 +//! 日程(`/api/system/Schedule` 6)。 +//! +//! 真源:官方 `jnpf-file` 的 `DocumentController` / `DocumentSpaceController` + +//! `jnpf-system` 的 `ScheduleNewController` + 官方前端 `api/teamwork/**`。 +//! +//! 🔴 **文件只存元数据**:本仓没有对象存储 / onlyoffice ⇒ +//! | 端点 | 行为 | +//! |---|---| +//! | 文件夹 / 改名 / 移动 / 复制 / 分享 / 回收站 / 最近 / 标签 | **真落库** | +//! | `UploadBlob` / `PackDownload` / `merge` | **明确业务失败**(没有文件服务) | +//! +//! 🔴 守卫:登录(官方是 `@SaCheckPermission("file.*")`,本仓无对应菜单种子)。 + +use axum::body::Bytes; +use axum::extract::{Path, RawQuery, State}; +use axum::http::HeaderMap; +use axum::Json; +use serde_json::{json, Map, Value}; + +use crate::platform::auth::require_login_face_b; +use crate::platform::envelope::{code, fail, ok, ActionResult}; +use crate::platform::ids::new_uuid; +use crate::platform::state::AppState; + +use super::helper::{db_error, params_of, parse_body, qv, Paging}; +use super::res::{self, i, t, Res}; + +const DOC: Res = Res { + table: "ext_document", + fields: &[ + t("parentId", "f_parent_id"), + t("spaceId", "f_space_id"), + i("type", "f_type"), + t("fullName", "f_full_name"), + t("filePath", "f_file_path"), + t("fileSize", "f_file_size"), + t("fileExtension", "f_file_extension"), + i("readCount", "f_read_count"), + i("isShare", "f_is_share"), + t("uploaderUrl", "f_uploader_url"), + t("tagId", "f_tag_id"), + ], + keyword: &["f_full_name"], + order: "COALESCE(f_type, 0) ASC, f_creator_time DESC NULLS LAST", + scope: "", +}; + +const SPACE: Res = Res { + table: "ext_document_space", + fields: &[ + i("type", "f_type"), + t("fullName", "f_full_name"), + i("downloadAuthority", "f_download_authority"), + i("uploadAuthority", "f_upload_authority"), + ], + keyword: &["f_full_name"], + order: "f_creator_time DESC NULLS LAST", + scope: "", +}; + +// ================================================================ 文件 + +pub async fn doc_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![ + res::filter(&raw, "parentId", "f_parent_id"), + res::filter(&raw, "type", "f_type"), + res::filter(&raw, "spaceId", "f_space_id"), + ]; + res::list_json(&state, &DOC, &raw, filters).await +} + +/// `GET /api/file/Document/list` —— 图片 / 文档清单(`type=1`)。 +pub async fn doc_image_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let filters = vec![("f_type", "1".to_string())]; + res::list_json(&state, &DOC, &raw, filters).await +} + +/// `POST /api/file/Document` —— 新建文件夹(也可以建「文件」元数据)。 +pub async fn doc_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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let mut obj = obj; + if !obj.contains_key("parentId") { + obj.insert("parentId".into(), json!("0")); + } + if !obj.contains_key("type") { + obj.insert("type".into(), json!(0)); + } + match res::create(&state.db, &DOC, &obj, &user.account).await { + Ok(id) => ok(json!({ "id": id })), + Err(e) => db_error(e, "新建文件"), + } +} + +pub async fn doc_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &DOC, &id).await +} + +/// `GET /api/file/Document/Detail?id=` —— 详情(query 传 id)。 +pub async fn doc_detail( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let id = qv(&raw, "id"); + if id.trim().is_empty() { + return fail(code::FAIL, "id 不能为空"); + } + res::info_json(&state, &DOC, &id).await +} + +pub async fn doc_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, + }; + res::update_json(&state, &DOC, &id, &body, &user.account).await +} + +/// `PUT /api/file/Document/tag` —— 批量打标签(`{ids, tagId}`)。 +pub async fn doc_tag( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let ids = id_array(&obj, "ids"); + let tag = obj + .get("tagId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + for id in ids { + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_tag_id = $1::text, f_last_modify_time = now() \ + WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0", + &[&tag, &id], + ) + .await + { + return db_error(e, "设置标签"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/Document/FolderTree` —— 文件夹树(平铺,前端自己拼)。 +pub async fn doc_folder_tree( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = if body.is_empty() { + Map::new() + } else { + match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + } + }; + let space = obj + .get("spaceId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let mut values: Vec> = Vec::new(); + let mut cond = String::from("COALESCE(f_type, 0) = 0 AND COALESCE(f_delete_mark, 0) = 0"); + if !space.is_empty() { + values.push(Some(space)); + cond.push_str(" AND f_space_id = $1::text"); + } + match state + .db + .query_json_params( + &format!( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", \ + COALESCE(f_parent_id, '0') AS \"parentId\", f_space_id AS \"spaceId\" \ + FROM ext_document WHERE {cond} ORDER BY f_full_name ASC" + ), + ¶ms_of(&values), + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "文件夹树"), + } +} + +/// `PUT /api/file/Document/Actions/MoveTo/{toId}` —— 批量移动。 +pub async fn doc_move( + State(state): State, + headers: HeaderMap, + Path(to_id): Path, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_parent_id = $1::text, f_last_modify_time = now() \ + WHERE f_id = $2::text AND COALESCE(f_delete_mark, 0) = 0", + &[&to_id, &id], + ) + .await + { + return db_error(e, "移动文件"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/Document/Actions/Copy/{toId}` —— 批量复制(浅复制)。 +pub async fn doc_copy( + State(state): State, + headers: HeaderMap, + Path(to_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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + let Some(src) = (match res::get(&state.db, &DOC, &id).await { + Ok(v) => v, + Err(e) => return db_error(e, "复制源查询"), + }) else { + continue; + }; + let mut copy: Map = src.as_object().cloned().unwrap_or_default(); + copy.remove("id"); + copy.insert("parentId".into(), json!(to_id)); + copy.insert("isShare".into(), json!(0)); + if let Some(name) = copy.get("fullName").and_then(Value::as_str) { + copy.insert("fullName".into(), json!(format!("{name}副本"))); + } + if let Err(e) = res::create(&state.db, &DOC, ©, &user.account).await { + return db_error(e, "复制文件"); + } + } + ok(Value::Null) +} + +/// 批量软删(递归:先把子孙的 delete_mark 置 1)。 +pub async fn doc_batch_delete( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params( + "WITH RECURSIVE tree AS ( \ + SELECT f_id FROM ext_document WHERE f_id = $1::text \ + UNION ALL \ + SELECT c.f_id FROM ext_document c JOIN tree t ON c.f_parent_id = t.f_id \ + ) \ + UPDATE ext_document SET f_delete_mark = 1, f_delete_time = now(), \ + f_delete_user_id = $2::text WHERE f_id IN (SELECT f_id FROM tree)", + &[&id, &user.account], + ) + .await + { + return db_error(e, "删除文件"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/Document/Actions/Share` —— 批量分享给用户。 +pub async fn doc_share( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let ids = id_array(&obj, "ids"); + let users = id_array(&obj, "userIds"); + if users.is_empty() { + return fail(code::FAIL, "分享对象不能为空"); + } + for doc in &ids { + for uid in &users { + if let Err(e) = state + .db + .exec_params( + "INSERT INTO ext_document_share \ + (f_id, f_document_id, f_user_id, f_share_type, f_delete_mark, f_tenant_id, \ + f_creator_time, f_creator_user_id) \ + VALUES ($1::text, $2::text, $3::text, 1, 0, '0', now(), $4::text)", + &[&new_uuid(), doc, uid, &user.account], + ) + .await + { + return db_error(e, "分享文件"); + } + } + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_is_share = 1, f_share_time = now() WHERE f_id = $1::text", + &[doc], + ) + .await + { + return db_error(e, "标记分享"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/Document/Actions/CancelShare` —— 取消分享。 +pub async fn doc_share_cancel( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document_share SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_document_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id], + ) + .await + { + return db_error(e, "取消分享"); + } + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_is_share = 0, f_share_time = NULL WHERE f_id = $1::text", + &[&id], + ) + .await + { + return db_error(e, "标记取消分享"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/Document/Actions/ShareAdjustment/{id}` —— 单文件重设分享对象。 +pub async fn doc_share_adjust( + 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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let users = id_array(&obj, "userIds"); + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document_share SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_document_id = $1::text AND COALESCE(f_delete_mark, 0) = 0", + &[&id], + ) + .await + { + return db_error(e, "清理原分享"); + } + for uid in &users { + if let Err(e) = state + .db + .exec_params( + "INSERT INTO ext_document_share \ + (f_id, f_document_id, f_user_id, f_share_type, f_delete_mark, f_tenant_id, \ + f_creator_time, f_creator_user_id) \ + VALUES ($1::text, $2::text, $3::text, 1, 0, '0', now(), $4::text)", + &[&new_uuid(), &id, uid, &user.account], + ) + .await + { + return db_error(e, "重设分享"); + } + } + let is_share = if users.is_empty() { 0 } else { 1 }; + let _ = state + .db + .exec_params( + "UPDATE ext_document SET f_is_share = $1::text::integer, f_share_time = now() \ + WHERE f_id = $2::text", + &[&is_share.to_string(), &id], + ) + .await; + ok(Value::Null) +} + +/// `GET /api/file/Document/Share` —— 我分享出去的。 +pub async fn doc_share_out( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let paging = Paging::of(&raw); + let keyword = qv(&raw, "keyword"); + let mut values: Vec> = Vec::new(); + let mut cond = String::from( + "COALESCE(d.f_delete_mark, 0) = 0 AND EXISTS (SELECT 1 FROM ext_document_share s \ + WHERE s.f_document_id = d.f_id AND COALESCE(s.f_delete_mark, 0) = 0)", + ); + if !keyword.trim().is_empty() { + values.push(Some(format!("%{}%", keyword.trim()))); + cond.push_str(" AND COALESCE(d.f_full_name, '') ILIKE $1::text"); + } + let total = state + .db + .query_json_params( + &format!( + "SELECT COUNT(*)::bigint AS \"total\" FROM ext_document d WHERE {cond}" + ), + ¶ms_of(&values), + ) + .await + .ok() + .and_then(|r| r.first().and_then(|v| v.get("total")).and_then(Value::as_i64)) + .unwrap_or(0); + values.push(Some(paging.page_size.to_string())); + let limit_at = values.len(); + values.push(Some(paging.offset.to_string())); + let offset_at = values.len(); + match state + .db + .query_json_params( + &format!( + "SELECT d.f_id AS \"id\", d.f_full_name AS \"fullName\", \ + COALESCE(d.f_type, 0)::bigint AS \"type\", d.f_file_size AS \"fileSize\", \ + d.f_file_extension AS \"fileExtension\", \ + COALESCE(d.f_is_share, 0)::bigint AS \"isShare\" \ + FROM ext_document d WHERE {cond} \ + ORDER BY d.f_creator_time DESC NULLS LAST \ + LIMIT ${limit_at}::text::integer OFFSET ${offset_at}::text::integer" + ), + ¶ms_of(&values), + ) + .await + { + Ok(rows) => ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )), + Err(e) => db_error(e, "我的共享"), + } +} + +/// `GET /api/file/Document/ShareTome` —— 分享给我的。 +pub async fn doc_share_tome( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let paging = Paging::of(&raw); + let values: Vec> = vec![Some(user.account.clone())]; + let cond = "COALESCE(d.f_delete_mark, 0) = 0 AND EXISTS (SELECT 1 FROM ext_document_share s \ + WHERE s.f_document_id = d.f_id AND s.f_user_id = $1::text \ + AND COALESCE(s.f_delete_mark, 0) = 0)"; + let total = state + .db + .query_json_params( + &format!("SELECT COUNT(*)::bigint AS \"total\" FROM ext_document d WHERE {cond}"), + ¶ms_of(&values), + ) + .await + .ok() + .and_then(|r| r.first().and_then(|v| v.get("total")).and_then(Value::as_i64)) + .unwrap_or(0); + match state + .db + .query_json_params( + &format!( + "SELECT d.f_id AS \"id\", d.f_full_name AS \"fullName\", \ + COALESCE(d.f_type, 0)::bigint AS \"type\", d.f_file_size AS \"fileSize\", \ + d.f_file_extension AS \"fileExtension\", \ + COALESCE(d.f_is_share, 0)::bigint AS \"isShare\" \ + FROM ext_document d WHERE {cond} \ + ORDER BY d.f_creator_time DESC NULLS LAST \ + LIMIT $2::text::integer OFFSET $3::text::integer" + ), + &[&user.account, &paging.page_size.to_string(), &paging.offset.to_string()], + ) + .await + { + Ok(rows) => ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )), + Err(e) => db_error(e, "共享给我"), + } +} + +/// `GET /api/file/Document/ShareUser/{id}` —— 某文件的分享对象。 +pub async fn doc_share_users( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match state + .db + .query_json_params( + "SELECT s.f_user_id AS \"id\", COALESCE(u.f_real_name, u.f_account) AS \"fullName\", \ + u.f_account AS \"account\" \ + FROM ext_document_share s LEFT JOIN base_user u ON u.f_id = s.f_user_id \ + WHERE s.f_document_id = $1::text AND COALESCE(s.f_delete_mark, 0) = 0 \ + GROUP BY s.f_user_id, u.f_real_name, u.f_account ORDER BY \"fullName\" ASC", + &[&id.trim()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "分享对象"), + } +} + +/// `GET /api/file/Document/Trash` —— 回收站(当前用户删的)。 +pub async fn doc_trash( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let paging = Paging::of(&raw); + let values: Vec> = vec![Some(user.account.clone())]; + let cond = "COALESCE(f_delete_mark, 0) = 1 AND f_delete_user_id = $1::text"; + let total = state + .db + .query_json_params( + &format!("SELECT COUNT(*)::bigint AS \"total\" FROM ext_document WHERE {cond}"), + ¶ms_of(&values), + ) + .await + .ok() + .and_then(|r| r.first().and_then(|v| v.get("total")).and_then(Value::as_i64)) + .unwrap_or(0); + match state + .db + .query_json_params( + &format!( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", \ + COALESCE(f_type, 0)::bigint AS \"type\", f_file_size AS \"fileSize\", \ + f_file_extension AS \"fileExtension\", \ + (EXTRACT(EPOCH FROM f_delete_time) * 1000)::bigint AS \"deleteTime\" \ + FROM ext_document WHERE {cond} \ + ORDER BY f_delete_time DESC NULLS LAST \ + LIMIT $2::text::integer OFFSET $3::text::integer" + ), + &[&user.account, &paging.page_size.to_string(), &paging.offset.to_string()], + ) + .await + { + Ok(rows) => ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )), + Err(e) => db_error(e, "回收站"), + } +} + +/// `POST /api/file/Document/Trash` —— 回收站**彻底删除**(物理删,连同分享关系)。 +pub async fn doc_trash_delete( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params("DELETE FROM ext_document_share WHERE f_document_id = $1::text", &[&id]) + .await + { + return db_error(e, "删除分享关系"); + } + if let Err(e) = state + .db + .exec_params("DELETE FROM ext_document WHERE f_id = $1::text", &[&id]) + .await + { + return db_error(e, "彻底删除"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/Document/Trash/Actions/Recovery` —— 还原。 +pub async fn doc_trash_recovery( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_delete_mark = 0, f_delete_time = NULL, \ + f_delete_user_id = NULL WHERE f_id = $1::text", + &[&id], + ) + .await + { + return db_error(e, "还原文件"); + } + } + ok(Value::Null) +} + +/// `GET /api/file/Document/recent` —— 最近访问(按最后修改倒序)。 +pub async fn doc_recent( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let paging = Paging::of(&raw); + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", \ + COALESCE(f_type, 0)::bigint AS \"type\", f_file_size AS \"fileSize\", \ + f_file_extension AS \"fileExtension\", \ + (EXTRACT(EPOCH FROM f_last_modify_time) * 1000)::bigint AS \"lastModifyTime\" \ + FROM ext_document WHERE COALESCE(f_delete_mark, 0) = 0 \ + ORDER BY f_last_modify_time DESC NULLS LAST \ + LIMIT $1::text::integer OFFSET $2::text::integer", + &[&paging.page_size.to_string(), &paging.offset.to_string()], + ) + .await + { + Ok(rows) => ok(json!(rows)), + Err(e) => db_error(e, "最近访问"), + } +} + +/// `GET /api/file/Document/getIcon` —— 图片清单(带扩展名,前端据此挑图标)。 +pub async fn doc_icon_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let paging = Paging::of(&raw); + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_file_extension AS \"fileExtension\", \ + f_uploader_url AS \"uploaderUrl\" \ + FROM ext_document WHERE COALESCE(f_type, 0) = 1 \ + AND COALESCE(f_delete_mark, 0) = 0 \ + AND LOWER(COALESCE(f_file_extension, '')) IN \ + ('png','jpg','jpeg','gif','webp','bmp','svg') \ + ORDER BY f_creator_time DESC NULLS LAST \ + LIMIT $1::text::integer OFFSET $2::text::integer", + &[&paging.page_size.to_string(), &paging.offset.to_string()], + ) + .await + { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "图片列表"), + } +} + +/// 上传 / 打包下载 / 分片合并 —— 都需要**文件服务** ⇒ 明确失败。 +pub async fn doc_file_service_unsupported( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + fail( + code::FAIL, + "本仓没有文件服务(对象存储 / 分片合并 / 打包下载):只支持文件元数据管理", + ) +} + +// ================================================================ 文件空间 + +pub async fn space_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::list_json(&state, &SPACE, &raw, vec![]).await +} + +pub async fn space_selector( + State(state): State, + headers: HeaderMap, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match res::all(&state.db, &SPACE).await { + Ok(list) => ok(super::helper::list_vo(list)), + Err(e) => db_error(e, "空间下拉"), + } +} + +pub async fn space_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, + }; + res::create_json(&state, &SPACE, &body, &user.account).await +} + +pub async fn space_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + res::info_json(&state, &SPACE, &id).await +} + +pub async fn space_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, + }; + res::update_json(&state, &SPACE, &id, &body, &user.account).await +} + +pub async fn space_delete( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_space_id = NULL WHERE f_space_id = $1::text", + &[&id.trim()], + ) + .await + { + return db_error(e, "解除空间文件"); + } + res::delete_json(&state, &SPACE, &id).await +} + +/// `POST /api/file/DocumentSpace/MoveOut` —— 把文件移出空间。 +pub async fn space_move_out( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_space_id = NULL WHERE f_id = $1::text", + &[&id], + ) + .await + { + return db_error(e, "移出空间"); + } + } + ok(Value::Null) +} + +/// `POST /api/file/DocumentSpace/Release` —— 把文件发布到空间。 +pub async fn space_release( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let space = obj + .get("spaceId") + .or_else(|| obj.get("id")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + if space.is_empty() { + return fail(code::FAIL, "空间 id 不能为空"); + } + for id in id_array(&obj, "ids") { + if let Err(e) = state + .db + .exec_params( + "UPDATE ext_document SET f_space_id = $1::text WHERE f_id = $2::text", + &[&space, &id], + ) + .await + { + return db_error(e, "发布到空间"); + } + } + ok(Value::Null) +} + +/// `GET /api/file/DocumentSpace/getDocumentList?id=` —— 空间下的文件。 +pub async fn space_documents( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let id = qv(&raw, "id"); + let filters = vec![("f_space_id", id)]; + res::list_json(&state, &DOC, &raw, filters).await +} + +// ================================================================ 日程 + +/// 把 `2026-11-03T10:00:00.000Z` / `2026-11-03 10:00:00` 归一成 PG 认的 `YYYY-MM-DD HH:MM:SS`。 +fn norm_day(raw: &str) -> String { + let s = raw.trim().replace('T', " "); + let s = s.trim_end_matches('Z').to_string(); + let s = s.split('.').next().unwrap_or(&s).to_string(); + if s.len() == 10 { + format!("{s} 00:00:00") + } else { + s + } +} + +fn day_of(obj: &Map, key: &str) -> Option { + obj.get(key) + .and_then(Value::as_str) + .map(norm_day) + .filter(|s| !s.is_empty()) +} + +/// `GET /api/system/Schedule?startDay=&endDay=` —— 我的日程(PageListVO)。 +pub async fn schedule_list( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let paging = Paging::of(&raw); + let mut values: Vec> = vec![Some(user.account.clone())]; + let mut cond = String::from( + "COALESCE(f_delete_mark, 0) = 0 AND f_creator_user_id = $1::text", + ); + let start = qv(&raw, "startDay"); + if !start.trim().is_empty() { + values.push(Some(norm_day(&start))); + cond.push_str(&format!(" AND f_start_day >= ${}::text::timestamp", values.len())); + } + let end = qv(&raw, "endDay"); + if !end.trim().is_empty() { + values.push(Some(norm_day(&end))); + cond.push_str(&format!(" AND f_start_day <= ${}::text::timestamp", values.len())); + } + let keyword = qv(&raw, "keyword"); + if !keyword.trim().is_empty() { + values.push(Some(format!("%{}%", keyword.trim()))); + cond.push_str(&format!(" AND COALESCE(f_title, '') ILIKE ${}::text", values.len())); + } + let total = state + .db + .query_json_params( + &format!("SELECT COUNT(*)::bigint AS \"total\" FROM base_schedule WHERE {cond}"), + ¶ms_of(&values), + ) + .await + .ok() + .and_then(|r| r.first().and_then(|v| v.get("total")).and_then(Value::as_i64)) + .unwrap_or(0); + values.push(Some(paging.page_size.to_string())); + let limit_at = values.len(); + values.push(Some(paging.offset.to_string())); + let offset_at = values.len(); + match state + .db + .query_json_params( + &format!( + "SELECT f_id AS \"id\", f_title AS \"title\", f_content AS \"content\", \ + f_category AS \"category\", COALESCE(f_urgent, 0)::bigint AS \"urgent\", \ + COALESCE(f_all_day, 0)::bigint AS \"allDay\", \ + to_char(f_start_day, 'YYYY-MM-DD HH24:MI:SS') AS \"startDay\", \ + f_start_time AS \"startTime\", \ + to_char(f_end_day, 'YYYY-MM-DD HH24:MI:SS') AS \"endDay\", \ + f_end_time AS \"endTime\", COALESCE(f_duration, 0)::bigint AS \"duration\", \ + f_color AS \"color\", COALESCE(f_reminder_time, 0)::bigint AS \"reminderTime\", \ + COALESCE(f_reminder_type, 0)::bigint AS \"reminderType\", \ + COALESCE(f_repetition, 0)::bigint AS \"repetition\", \ + f_group_id AS \"groupId\", f_files AS \"files\" \ + FROM base_schedule WHERE {cond} \ + ORDER BY f_start_day ASC NULLS LAST \ + LIMIT ${limit_at}::text::integer OFFSET ${offset_at}::text::integer" + ), + ¶ms_of(&values), + ) + .await + { + Ok(rows) => ok(super::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )), + Err(e) => db_error(e, "日程列表"), + } +} + +pub async fn schedule_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 parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let title = obj + .get("title") + .and_then(Value::as_str) + .unwrap_or_default() + .trim() + .to_string(); + if title.is_empty() { + return fail(code::FAIL, "日程标题不能为空"); + } + let id = new_uuid(); + let group = obj + .get("groupId") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .unwrap_or(&id) + .to_string(); + let start = day_of(&obj, "startDay").unwrap_or_else(|| "1970-01-01 00:00:00".to_string()); + let end = day_of(&obj, "endDay"); + let text = |k: &str| { + obj.get(k) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + let int = |k: &str| { + obj.get(k) + .and_then(|v| v.as_i64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))) + .unwrap_or(0) + .to_string() + }; + let mut values: Vec> = vec![ + Some(id.clone()), + Some(title), + Some(text("content")), + Some(text("category")), + Some(int("urgent")), + Some(int("allDay")), + Some(start), + Some(text("startTime")), + end, + Some(text("endTime")), + Some(int("duration")), + Some(text("color")), + Some(int("reminderTime")), + Some(int("reminderType")), + Some(text("sendConfigId")), + Some(text("sendConfigName")), + Some(int("repetition")), + Some(group), + Some(text("files")), + Some(user.account.clone()), + ]; + values.push(Some("0".to_string())); // f_enabled_mark + let n = values.len(); + if let Err(e) = state + .db + .exec_params( + &format!( + "INSERT INTO base_schedule (f_id, f_title, f_content, f_category, f_urgent, \ + f_all_day, f_start_day, f_start_time, f_end_day, f_end_time, f_duration, \ + f_color, f_reminder_time, f_reminder_type, f_send_config_id, \ + f_send_config_name, f_repetition, f_group_id, f_files, f_creator_user_id, \ + f_enabled_mark, f_delete_mark, f_tenant_id, f_creator_time) \ + VALUES ($1::text, $2::text, $3::text, $4::text, $5::text::integer, \ + $6::text::integer, $7::text::timestamp, $8::text, \ + NULLIF($9::text, '')::timestamp, $10::text, $11::text::integer, \ + $12::text, $13::text::integer, $14::text::integer, $15::text, $16::text, \ + $17::text::integer, $18::text, $19::text, $20::text, \ + ${n}::text::integer, 0, '0', now())" + ), + ¶ms_of(&values), + ) + .await + { + return db_error(e, "新建日程"); + } + ok(json!({ "id": id })) +} + +async fn schedule_row(state: &AppState, id: &str) -> Result, Json> { + state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_title AS \"title\", f_content AS \"content\", \ + f_category AS \"category\", COALESCE(f_urgent, 0)::bigint AS \"urgent\", \ + COALESCE(f_all_day, 0)::bigint AS \"allDay\", \ + to_char(f_start_day, 'YYYY-MM-DD HH24:MI:SS') AS \"startDay\", \ + f_start_time AS \"startTime\", \ + to_char(f_end_day, 'YYYY-MM-DD HH24:MI:SS') AS \"endDay\", \ + f_end_time AS \"endTime\", COALESCE(f_duration, 0)::bigint AS \"duration\", \ + f_color AS \"color\", COALESCE(f_reminder_time, 0)::bigint AS \"reminderTime\", \ + COALESCE(f_reminder_type, 0)::bigint AS \"reminderType\", \ + COALESCE(f_repetition, 0)::bigint AS \"repetition\", \ + f_group_id AS \"groupId\", f_files AS \"files\" \ + FROM base_schedule WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0 LIMIT 1", + &[&id.trim()], + ) + .await + .map(|rows| rows.into_iter().next()) + .map_err(|e| db_error(e, "日程查询")) +} + +pub async fn schedule_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + match schedule_row(&state, &id).await { + Ok(Some(row)) => ok(row), + Ok(None) => fail(code::FAIL, "日程不存在"), + Err(resp) => resp, + } +} + +/// `GET /api/system/Schedule/detail?groupId=&id=` —— 重复日程的一次详情。 +pub async fn schedule_detail( + State(state): State, + headers: HeaderMap, + raw: RawQuery, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let id = qv(&raw, "id"); + let group = qv(&raw, "groupId"); + let key = if !id.trim().is_empty() { id } else { group }; + if key.trim().is_empty() { + return fail(code::FAIL, "id 不能为空"); + } + match schedule_row(&state, &key).await { + Ok(Some(row)) => ok(row), + Ok(None) => fail(code::FAIL, "日程不存在"), + Err(resp) => resp, + } +} + +pub async fn schedule_update( + State(state): State, + headers: HeaderMap, + Path((id, _kind)): Path<(String, String)>, + body: Bytes, +) -> Json { + let user = match require_login_face_b(&state, &headers).await { + Ok(u) => u, + Err(resp) => return resp, + }; + let obj = match parse_body(&body) { + Ok(Value::Object(o)) => o, + Ok(_) => return fail(code::FAIL, "请求参数格式错误"), + Err(resp) => return resp, + }; + let mut sets: Vec = Vec::new(); + let mut values: Vec> = Vec::new(); + for (key, col, kind) in [ + ("title", "f_title", "text"), + ("content", "f_content", "text"), + ("category", "f_category", "text"), + ("color", "f_color", "text"), + ("startTime", "f_start_time", "text"), + ("endTime", "f_end_time", "text"), + ("files", "f_files", "text"), + ] { + if let Some(v) = obj.get(key).and_then(Value::as_str) { + values.push(Some(v.to_string())); + sets.push(format!("{col} = ${}::text", values.len())); + } + let _ = kind; + } + for (key, col) in [ + ("urgent", "f_urgent"), + ("allDay", "f_all_day"), + ("duration", "f_duration"), + ("reminderTime", "f_reminder_time"), + ("reminderType", "f_reminder_type"), + ("repetition", "f_repetition"), + ] { + if let Some(v) = obj + .get(key) + .and_then(|v| v.as_i64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))) + { + values.push(Some(v.to_string())); + sets.push(format!("{col} = ${}::text::integer", values.len())); + } + } + for (key, col) in [("startDay", "f_start_day"), ("endDay", "f_end_day")] { + if let Some(v) = day_of(&obj, key) { + values.push(Some(v)); + sets.push(format!("{col} = NULLIF(${}::text, '')::timestamp", values.len())); + } + } + if sets.is_empty() { + return fail(code::FAIL, "没有需要更新的字段"); + } + values.push(Some(user.account.clone())); + let user_at = values.len(); + values.push(Some(id.trim().to_string())); + let id_at = values.len(); + let sql = format!( + "UPDATE base_schedule SET {}, f_last_modify_time = now(), \ + f_last_modify_user_id = ${user_at}::text \ + WHERE f_id = ${id_at}::text AND COALESCE(f_delete_mark, 0) = 0", + sets.join(", ") + ); + match state.db.exec_params(&sql, ¶ms_of(&values)).await { + Ok(_) => ok(json!({ "id": id })), + Err(e) => db_error(e, "更新日程"), + } +} + +/// `DELETE /api/system/Schedule/{id}/{type}` —— 删除。 +/// +/// `type=2` ⇒ 删整组(重复日程全部),否则只删这一条。 +pub async fn schedule_delete( + State(state): State, + headers: HeaderMap, + Path((id, kind)): Path<(String, String)>, +) -> Json { + if let Err(resp) = require_login_face_b(&state, &headers).await { + return resp; + } + let sql = if kind.trim() == "2" { + "UPDATE base_schedule SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_group_id = (SELECT f_group_id FROM base_schedule WHERE f_id = $1::text) \ + AND COALESCE(f_delete_mark, 0) = 0" + } else { + "UPDATE base_schedule SET f_delete_mark = 1, f_delete_time = now() \ + WHERE f_id = $1::text AND COALESCE(f_delete_mark, 0) = 0" + }; + match state.db.exec_params(sql, &[&id.trim()]).await { + Ok(_) => ok(Value::Null), + Err(e) => db_error(e, "删除日程"), + } +} + +// ================================================================ 小工具 + +fn id_array(obj: &Map, key: &str) -> Vec { + obj.get(key) + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect() + }) + .unwrap_or_default() +} diff --git a/src/backend/src/routes.rs b/src/backend/src/routes.rs index aa43e2e..e95c83f 100644 --- a/src/backend/src/routes.rs +++ b/src/backend/src/routes.rs @@ -530,6 +530,8 @@ pub fn build_router(state: AppState) -> axum::Router { .route("/api/system/Dataset", get(compat::system::dataset_list)) .route("/api/system/Dataset", post(compat::system::dataset_create)) .route("/api/system/Dataset/getList", get(compat::system::dataset_get_list)) + .route("/api/system/Dataset/Selector", get(compat::system::dataset_selector)) + .route("/api/system/DatasetLog/{id}", get(compat::system::dataset_log)) .route("/api/system/Dataset/previewSql", post(compat::system::dataset_preview_sql)) .route("/api/system/Dataset/fields", post(compat::system::dataset_fields)) .route( @@ -627,6 +629,10 @@ pub fn build_router(state: AppState) -> axum::Router { "/api/system/InterfaceOauth/getInterfaceList", post(compat::system::interface_oauth_get_interface_list), ) + .route( + "/api/system/InterfaceOauth/saveInterfaceList", + post(compat::system::interface_oauth_save_interface_list), + ) .route( "/api/system/InterfaceOauth/dataInterfaceLog/{id}", get(compat::system::interface_oauth_data_interface_log), @@ -1499,6 +1505,7 @@ pub fn build_router(state: AppState) -> axum::Router { .route("/api/visualdev/ShortLink/{id}", get(compat::online_dev::short_link_info)) .route("/api/visualdev/ShortLink", put(compat::online_dev::short_link_save)) .route("/api/visualdev/ShortLink/getConfig/{id}", get(compat::online_dev::short_link_get_config)) + .route("/api/visualdev/ShortLink/{id}/Config", get(compat::online_dev::short_link_get_config)) .route("/api/visualdev/ShortLink/checkPwd", post(compat::online_dev::short_link_check_pwd)) .route("/api/visualdev/ShortLink/Config", get(compat::online_dev::short_link_config_data)) .route("/api/visualdev/ShortLink/{id}/ListLink", post(compat::online_dev::short_link_model_list)) @@ -1829,6 +1836,441 @@ pub fn build_router(state: AppState) -> axum::Router { "/api/message/Supplier/{id}/VariableList", get(compat::msg_center::supplier_variable_list), ) + // ================================================================ 批次 21:AI 中心(75 条) + // 🔴 官方 `jnpf-ai-v3` 的 13 个 Controller(Agent / Supplier / Model / Prompt / + // Knowledge / Document / Mcp / Serve / Skills / Tool / Chat / visualdev / workflow)。 + // 🔴 守卫:本仓没有 AI 中心菜单种子 ⇒ 一律「登录」(模块头有说明)。 + .route( + "/api/ai/Agent", + get(compat::ai::agent_list).post(compat::ai::agent_create), + ) + .route("/api/ai/Agent/Selector", get(compat::ai::agent_selector)) + .route("/api/ai/Agent/Save", post(compat::ai::agent_save_version)) + .route( + "/api/ai/Agent/Info/{id}", + get(compat::ai::agent_version_info) + .post(compat::ai::agent_version_copy) + .delete(compat::ai::agent_version_delete), + ) + .route("/api/ai/Agent/Version/{id}", get(compat::ai::agent_version_list)) + .route( + "/api/ai/Agent/{id}", + get(compat::ai::agent_info) + .put(compat::ai::agent_update) + .delete(compat::ai::agent_delete), + ) + .route("/api/ai/Agent/{id}/Actions/Copy", post(compat::ai::agent_copy)) + .route( + "/api/ai/AiSupplier", + get(compat::ai::supplier_list).post(compat::ai::supplier_create), + ) + .route("/api/ai/AiSupplier/Selector", get(compat::ai::supplier_selector)) + .route("/api/ai/AiSupplier/checkAi", post(compat::ai::supplier_check)) + .route( + "/api/ai/AiSupplier/{id}", + get(compat::ai::supplier_info) + .put(compat::ai::supplier_update) + .delete(compat::ai::supplier_delete), + ) + .route("/api/ai/Chat/Send", post(compat::ai::chat_send)) + .route("/api/ai/Chat/Translate", post(compat::ai::chat_translate)) + .route("/api/ai/Chat/Optimize", post(compat::ai::chat_optimize)) + .route("/api/ai/Chat/Close/{id}", get(compat::ai::chat_close)) + .route("/api/ai/Chat/history/list", get(compat::ai::chat_history_list)) + .route("/api/ai/Chat/history/cleanAll", delete(compat::ai::chat_history_clean)) + .route("/api/ai/Chat/history/get/{id}", get(compat::ai::chat_history_get)) + .route( + "/api/ai/Chat/history/update/{id}", + put(compat::ai::chat_history_update), + ) + .route( + "/api/ai/Chat/history/delete/{id}", + delete(compat::ai::chat_history_delete), + ) + .route( + "/api/ai/Document", + get(compat::ai::document_list).post(compat::ai::document_create), + ) + .route( + "/api/ai/Document/{id}", + get(compat::ai::document_info) + .put(compat::ai::document_update) + .delete(compat::ai::document_delete), + ) + .route("/api/ai/Document/{id}/getText", get(compat::ai::document_text)) + .route("/api/ai/Document/{id}/section", post(compat::ai::document_section)) + .route("/api/ai/Document/{id}/study", post(compat::ai::document_study)) + .route( + "/api/ai/Knowledge", + get(compat::ai::knowledge_list).post(compat::ai::knowledge_create), + ) + .route("/api/ai/Knowledge/Selector", get(compat::ai::knowledge_selector)) + .route( + "/api/ai/Knowledge/getListByIds", + post(compat::ai::knowledge_by_ids), + ) + .route( + "/api/ai/Knowledge/Relation/{id}", + get(compat::ai::knowledge_relation), + ) + .route( + "/api/ai/Knowledge/{id}", + get(compat::ai::knowledge_info) + .put(compat::ai::knowledge_update) + .delete(compat::ai::knowledge_delete), + ) + .route("/api/ai/Knowledge/{id}/Test", post(compat::ai::knowledge_test)) + .route( + "/api/ai/Mcp", + get(compat::ai::mcp_list).post(compat::ai::mcp_create), + ) + .route("/api/ai/Mcp/Selector", get(compat::ai::mcp_selector)) + .route("/api/ai/Mcp/Sync/{id}", get(compat::ai::mcp_sync)) + .route("/api/ai/Mcp/getListByIds", post(compat::ai::mcp_by_ids)) + .route( + "/api/ai/Mcp/{id}", + get(compat::ai::mcp_info) + .put(compat::ai::mcp_update) + .delete(compat::ai::mcp_delete), + ) + .route("/api/ai/Model", get(compat::ai::model_list)) + .route( + "/api/ai/Model/{id}", + get(compat::ai::model_info).put(compat::ai::model_update), + ) + .route( + "/api/ai/Prompt", + get(compat::ai::prompt_list).post(compat::ai::prompt_create), + ) + .route( + "/api/ai/Prompt/{id}", + get(compat::ai::prompt_info) + .put(compat::ai::prompt_update) + .delete(compat::ai::prompt_delete), + ) + .route( + "/api/ai/Serve", + get(compat::ai::serve_list).post(compat::ai::serve_create), + ) + .route("/api/ai/Serve/Selector", get(compat::ai::serve_selector)) + .route( + "/api/ai/Serve/{id}", + get(compat::ai::serve_info) + .put(compat::ai::serve_update) + .delete(compat::ai::serve_delete), + ) + .route("/api/ai/Skills", get(compat::ai::skills_list)) + .route("/api/ai/Skills/getListByIds", post(compat::ai::skills_by_ids)) + .route("/api/ai/Skills/{id}", get(compat::ai::skills_info)) + .route("/api/ai/Tool", get(compat::ai::tool_list)) + .route("/api/ai/Tool/getListByIds", post(compat::ai::tool_by_ids)) + .route("/api/ai/Tool/{id}", get(compat::ai::tool_info)) + .route("/api/ai/visualdev", post(compat::ai::ai_visualdev)) + .route("/api/ai/workflow", post(compat::ai::ai_workflow)) + // ================================================================ 批次 22:extend 示例(64 条) + // 🔴 官方 `jnpf-extend` 的 8 个 Controller(BigData / CrmOrder / DocumentPreview / + // Email / Employee / ProjectGantt / TableExample / saleOrder)。 + // 🔴 需要 SMTP / IMAP / 文件服务的动作如实失败(见 `compat/extend.rs` 模块头)。 + .route( + "/api/extend/BigData", + get(compat::extend::big_data_list).post(compat::extend::big_data_create), + ) + .route("/api/extend/CrmOrder", get(compat::extend::crm_order_list)) + .route("/api/extend/CrmOrder/Customer", get(compat::extend::crm_customer_list)) + .route("/api/extend/CrmOrder/Goods", get(compat::extend::crm_goods_list)) + .route( + "/api/extend/CrmOrder/OrderEntry/{id}/Items", + get(compat::extend::crm_order_entries), + ) + .route( + "/api/extend/CrmOrder/{id}", + delete(compat::extend::crm_order_delete), + ) + .route( + "/api/extend/CrmOrder/{id}/CollectionPlan", + get(compat::extend::crm_order_plans), + ) + .route( + "/api/extend/DocumentPreview", + get(compat::extend::document_preview_list), + ) + .route( + "/api/extend/DocumentPreview/{id}/Preview", + get(compat::extend::document_preview), + ) + .route( + "/api/extend/Email", + get(compat::extend::email_list).post(compat::extend::email_send), + ) + .route( + "/api/extend/Email/Actions/SaveDraft", + post(compat::extend::email_save_draft), + ) + .route( + "/api/extend/Email/Config", + get(compat::extend::email_config_get).put(compat::extend::email_config_save), + ) + .route( + "/api/extend/Email/Config/Actions/CheckMail", + post(compat::extend::email_check), + ) + .route("/api/extend/Email/Receive", post(compat::extend::email_receive)) + .route( + "/api/extend/Email/{id}", + get(compat::extend::email_info).delete(compat::extend::email_delete), + ) + .route( + "/api/extend/Email/{id}/Actions/Read", + put(compat::extend::email_read), + ) + .route( + "/api/extend/Email/{id}/Actions/Unread", + put(compat::extend::email_unread), + ) + .route( + "/api/extend/Email/{id}/Actions/Star", + put(compat::extend::email_star), + ) + .route( + "/api/extend/Email/{id}/Actions/Unstar", + put(compat::extend::email_unstar), + ) + .route("/api/extend/Employee", get(compat::extend::employee_list)) + .route( + "/api/extend/Employee/ExportData", + get(compat::extend::export_unsupported), + ) + .route( + "/api/extend/Employee/ImportData", + post(compat::extend::export_unsupported), + ) + .route( + "/api/extend/Employee/ImportPreview", + get(compat::extend::export_unsupported), + ) + .route( + "/api/extend/Employee/TemplateDownload", + get(compat::extend::export_unsupported), + ) + .route( + "/api/extend/Employee/{id}", + delete(compat::extend::employee_delete), + ) + .route( + "/api/extend/ProjectGantt", + get(compat::extend::project_list).post(compat::extend::project_create), + ) + .route( + "/api/extend/ProjectGantt/Task", + post(compat::extend::project_task_create), + ) + .route( + "/api/extend/ProjectGantt/Task/{id}", + get(compat::extend::project_task_info).put(compat::extend::project_task_update), + ) + .route( + "/api/extend/ProjectGantt/{id}", + get(compat::extend::project_info) + .put(compat::extend::project_update) + .delete(compat::extend::project_delete), + ) + .route( + "/api/extend/ProjectGantt/{id}/Task", + get(compat::extend::project_task_list), + ) + .route( + "/api/extend/ProjectGantt/{id}/Task/Selector/{taskId}", + get(compat::extend::project_task_selector), + ) + .route( + "/api/extend/TableExample", + get(compat::extend::table_list).post(compat::extend::table_create), + ) + .route("/api/extend/TableExample/All", get(compat::extend::table_all)) + .route( + "/api/extend/TableExample/CityList/{id}", + get(compat::extend::table_city_list), + ) + .route( + "/api/extend/TableExample/ControlSample/{id}", + get(compat::extend::table_control_sample), + ) + .route( + "/api/extend/TableExample/IndustryList", + get(compat::extend::table_industry_list), + ) + .route( + "/api/extend/TableExample/UpdateSign/{id}", + put(compat::extend::table_update_sign), + ) + .route( + "/api/extend/TableExample/{id}", + get(compat::extend::table_info) + .put(compat::extend::table_update) + .delete(compat::extend::table_delete), + ) + .route( + "/api/extend/TableExample/{id}/Actions/Postil", + get(compat::extend::table_postil_list), + ) + .route( + "/api/extend/TableExample/{id}/Actions/RowsEdit", + put(compat::extend::table_rows_edit), + ) + .route( + "/api/extend/TableExample/{id}/Postil", + post(compat::extend::table_postil_add), + ) + .route( + "/api/extend/TableExample/{id}/Postil/{index}", + delete(compat::extend::table_postil_delete), + ) + .route( + "/api/extend/saleOrder/Classify", + get(compat::extend::sale_classify_list), + ) + .route( + "/api/extend/saleOrder/Customer", + get(compat::extend::sale_customer_list), + ) + .route( + "/api/extend/saleOrder/Goods", + get(compat::extend::sale_goods_list), + ) + .route( + "/api/extend/saleOrder/Goods/Selector", + get(compat::extend::sale_goods_selector), + ) + .route( + "/api/extend/saleOrder/Goods/getGoodList", + get(compat::extend::sale_goods_by_type), + ) + .route( + "/api/extend/saleOrder/Product", + get(compat::extend::sale_order_list).post(compat::extend::sale_order_create_with_entries), + ) + .route( + "/api/extend/saleOrder/Product/ProductEntry/{id}", + get(compat::extend::sale_order_entries), + ) + .route( + "/api/extend/saleOrder/Product/{id}", + get(compat::extend::sale_order_info) + .put(compat::extend::sale_order_update) + .delete(compat::extend::sale_order_delete), + ) + // ================================================================ 批次 23:teamwork(40 条) + // 🔴 官方 `jnpf-file` 的文档 / 空间 + `jnpf-system` 的日程。 + // 🔴 文件只存元数据:上传 / 打包下载 / 分片合并如实失败(见 `compat/teamwork.rs`)。 + .route( + "/api/file/Document", + get(compat::teamwork::doc_list).post(compat::teamwork::doc_create), + ) + .route("/api/file/Document/list", get(compat::teamwork::doc_image_list)) + .route("/api/file/Document/tag", put(compat::teamwork::doc_tag)) + .route( + "/api/file/Document/BatchDelete", + post(compat::teamwork::doc_batch_delete), + ) + .route( + "/api/file/Document/FolderTree", + post(compat::teamwork::doc_folder_tree), + ) + .route("/api/file/Document/Detail", get(compat::teamwork::doc_detail)) + .route( + "/api/file/Document/Actions/MoveTo/{toId}", + put(compat::teamwork::doc_move), + ) + .route( + "/api/file/Document/Actions/Copy/{toId}", + post(compat::teamwork::doc_copy), + ) + .route( + "/api/file/Document/Actions/Share", + post(compat::teamwork::doc_share), + ) + .route( + "/api/file/Document/Actions/CancelShare", + post(compat::teamwork::doc_share_cancel), + ) + .route( + "/api/file/Document/Actions/ShareAdjustment/{id}", + post(compat::teamwork::doc_share_adjust), + ) + .route("/api/file/Document/Share", get(compat::teamwork::doc_share_out)) + .route( + "/api/file/Document/ShareTome", + get(compat::teamwork::doc_share_tome), + ) + .route( + "/api/file/Document/ShareUser/{id}", + get(compat::teamwork::doc_share_users), + ) + .route( + "/api/file/Document/Trash", + get(compat::teamwork::doc_trash).post(compat::teamwork::doc_trash_delete), + ) + .route( + "/api/file/Document/Trash/Actions/Recovery", + post(compat::teamwork::doc_trash_recovery), + ) + .route( + "/api/file/Document/PackDownload", + post(compat::teamwork::doc_file_service_unsupported), + ) + .route( + "/api/file/Document/merge", + post(compat::teamwork::doc_file_service_unsupported), + ) + .route( + "/api/file/Document/UploadBlob", + post(compat::teamwork::doc_file_service_unsupported), + ) + .route("/api/file/Document/getIcon", get(compat::teamwork::doc_icon_list)) + .route("/api/file/Document/recent", get(compat::teamwork::doc_recent)) + .route( + "/api/file/Document/{id}", + get(compat::teamwork::doc_info).put(compat::teamwork::doc_update), + ) + .route( + "/api/file/DocumentSpace", + get(compat::teamwork::space_list).post(compat::teamwork::space_create), + ) + .route( + "/api/file/DocumentSpace/MoveOut", + post(compat::teamwork::space_move_out), + ) + .route( + "/api/file/DocumentSpace/Release", + post(compat::teamwork::space_release), + ) + .route( + "/api/file/DocumentSpace/Selector", + get(compat::teamwork::space_selector), + ) + .route( + "/api/file/DocumentSpace/getDocumentList", + get(compat::teamwork::space_documents), + ) + .route( + "/api/file/DocumentSpace/{id}", + get(compat::teamwork::space_info) + .put(compat::teamwork::space_update) + .delete(compat::teamwork::space_delete), + ) + .route( + "/api/system/Schedule", + get(compat::teamwork::schedule_list).post(compat::teamwork::schedule_create), + ) + .route( + "/api/system/Schedule/detail", + get(compat::teamwork::schedule_detail), + ) + .route("/api/system/Schedule/{id}", get(compat::teamwork::schedule_info)) + .route( + "/api/system/Schedule/{id}/{kind}", + put(compat::teamwork::schedule_update).delete(compat::teamwork::schedule_delete), + ) .merge(crate::bootstrap::pack_router_or_empty()); // 🔴 **仅测试构建**存在的「故意 panic」端点 —— 用来钉住 catch-all 中间件 diff --git a/src/backend/tests/ext_batches_it.rs b/src/backend/tests/ext_batches_it.rs new file mode 100644 index 0000000..2426125 --- /dev/null +++ b/src/backend/tests/ext_batches_it.rs @@ -0,0 +1,615 @@ +//! 批次 21–23 —— **aiCenter(75) / extend(64) / teamwork(40)** 的集成测试。 +//! +//! 🔴 三族的形状分两类(与 `platform/compat/{ai,extend,teamwork}.rs` 的口径一致): +//! ① **本地可自洽**(元数据 CRUD / 目录 / 分享 / 回收站 / 日程 / 示例数据) +//! ⇒ **真落库**(`base_ai_*` / `ext_*` / `base_schedule`); +//! ② **要外部能力**(LLM / SMTP / IMAP / MCP / 文件服务 / Excel) +//! ⇒ **明确业务失败**(`code=400` + `data:null` + 人话),绝不返假成功。 +//! +//! 🔴 断言三类: +//! ① 路由存在(每族抽样,含静态段与参数段混排 —— matchit 冲突会让 `build_app` panic); +//! ② 真实现的精确形状(`PageListVO` vs `ListVO`、字段名、落库闭环); +//! ③ 能力缺失端点的诚实失败。 + +use std::path::PathBuf; +use std::sync::Arc; + +use serde_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-ext-batches-it", + ))), + db: Arc::new(db.clone()), + sessions: Arc::new(SessionStore::default()), + tickets: Arc::new(TicketStore::default()), + } +} + +async fn raw_call( + port: u16, + method: &str, + path: &str, + token: &str, + body: Option<&str>, +) -> (u16, 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 (head, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔"); + let status = head + .split_whitespace() + .nth(1) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + (status, serde_json::from_str(body.trim()).unwrap_or(Value::Null)) +} + +async fn call(port: u16, method: &str, path: &str, token: &str, body: Option<&str>) -> Value { + raw_call(port, method, path, token, body).await.1 +} + +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) +} + +fn id_of(v: &Value) -> String { + v["data"]["id"] + .as_str() + .unwrap_or_else(|| panic!("必须返 id: {v}")) + .to_string() +} + +/// 三族**路由存在性**:静/动段混排(matchit 冲突会让 `build_app` panic), +/// 且不能出现 404(未知路由)/405(方法不对)。 +#[tokio::test] +async fn routes_of_three_families_exist() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + let probes: Vec<(&str, String)> = vec![ + ("GET", "/api/ai/Agent".into()), + ("GET", "/api/ai/Agent/Selector".into()), + ("GET", "/api/ai/Agent/Version/x".into()), + ("GET", "/api/ai/AiSupplier".into()), + ("GET", "/api/ai/Knowledge/Selector".into()), + ("GET", "/api/ai/Mcp/Selector".into()), + ("GET", "/api/ai/Model".into()), + ("GET", "/api/ai/Prompt".into()), + ("GET", "/api/ai/Serve/Selector".into()), + ("GET", "/api/ai/Skills".into()), + ("GET", "/api/ai/Tool".into()), + ("GET", "/api/ai/Chat/history/list".into()), + ("GET", "/api/extend/BigData".into()), + ("GET", "/api/extend/CrmOrder".into()), + ("GET", "/api/extend/CrmOrder/Customer".into()), + ("GET", "/api/extend/DocumentPreview".into()), + ("GET", "/api/extend/Email".into()), + ("GET", "/api/extend/Email/Config".into()), + ("GET", "/api/extend/Employee".into()), + ("GET", "/api/extend/ProjectGantt".into()), + ("GET", "/api/extend/TableExample/IndustryList".into()), + ("GET", "/api/extend/TableExample/All".into()), + ("GET", "/api/extend/saleOrder/Classify".into()), + ("GET", "/api/extend/saleOrder/Goods/Selector".into()), + ("GET", "/api/file/Document".into()), + ("GET", "/api/file/Document/Share".into()), + ("GET", "/api/file/Document/ShareTome".into()), + ("GET", "/api/file/Document/Trash".into()), + ("GET", "/api/file/Document/recent".into()), + ("GET", "/api/file/DocumentSpace/Selector".into()), + ("GET", "/api/system/Schedule".into()), + // 批次 21–23 收尾补的 4 条(数据集下拉 / 执行日志 / 外链配置 ×2) + ("GET", "/api/system/Dataset/Selector".into()), + ("GET", "/api/system/DatasetLog/x".into()), + ("GET", "/api/visualdev/ShortLink/x/Config".into()), + ("GET", "/api/visualdev/ShortLink/getConfig/x".into()), + ]; + let v = call( + port, + "POST", + "/api/system/InterfaceOauth/saveInterfaceList", + &token, + Some(r#"{"id":"nope"}"#), + ) + .await; + assert_eq!(v["code"], 400, "不存在的认证 id 必须诚实失败: {v}"); + + for (method, path) in probes { + let (status, body) = raw_call(port, method, &path, &token, None).await; + assert_eq!(status, 200, "{method} {path} 必须命中路由,实际 HTTP {status} / {body}"); + assert_ne!(body["code"], 404, "{method} {path} 未注册: {body}"); + } +} + +/// AI 中心:供应商(口令不下发)→ 知识库 → 文档 → 学习 → 关键词召回 → 版本。 +#[tokio::test] +async fn ai_center_crud_and_recall_work() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + let sup = call( + port, + "POST", + "/api/ai/AiSupplier", + &token, + Some(r#"{"fullName":"IT供应商","enCode":"it_sup","url":"https://x/v1","credential":"sk-secret"}"#), + ) + .await; + assert_eq!(sup["code"], 200, "{sup}"); + let list = call(port, "GET", "/api/ai/AiSupplier?currentPage=1&pageSize=20", &token, None).await; + let row = list["data"]["list"] + .as_array() + .and_then(|a| a.iter().find(|r| r["enCode"] == "it_sup")) + .expect("供应商必须出现在列表"); + assert_eq!(row["credential"], "", "口令**不得**下发"); + assert_eq!(row["credentialConfigured"], true, "必须告诉前端「已配置」"); + + let k = call(port, "POST", "/api/ai/Knowledge", &token, Some(r#"{"fullName":"制度库","way":1}"#)).await; + let kid = id_of(&k); + let d = call( + port, + "POST", + "/api/ai/Document", + &token, + Some(&format!( + r#"{{"knowledgeId":"{kid}","fullName":"制度.txt","type":1,"wayJson":{{"content":"报销:差旅费按标准。\n请假:提前一天。"}}}}"# + )), + ) + .await; + let did = id_of(&d); + + let studied = call( + port, + "POST", + &format!("/api/ai/Document/{did}/study"), + &token, + Some(r#"{"text":"报销:差旅费按标准。\n请假:提前一天。"}"#), + ) + .await; + assert_eq!(studied["code"], 200, "{studied}"); + assert_eq!(studied["data"]["num"], 2, "两行必须切成两段: {studied}"); + + let recall = call( + port, + "POST", + &format!("/api/ai/Knowledge/{kid}/Test"), + &token, + Some(r#"{"question":"报销 差旅费"}"#), + ) + .await; + assert_eq!(recall["code"], 200, "{recall}"); + assert!( + recall["data"]["total"].as_i64().unwrap_or(0) >= 1, + "关键词召回必须命中: {recall}" + ); + + let agent = call( + port, + "POST", + "/api/ai/Agent", + &token, + Some(r#"{"fullName":"IT助手","type":1}"#), + ) + .await; + let aid = id_of(&agent); + let saved = call( + port, + "POST", + "/api/ai/Agent/Save", + &token, + Some(&format!( + r#"{{"agentId":"{aid}","modelId":"m1","configJson":{{"temperature":0.1}}}}"# + )), + ) + .await; + assert_eq!(saved["code"], 200, "{saved}"); + let versions = call(port, "GET", &format!("/api/ai/Agent/Version/{aid}"), &token, None).await; + let arr = versions["data"].as_array().expect("版本列表必须是**裸数组**"); + assert_eq!(arr.len(), 1, "{versions}"); + assert_eq!(arr[0]["version"], "V1"); + + // 清理(软删;列表不应再出现) + assert_eq!( + call(port, "DELETE", &format!("/api/ai/Agent/{aid}"), &token, None).await["code"], + 200 + ); + assert_eq!( + call(port, "DELETE", &format!("/api/ai/Knowledge/{kid}"), &token, None).await["code"], + 200 + ); + let after = call(port, "GET", "/api/ai/Knowledge?currentPage=1&pageSize=20", &token, None).await; + assert!( + !after["data"]["list"] + .as_array() + .map(|a| a.iter().any(|r| r["id"] == kid.as_str())) + .unwrap_or(false), + "软删后不该出现: {after}" + ); +} + +/// AI 中心:需要外部能力的动作必须**诚实失败**。 +#[tokio::test] +async fn ai_external_actions_fail_honestly() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + for (method, path, body) in [ + ("POST", "/api/ai/AiSupplier/checkAi", Some("{}")), + ("POST", "/api/ai/Chat/Send", Some(r#"{"content":"hi"}"#)), + ("POST", "/api/ai/Chat/Translate", Some("{}")), + ("POST", "/api/ai/Chat/Optimize", Some("{}")), + ] { + let v = call(port, method, path, &token, body).await; + assert_eq!(v["code"], 400, "{path} 必须明确失败: {v}"); + assert_eq!(v["data"], Value::Null, "{path} 失败时 data 必须是 null"); + assert!( + v["msg"].as_str().map(|s| !s.is_empty()).unwrap_or(false), + "{path} 必须给原因: {v}" + ); + } + // 不存在的 MCP 同步 ⇒ 先报「不存在」,存在但连不上 ⇒ 400(都是诚实的)。 + let mcp = call(port, "POST", "/api/ai/Mcp", &token, Some(r#"{"fullName":"本地MCP"}"#)).await; + let mid = id_of(&mcp); + let sync = call(port, "GET", &format!("/api/ai/Mcp/Sync/{mid}"), &token, None).await; + assert_eq!(sync["code"], 400, "{sync}"); +} + +/// extend:项目 / 任务 / 控件示例(行编辑 + 批注)/ 销售订单(主表 + 明细)。 +#[tokio::test] +async fn extend_demo_modules_work() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + let p = call( + port, + "POST", + "/api/extend/ProjectGantt", + &token, + Some(r#"{"projectName":"IT项目","manager":"admin","startDate":"2026-11-01","endDate":"2026-12-01"}"#), + ) + .await; + let pid = id_of(&p); + let t = call( + port, + "POST", + "/api/extend/ProjectGantt/Task", + &token, + Some(&format!( + r#"{{"projectId":"{pid}","taskName":"需求","startDate":"2026-11-01","endDate":"2026-11-10","progress":30}}"# + )), + ) + .await; + let tid = id_of(&t); + let tasks = call( + port, + "GET", + &format!("/api/extend/ProjectGantt/{pid}/Task?currentPage=1&pageSize=10"), + &token, + None, + ) + .await; + assert_eq!(tasks["data"]["pagination"]["total"], 1, "{tasks}"); + let sel = call( + port, + "GET", + &format!("/api/extend/ProjectGantt/{pid}/Task/Selector/{tid}"), + &token, + None, + ) + .await; + assert_eq!( + sel["data"]["list"].as_array().map(|a| a.len()).unwrap_or(1), + 0, + "父任务候选要排除自己: {sel}" + ); + + let tb = call( + port, + "POST", + "/api/extend/TableExample", + &token, + Some(r#"{"fullName":"控件甲","type":1,"industry":"1","sign":"A"}"#), + ) + .await; + let tbid = id_of(&tb); + assert_eq!( + call( + port, + "PUT", + &format!("/api/extend/TableExample/{tbid}/Actions/RowsEdit"), + &token, + Some(r#"{"rows":[{"a":1},{"a":2}]}"#), + ) + .await["code"], + 200 + ); + assert_eq!( + call( + port, + "POST", + &format!("/api/extend/TableExample/{tbid}/Postil"), + &token, + Some(r#"{"content":"第一条"}"#), + ) + .await["code"], + 200 + ); + let postils = call( + port, + "GET", + &format!("/api/extend/TableExample/{tbid}/Actions/Postil"), + &token, + None, + ) + .await; + assert_eq!( + postils["data"]["list"].as_array().map(|a| a.len()).unwrap_or(0), + 1, + "{postils}" + ); + + let so = call( + port, + "POST", + "/api/extend/saleOrder/Product", + &token, + Some(r#"{"orderNo":"SO-IT","customerName":"客户甲","orderDate":"2026-11-03","total":"100.00","goodsList":[{"goodsName":"商品A","qty":2,"price":"50.00","amount":"100.00"}]}"#), + ) + .await; + let soid = id_of(&so); + let entries = call( + port, + "GET", + &format!("/api/extend/saleOrder/Product/ProductEntry/{soid}"), + &token, + None, + ) + .await; + let items = entries["data"]["list"].as_array().expect("明细必须是 ListVO"); + assert_eq!(items.len(), 1, "{entries}"); + assert_eq!(items[0]["goodsName"], "商品A"); + + // 需要 SMTP / 文件服务的动作 ⇒ 400 + let mail = call(port, "POST", "/api/extend/Email", &token, Some("{}")).await; + assert_eq!(mail["code"], 400, "{mail}"); + let export = call(port, "GET", "/api/extend/Employee/ExportData", &token, None).await; + assert_eq!(export["code"], 400, "{export}"); +} + +/// teamwork:目录 / 移动 / 复制 / 分享 / 回收站 / 空间 / 日程。 +#[tokio::test] +async fn teamwork_documents_and_schedule_work() { + let _g = LOCK.lock().await; + let (port, token) = boot().await; + + let folder = call(port, "POST", "/api/file/Document", &token, Some(r#"{"fullName":"IT文件夹","type":0}"#)).await; + let fid = id_of(&folder); + let doc = call( + port, + "POST", + "/api/file/Document", + &token, + Some(&format!( + r#"{{"fullName":"说明.txt","type":1,"parentId":"{fid}","fileSize":"12","fileExtension":"txt"}}"# + )), + ) + .await; + let did = id_of(&doc); + let listed = call( + port, + "GET", + &format!("/api/file/Document?currentPage=1&pageSize=10&parentId={fid}"), + &token, + None, + ) + .await; + assert_eq!(listed["data"]["pagination"]["total"], 1, "{listed}"); + assert_eq!( + listed["data"]["list"][0]["id"], did, + "列表必须带 id(编辑/删除要靠它)" + ); + + assert_eq!( + call(port, "PUT", "/api/file/Document/Actions/MoveTo/0", &token, Some(&format!(r#"{{"ids":["{did}"]}}"#))).await["code"], + 200 + ); + assert_eq!( + call(port, "POST", &format!("/api/file/Document/Actions/Copy/{fid}"), &token, Some(&format!(r#"{{"ids":["{did}"]}}"#))).await["code"], + 200 + ); + assert_eq!( + call( + port, + "POST", + "/api/file/Document/Actions/Share", + &token, + Some(&format!(r#"{{"ids":["{did}"],"userIds":["4be057be-9e62-4726-a1e1-383a5c85daee"]}}"#)), + ) + .await["code"], + 200 + ); + let users = call(port, "GET", &format!("/api/file/Document/ShareUser/{did}"), &token, None).await; + assert_eq!( + users["data"]["list"].as_array().map(|a| a.len()).unwrap_or(0), + 1, + "{users}" + ); + + assert_eq!( + call(port, "POST", "/api/file/Document/BatchDelete", &token, Some(&format!(r#"{{"ids":["{did}"]}}"#))).await["code"], + 200 + ); + let trash = call(port, "GET", "/api/file/Document/Trash?currentPage=1&pageSize=10", &token, None).await; + assert!( + trash["data"]["list"].as_array().map(|a| a.iter().any(|r| r["id"] == did.as_str())).unwrap_or(false), + "回收站必须能看到: {trash}" + ); + assert_eq!( + call(port, "POST", "/api/file/Document/Trash/Actions/Recovery", &token, Some(&format!(r#"{{"ids":["{did}"]}}"#))).await["code"], + 200 + ); + + let space = call(port, "POST", "/api/file/DocumentSpace", &token, Some(r#"{"fullName":"IT空间","type":1}"#)).await; + let sid = id_of(&space); + assert_eq!( + call( + port, + "POST", + "/api/file/DocumentSpace/Release", + &token, + Some(&format!(r#"{{"spaceId":"{sid}","ids":["{did}"]}}"#)), + ) + .await["code"], + 200 + ); + let in_space = call( + port, + "GET", + &format!("/api/file/DocumentSpace/getDocumentList?id={sid}¤tPage=1&pageSize=10"), + &token, + None, + ) + .await; + assert_eq!(in_space["data"]["pagination"]["total"], 1, "{in_space}"); + + let sc = call( + port, + "POST", + "/api/system/Schedule", + &token, + Some(r#"{"title":"IT日程","content":"内容","startDay":"2026-11-05 09:00:00","endDay":"2026-11-05 10:00:00","category":"1","urgent":1}"#), + ) + .await; + let scid = id_of(&sc); + let sl = call(port, "GET", "/api/system/Schedule?currentPage=1&pageSize=10", &token, None).await; + assert_eq!(sl["data"]["pagination"]["total"], 1, "{sl}"); + assert_eq!( + sl["data"]["list"][0]["startDay"], "2026-11-05 09:00:00", + "startDay 必须是可被 dayjs 解析的字符串: {sl}" + ); + assert_eq!( + call(port, "PUT", &format!("/api/system/Schedule/{scid}/1"), &token, Some(r#"{"title":"IT日程2"}"#)).await["code"], + 200 + ); + assert_eq!( + call(port, "DELETE", &format!("/api/system/Schedule/{scid}/1"), &token, None).await["code"], + 200 + ); + let after = call(port, "GET", "/api/system/Schedule?currentPage=1&pageSize=10", &token, None).await; + assert_eq!(after["data"]["pagination"]["total"], 0, "{after}"); +} + +/// 未登录:三族都必须 `602`(面 B 会话失效码),不能 404/500。 +#[tokio::test] +async fn three_families_require_login() { + let _g = LOCK.lock().await; + let (port, _token) = boot().await; + for path in [ + "/api/ai/Agent", + "/api/extend/BigData", + "/api/file/Document", + "/api/system/Schedule", + ] { + let (status, body) = raw_call(port, "GET", path, "", None).await; + assert_eq!(status, 200, "{path} 必须 HTTP 200 + 信封"); + assert_eq!(body["code"], 602, "{path} 未登录必须 602: {body}"); + } +}