diff --git a/.workbuddy/memory/2026-11-03.md b/.workbuddy/memory/2026-11-03.md index 4501657..ffd145b 100644 --- a/.workbuddy/memory/2026-11-03.md +++ b/.workbuddy/memory/2026-11-03.md @@ -89,3 +89,12 @@ - **与原计划的差异**:① `pub(crate)` → `pub`(10 处):跨 crate 后失效;② `crud.rs` 3 个测试原依赖 `crate::modules::all_specs()`(业务层)⇒ 改用**契约层合成 spec** 参数化测试,顺带发现**技术债**:`write_cast` 的 numeric 映射是**列名枚举**(`f_price`/`f_stock`)而非 spec 声明 ⇒ 新表带 `f_amount` 会静默缺 `::numeric`;③ `registry.rs` 测试改自建库 + `seed::ensure_base(db, &[])`;④ `test_support.rs` 留壳层(依赖装配根的业务 DDL)。 - **数字**:转发壳每文件 ≤ 10 行;`cargo build` 零警告;`cargo test` **695 passed / 0 failed**(与基线一致);`check-arch` 14/14;`--self-test` 6/6;`check-boundary` 11/11;`check-contract` 10/10(反自证 12 例全过);`check-module` 123/123;`check-citations` 4/4;`verify.sh --smoke` 14 步全绿(512.3s)。 - ⏭ **下一步 = M3(`sspf-compat-core`)**:迁 `compat/helper.rs`(902) + `compat/res.rs`(460)。M2 的「转发壳 + 闸门扫真源 + 反自证两处注入」套路直接复用。⚠️ M4 之后必须做 `check-contract-scan.py` 的 compat 包收编 + 重跑 `--self-test`。 + +### 15:58–16:05 四个决策拍板 + M3 完成(tag v0.1.3-m3) + +- **四个决策(用户拍板,已写入 docs/CRATES-MIGRATION.md §11)**:① `platform/` 转发壳**最后删**(M7);② compat **拆 6 个包**(按官方模块名);③ `mcp_compat.rs` **放 crates**;④ `tests/` **跟着拆**(单元测试随代码进 crate、集成测试留壳测装配结果)。 +- **M3**:`compat/helper.rs`(994) + `compat/res.rs`(460) → `crates/sspf-compat-core/src/`;壳留 `pub use sspf_compat_core::::*` ⇒ 14 个契约面模块 `use super::helper::{…}` 零感知。路径改写 `crate::platform::X` → `sspf_core::X`(独立 crate 不能用 `crate::X`);**`pub(super)` → `pub` 54 处**(转发壳的 `pub use …::*` 只转发 `pub` 项,含 struct 字段)。 +- **闸门(两处都扫纪律)**:AR11 扫真源+壳 + 新增 Cargo.toml 级判据(sspf-compat-core 不许依赖 sspf-compat-*);反自证 6/6 两处注入;`check-contract-scan.py` 的 `plat_files` 对 `compat__` 收真源+壳**同键拼接**(守卫常量在 helper 真源里,漏收则 CC6 假漂移)。 +- 🔴 **踩坑(真踩了)**:反向验证后用 `git checkout -- ` 清理探针 ⇒ **把 M3 的改写一并回退到暂存区**(`crate::platform`×14、`pub(super)`×54 复活,编译会炸)。**教训:有未暂存改动的文件绝不能用 `git checkout --` 清理临时改动** ⇒ 必须用 Python/编辑精确删目标行。这次是靠事后核验文件内容才发现的。 +- **数字**:`cargo build` 零警告;`cargo test` **695/0**;`check-arch` 14/14;`--self-test` 6/6;`check-boundary` 11/11;`check-contract` 10/10(CC6 零漂移);`check-module` 123/123;`check-citations` 4/4;`verify --smoke` 14 步全绿(561.3s)。 +- ⏭ **下一步 = M4(六个契约面包)**:`sspf-compat-{system,permission,msg,workflow,ext,online-dev}`。⚠️ 必须同步做 `check-contract-scan.py` 六包收编 + 重跑 `--self-test`。 diff --git a/Cargo.lock b/Cargo.lock index 28ba79e..13500ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1083,6 +1083,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "sspf-compat-core" +version = "0.1.0" +dependencies = [ + "axum", + "serde", + "serde_json", + "sspf-contract", + "sspf-core", +] + [[package]] name = "sspf-contract" version = "0.1.0" @@ -1184,6 +1195,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", + "sspf-compat-core", "sspf-contract", "sspf-core", "sspf-lowcode", diff --git a/HANDOFF.md b/HANDOFF.md index b8f987b..d4c536b 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -132,6 +132,38 @@ M2 的「转发壳 + 闸门扫真源 + 反自证两处注入」套路**直接复 --- +## 0-0-pre4. 2026-11-03 16:00 **M3 完成** + 四个决策拍板(tag `v0.1.3-m3`) + +**四个决策已拍板**(写入 `docs/CRATES-MIGRATION.md` §11): +① `platform/` 转发壳**最后删**(M7);② compat **拆 6 个包**;③ `mcp_compat.rs` **放 crates**;④ `tests/` **跟着拆**(单元测试随代码进 crate、集成测试留壳测装配)。 + +**M3 做了什么**:`compat/helper.rs`(994) + `compat/res.rs`(460) `git mv` 进 `crates/sspf-compat-core/src/`, +壳留 `pub use sspf_compat_core::::*;` ⇒ **14 个契约面模块的 `use super::helper::{…}` 零感知**。 + +**实际做法**:① 路径改写 `crate::platform::X` → `sspf_core::X`(独立 crate 不能用 `crate::X`); +② **`pub(super)` → `pub`(54 处)** —— 转发壳的 `pub use …::*` 只转发 `pub` 项,不提权则 14 个模块找不到 +`EN_USER`/`Paging`/`MenuRow`(含 struct 字段);③ helper 的 8 个单测自足 ⇒ 随迁,总数仍 695。 + +**闸门改造(同「两处都扫」纪律)**: +- `check-arch.sh` AR11 扫真源 + 壳,**新增 Cargo.toml 级判据**(`sspf-compat-core` 不许依赖 `sspf-compat-*`);反自证 6/6 两处注入、按路径分别验 +- `check-contract-scan.py` 的 `plat_files` 对 `compat__` **收真源 + 壳同键拼接** —— 守卫常量(`EN_ROLE` 等)在 helper 真源里,漏收则 CC6 假漂移 +- 修 1 条引文(`compat/helper.rs:89-92` → `crates/sspf-compat-core/src/helper.rs:87-91`) + +**反向验证**:只往真源 helper 塞 `use crate::res::Res;` ⇒ AR11 报红;清理后恢复绿。 + +**🔴 踩坑(已记入工作区记忆)**:反向验证后用 `git checkout -- ` 清理探针 ⇒ **把 M3 改写一并回退到暂存区** +(`crate::platform`×14、`pub(super)`×54 复活)。**教训:有未暂存改动的文件绝不能用 `git checkout --`** ⇒ 用 Python 精确删探针行。 + +**出口判据(全部达成)**: +`cargo build` 零警告;`cargo test --workspace` = **695 passed / 0 failed**;`check-arch` 14/14;`--self-test` 6/6; +`check-boundary` 11/11;`check-contract` 10/10(CC6 零漂移 ⇒ 守卫推导仍有效);`check-module` 123/123; +`check-citations` 4/4;`verify.sh --smoke` **14 步全绿**(561.3s)。 + +**⏭ 下一步 = M4(六个契约面包并行下沉)**:`sspf-compat-{system,permission,msg,workflow,ext,online-dev}`。 +⚠️ M4 必须同步做 `check-contract-scan.py` 六包收编 + 重跑 `--self-test`。 + +--- + ## 0-0. 2026-11-02 23:13 验证修复轮(官方前端 + dacli 真跑后修的) 用官方 vue 前端 + dacli + 586 条端点探针做过一轮真实系统性验证(报告: diff --git a/crates/sspf-compat-core/Cargo.toml b/crates/sspf-compat-core/Cargo.toml new file mode 100644 index 0000000..c67afc9 --- /dev/null +++ b/crates/sspf-compat-core/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "sspf-compat-core" +version.workspace = true +edition.workspace = true +rust-version.workspace = true + +# 🔴 **契约面公共底座**(M3 起从 `src/backend/src/platform/compat/` 下沉到这里)。 +# +# 装什么:`helper`(面 B 判别 / 登录守卫 / 分页信封 / SQL 参数 / 菜单与用户信息构造 / +# 守卫常量)+ `res`(通用单表资源引擎)—— 即被 14 个契约面模块**共用**的那层。 +# +# 🔴 **依赖纪律**: +# - 允许:平台核心(`sspf-core`:auth/权限/CRUD/信封/会话/应用状态) +# + 契约层(判别头 / 码表)+ axum(HTTP 包装)+ 序列化。 +# - 禁止:**业务包**(`sspf_pack_*`)—— 契约面不许认识任何业务。 +# - 禁止:**其它契约面模块**(`sspf-compat-*`)—— 本包是底座,被 14 个模块依赖; +# 反向依赖任何一个都会成环(AR11 的跨 crate 形态)。 +# +# 🔴 **为什么单独一个 crate**:14 个契约面模块都 `use super::helper::{…}`。 +# 底座先下沉 ⇒ M4 的 6 个包都能依赖它,不必互相依赖。 +[dependencies] +# 平台核心(auth / 权限 / CRUD / 信封 / 会话 / AppState) +sspf-core = { path = "../sspf-core" } +# 契约层(判别头 `is_face_b` / `VUE_VERSION`) +sspf-contract = { path = "../sspf-contract" } + +axum = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/sspf-compat-core/src/helper.rs b/crates/sspf-compat-core/src/helper.rs new file mode 100644 index 0000000..e0b19d5 --- /dev/null +++ b/crates/sspf-compat-core/src/helper.rs @@ -0,0 +1,994 @@ +//! helper —— 契约面的**公共底座**(导入 / 通用工具 / 判别 / 守卫 / 共享常量 / +//! 菜单与用户信息构造)。 +//! +//! 🔴 **为什么单独一个 `helper`**:契约面按官方模块拆开后,下列东西被**多个模块共用** +//! —— 放任何一个模块里都会让别的模块反向依赖它 ⇒ 拆分的意义就没了。 +//! 典型:面 B 判别头 `is_face_b`(**全部** handler 都要过)、登录守卫 `guard`、 +//! 分页信封 `page_list`、SQL 参数拼装 `params_of`、菜单树构造 `build_menu_tree`、 +//! 当前用户信息 `build_user_info`。 +//! +//! 🔴 **本文件不装业务知识**:只放「怎么把官方形状的请求变成响应」的基础设施。 +//! 真源:`JNPF_COMPAT_SURFACE.md`(§2.2 判别头 / §3 端点 / §4 码表)。 + + +use std::collections::{HashMap, HashSet}; +use axum::body::Bytes; +use axum::extract::{Path, RawQuery, State}; +use axum::http::HeaderMap; +use axum::Json; +use serde_json::{json, Map, Value}; +use sspf_core::envelope::{code, fail, ok, ActionResult}; +use sspf_core::db::{pglite, pglite::ToSql, Db}; +use sspf_core::auth::require_login_face_b; +use sspf_core::auth::resolve_user; +use sspf_core::crud::value_to_text; +use sspf_core::authorization::has_en_code_permission; +use sspf_core::authorization::resolve_user_module_ids; +use sspf_core::session::TokenUser; +use sspf_core::state::AppState; +use sspf_core::registry; +pub use sspf_contract::headers::VUE_VERSION; +/// 本仓的系统 id(`currentSystemId` / `userInfo.systemId` / 菜单 `systemId` 的兜底值)。 +/// +/// 🔴 单一真源在 [`sspf_core::registry`](`base_system.f_id`);这里只是别名, +/// **不要另写一份字面量**——否则主系统 id 改一处漏一处。 +pub const SYSTEM_ID: &str = registry::MAIN_SYSTEM_ID; + +/// 本仓的系统编码(`userInfo.systemCode`)。 +/// +/// 🔴 官方常量 `JnpfConst.MAIN_SYSTEM_CODE = "mainSystem"`;前端也硬比较这个值 +/// (`systemCode === 'mainSystem'` 决定首页布局)⇒ 同样只做别名。 +pub const SYSTEM_CODE: &str = registry::MAIN_SYSTEM_CODE; + +/// `@SaCheckPermission("permission.user")`。 +pub const EN_USER: &str = "permission.user"; + +/// `@SaCheckPermission("permission.role")`。 +pub const EN_ROLE: &str = "permission.role"; + +/// `@SaCheckPermission("permission.organize")`。 +pub const EN_ORGANIZE: &str = "permission.organize"; + +/// `@SaCheckPermission("permission.menu")`。 +pub const EN_MENU: &str = "permission.menu"; + +/// `@SaCheckPermission("permission.position")`。 +pub const EN_POSITION: &str = "permission.position"; + +/// 🔴 `@SaCheckPermission("permission.identity")`(官方 `StandingController`)。 +pub const EN_IDENTITY: &str = "permission.identity"; + +/// 🔴 `@SaCheckPermission("permission.authGroup")`(官方 `PermissionGroupController`)。 +pub const EN_AUTH_GROUP: &str = "permission.authGroup"; + +/// 🔴 `@SaCheckPermission("permission.action")`。 +/// +/// 🔴 官方 `ActionController` 是 `{"permission.auth", "permission.role", "permission.action"}` +/// 的 **SaMode.OR** 三选一;本仓的 `guard()` 只吃**一个**点权限码 +/// ⇒ 取**动作自己的**那个(最贴近语义)。 +pub const EN_ACTION: &str = "permission.action"; + +/// 🔴 `@SaCheckPermission("msgCenter.notice")`(官方 `NoticeController` 的公告那半截)。 +/// +/// 🔴 **只有公告守它**;消息列表 / 全部已读 / 读消息 / 删记录 / 回执 +/// **都不带** `@SaCheckPermission` —— 登录即可用(谁看自己的消息都不该要授权)。 +pub const EN_NOTICE: &str = "msgCenter.notice"; + +/// 菜单树的最大层数(防御 `f_parent_id` 被改成人为环时的无限递归)。 +pub const MAX_TREE_DEPTH: usize = 32; + +/// 🔴 **这个请求是不是「面 B」** —— 判别头 `Vue-Version: 3`。 +/// +/// **唯一的全局判别规则**(`JNPF_COMPAT_SURFACE.md` §2.2): +/// ```text +/// 请求头含 "Vue-Version: 3" ⇒ 走【面 B】官方形状 +/// 否则 ⇒ 走【面 A】ssw 形状 +/// ``` +pub fn is_face_b(headers: &HeaderMap) -> bool { + // 判据真值源在契约层:MCP 适配器、后续插件都要用同一份判断, + // 不许各自再写一遍 `Vue-Version == "3"`(写错一处就是两面串味)。 + sspf_contract::headers::is_face_b(headers) +} + +/// DB 报错 ⇒ 面 B 的 `500`(官方 `EXCEPTION`);真因只进服务端日志,**不外泄**。 +pub fn db_error(e: pglite::Error, ctx: &str) -> Json { + eprintln!("[face-b] {ctx}失败: {e}"); + fail(code::EXCEPTION, "系统异常,请联系管理员") +} + +/// 解析 JSON body;失败 ⇒ `fail(400, "请求参数格式错误")`。 +/// +/// 🔴 **不用 axum 的 `Json`**:它的解析失败会返回 **422 + 非信封 body** ⇒ 契约破。 +pub fn parse_body(body: &Bytes) -> Result> { + match serde_json::from_slice::(body) { + Ok(v) => Ok(v), + Err(_) => Err(fail(code::FAIL, "请求参数格式错误")), + } +} + +/// 分页参数(官方 `Pagination.java`:`pageSize` 默认 `20` / `currentPage` 默认 `1`)。 +pub struct Paging { + pub current_page: i64, + pub page_size: i64, + pub offset: i64, +} + +impl Paging { + /// 从 query 取分页参数;**缺失 / 非法 ⇒ 用官方默认值**(不报错)。 + pub fn of(raw: &RawQuery) -> Self { + let current_page = sspf_core::sys::query_param(raw, "currentPage") + .trim() + .parse::() + .unwrap_or(1) + .max(1); + // 🔴 `pageSize` 夹在 `[1, 1000]` —— 防「pageSize=0」把 SQL 打成语法错、 + // 防超大值把整表拉进内存。 + let page_size = sspf_core::sys::query_param(raw, "pageSize") + .trim() + .parse::() + .unwrap_or(20) + .clamp(1, 1000); + Self { + current_page, + page_size, + offset: (current_page - 1) * page_size, + } + } + + /// 从 **JSON body** 取分页参数(官方好几个「列表」是 `POST`,分页在 body 里 —— + /// 例如 `POST /api/message/Notice/List`)。缺失 / 非法同样回落官方默认值。 + pub fn of_body(obj: &Map) -> Self { + let num = |key: &str| { + obj.get(key) + .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) + }; + let current_page = num("currentPage").unwrap_or(1).max(1); + // 🔴 同一道夹逼:`pageSize` 落在 `[1, 1000]`。 + let page_size = num("pageSize").unwrap_or(20).clamp(1, 1000); + Self { + current_page, + page_size, + offset: (current_page - 1) * page_size, + } + } +} + +/// 官方 `PageListVO` —— `{pagination:{currentPage,pageSize,total}, list:[…]}`。 +/// +/// 🔴 **`data` 必须是对象**(不是裸数组)—— 官方 `PageListVO` 有 `pagination` + `list` 两个字段。 +pub fn page_list(current_page: i64, page_size: i64, total: i64, list: Vec) -> Value { + json!({ + "pagination": { + "currentPage": current_page, + "pageSize": page_size, + "total": total, + }, + "list": list, + }) +} + +/// 官方 `ListVO` —— `{list:[…]}`(**只有 `list` 一个字段**)。 +pub fn list_vo(list: Vec) -> Value { + json!({ "list": list }) +} + +/// 绑定参数数组 ⇒ `&[&(dyn ToSql + Sync)]`(值一律按 text 传,类型转换交给 SQL 里的 CAST)。 +pub fn params_of(values: &[Option]) -> Vec<&(dyn ToSql + Sync)> { + values.iter().map(|v| v as &(dyn ToSql + Sync)).collect() +} + +/// 面 B 的守卫:**登录(602)** + **点权限(`f_en_code` ⇒ 403)**。 +pub async fn guard( + state: &AppState, + headers: &HeaderMap, + en_code: &str, +) -> Result> { + let user = require_login_face_b(state, headers).await?; + // 🔴 多应用:按 `App-Code` 解析当前系统 ⇒ 点权限判据限定在该系统。 + let system_id = + registry::resolve_system_id(&state.db, registry::app_code_of(headers).as_deref()).await; + if has_en_code_permission(&state.db, &user.user_id, user.is_admin, en_code, &system_id).await { + Ok(user) + } else { + Err(fail(code::NO_PERMISSION, "无权限")) + } +} + +/// 一行菜单(`AllMenuSelectVO` 那 15 个字段的原料)。 +pub struct MenuRow { + pub id: String, + pub full_name: String, + pub en_code: Option, + pub parent_id: String, + pub icon: Option, + pub url_address: Option, + pub page_address: Option, + pub link_target: Option, + pub menu_type: i64, + pub property_json: Option, + pub sort_code: i64, + pub system_id: Option, + pub is_data: bool, +} + +/// 菜单投影(面 B 专用)—— 🔴 **显式列出每一列并加 `AS ""` 别名** +/// (PG 会把未加引号的标识符折叠成小写 ⇒ `row_to_json` 的键会变样且**静默**)。 +pub const MENU_PROJECTION: &str = "f_id AS \"id\", f_full_name AS \"fullName\", \ + f_en_code AS \"enCode\", COALESCE(f_parent_id, '0') AS \"parentId\", \ + f_icon AS \"icon\", f_url_address AS \"urlAddress\", \ + f_page_address AS \"pageAddress\", f_link_target AS \"linkTarget\", \ + COALESCE(f_type, 2) AS \"type\", f_property_json AS \"propertyJson\", \ + COALESCE(f_sort_code, 0) AS \"sortCode\", f_system_id AS \"systemId\", \ + COALESCE(f_is_data_authorize, 0) AS \"isData\""; + +/// 读当前用户**可见**的菜单行(未软删 + 四源合并过滤)。 +/// +/// 🔴 非管理员的可见集合来自 `resolve_user_module_ids`(四源合并:直授/角色/组织/岗位), +/// 与面 A 的 `build_menu_list` **同一套判据** ⇒ 两个面看到的菜单集合一致。 +pub async fn load_menus(db: &Db, user_id: &str, is_admin: i32, system_id: &str) -> Vec { + let sql = format!( + "SELECT {MENU_PROJECTION} FROM base_module WHERE f_delete_mark = 0 \ + AND f_system_id = $1::text \ + ORDER BY f_sort_code ASC, f_full_name ASC" + ); + let rows = match db.query_json_params(&sql, &[&system_id]).await { + Ok(rows) => rows, + Err(e) => { + eprintln!("[face-b] 菜单查询失败(按空菜单处理): {e}"); + return Vec::new(); + } + }; + let mut items: Vec = rows.iter().filter_map(parse_menu_row).collect(); + if is_admin != 1 { + let visible = resolve_user_module_ids(db, user_id).await; + items.retain(|m| visible.contains(&m.id)); + } + items +} + +/// 一行 JSON ⇒ [`MenuRow`]。 +pub fn parse_menu_row(row: &Value) -> Option { + let id = row["id"].as_str()?.to_string(); + if id.is_empty() { + return None; + } + Some(MenuRow { + id, + full_name: row["fullName"].as_str().unwrap_or_default().to_string(), + en_code: row["enCode"].as_str().map(str::to_string), + // 🔴 react: `parentId: m.parentId || '0'` —— 空 ⇒ `'0'`。 + parent_id: match row["parentId"].as_str() { + Some(p) if !p.is_empty() => p.to_string(), + _ => "0".to_string(), + }, + icon: row["icon"].as_str().map(str::to_string), + url_address: row["urlAddress"].as_str().map(str::to_string), + page_address: row["pageAddress"].as_str().map(str::to_string), + link_target: row["linkTarget"].as_str().map(str::to_string), + menu_type: row["type"].as_i64().unwrap_or(2), + property_json: row["propertyJson"].as_str().map(str::to_string), + sort_code: row["sortCode"].as_i64().unwrap_or(0), + system_id: row["systemId"].as_str().map(str::to_string), + is_data: row["isData"].as_i64().unwrap_or(0) != 0, + }) +} + +/// `f_property_json`(TEXT)⇒ JSON 值;空 / 非法 ⇒ `null`。 +fn parse_property_json(raw: Option<&str>) -> Value { + let Some(text) = raw else { + return Value::Null; + }; + let trimmed = text.trim(); + if trimmed.is_empty() { + return Value::Null; + } + serde_json::from_str::(trimmed).unwrap_or(Value::Null) +} + +/// 菜单在**面 B** 里对外的 `urlAddress` —— 官方前端的**视图路径**。 +/// +/// 规则(与官方前端 `generate-routes-backend.ts:57` 对目录的做法**同一条**): +/// `f_en_code` 的点换斜杠(`permission.user` ⇒ `permission/user`)。 +/// 🔴 库里的 `f_url_address` 是**面 A** 的守卫 key(`system/User`),**不能**直接给面 B。 +/// +/// 🔴 **本函数住在 helper,不住 `system.rs`** —— 它只依赖字符串处理, +/// 而 `system.rs` 依赖 helper(`guard` / `Paging` / `MenuRow` …)。 +/// 若 helper 反过来依赖 system ⇒ **循环依赖**(跨 crate 时编译器直接报错)。 +pub fn official_view_path(en_code: Option<&str>, fallback: Option<&str>) -> Option { + let code = en_code.map(str::trim).filter(|s| !s.is_empty())?; + let path = code.replace('.', "/"); + if path.is_empty() { + return fallback.map(str::to_string); + } + Some(path) +} + +/// 一个菜单节点 ⇒ 官方 `AllMenuSelectVO`(**15 个字段,一个不少**)。 +/// +/// 🔴 **键名与顺序照官方 `AllMenuSelectVO.java:12-50`**(`id` / `fullName` / `enCode` / +/// `parentId` / `icon` / `hasChildren` / `urlAddress` / `pageAddress` / `linkTarget` / +/// `children` / `type` / `propertyJson` / `sortCode` / `systemId` / `isData`)。 +pub fn menu_value(row: MenuRow, children: Vec, has_children: bool) -> Value { + let MenuRow { + id, + full_name, + en_code, + parent_id, + icon, + url_address, + page_address, + link_target, + menu_type, + property_json, + sort_code, + system_id, + is_data, + } = row; + json!({ + "id": id, + "fullName": full_name, + "enCode": en_code, + "parentId": parent_id, + "icon": icon, + "hasChildren": has_children, + // 🔴 **面 B 的 `urlAddress` 必须是「官方前端的视图路径」**,不是库里的 `f_url_address`。 + // 前端 `packages/utils/src/helpers/generate-routes-backend.ts:71-92`: + // `route.path = '/' + urlAddress`,且 `component = pageMap['/' + urlAddress + '/index.vue']` + // (`pageMap` = `import.meta.glob('../views/**/*.vue'`)⇒ 值必须指向**真实 .vue 文件**。 + // 而库里的 `f_url_address`(`system/User`)是**面 A** 的守卫 key,官方前端没有 + // `views/system/User/index.vue` ⇒ 点了菜单永远 404。 + // 官方自己的口径就是「编码 ⇒ 路径」(同一文件 `:57` 对目录/应用用的是 + // `/${enCode.replaceAll('.', '/')}`)⇒ 这里对**所有类型**统一用同一条规则: + // `permission.user` ⇒ `permission/user` ⇒ 命中 `views/permission/user/index.vue` ✅ + "urlAddress": official_view_path(en_code.as_deref(), url_address.as_deref()), + "pageAddress": page_address, + "linkTarget": link_target, + "children": children, + "type": menu_type, + "propertyJson": parse_property_json(property_json.as_deref()), + "sortCode": sort_code, + // 🔴 种子菜单的 `f_system_id` 是 NULL ⇒ 兜底成本仓系统 id(单系统)。 + "systemId": system_id + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| SYSTEM_ID.to_string()), + "isData": is_data, + }) +} + +/// 递归建一棵子树。 +/// +/// 🔴 **本函数住在 helper,不住 `system.rs`** —— 它只依赖 helper 自己的 +/// `menu_value` 与 `MAX_TREE_DEPTH`;而 `system.rs` 依赖 helper +/// ⇒ 放 system 会形成**循环依赖**(拆 crate 后编译器直接报错)。 +pub fn menu_node( + row: MenuRow, + by_parent: &mut HashMap>, + depth: usize, +) -> Value { + // 防御:`f_parent_id` 被改成人为环时不要无限递归(层数封顶 ⇒ 截断)。 + let children: Vec = if depth >= MAX_TREE_DEPTH { + Vec::new() + } else { + by_parent + .remove(&row.id) + .unwrap_or_default() + .into_iter() + .map(|child| menu_node(child, by_parent, depth + 1)) + .collect() + }; + let has_children = !children.is_empty(); + menu_value(row, children, has_children) +} + +/// 建菜单树(根 = `parentId` 为空 / `'0'` / **父不在可见集合内**)。 +fn build_menu_tree(rows: Vec) -> Vec { + let visible: HashSet = rows.iter().map(|m| m.id.clone()).collect(); + let mut by_parent: HashMap> = HashMap::new(); + let mut roots: Vec = Vec::new(); + for row in rows { + if row.parent_id != "0" && visible.contains(&row.parent_id) { + by_parent.entry(row.parent_id.clone()).or_default().push(row); + } else { + roots.push(row); + } + } + roots + .into_iter() + .map(|row| menu_node(row, &mut by_parent, 0)) + .collect() +} + +/// 官方 `PermissionModel` 列表 —— **每个可见菜单一条**。 +/// +/// 🔴 **官方语义**:`modelId` = **菜单 id** +/// (官方前端 `views/common/dynamicModel/list/index.vue:739`: +/// `permissionList.find(o => o.modelId === searchInfo.menuId)`) +/// ⇒ 本仓按「菜单」给一条,`moduleName` = 菜单全名。 +/// +/// 🔴 `button` / `column` / `resource` / `form` **恒为空数组** —— 本仓**不实现** +/// 按钮级权限(`base_module_button` / `_column` / `_form` / `_data` 都不做) +/// ⇒ 官方前端的按钮会被过滤掉(**已知限制 B4**,`docs/known-limitations.md` §H)。 +fn build_permission_list(rows: &[MenuRow]) -> Vec { + rows.iter() + .map(|m| { + json!({ + "modelId": m.id, + "moduleName": m.full_name, + "button": [], + "column": [], + "resource": [], + "form": [], + }) + }) + .collect() +} + +/// `GET /api/oauth/CurrentUser` 的**面 B**分支 —— 官方 `PcUserVO` 形状。 +/// +/// 🔴 **顶层五个字段一个都不能少**(官方前端 `store/auth.ts:121` 逐个取用): +/// `menuList` / `permissionList` / `userInfo` / `currentSystemId` / `sysConfigInfo`。 +/// +/// 🔴 未登录 ⇒ **`602`**(官方前端只对 `601`/`602` 清 token ⇒ 返 `600` 会卡住不跳登录)。 +pub async fn current_user(state: &AppState, headers: &HeaderMap) -> Json { + let Some(user) = resolve_user(state, headers) else { + return fail(code::SESSION_ERROR, "登录状态已失效,请重新登录"); + }; + + // 🔴 多应用:按 `App-Code` 解析当前系统 ⇒ 菜单树 / userInfo / currentSystemId 都按该系统。 + let sys = registry::resolve_system(&state.db, registry::app_code_of(headers).as_deref()).await; + let menus = load_menus(&state.db, &user.user_id, user.is_admin, &sys.id).await; + let permission_list = build_permission_list(&menus); + let menu_list = build_menu_tree(menus); + let user_info = build_user_info(&state.db, &user, &sys.id, &sys.code).await; + + ok(json!({ + "menuList": menu_list.clone(), + "permissionList": permission_list, + // 🔴 官方 `GetUserInfoModel`(`basic.d.ts:94-100`)声明了 `routerList` 但 + // **前端一处都没读**(`grep routerList` 在 app/packages 里 0 命中); + // 为对齐类型仍给出同一棵树,避免将来有页面取值时拿到 undefined。 + "routerList": menu_list, + "userInfo": user_info, + "currentSystemId": sys.id, + // 🔴 `sysConfigInfo` 返 **空对象**(不是 null)⇒ 官方前端 `baseStore.setSysConfig` 不炸。 + "sysConfigInfo": {}, + })) +} + +/// 官方 `UserCommonInfoVO`(15 个字段)。 +/// +/// 🔴 `isAdministrator` 在这里是 **布尔**(官方 `UserCommonInfoVO.java:75` 是 `Boolean`)—— +/// 而**列表项**里它是**数字**(官方 `UserListVO.java:60` 是 `Integer`)⇒ 两处**故意不同**。 +async fn build_user_info(db: &Db, user: &TokenUser, system_id: &str, system_code: &str) -> Value { + let rows = match db + .query_json_params( + "SELECT f_real_name AS \"realName\", f_head_icon AS \"headIcon\", \ + f_organize_id AS \"organizeId\", f_position_id AS \"positionId\", \ + f_mobile_phone AS \"mobilePhone\", f_email AS \"email\", \ + f_gender AS \"gender\", f_role_id AS \"roleId\", f_group_id AS \"groupId\", \ + f_secretkey AS \"secretKey\", f_manager_id AS \"manager\", \ + (EXTRACT(EPOCH FROM f_birthday) * 1000)::bigint AS \"birthday\", \ + (EXTRACT(EPOCH FROM f_prev_log_time) * 1000)::bigint AS \"prevLoginTime\", \ + f_prev_log_ip AS \"prevLoginIp\" \ + FROM base_user WHERE f_id = $1::text AND f_delete_mark = 0 LIMIT 1", + &[&user.user_id], + ) + .await + { + Ok(rows) => rows, + Err(e) => { + eprintln!("[face-b] 读用户信息失败: {e}"); + Vec::new() + } + }; + let row = rows.first(); + let real_name = row + .and_then(|r| r["realName"].as_str()) + .filter(|s| !s.is_empty()) + .unwrap_or(user.account.as_str()) + .to_string(); + let head_icon = row.and_then(|r| r["headIcon"].as_str()).map(str::to_string); + let organize_id = row + .and_then(|r| r["organizeId"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let position_id = row + .and_then(|r| r["positionId"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let prev_login_time = row.and_then(|r| r["prevLoginTime"].as_i64()); + let prev_login_ip = row + .and_then(|r| r["prevLoginIp"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let organize_name = match organize_id.as_deref() { + Some(id) => organize_name_of(db, id).await, + None => None, + }; + // 🔴 `f_role_id` / `f_group_id` 是 TEXT(官方历史遗留,逗号分隔)⇒ 拆成数组。 + // 官方 `UserInfo` 把 `roleIds` / `groupIds` / `organizeIds` 声明成**非可选数组**, + // 前端 store 会直接遍历 ⇒ 缺键或给 null 都可能崩,这里一律给空数组兜底。 + let text_of = |key: &str| { + row.and_then(|r| r[key].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string) + }; + let split_ids = |key: &str| -> Vec { + text_of(key) + .map(|s| { + s.split(',') + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(str::to_string) + .collect() + }) + .unwrap_or_default() + }; + let role_ids = split_ids("roleId"); + let group_ids = split_ids("groupId"); + let organize_ids: Vec = organize_id.iter().cloned().collect(); + let organize_list_vo: Vec = organize_id + .as_ref() + .map(|id| { + vec![json!({ + "id": id, + "fullName": organize_name.clone().unwrap_or_default(), + })] + }) + .unwrap_or_default(); + + json!({ + "userId": user.user_id, + "userAccount": user.account, + "userName": real_name, + "headIcon": head_icon, + // ---- 以下为官方 `UserInfo`(`basic.d.ts:52-92`)的完整字段集 ---- + // 🔴 该类型里 `roleIds` / `groupIds` / `organizeIds` / `positionIds` / + // `organizeList` / `positionList` / `standingList` 都是**非可选数组** ⇒ + // 必须给 [](缺键会让前端 store 遍历时崩)。 + "gender": text_of("gender"), + "birthday": row.and_then(|r| r["birthday"].as_i64()), + "mobilePhone": text_of("mobilePhone"), + "email": text_of("email"), + "manager": text_of("manager"), + "organizeId": organize_id, + "organizeIds": organize_ids, + "organizeName": organize_name, + "organizeList": organize_list_vo, + "positionId": position_id, + // 🔴 本仓**没有**岗位表(`base_position` 不在 v1 范围)⇒ 恒空。 + "positionIds": Vec::::new(), + "positionList": Vec::::new(), + "positionName": Value::Null, + "roleIds": role_ids, + "roleName": Value::Null, + "groupIds": group_ids, + "standingList": Vec::::new(), + "portalId": Value::Null, + "departmentId": Value::Null, + "departmentName": Value::Null, + "systemId": system_id, + "systemCode": system_code, + "systemName": if system_code == SYSTEM_CODE { "系统平台" } else { "" }, + "systemColor": "", + "systemIcon": "", + "securityKey": text_of("secretKey").unwrap_or_default(), + "signId": "", + "signImg": "", + "saasAppId": "", + "saasAppName": "", + // 🔴 前端 `store/auth.ts:143` 的 `handleUpdatePreferences`: + // `if (userInfo.preferenceJson) preferenceJson = JSON.parse(userInfo.preferenceJson)` + // ⇒ **空串会被判假** ⇒ 保留前端自带的 `defaultPreferencesConfig`; + // 而给 `"{}"` 会被 parse 成空对象 ⇒ `updatePreferences({})` 把整套偏好清空 + // ⇒ `app.locale` / `app.defaultHomePath` 全丢 ⇒ 抛错 ⇒ `fetchUserInfo` 进 catch + // ⇒ 立刻 logout(**登录页原地打转的真正原因**,排查了两个小时的那条)。 + // ⇒ 必须是**字符串**,且必须是**空串**(不是 `"{}"`)。 + "preferenceJson": "", + // 🔴 官方 `prevLogin`:1 = 上次登录 / 2 = 本次登录。本仓不区分 ⇒ 恒 1。 + "prevLogin": 1, + "prevLoginTime": prev_login_time, + "prevLoginIPAddress": prev_login_ip, + "prevLoginIPAddressName": Value::Null, + "isAdministrator": user.is_admin == 1, + }) +} + +/// 取 body 里的 id 数组(`{ids:[…]}` / `{ids:"a,b"}` 都认)。 +/// +/// 🔴 非数组 ⇒ **空集合**(官方批量接口对空集合返回成功,不报错)。 +/// 取 `obj[key]` 的字符串 id 数组(数组或逗号串都收;空 ⇒ 空数组)。 +pub fn id_list_of(obj: &Map, key: &str) -> Vec { + match obj.get(key) { + Some(Value::Array(items)) => items + .iter() + .filter_map(|v| match v { + Value::String(s) if !s.is_empty() => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + }) + .collect(), + Some(Value::String(s)) if !s.is_empty() => { + s.split(',').map(|x| x.trim().to_string()).collect() + } + _ => Vec::new(), + } +} + +pub fn id_list(obj: &Map) -> Vec { + match obj.get("ids") { + Some(Value::Array(items)) => items + .iter() + .filter_map(|v| match v { + Value::String(s) if !s.is_empty() => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + }) + .collect(), + Some(Value::String(s)) if !s.is_empty() => { + s.split(',').map(|x| x.trim().to_string()).collect() + } + _ => Vec::new(), + } +} + +/// `$1::text::integer` 这种占位符(**统一走 text 传值,类型交给 SQL 里的 CAST**)。 +pub fn placeholder(index: usize, cast: &str) -> String { + format!("${index}::text{cast}") +} + +/// 详情投影 —— 编辑弹窗 `setFieldsValue(res.data)` **直接吃这份**。 +/// +/// 🔴 少一个键 ⇒ 弹窗里那一格永远是空的,而且**不报错**(静默)。 +/// 🔴 `birthday` / `entryDate` 用 `to_char(…,'YYYY-MM-DD')`:官方 VO 是日期串, +/// `::text` 会带出 ` 00:00:00` ⇒ DatePicker 解析失败。 +/// +/// 🔴 **本常量住在 helper,不住 `permission.rs`** —— 它被 helper 的 `user_info` 用; +/// 而 helper 被 14 个契约面模块依赖 ⇒ 放 permission 会形成**循环依赖**。 +pub const USER_DETAIL_COLUMNS: &str = "f_id AS \"id\", f_account AS \"account\", \ + f_real_name AS \"realName\", f_nick_name AS \"nickName\", f_head_icon AS \"headIcon\", \ + f_gender AS \"gender\", to_char(f_birthday, 'YYYY-MM-DD') AS \"birthday\", \ + f_mobile_phone AS \"mobilePhone\", f_tele_phone AS \"telePhone\", f_landline AS \"landline\", \ + f_email AS \"email\", f_nation AS \"nation\", f_native_place AS \"nativePlace\", \ + to_char(f_entry_date, 'YYYY-MM-DD') AS \"entryDate\", \ + f_certificates_type AS \"certificatesType\", \ + f_certificates_number AS \"certificatesNumber\", f_education AS \"education\", \ + f_urgent_contacts AS \"urgentContacts\", f_urgent_tele_phone AS \"urgentTelePhone\", \ + f_postal_address AS \"postalAddress\", f_signature AS \"signature\", \ + f_description AS \"description\", COALESCE(f_sort_code, 0) AS \"sortCode\", \ + COALESCE(f_enabled_mark, 0) AS \"enabledMark\", f_rank AS \"ranks\", \ + f_organize_id AS \"organizeId\", f_position_id AS \"positionId\", \ + COALESCE(f_is_administrator, 0) AS \"isAdministrator\", \ + COALESCE(f_lock_mark, 0) AS \"lockMark\", f_unlock_time AS \"unlockTime\", \ + (EXTRACT(EPOCH FROM f_creator_time) * 1000)::bigint AS \"creatorTime\", \ + f_creator_user_id AS \"creatorUserId\", f_tenant_id AS \"tenantId\", \ + COALESCE(f_delete_mark, 0) AS \"deleteMark\""; + +/// 机构名(查不到 ⇒ `None`)。 +/// +/// 🔴 **本函数住在 helper,不住 `permission.rs`** —— 它被 helper 的 +/// `build_user_info` 用;放 permission 会形成**循环依赖**(同 `USER_DETAIL_COLUMNS`)。 +pub async fn organize_name_of(db: &Db, id: &str) -> Option { + let rows = match db + .query_json_params( + "SELECT f_full_name AS \"fullName\" FROM base_organize \ + WHERE f_id = $1::text AND f_delete_mark = 0 LIMIT 1", + &[&id], + ) + .await + { + Ok(rows) => rows, + Err(e) => { + eprintln!("[face-b] 读机构名失败: {e}"); + return None; + } + }; + rows.first() + .and_then(|r| r["fullName"].as_str()) + .map(str::to_string) +} + +/// `GET /api/permission/Users/{id}` —— 单条详情(编辑弹窗)。 +/// +/// ⚠️ **`{id}` 会吞掉所有「`Users/` 下一段的静态 GET」**(`Selector` / `getWorkByUser` / +/// `getUserList` …):它们现在会落到这里、返 `400 用户不存在`,而不是 404。 +/// matchit 的口径是**静态段优先** ⇒ 一旦把那些路由注册进来,自动夺回,无需改这里。 +pub async fn user_info( + State(state): State, + headers: HeaderMap, + Path(id): Path, +) -> Json { + if let Err(resp) = guard(&state, &headers, EN_USER).await { + return resp; + } + let id = id.trim().to_string(); + let sql = format!( + "SELECT {USER_DETAIL_COLUMNS} FROM base_user \ + WHERE f_id = $1::text AND f_delete_mark = 0 LIMIT 1" + ); + let rows = match state.db.query_json_params(&sql, &[&id]).await { + Ok(rows) => rows, + Err(e) => return db_error(e, "用户详情查询"), + }; + match rows.into_iter().next() { + Some(row) => ok(row), + None => fail(code::FAIL, "用户不存在"), + } +} + +/// 用户选择器的投影(`QueryUserSelect` 要 `id` + `fullName`,多选还要 `headIcon`)。 +pub const USER_SELECTOR_PROJECTION: &str = "f_id AS \"id\", f_real_name AS \"fullName\", \ + f_account AS \"account\", f_head_icon AS \"headIcon\", \ + f_organize_id AS \"organizeId\", f_gender AS \"gender\""; + +/// 批量取「姓名/账号」标签(官方 `realName + "/" + account`)。 +/// +/// 🔴 **按 `f_id` 与 `f_account` 双键建表**:本仓写 `f_creator_user_id` 时用的是**账号** +/// (见 `seed.rs` 的 `ADMIN_ACCOUNT`),而官方的历史数据里是 **id** +/// ⇒ 只按其中一种查,另一种就永远显示空。两种都收,key 也两样都放。 +pub async fn user_labels(state: &AppState, ids: &[String]) -> HashMap { + let mut unique: Vec = ids.iter().filter(|s| !s.is_empty()).cloned().collect(); + unique.sort(); + unique.dedup(); + if unique.is_empty() { + return HashMap::new(); + } + let joined = unique.join(","); + match state + .db + .query_json_params( + "SELECT f_id AS \"id\", f_real_name AS \"realName\", f_account AS \"account\" \ + FROM base_user \ + WHERE f_id = ANY(string_to_array($1::text, ',')) \ + OR f_account = ANY(string_to_array($1::text, ','))", + &[&joined], + ) + .await + { + Ok(rows) => { + let mut map = HashMap::new(); + for row in rows { + let id = row + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let account = row.get("account").and_then(Value::as_str).unwrap_or(""); + let name = row + .get("realName") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .unwrap_or(account); + let label = if account.is_empty() || name == account { + name.to_string() + } else { + format!("{name}/{account}") + }; + if !id.is_empty() { + map.insert(id, label.clone()); + } + if !account.is_empty() { + map.insert(account.to_string(), label); + } + } + map + } + Err(e) => { + eprintln!("[face-b] 用户标签查询失败(降级为空): {e}"); + HashMap::new() + } + } +} + +/// 面 B 的「任一权限」守卫 —— 官方用 `@SaCheckPermission(..., mode = SaMode.OR)` 的地方。 +pub async fn guard_any( + state: &AppState, + headers: &HeaderMap, + en_codes: &[&str], +) -> Result> { + let user = require_login_face_b(state, headers).await?; + let system_id = + registry::resolve_system_id(&state.db, registry::app_code_of(headers).as_deref()).await; + for en_code in en_codes { + if has_en_code_permission(&state.db, &user.user_id, user.is_admin, en_code, &system_id).await + { + return Ok(user); + } + } + Err(fail(code::NO_PERMISSION, "无权限")) +} + +/// JSON 对象里取文本(**去首尾空白**,空串 ⇒ `None`)。 +pub fn text_field(obj: &Map, key: &str) -> Option { + let raw = value_to_text(obj.get(key))?; + let trimmed = raw.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } +} + +/// JSON 对象里取整数(`1` / `"1"` / `true` 都认)—— 用于 `::text::integer` 参数位。 +/// +/// 🔴 不能把 JSON 数字直接 `value_to_text` 后当参数:`1.0` 会变成 `"1.0"`, +/// `'1.0'::text::integer` 在 PG 里是**硬错误**(`invalid input syntax`)。 +pub fn int_field(obj: &Map, key: &str) -> Option { + match obj.get(key)? { + Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)), + Value::String(s) => s.trim().parse::().ok(), + Value::Bool(b) => Some(i64::from(*b)), + _ => None, + } +} + +/// 取 query 里的字符串参数(去空白)。 +pub fn qv(raw: &RawQuery, key: &str) -> String { + sspf_core::sys::query_param(raw, key).trim().to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn headers_with(vue_version: Option<&str>) -> HeaderMap { + let mut headers = HeaderMap::new(); + if let Some(v) = vue_version { + headers.insert( + VUE_VERSION, + axum::http::HeaderValue::from_str(v).expect("头值必须是合法 ASCII"), + ); + } + headers + } + + /// 🔴 **判别规则只有一条**:头 `Vue-Version: 3` ⇒ 面 B;否则面 A。 + #[test] + fn discriminator_is_vue_version_header() { + assert!(is_face_b(&headers_with(Some("3")))); + assert!(!is_face_b(&headers_with(None))); + // 🔴 本仓前端也发 `App-Code` / `Jnpf-Origin` ⇒ **不能**拿它们当判据。 + let mut headers = headers_with(None); + headers.insert("app-code", axum::http::HeaderValue::from_static("mainSystem")); + headers.insert("jnpf-origin", axum::http::HeaderValue::from_static("pc")); + assert!(!is_face_b(&headers), "App-Code / Jnpf-Origin 绝不能当判别头"); + } + + /// 头值带空格也应识别(HTTP 头值两侧空白无意义)。 + #[test] + fn discriminator_ignores_surrounding_whitespace() { + assert!(is_face_b(&headers_with(Some(" 3 ")))); + } + + /// 头值不是 `3`(如 `2`)⇒ 不是面 B。 + #[test] + fn discriminator_rejects_other_values() { + assert!(!is_face_b(&headers_with(Some("2")))); + assert!(!is_face_b(&headers_with(Some("")))); + } + + /// 🔴 **官方 `PageListVO` 形状**:`{pagination:{currentPage,pageSize,total}, list:[…]}`。 + #[test] + fn page_list_vo_has_pagination_and_list() { + let v = page_list(2, 20, 42, vec![json!({"id": "u1"})]); + assert_eq!(v["pagination"]["currentPage"], 2); + assert_eq!(v["pagination"]["pageSize"], 20); + assert_eq!(v["pagination"]["total"], 42); + assert!(v["list"].is_array()); + assert_eq!(v["list"][0]["id"], "u1"); + } + + /// 🔴 **官方 `ListVO` 形状**:`{list:[…]}`(**只有** `list` 一个字段)。 + #[test] + fn list_vo_has_only_list() { + let v = list_vo(vec![json!({"id": "m1"})]); + assert!(v.get("list").is_some()); + assert!(v.get("pagination").is_none()); + assert_eq!(v.as_object().map(|o| o.len()), Some(1)); + } + + /// 分页参数:缺省 ⇒ 官方默认(`pageSize=20` / `currentPage=1`)。 + #[test] + fn paging_defaults_to_official_values() { + let raw = RawQuery(None); + let p = Paging::of(&raw); + assert_eq!(p.current_page, 1); + assert_eq!(p.page_size, 20); + assert_eq!(p.offset, 0); + } + + /// 分页参数:回显请求值;`pageSize=0` / 负数 ⇒ 夹到 1(不生成非法 SQL)。 + #[test] + fn paging_echoes_and_clamps() { + let raw = RawQuery(Some("currentPage=3&pageSize=5".to_string())); + let p = Paging::of(&raw); + assert_eq!(p.current_page, 3); + assert_eq!(p.page_size, 5); + assert_eq!(p.offset, 10); + + let raw = RawQuery(Some("pageSize=0¤tPage=-1".to_string())); + let p = Paging::of(&raw); + assert_eq!(p.current_page, 1); + assert_eq!(p.page_size, 1); + } + + /// 🔴 **菜单节点必须齐 15 个官方字段**(`AllMenuSelectVO.java:12-50`)。 + #[test] + fn menu_node_has_all_15_official_keys() { + let row = MenuRow { + id: "m1".to_string(), + full_name: "用户管理".to_string(), + en_code: Some("permission.user".to_string()), + parent_id: "0".to_string(), + icon: None, + url_address: Some("system/User".to_string()), + page_address: None, + link_target: None, + menu_type: 2, + property_json: None, + sort_code: 2, + system_id: None, + is_data: false, + }; + let v = menu_value(row, Vec::new(), false); + for key in [ + "id", + "fullName", + "enCode", + "parentId", + "icon", + "hasChildren", + "urlAddress", + "pageAddress", + "linkTarget", + "children", + "type", + "propertyJson", + "sortCode", + "systemId", + "isData", + ] { + assert!(v.get(key).is_some(), "面 B 菜单节点必须含键 {key}"); + } + // 🔴 `systemId` 为 NULL ⇒ 兜底成本仓系统 id(单系统)。 + assert_eq!(v["systemId"], SYSTEM_ID); + assert_eq!(v["isData"], false); + assert_eq!(v["children"].as_array().map(|a| a.len()), Some(0)); + } + + /// `propertyJson`:空 ⇒ `null`;合法 JSON ⇒ 解析;非法 ⇒ `null`。 + #[test] + fn property_json_is_parsed_or_null() { + assert_eq!(parse_property_json(None), Value::Null); + assert_eq!(parse_property_json(Some(" ")), Value::Null); + assert_eq!(parse_property_json(Some("{\"a\":1}"))["a"], 1); + assert_eq!(parse_property_json(Some("not json")), Value::Null); + } + + /// 🔴 **`permissionList` 的 `modelId` 是菜单 id**(官方语义:`find(o => o.modelId === menuId)`)。 + #[test] + fn permission_list_model_id_is_menu_id() { + let rows = vec![MenuRow { + id: "m_user".to_string(), + full_name: "用户管理".to_string(), + en_code: Some("permission.user".to_string()), + parent_id: "m_sys".to_string(), + icon: None, + url_address: None, + page_address: None, + link_target: None, + menu_type: 2, + property_json: None, + sort_code: 2, + system_id: None, + is_data: false, + }]; + let list = build_permission_list(&rows); + assert_eq!(list.len(), 1); + assert_eq!(list[0]["modelId"], "m_user"); + assert_eq!(list[0]["moduleName"], "用户管理"); + for key in ["button", "column", "resource", "form"] { + assert_eq!(list[0][key].as_array().map(|a| a.len()), Some(0)); + } + } +} diff --git a/crates/sspf-compat-core/src/lib.rs b/crates/sspf-compat-core/src/lib.rs new file mode 100644 index 0000000..739ffc0 --- /dev/null +++ b/crates/sspf-compat-core/src/lib.rs @@ -0,0 +1,21 @@ +//! # sspf-compat-core —— 契约面公共底座(面 B) +//! +//! 被 **14 个**契约面模块共用的基础设施,M3 起从 `src/backend/src/platform/compat/` +//! 下沉到这里(见 `docs/CRATES-MIGRATION.md` §4 M3)。 +//! +//! | 模块 | 装什么 | +//! |---|---| +//! | [`helper`] | 面 B 判别头 / 登录守卫 / 分页信封 `PageListVO` / SQL 参数拼装 / 菜单树与用户信息构造 / 守卫常量 | +//! | [`res`] | 通用**单表**资源引擎(`aiCenter`/`extend`/`teamwork` 约 150 条端点的 list/info/create/update/delete 共用) | +//! +//! 🔴 **依赖纪律(AR11 的跨 crate 形态)**:本 crate **只许**依赖 +//! `sspf-core`(平台核心)+ `sspf-contract`(判别头/码表)+ axum/serde。 +//! **禁止**依赖 `sspf-compat-*` 其它契约面包 / `sspf_pack_*` 业务包 —— +//! 本包是底座,被 14 个模块依赖;反向依赖任何一个都会成环。 +//! +//! 🔴 **`src/backend/src/platform/compat/{helper,res}.rs` 只是转发壳** +//! (`pub use sspf_compat_core::helper::*;`)⇒ 14 个模块的 +//! `use super::helper::{…}` **不用改**(M4 才统一改 import 路径)。 + +pub mod helper; +pub mod res; diff --git a/crates/sspf-compat-core/src/res.rs b/crates/sspf-compat-core/src/res.rs new file mode 100644 index 0000000..0c86336 --- /dev/null +++ b/crates/sspf-compat-core/src/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 sspf_core::db::{pglite, Db}; +use sspf_core::envelope::{code, fail, ok, ActionResult}; +use sspf_core::ids::new_uuid; +use sspf_core::state::AppState; + +use crate::helper::{db_error, params_of, parse_body, qv, Paging}; + +/// 列类型(决定投影与写入的 SQL 形状)。 +#[derive(Clone, Copy)] +pub enum Kind { + Text, + Int, + Json, +} + +/// 一列的映射:JSON 键 ↔ 物理列。 +pub struct Field { + pub json: &'static str, + pub col: &'static str, + pub kind: Kind, +} + +/// `Field` 的简写构造(模块里用 `t("fullName", "f_full_name")` 声明)。 +pub const fn t(json: &'static str, col: &'static str) -> Field { + Field { + json, + col, + kind: Kind::Text, + } +} + +pub const fn i(json: &'static str, col: &'static str) -> Field { + Field { + json, + col, + kind: Kind::Int, + } +} + +pub const fn j(json: &'static str, col: &'static str) -> Field { + Field { + json, + col, + kind: Kind::Json, + } +} + +/// 一张资源的声明。 +pub 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 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(crate::helper::page_list( + paging.current_page, + paging.page_size, + total, + rows, + )) +} + +/// 不分页的 `ListVO`。 +pub 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 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 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 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 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 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 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 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 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 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 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 fn filter(raw: &RawQuery, key: &str, col: &'static str) -> (&'static str, String) { + (col, qv(raw, key)) +} + + diff --git a/docs/CRATES-MIGRATION.md b/docs/CRATES-MIGRATION.md index 8a5f68a..100475e 100644 --- a/docs/CRATES-MIGRATION.md +++ b/docs/CRATES-MIGRATION.md @@ -2,9 +2,9 @@ > **基线锚点**:`v0.1.0`(commit `b957a11`,已推送到 `origin`) > **制定时间**:2026-11-03 -> **状态**:**M2 已完成**(tag `v0.1.2-m2`)—— 平台核心 19 个模块下沉到 `crates/sspf-core/`, -> `platform/*.rs` 只剩转发壳;闸门同步改造(扫真源而非空壳)。 -> 下一步 = M3(`sspf-compat-core` 契约面公共底座) +> **状态**:**M3 已完成**(tag `v0.1.3-m3`)—— 契约面公共底座 `sspf-compat-core` 下沉完成; +> 四个决策已拍板(§11):壳最后删 / compat 拆 6 包 / mcp_compat 放 crates / tests 跟着拆。 +> 下一步 = M4(六个契约面包并行下沉) --- @@ -82,7 +82,7 @@ crates/sspf-contract/src/headers.rs:32 pub fn is_face_b(headers: &HeaderMap) -> bool # 已有,且带 3 条单测 ``` -当前 `compat/helper.rs:89-92` 只是一个**转发壳**: +当前 [`crates/sspf-compat-core/src/helper.rs:87-91`](crates/sspf-compat-core/src/helper.rs)(M3 起真源在此)只是一个**转发壳**: ```rust pub fn is_face_b(headers: &HeaderMap) -> bool { sspf_contract::headers::is_face_b(headers) @@ -351,13 +351,39 @@ ssw-platform/ - [x] `check-module.sh` 123/123;`check-citations.sh` 4/4 - [x] `verify.sh --smoke` 14 步全绿(512.3s) -### 批次 M3 —— 契约面公共底座:`sspf-compat-core` +### 批次 M3 —— 契约面公共底座:`sspf-compat-core` ✅ 已完成(tag `v0.1.3-m3`) -**迁入**:`platform/compat/helper.rs`(902 行)+ `platform/compat/res.rs`(460 行) +**迁入**:`platform/compat/helper.rs`(994 行)+ `platform/compat/res.rs`(460 行)→ `crates/sspf-compat-core/src/` -**新 crate**:`crates/sspf-compat-core`(依赖 axum + sspf-core + sspf-contract + sspf-store) +**新 crate**:`crates/sspf-compat-core`(依赖 sspf-core + sspf-contract + axum + serde + serde_json) -**出口判据**:`check-contract-scan.py` 的守卫推导**仍然有效**(见 §5 闸门改造)。 +**保留转发壳**:`src/backend/src/platform/compat/{helper,res}.rs` = `pub use sspf_compat_core::::*;` +⇒ **14 个契约面模块的 `use super::helper::{…}` 零感知**(M4 才统一改 import)。 + +**实际做法**: +1. **路径改写**:`crate::platform::X` → `sspf_core::X`(本 crate 是独立 crate,不能用 `crate::X`);res.rs 的 `super::helper` → `crate::helper`。 +2. **`pub(super)` → `pub`(54 处)**:转发壳的 `pub use …::*` **只转发 `pub` 项** ⇒ 不提权则 14 个模块找不到 `EN_USER`/`Paging`/`MenuRow` 等(含 struct 字段)。 +3. **测试随迁**:helper 的 8 个单测(判别头 / PageListVO / ListVO / Paging / 菜单 15 字段)自足(只用 `super::*`)⇒ 随文件进新 crate,总测试数不变 695。 + +**闸门改造(同 M2 纪律 = 两处都扫)**: +| 闸门 | 改造 | +|---|---| +| `check-arch.sh` AR11 | 扫真源 `crates/sspf-compat-core/src/helper.rs` + 壳;**新增 Cargo.toml 级判据**(`sspf-compat-core` 不许依赖 `sspf-compat-*`,M4 的 6 个包) | +| `check-arch.sh` 反自证 6/6 | **两处都注入**探针(真源 + 壳),按路径分别验 | +| `check-contract-scan.py` | `plat_files` 的 `compat__` **收真源 + 壳同键拼接** —— 守卫常量(`EN_ROLE` 等)在 helper 真源里,漏收则 CC6 假漂移 | +| `docs/CRATES-MIGRATION.md` | 引文 `compat/helper.rs:89-92` → `crates/sspf-compat-core/src/helper.rs:87-91` | + +**反向验证**:只往真源 helper 塞 `use crate::res::Res;` ⇒ AR11 报红;清理后恢复绿。 + +**🔴 踩坑(已记入记忆)**:反向验证后用 `git checkout -- ` 清理探针 ⇒ **把 M3 的改写一并回退到暂存区**(`crate::platform`×14、`pub(super)`×54 复活)。**教训:有未暂存改动的文件绝不能用 `git checkout --` 清理** ⇒ 用 Python 精确删探针行。 + +**出口判据(全部达成)**: +- [x] `cargo build --workspace` 零警告 +- [x] `cargo test --workspace` **695 passed / 0 failed**(与基线一致) +- [x] `check-arch.sh` 14/14;`--self-test` 6/6 +- [x] `check-boundary.sh` 11/11;`check-contract.sh` 10/10(守卫推导仍有效,CC6 零漂移) +- [x] `check-module.sh` 123/123;`check-citations.sh` 4/4 +- [x] `verify.sh --smoke` 14 步全绿(561.3s) ### 批次 M4 —— 契约面业务包(6 个并行包) @@ -555,34 +581,37 @@ bash scripts/verify.sh --smoke # 14 步全绿 --- -## 11. 待确认决策 +## 11. 决策(✅ 已拍板 2026-11-03) -1. **M2 保留 `platform/` re-export 转发壳,还是直接删掉?** - - 保留 ⇒ 上层零感知、改动小,但壳里多 20 个转发文件 - - 删除 ⇒ 壳更干净,但全仓 import 要改(测试 30+ 处) - - **建议**:保留一个版本(M7 再决定删不删) +1. ✅ **`platform/` 转发壳最后删掉**(M7 执行)。 + - **影响**:全仓 import 要改(测试 30+ 处、routes/modules)⇒ 是「大爆炸」改动。 + - **缓解**:M7 前转发壳一直保留(每批零感知),**最后一次性**改 import + 删壳; + 删壳时 AR9/AR10/CP1/CP2 的「两处都扫」收敛为只扫 `crates/`(壳没了)。 + - **M7 出口判据**:`src/backend/src/platform/` 目录整个删除;全仓无 `crate::platform::` 引用。 -2. **compat 包拆几个?** 现在按「官方模块名」拆 6 个。 - 另一种拆法:按「业务域」拆 3 个(大系统/大流程/大消息)。 - **建议**:按官方模块名(边界清晰、与官方前端 `api/` 目录一一对应) +2. ✅ **compat 拆 6 个包**(按官方模块名):`sspf-compat-{system,permission,msg,workflow,ext,online-dev}`。 + - 边界清晰、与官方前端 `api/` 目录一一对应。 + - **M4 必须同步**:`check-contract-scan.py` 收编 6 个包 + 重跑 `--self-test`。 -3. **`mcp_compat.rs` 放 crates 还是留壳?** - 它依赖**所有** compat 包 ⇒ 放 crates 会让「壳依赖能力」变成「能力依赖能力」。 - **建议**:放 crates(它是独立能力),但**接受**它是依赖图里唯一的高扇入节点 +3. ✅ **`mcp_compat.rs` 放 crates**(`sspf-mcp-adapter`)。 + - 接受它是依赖图里唯一的高扇入节点(依赖所有 compat 包)。 + - **防回退**:M6 加 AR 条目「`sspf-mcp-adapter` 之外不许依赖 compat 包」。 -4. **`src/backend/tests/` 要不要跟着拆到各 crate 的 `tests/`?** - - 拆 ⇒ 测试与代码同域,但需要共享 pglite 单例(`test_support.rs`)跨 crate 复用 - - 不拆 ⇒ 留壳里(`tests/` 是壳的一部分,测的是「装配后的整体」⇒ 语义更对) - - **建议**:不拆(集成测试测的是装配结果,留在壳侧语义正确) +4. ✅ **`tests/` 跟着拆**到各 crate 的 `tests/`。 + - **影响**:`test_support.rs`(进程级共享 pglite)目前依赖装配根 `bootstrap::ensure_schema_all` + (认识业务 DDL)⇒ 拆测试必须先把「测试建库」改成**各 crate 自足**(core 的测试用 + `seed::ensure_base(db, &[])`;compat 的测试建自己的契约面表;业务集成测试留壳侧测装配)。 + - **分层**:单元测试随代码进各 crate;**集成测试**(测「装配后的整体」,如 `pack_smoke_it.rs`)**留壳侧**。 --- ## 12. 立即可做的下一步 -**执行 M3(契约面公共底座 `sspf-compat-core`)**。理由: -1. M1(解环)/ M2(平台核心下沉)已完成并打 tag —— 地基已稳 -2. `compat/helper.rs`(902 行)+ `res.rs`(460 行)是 **14 个契约面模块**的公共底座 ⇒ 先下沉它,M4 的 6 个包才都能依赖它 -3. 有现成套路可复用:M2 的「转发壳 + 闸门扫真源 + 反自证两处注入」直接套用 +**执行 M4(六个契约面包并行下沉)**。理由: +1. M1(解环)/ M2(平台核心)/ M3(契约面底座)已完成并打 tag —— 地基与底座都稳了 +2. 决策 ② 已拍板:按官方模块名拆 **6 个包**(`sspf-compat-{system,permission,msg,workflow,ext,online-dev}`) +3. 套路成熟:M2/M3 的「转发壳 + 闸门两处扫 + 反自证两处注入」直接复用 -M3 完成后打 tag `v0.1.3-m3`,再进 M4(6 个契约面包并行)。 -⚠️ M4 之后**必须**做 §5.2 的 `check-contract-scan.py` 兼容包收编 + 重跑 `--self-test`。 +M4 完成后打 tag `v0.1.4-m4`。 +⚠️ **M4 必须同步做** §5.2 的 `check-contract-scan.py` 六包收编 + 重跑 `--self-test`(守卫推导的存亡线)。 +之后 = M5(`sspf-lowcode-exec`)→ M6(`sspf-mcp-adapter`,决策③放 crates)→ M7(收口:删壳 + tests 拆分 + AR12/AR13)。 diff --git a/scripts/check-arch.sh b/scripts/check-arch.sh index 3a829e7..34fc61d 100755 --- a/scripts/check-arch.sh +++ b/scripts/check-arch.sh @@ -299,17 +299,36 @@ PY # M1 已把 `menu_node` / `official_view_path` / `USER_DETAIL_COLUMNS` / # `organize_name_of` 搬进 helper,切断了这两条边。 # -# 判据:`compat/helper.rs` 里不许 `use super::` 指向**非 helper 的模块**。 +# 🔴 **M3 起底座真源在 `crates/sspf-compat-core/src/helper.rs`**(壳只剩 `pub use`) +# ⇒ 两处都扫(扫真源管实现 + 扫壳防塞私货)。跨 crate 形态的同一纪律 = +# `sspf-compat-core` 的 Cargo.toml 不许依赖 `sspf-compat-*`(M4 的 6 个包)。 +# +# 判据(两处): +# ① `helper.rs`(真源或壳)里不许 `use super::` 指向**非 helper 的模块**, +# 也不许 `use crate::res`(同 crate 内的反向依赖); +# ② `crates/sspf-compat-core/Cargo.toml` 不许依赖 `sspf-compat-*`。 check_ar11() { - local f="$KERNEL/src/platform/compat/helper.rs" - [ -f "$f" ] || { skip "AR11 compat/helper.rs 不存在"; return; } - local hits - hits="$(grep -nE '^[[:space:]]*(pub )?use[[:space:]]+super::[a-z_]+' "$f" 2>/dev/null \ - | grep -v 'super::helper' || true)" + local files=() + [ -f "$CRATES/sspf-compat-core/src/helper.rs" ] && files+=("$CRATES/sspf-compat-core/src/helper.rs") + [ -f "$KERNEL/src/platform/compat/helper.rs" ] && files+=("$KERNEL/src/platform/compat/helper.rs") + local hits="" + if [ "${#files[@]}" -gt 0 ]; then + hits="$(grep -nE '^[[:space:]]*(pub )?use[[:space:]]+(super::[a-z_]+|crate::res)' "${files[@]}" 2>/dev/null \ + | grep -vE 'super::helper|crate::helper' || true)" + fi + # 跨 crate 形态:底座的 Cargo.toml 不许依赖 6 个契约面包 + local toml="$CRATES/sspf-compat-core/Cargo.toml" + if [ -f "$toml" ]; then + local dep_hits + dep_hits="$(grep -nE '^\s*sspf-compat-[a-z-]+\s*=' "$toml" 2>/dev/null || true)" + if [ -n "$dep_hits" ]; then + hits="${hits:+$hits$'\n'}${dep_hits}" + fi + fi if [ -z "$hits" ]; then - ok "AR11 契约面底座(helper)不依赖其它契约面模块(14 个模块依赖它 ⇒ 反向依赖即成环)" + ok "AR11 契约面底座(helper/sspf-compat-core)不依赖其它契约面模块(14 个模块依赖它 ⇒ 反向依赖即成环)" else - bad "AR11 契约面底座(helper)反向依赖契约面业务模块(拆 crate 时即成环):" + bad "AR11 契约面底座反向依赖契约面业务模块(拆 crate 时即成环):" printf '%s\n' "$hits" | sed 's/^/ /' fi } @@ -593,28 +612,29 @@ RS echo "── 反自证 6/6:往契约面底座塞 use super::system,AR11 必须报 ❌ ──" # - # 🔴 造在**临时副本**上:不动真文件(helper.rs 是 900+ 行的活文件)。 - local a11dir="$KERNEL/src/platform/compat" - local a11probe="$a11dir/__ar11_selftest.rs" - if [ -d "$a11dir" ] && [ -f "$a11dir/helper.rs" ]; then - # 🔴 AR11 只扫 `helper.rs` ⇒ 探针必须是 helper.rs 本身。 - # 做法:备份真文件 → 追加违规行 → 跑判据 → 还原。 - cp "$a11dir/helper.rs" "$a11dir/helper.rs.bak" - printf '\nuse super::system::menu_node;\n' >> "$a11dir/helper.rs" - before=$FAIL - check_ar11 >/dev/null 2>&1 - caught=0 - [ "$FAIL" -gt "$before" ] && caught=1 - mv "$a11dir/helper.rs.bak" "$a11dir/helper.rs" - FAIL=$before - if [ "$caught" -eq 1 ]; then - echo "✅ 反自证通过:AR11 抓到了契约面底座里的 use super::system" - else - echo "❌ 反自证失败:AR11 没抓到底座的反向依赖 ⇒ 尺子是假的" - rc=1 - fi + # 🔴 **M3 起底座有两处**:真源 `crates/sspf-compat-core/src/helper.rs`(实现) + # + 转发壳 `src/backend/src/platform/compat/helper.rs`。**两处都注入、 + # 两处都被抓到**才算尺子有效(只注入一处会漏判「闸门只扫壳/只扫真源」)。 + # 做法:备份真文件 → 追加违规行 → 跑判据 → 还原(helper.rs 是活文件)。 + local a11ok=0 + local a11core="$CRATES/sspf-compat-core/src/helper.rs" + local a11shell="$KERNEL/src/platform/compat/helper.rs" + local a11need=0 a11c=0 a11out + if [ -f "$a11core" ] || [ -f "$a11shell" ]; then + [ -f "$a11core" ] && cp "$a11core" "$a11core.bak" && printf '\nuse super::system::menu_node;\n' >> "$a11core" && a11need=$((a11need+1)) + [ -f "$a11shell" ] && cp "$a11shell" "$a11shell.bak" && printf '\nuse super::system::menu_node;\n' >> "$a11shell" && a11need=$((a11need+1)) + a11out="$(check_ar11 2>&1 || true)" + [ -f "$a11core.bak" ] && mv "$a11core.bak" "$a11core" + [ -f "$a11shell.bak" ] && mv "$a11shell.bak" "$a11shell" + [ -f "$a11core" ] && { echo "$a11out" | grep -q "sspf-compat-core/src/helper.rs" && a11c=$((a11c+1)); } + [ -f "$a11shell" ] && { echo "$a11out" | grep -q "platform/compat/helper.rs" && a11c=$((a11c+1)); } + [ "$a11need" -gt 0 ] && [ "$a11c" -ge "$a11need" ] && a11ok=1 + fi + if [ "$a11ok" -eq 1 ]; then + echo "✅ 反自证通过:AR11 抓到了真源与转发壳里的 use super::system" else - echo "⏭ 跳过 AR11 反自证(契约面目录或 helper.rs 不存在)" + echo "❌ 反自证失败:AR11 没抓到底座的反向依赖(或漏扫了真源/转发壳)⇒ 尺子是假的" + rc=1 fi return $rc diff --git a/scripts/check-contract-scan.py b/scripts/check-contract-scan.py index d6aff6f..4685993 100644 --- a/scripts/check-contract-scan.py +++ b/scripts/check-contract-scan.py @@ -856,13 +856,18 @@ def scan_code(src_dir, packs_dir=None): # 契约面按官方模块名分文件(`online_dev.rs` / `report.rs` / `system.rs` …), # 路由注册写 `compat::<模块>::` ⇒ 这些文件**必须**进 `plat_files`, # 否则守卫推导**全部推不出**(CC6 退化成「全是 WARN」⇒ 静默失效)。 - compat_dir = os.path.join(plat_dir, "compat") - if os.path.isdir(compat_dir): - for name in sorted(os.listdir(compat_dir)): - if name.endswith(".rs"): - p = os.path.join(compat_dir, name) - o = read(p) - plat_files["compat__" + name[:-3]] = (o, mask_rust(o)) + # 🔴 **M3 起契约面底座真源在 `crates/sspf-compat-core/src/`**(`helper.rs` 装守卫常量 + # `EN_ROLE` 等)⇒ 必须一并收(与壳同键拼接),否则守卫常量找不到 ⇒ CC6 假漂移。 + compat_dirs = [ + os.path.join(ROOT, "crates", "sspf-compat-core", "src"), # M3 真源(helper/res) + os.path.join(plat_dir, "compat"), # 壳 + 尚未搬走的模块 + ] + for d in compat_dirs: + if os.path.isdir(d): + for name in sorted(os.listdir(d)): + if name.endswith(".rs"): + p = os.path.join(d, name) + _absorb("compat__" + name[:-3], read(p)) # 🔴 **全局常量索引**(批次 17 补):契约面按官方模块分文件后, # 守卫常量(`EN_ROLE` / `EN_ORGANIZE` / `EN_ACTION` …)**集中在 # `compat/helper.rs`** 里,被各模块 `use super::helper::{…}` 导入 diff --git a/src/backend/Cargo.toml b/src/backend/Cargo.toml index bd1125c..efdd803 100644 --- a/src/backend/Cargo.toml +++ b/src/backend/Cargo.toml @@ -45,6 +45,10 @@ sspf-store = { path = "../../crates/sspf-store" } # `src/backend/src/platform/*.rs` 现在只是转发壳(`pub use sspf_core::*`)⇒ 上层零感知。 sspf-core = { path = "../../crates/sspf-core" } +# 🔴 **契约面公共底座**(M3)—— 面 B 判别 / 登录守卫 / 分页信封 / 通用单表资源引擎。 +# `src/backend/src/platform/compat/{helper,res}.rs` 现在只是转发壳 ⇒ 14 个模块零感知。 +sspf-compat-core = { path = "../../crates/sspf-compat-core" } + # MCP 工具层(元工具 + 分层加载)—— 内核实现它的 PlatformAdapter,反向依赖 sspf-mcp = { path = "../../crates/sspf-mcp" } # 低代码元数据引擎(纯计算:解析/校验/SQL 生成) diff --git a/src/backend/src/platform/compat/helper.rs b/src/backend/src/platform/compat/helper.rs index b83fcd6..cd84983 100644 --- a/src/backend/src/platform/compat/helper.rs +++ b/src/backend/src/platform/compat/helper.rs @@ -1,994 +1,5 @@ -//! helper —— 契约面的**公共底座**(导入 / 通用工具 / 判别 / 守卫 / 共享常量 / -//! 菜单与用户信息构造)。 -//! -//! 🔴 **为什么单独一个 `helper`**:契约面按官方模块拆开后,下列东西被**多个模块共用** -//! —— 放任何一个模块里都会让别的模块反向依赖它 ⇒ 拆分的意义就没了。 -//! 典型:面 B 判别头 `is_face_b`(**全部** handler 都要过)、登录守卫 `guard`、 -//! 分页信封 `page_list`、SQL 参数拼装 `params_of`、菜单树构造 `build_menu_tree`、 -//! 当前用户信息 `build_user_info`。 -//! -//! 🔴 **本文件不装业务知识**:只放「怎么把官方形状的请求变成响应」的基础设施。 -//! 真源:`JNPF_COMPAT_SURFACE.md`(§2.2 判别头 / §3 端点 / §4 码表)。 +//! helper —— **转发壳**:真源在 [`sspf_compat_core::helper`](M3 契约面公共底座)。 +//! 🔴 只做转发、不含实现;14 个契约面模块的 `use super::helper::{…}` 不用改。 +//! 为什么留壳、闸门怎么改:见 `docs/CRATES-MIGRATION.md` §4 M3。 - -use std::collections::{HashMap, HashSet}; -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::envelope::{code, fail, ok, ActionResult}; -use crate::platform::db::{pglite, pglite::ToSql, Db}; -use crate::platform::auth::require_login_face_b; -use crate::platform::auth::resolve_user; -use crate::platform::crud::value_to_text; -use crate::platform::authorization::has_en_code_permission; -use crate::platform::authorization::resolve_user_module_ids; -use crate::platform::session::TokenUser; -use crate::platform::state::AppState; -use crate::platform::registry; -pub use sspf_contract::headers::VUE_VERSION; -/// 本仓的系统 id(`currentSystemId` / `userInfo.systemId` / 菜单 `systemId` 的兜底值)。 -/// -/// 🔴 单一真源在 [`crate::platform::registry`](`base_system.f_id`);这里只是别名, -/// **不要另写一份字面量**——否则主系统 id 改一处漏一处。 -pub(super) const SYSTEM_ID: &str = registry::MAIN_SYSTEM_ID; - -/// 本仓的系统编码(`userInfo.systemCode`)。 -/// -/// 🔴 官方常量 `JnpfConst.MAIN_SYSTEM_CODE = "mainSystem"`;前端也硬比较这个值 -/// (`systemCode === 'mainSystem'` 决定首页布局)⇒ 同样只做别名。 -pub const SYSTEM_CODE: &str = registry::MAIN_SYSTEM_CODE; - -/// `@SaCheckPermission("permission.user")`。 -pub(super) const EN_USER: &str = "permission.user"; - -/// `@SaCheckPermission("permission.role")`。 -pub(super) const EN_ROLE: &str = "permission.role"; - -/// `@SaCheckPermission("permission.organize")`。 -pub(super) const EN_ORGANIZE: &str = "permission.organize"; - -/// `@SaCheckPermission("permission.menu")`。 -pub(super) const EN_MENU: &str = "permission.menu"; - -/// `@SaCheckPermission("permission.position")`。 -pub(super) const EN_POSITION: &str = "permission.position"; - -/// 🔴 `@SaCheckPermission("permission.identity")`(官方 `StandingController`)。 -pub(super) const EN_IDENTITY: &str = "permission.identity"; - -/// 🔴 `@SaCheckPermission("permission.authGroup")`(官方 `PermissionGroupController`)。 -pub(super) const EN_AUTH_GROUP: &str = "permission.authGroup"; - -/// 🔴 `@SaCheckPermission("permission.action")`。 -/// -/// 🔴 官方 `ActionController` 是 `{"permission.auth", "permission.role", "permission.action"}` -/// 的 **SaMode.OR** 三选一;本仓的 `guard()` 只吃**一个**点权限码 -/// ⇒ 取**动作自己的**那个(最贴近语义)。 -pub(super) const EN_ACTION: &str = "permission.action"; - -/// 🔴 `@SaCheckPermission("msgCenter.notice")`(官方 `NoticeController` 的公告那半截)。 -/// -/// 🔴 **只有公告守它**;消息列表 / 全部已读 / 读消息 / 删记录 / 回执 -/// **都不带** `@SaCheckPermission` —— 登录即可用(谁看自己的消息都不该要授权)。 -pub(super) const EN_NOTICE: &str = "msgCenter.notice"; - -/// 菜单树的最大层数(防御 `f_parent_id` 被改成人为环时的无限递归)。 -pub(super) const MAX_TREE_DEPTH: usize = 32; - -/// 🔴 **这个请求是不是「面 B」** —— 判别头 `Vue-Version: 3`。 -/// -/// **唯一的全局判别规则**(`JNPF_COMPAT_SURFACE.md` §2.2): -/// ```text -/// 请求头含 "Vue-Version: 3" ⇒ 走【面 B】官方形状 -/// 否则 ⇒ 走【面 A】ssw 形状 -/// ``` -pub fn is_face_b(headers: &HeaderMap) -> bool { - // 判据真值源在契约层:MCP 适配器、后续插件都要用同一份判断, - // 不许各自再写一遍 `Vue-Version == "3"`(写错一处就是两面串味)。 - sspf_contract::headers::is_face_b(headers) -} - -/// DB 报错 ⇒ 面 B 的 `500`(官方 `EXCEPTION`);真因只进服务端日志,**不外泄**。 -pub(super) fn db_error(e: pglite::Error, ctx: &str) -> Json { - eprintln!("[face-b] {ctx}失败: {e}"); - fail(code::EXCEPTION, "系统异常,请联系管理员") -} - -/// 解析 JSON body;失败 ⇒ `fail(400, "请求参数格式错误")`。 -/// -/// 🔴 **不用 axum 的 `Json`**:它的解析失败会返回 **422 + 非信封 body** ⇒ 契约破。 -pub(super) fn parse_body(body: &Bytes) -> Result> { - match serde_json::from_slice::(body) { - Ok(v) => Ok(v), - Err(_) => Err(fail(code::FAIL, "请求参数格式错误")), - } -} - -/// 分页参数(官方 `Pagination.java`:`pageSize` 默认 `20` / `currentPage` 默认 `1`)。 -pub(super) struct Paging { - pub(super) current_page: i64, - pub(super) page_size: i64, - pub(super) offset: i64, -} - -impl Paging { - /// 从 query 取分页参数;**缺失 / 非法 ⇒ 用官方默认值**(不报错)。 - pub(super) fn of(raw: &RawQuery) -> Self { - let current_page = crate::platform::sys::query_param(raw, "currentPage") - .trim() - .parse::() - .unwrap_or(1) - .max(1); - // 🔴 `pageSize` 夹在 `[1, 1000]` —— 防「pageSize=0」把 SQL 打成语法错、 - // 防超大值把整表拉进内存。 - let page_size = crate::platform::sys::query_param(raw, "pageSize") - .trim() - .parse::() - .unwrap_or(20) - .clamp(1, 1000); - Self { - current_page, - page_size, - offset: (current_page - 1) * page_size, - } - } - - /// 从 **JSON body** 取分页参数(官方好几个「列表」是 `POST`,分页在 body 里 —— - /// 例如 `POST /api/message/Notice/List`)。缺失 / 非法同样回落官方默认值。 - pub(super) fn of_body(obj: &Map) -> Self { - let num = |key: &str| { - obj.get(key) - .and_then(|v| v.as_i64().or_else(|| v.as_str()?.trim().parse().ok())) - }; - let current_page = num("currentPage").unwrap_or(1).max(1); - // 🔴 同一道夹逼:`pageSize` 落在 `[1, 1000]`。 - let page_size = num("pageSize").unwrap_or(20).clamp(1, 1000); - Self { - current_page, - page_size, - offset: (current_page - 1) * page_size, - } - } -} - -/// 官方 `PageListVO` —— `{pagination:{currentPage,pageSize,total}, list:[…]}`。 -/// -/// 🔴 **`data` 必须是对象**(不是裸数组)—— 官方 `PageListVO` 有 `pagination` + `list` 两个字段。 -pub(super) fn page_list(current_page: i64, page_size: i64, total: i64, list: Vec) -> Value { - json!({ - "pagination": { - "currentPage": current_page, - "pageSize": page_size, - "total": total, - }, - "list": list, - }) -} - -/// 官方 `ListVO` —— `{list:[…]}`(**只有 `list` 一个字段**)。 -pub(super) fn list_vo(list: Vec) -> Value { - json!({ "list": list }) -} - -/// 绑定参数数组 ⇒ `&[&(dyn ToSql + Sync)]`(值一律按 text 传,类型转换交给 SQL 里的 CAST)。 -pub(super) fn params_of(values: &[Option]) -> Vec<&(dyn ToSql + Sync)> { - values.iter().map(|v| v as &(dyn ToSql + Sync)).collect() -} - -/// 面 B 的守卫:**登录(602)** + **点权限(`f_en_code` ⇒ 403)**。 -pub(super) async fn guard( - state: &AppState, - headers: &HeaderMap, - en_code: &str, -) -> Result> { - let user = require_login_face_b(state, headers).await?; - // 🔴 多应用:按 `App-Code` 解析当前系统 ⇒ 点权限判据限定在该系统。 - let system_id = - registry::resolve_system_id(&state.db, registry::app_code_of(headers).as_deref()).await; - if has_en_code_permission(&state.db, &user.user_id, user.is_admin, en_code, &system_id).await { - Ok(user) - } else { - Err(fail(code::NO_PERMISSION, "无权限")) - } -} - -/// 一行菜单(`AllMenuSelectVO` 那 15 个字段的原料)。 -pub(super) struct MenuRow { - pub(super) id: String, - pub(super) full_name: String, - pub(super) en_code: Option, - pub(super) parent_id: String, - pub(super) icon: Option, - pub(super) url_address: Option, - pub(super) page_address: Option, - pub(super) link_target: Option, - pub(super) menu_type: i64, - pub(super) property_json: Option, - pub(super) sort_code: i64, - pub(super) system_id: Option, - pub(super) is_data: bool, -} - -/// 菜单投影(面 B 专用)—— 🔴 **显式列出每一列并加 `AS ""` 别名** -/// (PG 会把未加引号的标识符折叠成小写 ⇒ `row_to_json` 的键会变样且**静默**)。 -pub(super) const MENU_PROJECTION: &str = "f_id AS \"id\", f_full_name AS \"fullName\", \ - f_en_code AS \"enCode\", COALESCE(f_parent_id, '0') AS \"parentId\", \ - f_icon AS \"icon\", f_url_address AS \"urlAddress\", \ - f_page_address AS \"pageAddress\", f_link_target AS \"linkTarget\", \ - COALESCE(f_type, 2) AS \"type\", f_property_json AS \"propertyJson\", \ - COALESCE(f_sort_code, 0) AS \"sortCode\", f_system_id AS \"systemId\", \ - COALESCE(f_is_data_authorize, 0) AS \"isData\""; - -/// 读当前用户**可见**的菜单行(未软删 + 四源合并过滤)。 -/// -/// 🔴 非管理员的可见集合来自 `resolve_user_module_ids`(四源合并:直授/角色/组织/岗位), -/// 与面 A 的 `build_menu_list` **同一套判据** ⇒ 两个面看到的菜单集合一致。 -pub(super) async fn load_menus(db: &Db, user_id: &str, is_admin: i32, system_id: &str) -> Vec { - let sql = format!( - "SELECT {MENU_PROJECTION} FROM base_module WHERE f_delete_mark = 0 \ - AND f_system_id = $1::text \ - ORDER BY f_sort_code ASC, f_full_name ASC" - ); - let rows = match db.query_json_params(&sql, &[&system_id]).await { - Ok(rows) => rows, - Err(e) => { - eprintln!("[face-b] 菜单查询失败(按空菜单处理): {e}"); - return Vec::new(); - } - }; - let mut items: Vec = rows.iter().filter_map(parse_menu_row).collect(); - if is_admin != 1 { - let visible = resolve_user_module_ids(db, user_id).await; - items.retain(|m| visible.contains(&m.id)); - } - items -} - -/// 一行 JSON ⇒ [`MenuRow`]。 -pub(super) fn parse_menu_row(row: &Value) -> Option { - let id = row["id"].as_str()?.to_string(); - if id.is_empty() { - return None; - } - Some(MenuRow { - id, - full_name: row["fullName"].as_str().unwrap_or_default().to_string(), - en_code: row["enCode"].as_str().map(str::to_string), - // 🔴 react: `parentId: m.parentId || '0'` —— 空 ⇒ `'0'`。 - parent_id: match row["parentId"].as_str() { - Some(p) if !p.is_empty() => p.to_string(), - _ => "0".to_string(), - }, - icon: row["icon"].as_str().map(str::to_string), - url_address: row["urlAddress"].as_str().map(str::to_string), - page_address: row["pageAddress"].as_str().map(str::to_string), - link_target: row["linkTarget"].as_str().map(str::to_string), - menu_type: row["type"].as_i64().unwrap_or(2), - property_json: row["propertyJson"].as_str().map(str::to_string), - sort_code: row["sortCode"].as_i64().unwrap_or(0), - system_id: row["systemId"].as_str().map(str::to_string), - is_data: row["isData"].as_i64().unwrap_or(0) != 0, - }) -} - -/// `f_property_json`(TEXT)⇒ JSON 值;空 / 非法 ⇒ `null`。 -fn parse_property_json(raw: Option<&str>) -> Value { - let Some(text) = raw else { - return Value::Null; - }; - let trimmed = text.trim(); - if trimmed.is_empty() { - return Value::Null; - } - serde_json::from_str::(trimmed).unwrap_or(Value::Null) -} - -/// 菜单在**面 B** 里对外的 `urlAddress` —— 官方前端的**视图路径**。 -/// -/// 规则(与官方前端 `generate-routes-backend.ts:57` 对目录的做法**同一条**): -/// `f_en_code` 的点换斜杠(`permission.user` ⇒ `permission/user`)。 -/// 🔴 库里的 `f_url_address` 是**面 A** 的守卫 key(`system/User`),**不能**直接给面 B。 -/// -/// 🔴 **本函数住在 helper,不住 `system.rs`** —— 它只依赖字符串处理, -/// 而 `system.rs` 依赖 helper(`guard` / `Paging` / `MenuRow` …)。 -/// 若 helper 反过来依赖 system ⇒ **循环依赖**(跨 crate 时编译器直接报错)。 -pub(super) fn official_view_path(en_code: Option<&str>, fallback: Option<&str>) -> Option { - let code = en_code.map(str::trim).filter(|s| !s.is_empty())?; - let path = code.replace('.', "/"); - if path.is_empty() { - return fallback.map(str::to_string); - } - Some(path) -} - -/// 一个菜单节点 ⇒ 官方 `AllMenuSelectVO`(**15 个字段,一个不少**)。 -/// -/// 🔴 **键名与顺序照官方 `AllMenuSelectVO.java:12-50`**(`id` / `fullName` / `enCode` / -/// `parentId` / `icon` / `hasChildren` / `urlAddress` / `pageAddress` / `linkTarget` / -/// `children` / `type` / `propertyJson` / `sortCode` / `systemId` / `isData`)。 -pub(super) fn menu_value(row: MenuRow, children: Vec, has_children: bool) -> Value { - let MenuRow { - id, - full_name, - en_code, - parent_id, - icon, - url_address, - page_address, - link_target, - menu_type, - property_json, - sort_code, - system_id, - is_data, - } = row; - json!({ - "id": id, - "fullName": full_name, - "enCode": en_code, - "parentId": parent_id, - "icon": icon, - "hasChildren": has_children, - // 🔴 **面 B 的 `urlAddress` 必须是「官方前端的视图路径」**,不是库里的 `f_url_address`。 - // 前端 `packages/utils/src/helpers/generate-routes-backend.ts:71-92`: - // `route.path = '/' + urlAddress`,且 `component = pageMap['/' + urlAddress + '/index.vue']` - // (`pageMap` = `import.meta.glob('../views/**/*.vue'`)⇒ 值必须指向**真实 .vue 文件**。 - // 而库里的 `f_url_address`(`system/User`)是**面 A** 的守卫 key,官方前端没有 - // `views/system/User/index.vue` ⇒ 点了菜单永远 404。 - // 官方自己的口径就是「编码 ⇒ 路径」(同一文件 `:57` 对目录/应用用的是 - // `/${enCode.replaceAll('.', '/')}`)⇒ 这里对**所有类型**统一用同一条规则: - // `permission.user` ⇒ `permission/user` ⇒ 命中 `views/permission/user/index.vue` ✅ - "urlAddress": official_view_path(en_code.as_deref(), url_address.as_deref()), - "pageAddress": page_address, - "linkTarget": link_target, - "children": children, - "type": menu_type, - "propertyJson": parse_property_json(property_json.as_deref()), - "sortCode": sort_code, - // 🔴 种子菜单的 `f_system_id` 是 NULL ⇒ 兜底成本仓系统 id(单系统)。 - "systemId": system_id - .filter(|s| !s.trim().is_empty()) - .unwrap_or_else(|| SYSTEM_ID.to_string()), - "isData": is_data, - }) -} - -/// 递归建一棵子树。 -/// -/// 🔴 **本函数住在 helper,不住 `system.rs`** —— 它只依赖 helper 自己的 -/// `menu_value` 与 `MAX_TREE_DEPTH`;而 `system.rs` 依赖 helper -/// ⇒ 放 system 会形成**循环依赖**(拆 crate 后编译器直接报错)。 -pub(super) fn menu_node( - row: MenuRow, - by_parent: &mut HashMap>, - depth: usize, -) -> Value { - // 防御:`f_parent_id` 被改成人为环时不要无限递归(层数封顶 ⇒ 截断)。 - let children: Vec = if depth >= MAX_TREE_DEPTH { - Vec::new() - } else { - by_parent - .remove(&row.id) - .unwrap_or_default() - .into_iter() - .map(|child| menu_node(child, by_parent, depth + 1)) - .collect() - }; - let has_children = !children.is_empty(); - menu_value(row, children, has_children) -} - -/// 建菜单树(根 = `parentId` 为空 / `'0'` / **父不在可见集合内**)。 -fn build_menu_tree(rows: Vec) -> Vec { - let visible: HashSet = rows.iter().map(|m| m.id.clone()).collect(); - let mut by_parent: HashMap> = HashMap::new(); - let mut roots: Vec = Vec::new(); - for row in rows { - if row.parent_id != "0" && visible.contains(&row.parent_id) { - by_parent.entry(row.parent_id.clone()).or_default().push(row); - } else { - roots.push(row); - } - } - roots - .into_iter() - .map(|row| menu_node(row, &mut by_parent, 0)) - .collect() -} - -/// 官方 `PermissionModel` 列表 —— **每个可见菜单一条**。 -/// -/// 🔴 **官方语义**:`modelId` = **菜单 id** -/// (官方前端 `views/common/dynamicModel/list/index.vue:739`: -/// `permissionList.find(o => o.modelId === searchInfo.menuId)`) -/// ⇒ 本仓按「菜单」给一条,`moduleName` = 菜单全名。 -/// -/// 🔴 `button` / `column` / `resource` / `form` **恒为空数组** —— 本仓**不实现** -/// 按钮级权限(`base_module_button` / `_column` / `_form` / `_data` 都不做) -/// ⇒ 官方前端的按钮会被过滤掉(**已知限制 B4**,`docs/known-limitations.md` §H)。 -fn build_permission_list(rows: &[MenuRow]) -> Vec { - rows.iter() - .map(|m| { - json!({ - "modelId": m.id, - "moduleName": m.full_name, - "button": [], - "column": [], - "resource": [], - "form": [], - }) - }) - .collect() -} - -/// `GET /api/oauth/CurrentUser` 的**面 B**分支 —— 官方 `PcUserVO` 形状。 -/// -/// 🔴 **顶层五个字段一个都不能少**(官方前端 `store/auth.ts:121` 逐个取用): -/// `menuList` / `permissionList` / `userInfo` / `currentSystemId` / `sysConfigInfo`。 -/// -/// 🔴 未登录 ⇒ **`602`**(官方前端只对 `601`/`602` 清 token ⇒ 返 `600` 会卡住不跳登录)。 -pub async fn current_user(state: &AppState, headers: &HeaderMap) -> Json { - let Some(user) = resolve_user(state, headers) else { - return fail(code::SESSION_ERROR, "登录状态已失效,请重新登录"); - }; - - // 🔴 多应用:按 `App-Code` 解析当前系统 ⇒ 菜单树 / userInfo / currentSystemId 都按该系统。 - let sys = registry::resolve_system(&state.db, registry::app_code_of(headers).as_deref()).await; - let menus = load_menus(&state.db, &user.user_id, user.is_admin, &sys.id).await; - let permission_list = build_permission_list(&menus); - let menu_list = build_menu_tree(menus); - let user_info = build_user_info(&state.db, &user, &sys.id, &sys.code).await; - - ok(json!({ - "menuList": menu_list.clone(), - "permissionList": permission_list, - // 🔴 官方 `GetUserInfoModel`(`basic.d.ts:94-100`)声明了 `routerList` 但 - // **前端一处都没读**(`grep routerList` 在 app/packages 里 0 命中); - // 为对齐类型仍给出同一棵树,避免将来有页面取值时拿到 undefined。 - "routerList": menu_list, - "userInfo": user_info, - "currentSystemId": sys.id, - // 🔴 `sysConfigInfo` 返 **空对象**(不是 null)⇒ 官方前端 `baseStore.setSysConfig` 不炸。 - "sysConfigInfo": {}, - })) -} - -/// 官方 `UserCommonInfoVO`(15 个字段)。 -/// -/// 🔴 `isAdministrator` 在这里是 **布尔**(官方 `UserCommonInfoVO.java:75` 是 `Boolean`)—— -/// 而**列表项**里它是**数字**(官方 `UserListVO.java:60` 是 `Integer`)⇒ 两处**故意不同**。 -async fn build_user_info(db: &Db, user: &TokenUser, system_id: &str, system_code: &str) -> Value { - let rows = match db - .query_json_params( - "SELECT f_real_name AS \"realName\", f_head_icon AS \"headIcon\", \ - f_organize_id AS \"organizeId\", f_position_id AS \"positionId\", \ - f_mobile_phone AS \"mobilePhone\", f_email AS \"email\", \ - f_gender AS \"gender\", f_role_id AS \"roleId\", f_group_id AS \"groupId\", \ - f_secretkey AS \"secretKey\", f_manager_id AS \"manager\", \ - (EXTRACT(EPOCH FROM f_birthday) * 1000)::bigint AS \"birthday\", \ - (EXTRACT(EPOCH FROM f_prev_log_time) * 1000)::bigint AS \"prevLoginTime\", \ - f_prev_log_ip AS \"prevLoginIp\" \ - FROM base_user WHERE f_id = $1::text AND f_delete_mark = 0 LIMIT 1", - &[&user.user_id], - ) - .await - { - Ok(rows) => rows, - Err(e) => { - eprintln!("[face-b] 读用户信息失败: {e}"); - Vec::new() - } - }; - let row = rows.first(); - let real_name = row - .and_then(|r| r["realName"].as_str()) - .filter(|s| !s.is_empty()) - .unwrap_or(user.account.as_str()) - .to_string(); - let head_icon = row.and_then(|r| r["headIcon"].as_str()).map(str::to_string); - let organize_id = row - .and_then(|r| r["organizeId"].as_str()) - .filter(|s| !s.is_empty()) - .map(str::to_string); - let position_id = row - .and_then(|r| r["positionId"].as_str()) - .filter(|s| !s.is_empty()) - .map(str::to_string); - let prev_login_time = row.and_then(|r| r["prevLoginTime"].as_i64()); - let prev_login_ip = row - .and_then(|r| r["prevLoginIp"].as_str()) - .filter(|s| !s.is_empty()) - .map(str::to_string); - let organize_name = match organize_id.as_deref() { - Some(id) => organize_name_of(db, id).await, - None => None, - }; - // 🔴 `f_role_id` / `f_group_id` 是 TEXT(官方历史遗留,逗号分隔)⇒ 拆成数组。 - // 官方 `UserInfo` 把 `roleIds` / `groupIds` / `organizeIds` 声明成**非可选数组**, - // 前端 store 会直接遍历 ⇒ 缺键或给 null 都可能崩,这里一律给空数组兜底。 - let text_of = |key: &str| { - row.and_then(|r| r[key].as_str()) - .filter(|s| !s.is_empty()) - .map(str::to_string) - }; - let split_ids = |key: &str| -> Vec { - text_of(key) - .map(|s| { - s.split(',') - .map(str::trim) - .filter(|x| !x.is_empty()) - .map(str::to_string) - .collect() - }) - .unwrap_or_default() - }; - let role_ids = split_ids("roleId"); - let group_ids = split_ids("groupId"); - let organize_ids: Vec = organize_id.iter().cloned().collect(); - let organize_list_vo: Vec = organize_id - .as_ref() - .map(|id| { - vec![json!({ - "id": id, - "fullName": organize_name.clone().unwrap_or_default(), - })] - }) - .unwrap_or_default(); - - json!({ - "userId": user.user_id, - "userAccount": user.account, - "userName": real_name, - "headIcon": head_icon, - // ---- 以下为官方 `UserInfo`(`basic.d.ts:52-92`)的完整字段集 ---- - // 🔴 该类型里 `roleIds` / `groupIds` / `organizeIds` / `positionIds` / - // `organizeList` / `positionList` / `standingList` 都是**非可选数组** ⇒ - // 必须给 [](缺键会让前端 store 遍历时崩)。 - "gender": text_of("gender"), - "birthday": row.and_then(|r| r["birthday"].as_i64()), - "mobilePhone": text_of("mobilePhone"), - "email": text_of("email"), - "manager": text_of("manager"), - "organizeId": organize_id, - "organizeIds": organize_ids, - "organizeName": organize_name, - "organizeList": organize_list_vo, - "positionId": position_id, - // 🔴 本仓**没有**岗位表(`base_position` 不在 v1 范围)⇒ 恒空。 - "positionIds": Vec::::new(), - "positionList": Vec::::new(), - "positionName": Value::Null, - "roleIds": role_ids, - "roleName": Value::Null, - "groupIds": group_ids, - "standingList": Vec::::new(), - "portalId": Value::Null, - "departmentId": Value::Null, - "departmentName": Value::Null, - "systemId": system_id, - "systemCode": system_code, - "systemName": if system_code == SYSTEM_CODE { "系统平台" } else { "" }, - "systemColor": "", - "systemIcon": "", - "securityKey": text_of("secretKey").unwrap_or_default(), - "signId": "", - "signImg": "", - "saasAppId": "", - "saasAppName": "", - // 🔴 前端 `store/auth.ts:143` 的 `handleUpdatePreferences`: - // `if (userInfo.preferenceJson) preferenceJson = JSON.parse(userInfo.preferenceJson)` - // ⇒ **空串会被判假** ⇒ 保留前端自带的 `defaultPreferencesConfig`; - // 而给 `"{}"` 会被 parse 成空对象 ⇒ `updatePreferences({})` 把整套偏好清空 - // ⇒ `app.locale` / `app.defaultHomePath` 全丢 ⇒ 抛错 ⇒ `fetchUserInfo` 进 catch - // ⇒ 立刻 logout(**登录页原地打转的真正原因**,排查了两个小时的那条)。 - // ⇒ 必须是**字符串**,且必须是**空串**(不是 `"{}"`)。 - "preferenceJson": "", - // 🔴 官方 `prevLogin`:1 = 上次登录 / 2 = 本次登录。本仓不区分 ⇒ 恒 1。 - "prevLogin": 1, - "prevLoginTime": prev_login_time, - "prevLoginIPAddress": prev_login_ip, - "prevLoginIPAddressName": Value::Null, - "isAdministrator": user.is_admin == 1, - }) -} - -/// 取 body 里的 id 数组(`{ids:[…]}` / `{ids:"a,b"}` 都认)。 -/// -/// 🔴 非数组 ⇒ **空集合**(官方批量接口对空集合返回成功,不报错)。 -/// 取 `obj[key]` 的字符串 id 数组(数组或逗号串都收;空 ⇒ 空数组)。 -pub(super) fn id_list_of(obj: &Map, key: &str) -> Vec { - match obj.get(key) { - Some(Value::Array(items)) => items - .iter() - .filter_map(|v| match v { - Value::String(s) if !s.is_empty() => Some(s.clone()), - Value::Number(n) => Some(n.to_string()), - _ => None, - }) - .collect(), - Some(Value::String(s)) if !s.is_empty() => { - s.split(',').map(|x| x.trim().to_string()).collect() - } - _ => Vec::new(), - } -} - -pub(super) fn id_list(obj: &Map) -> Vec { - match obj.get("ids") { - Some(Value::Array(items)) => items - .iter() - .filter_map(|v| match v { - Value::String(s) if !s.is_empty() => Some(s.clone()), - Value::Number(n) => Some(n.to_string()), - _ => None, - }) - .collect(), - Some(Value::String(s)) if !s.is_empty() => { - s.split(',').map(|x| x.trim().to_string()).collect() - } - _ => Vec::new(), - } -} - -/// `$1::text::integer` 这种占位符(**统一走 text 传值,类型交给 SQL 里的 CAST**)。 -pub(super) fn placeholder(index: usize, cast: &str) -> String { - format!("${index}::text{cast}") -} - -/// 详情投影 —— 编辑弹窗 `setFieldsValue(res.data)` **直接吃这份**。 -/// -/// 🔴 少一个键 ⇒ 弹窗里那一格永远是空的,而且**不报错**(静默)。 -/// 🔴 `birthday` / `entryDate` 用 `to_char(…,'YYYY-MM-DD')`:官方 VO 是日期串, -/// `::text` 会带出 ` 00:00:00` ⇒ DatePicker 解析失败。 -/// -/// 🔴 **本常量住在 helper,不住 `permission.rs`** —— 它被 helper 的 `user_info` 用; -/// 而 helper 被 14 个契约面模块依赖 ⇒ 放 permission 会形成**循环依赖**。 -pub(super) const USER_DETAIL_COLUMNS: &str = "f_id AS \"id\", f_account AS \"account\", \ - f_real_name AS \"realName\", f_nick_name AS \"nickName\", f_head_icon AS \"headIcon\", \ - f_gender AS \"gender\", to_char(f_birthday, 'YYYY-MM-DD') AS \"birthday\", \ - f_mobile_phone AS \"mobilePhone\", f_tele_phone AS \"telePhone\", f_landline AS \"landline\", \ - f_email AS \"email\", f_nation AS \"nation\", f_native_place AS \"nativePlace\", \ - to_char(f_entry_date, 'YYYY-MM-DD') AS \"entryDate\", \ - f_certificates_type AS \"certificatesType\", \ - f_certificates_number AS \"certificatesNumber\", f_education AS \"education\", \ - f_urgent_contacts AS \"urgentContacts\", f_urgent_tele_phone AS \"urgentTelePhone\", \ - f_postal_address AS \"postalAddress\", f_signature AS \"signature\", \ - f_description AS \"description\", COALESCE(f_sort_code, 0) AS \"sortCode\", \ - COALESCE(f_enabled_mark, 0) AS \"enabledMark\", f_rank AS \"ranks\", \ - f_organize_id AS \"organizeId\", f_position_id AS \"positionId\", \ - COALESCE(f_is_administrator, 0) AS \"isAdministrator\", \ - COALESCE(f_lock_mark, 0) AS \"lockMark\", f_unlock_time AS \"unlockTime\", \ - (EXTRACT(EPOCH FROM f_creator_time) * 1000)::bigint AS \"creatorTime\", \ - f_creator_user_id AS \"creatorUserId\", f_tenant_id AS \"tenantId\", \ - COALESCE(f_delete_mark, 0) AS \"deleteMark\""; - -/// 机构名(查不到 ⇒ `None`)。 -/// -/// 🔴 **本函数住在 helper,不住 `permission.rs`** —— 它被 helper 的 -/// `build_user_info` 用;放 permission 会形成**循环依赖**(同 `USER_DETAIL_COLUMNS`)。 -pub(super) async fn organize_name_of(db: &Db, id: &str) -> Option { - let rows = match db - .query_json_params( - "SELECT f_full_name AS \"fullName\" FROM base_organize \ - WHERE f_id = $1::text AND f_delete_mark = 0 LIMIT 1", - &[&id], - ) - .await - { - Ok(rows) => rows, - Err(e) => { - eprintln!("[face-b] 读机构名失败: {e}"); - return None; - } - }; - rows.first() - .and_then(|r| r["fullName"].as_str()) - .map(str::to_string) -} - -/// `GET /api/permission/Users/{id}` —— 单条详情(编辑弹窗)。 -/// -/// ⚠️ **`{id}` 会吞掉所有「`Users/` 下一段的静态 GET」**(`Selector` / `getWorkByUser` / -/// `getUserList` …):它们现在会落到这里、返 `400 用户不存在`,而不是 404。 -/// matchit 的口径是**静态段优先** ⇒ 一旦把那些路由注册进来,自动夺回,无需改这里。 -pub async fn user_info( - State(state): State, - headers: HeaderMap, - Path(id): Path, -) -> Json { - if let Err(resp) = guard(&state, &headers, EN_USER).await { - return resp; - } - let id = id.trim().to_string(); - let sql = format!( - "SELECT {USER_DETAIL_COLUMNS} FROM base_user \ - WHERE f_id = $1::text AND f_delete_mark = 0 LIMIT 1" - ); - let rows = match state.db.query_json_params(&sql, &[&id]).await { - Ok(rows) => rows, - Err(e) => return db_error(e, "用户详情查询"), - }; - match rows.into_iter().next() { - Some(row) => ok(row), - None => fail(code::FAIL, "用户不存在"), - } -} - -/// 用户选择器的投影(`QueryUserSelect` 要 `id` + `fullName`,多选还要 `headIcon`)。 -pub(super) const USER_SELECTOR_PROJECTION: &str = "f_id AS \"id\", f_real_name AS \"fullName\", \ - f_account AS \"account\", f_head_icon AS \"headIcon\", \ - f_organize_id AS \"organizeId\", f_gender AS \"gender\""; - -/// 批量取「姓名/账号」标签(官方 `realName + "/" + account`)。 -/// -/// 🔴 **按 `f_id` 与 `f_account` 双键建表**:本仓写 `f_creator_user_id` 时用的是**账号** -/// (见 `seed.rs` 的 `ADMIN_ACCOUNT`),而官方的历史数据里是 **id** -/// ⇒ 只按其中一种查,另一种就永远显示空。两种都收,key 也两样都放。 -pub(super) async fn user_labels(state: &AppState, ids: &[String]) -> HashMap { - let mut unique: Vec = ids.iter().filter(|s| !s.is_empty()).cloned().collect(); - unique.sort(); - unique.dedup(); - if unique.is_empty() { - return HashMap::new(); - } - let joined = unique.join(","); - match state - .db - .query_json_params( - "SELECT f_id AS \"id\", f_real_name AS \"realName\", f_account AS \"account\" \ - FROM base_user \ - WHERE f_id = ANY(string_to_array($1::text, ',')) \ - OR f_account = ANY(string_to_array($1::text, ','))", - &[&joined], - ) - .await - { - Ok(rows) => { - let mut map = HashMap::new(); - for row in rows { - let id = row - .get("id") - .and_then(Value::as_str) - .unwrap_or_default() - .to_string(); - let account = row.get("account").and_then(Value::as_str).unwrap_or(""); - let name = row - .get("realName") - .and_then(Value::as_str) - .filter(|s| !s.is_empty()) - .unwrap_or(account); - let label = if account.is_empty() || name == account { - name.to_string() - } else { - format!("{name}/{account}") - }; - if !id.is_empty() { - map.insert(id, label.clone()); - } - if !account.is_empty() { - map.insert(account.to_string(), label); - } - } - map - } - Err(e) => { - eprintln!("[face-b] 用户标签查询失败(降级为空): {e}"); - HashMap::new() - } - } -} - -/// 面 B 的「任一权限」守卫 —— 官方用 `@SaCheckPermission(..., mode = SaMode.OR)` 的地方。 -pub(super) async fn guard_any( - state: &AppState, - headers: &HeaderMap, - en_codes: &[&str], -) -> Result> { - let user = require_login_face_b(state, headers).await?; - let system_id = - registry::resolve_system_id(&state.db, registry::app_code_of(headers).as_deref()).await; - for en_code in en_codes { - if has_en_code_permission(&state.db, &user.user_id, user.is_admin, en_code, &system_id).await - { - return Ok(user); - } - } - Err(fail(code::NO_PERMISSION, "无权限")) -} - -/// JSON 对象里取文本(**去首尾空白**,空串 ⇒ `None`)。 -pub(super) fn text_field(obj: &Map, key: &str) -> Option { - let raw = value_to_text(obj.get(key))?; - let trimmed = raw.trim(); - if trimmed.is_empty() { - None - } else { - Some(trimmed.to_string()) - } -} - -/// JSON 对象里取整数(`1` / `"1"` / `true` 都认)—— 用于 `::text::integer` 参数位。 -/// -/// 🔴 不能把 JSON 数字直接 `value_to_text` 后当参数:`1.0` 会变成 `"1.0"`, -/// `'1.0'::text::integer` 在 PG 里是**硬错误**(`invalid input syntax`)。 -pub(super) fn int_field(obj: &Map, key: &str) -> Option { - match obj.get(key)? { - Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)), - Value::String(s) => s.trim().parse::().ok(), - Value::Bool(b) => Some(i64::from(*b)), - _ => None, - } -} - -/// 取 query 里的字符串参数(去空白)。 -pub(super) fn qv(raw: &RawQuery, key: &str) -> String { - crate::platform::sys::query_param(raw, key).trim().to_string() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn headers_with(vue_version: Option<&str>) -> HeaderMap { - let mut headers = HeaderMap::new(); - if let Some(v) = vue_version { - headers.insert( - VUE_VERSION, - axum::http::HeaderValue::from_str(v).expect("头值必须是合法 ASCII"), - ); - } - headers - } - - /// 🔴 **判别规则只有一条**:头 `Vue-Version: 3` ⇒ 面 B;否则面 A。 - #[test] - fn discriminator_is_vue_version_header() { - assert!(is_face_b(&headers_with(Some("3")))); - assert!(!is_face_b(&headers_with(None))); - // 🔴 本仓前端也发 `App-Code` / `Jnpf-Origin` ⇒ **不能**拿它们当判据。 - let mut headers = headers_with(None); - headers.insert("app-code", axum::http::HeaderValue::from_static("mainSystem")); - headers.insert("jnpf-origin", axum::http::HeaderValue::from_static("pc")); - assert!(!is_face_b(&headers), "App-Code / Jnpf-Origin 绝不能当判别头"); - } - - /// 头值带空格也应识别(HTTP 头值两侧空白无意义)。 - #[test] - fn discriminator_ignores_surrounding_whitespace() { - assert!(is_face_b(&headers_with(Some(" 3 ")))); - } - - /// 头值不是 `3`(如 `2`)⇒ 不是面 B。 - #[test] - fn discriminator_rejects_other_values() { - assert!(!is_face_b(&headers_with(Some("2")))); - assert!(!is_face_b(&headers_with(Some("")))); - } - - /// 🔴 **官方 `PageListVO` 形状**:`{pagination:{currentPage,pageSize,total}, list:[…]}`。 - #[test] - fn page_list_vo_has_pagination_and_list() { - let v = page_list(2, 20, 42, vec![json!({"id": "u1"})]); - assert_eq!(v["pagination"]["currentPage"], 2); - assert_eq!(v["pagination"]["pageSize"], 20); - assert_eq!(v["pagination"]["total"], 42); - assert!(v["list"].is_array()); - assert_eq!(v["list"][0]["id"], "u1"); - } - - /// 🔴 **官方 `ListVO` 形状**:`{list:[…]}`(**只有** `list` 一个字段)。 - #[test] - fn list_vo_has_only_list() { - let v = list_vo(vec![json!({"id": "m1"})]); - assert!(v.get("list").is_some()); - assert!(v.get("pagination").is_none()); - assert_eq!(v.as_object().map(|o| o.len()), Some(1)); - } - - /// 分页参数:缺省 ⇒ 官方默认(`pageSize=20` / `currentPage=1`)。 - #[test] - fn paging_defaults_to_official_values() { - let raw = RawQuery(None); - let p = Paging::of(&raw); - assert_eq!(p.current_page, 1); - assert_eq!(p.page_size, 20); - assert_eq!(p.offset, 0); - } - - /// 分页参数:回显请求值;`pageSize=0` / 负数 ⇒ 夹到 1(不生成非法 SQL)。 - #[test] - fn paging_echoes_and_clamps() { - let raw = RawQuery(Some("currentPage=3&pageSize=5".to_string())); - let p = Paging::of(&raw); - assert_eq!(p.current_page, 3); - assert_eq!(p.page_size, 5); - assert_eq!(p.offset, 10); - - let raw = RawQuery(Some("pageSize=0¤tPage=-1".to_string())); - let p = Paging::of(&raw); - assert_eq!(p.current_page, 1); - assert_eq!(p.page_size, 1); - } - - /// 🔴 **菜单节点必须齐 15 个官方字段**(`AllMenuSelectVO.java:12-50`)。 - #[test] - fn menu_node_has_all_15_official_keys() { - let row = MenuRow { - id: "m1".to_string(), - full_name: "用户管理".to_string(), - en_code: Some("permission.user".to_string()), - parent_id: "0".to_string(), - icon: None, - url_address: Some("system/User".to_string()), - page_address: None, - link_target: None, - menu_type: 2, - property_json: None, - sort_code: 2, - system_id: None, - is_data: false, - }; - let v = menu_value(row, Vec::new(), false); - for key in [ - "id", - "fullName", - "enCode", - "parentId", - "icon", - "hasChildren", - "urlAddress", - "pageAddress", - "linkTarget", - "children", - "type", - "propertyJson", - "sortCode", - "systemId", - "isData", - ] { - assert!(v.get(key).is_some(), "面 B 菜单节点必须含键 {key}"); - } - // 🔴 `systemId` 为 NULL ⇒ 兜底成本仓系统 id(单系统)。 - assert_eq!(v["systemId"], SYSTEM_ID); - assert_eq!(v["isData"], false); - assert_eq!(v["children"].as_array().map(|a| a.len()), Some(0)); - } - - /// `propertyJson`:空 ⇒ `null`;合法 JSON ⇒ 解析;非法 ⇒ `null`。 - #[test] - fn property_json_is_parsed_or_null() { - assert_eq!(parse_property_json(None), Value::Null); - assert_eq!(parse_property_json(Some(" ")), Value::Null); - assert_eq!(parse_property_json(Some("{\"a\":1}"))["a"], 1); - assert_eq!(parse_property_json(Some("not json")), Value::Null); - } - - /// 🔴 **`permissionList` 的 `modelId` 是菜单 id**(官方语义:`find(o => o.modelId === menuId)`)。 - #[test] - fn permission_list_model_id_is_menu_id() { - let rows = vec![MenuRow { - id: "m_user".to_string(), - full_name: "用户管理".to_string(), - en_code: Some("permission.user".to_string()), - parent_id: "m_sys".to_string(), - icon: None, - url_address: None, - page_address: None, - link_target: None, - menu_type: 2, - property_json: None, - sort_code: 2, - system_id: None, - is_data: false, - }]; - let list = build_permission_list(&rows); - assert_eq!(list.len(), 1); - assert_eq!(list[0]["modelId"], "m_user"); - assert_eq!(list[0]["moduleName"], "用户管理"); - for key in ["button", "column", "resource", "form"] { - assert_eq!(list[0][key].as_array().map(|a| a.len()), Some(0)); - } - } -} +pub use sspf_compat_core::helper::*; diff --git a/src/backend/src/platform/compat/res.rs b/src/backend/src/platform/compat/res.rs index 67e3b16..0199044 100644 --- a/src/backend/src/platform/compat/res.rs +++ b/src/backend/src/platform/compat/res.rs @@ -1,460 +1,5 @@ -//! 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)) -} - +//! res —— **转发壳**:真源在 [`sspf_compat_core::res`](M3 契约面公共底座)。 +//! 🔴 只做转发、不含实现;14 个契约面模块的 `use super::res::{…}` 不用改。 +//! 为什么留壳、闸门怎么改:见 `docs/CRATES-MIGRATION.md` §4 M3。 +pub use sspf_compat_core::res::*;