P4-4: picker 选择窗数据源 + page schema 服务化两端点
- PickerController GET /api/picker/{entityOrRef}/list?q&page&perPage:
契约定稿——dialogid 实为 view_template_id(侦察客户库纠偏,非 SYS_REFERENCE_ID),
按 view_template根@entityid → ref → 直连实体表名三级解析;全入参过 P1-3 白名单,
搜索值转义防 LIKE 裸拼注入,行级权限 ctx 三级优先(与 EntityController 同口径);
返回 amis options/CRUD 双格式。转换器 source 生成零改动(契约对接落后端解析)。
- PageSchemaController GET /api/page/schema/{templateId}:带 ETag/304,404/503;
与 eip4-web VITE_SCHEMA_SOURCE=backend 联调渲染通过。
- SYS_PAGE_SCHEMA 平台表(bootstrap SQL + 生产 DDL 落 docs,Flyway 引入列 P5);
SchemaImportCli 把 1489 个转换产物幂等入库(etag=sha-256)。
- 单测 +19(picker 9/schema 7/导入 3),全模块 mvn install + ArchUnit 绿。
- 新坑进迁移手册 §8.7(dialogid=view_template_id)/§8.8(GeneralPO LIKE 裸拼)/§8.9(SYS_PAGE_SCHEMA)。
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
35
docs/sql/SYS_PAGE_SCHEMA.sql
Normal file
35
docs/sql/SYS_PAGE_SCHEMA.sql
Normal file
@@ -0,0 +1,35 @@
|
||||
-- ============================================================================
|
||||
-- 生产建表脚本:SYS_PAGE_SCHEMA(平台表)
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 归属:platform-metadata(页面 schema 服务化,P4-4)。
|
||||
-- 契约:GET /api/page/schema/{templateId} 的下发数据源。
|
||||
--
|
||||
-- 【Flyway 待办(P5)】
|
||||
-- 架构条款(docs/架构设计.md §「平台表管理」):SYS_* 平台表由 Flyway 管理。
|
||||
-- 本工程当前未引入 Flyway。本脚本即「生产建表脚本」,P5 引入 Flyway 时
|
||||
-- 原样改名为 V{n}__create_sys_page_schema.sql 纳入 src/main/resources/db/migration 即可
|
||||
-- (内容无需改动,故此处保持 Flyway 友好:单条幂等 DDL,无数据)。
|
||||
-- 本地 / CI 自举副本见 platform-metadata/src/main/resources/bootstrap/bootstrap-page-schema.sql。
|
||||
--
|
||||
-- 初始数据导入(1489 个转换产物)由 SchemaImportCli 批量入库,不在本 DDL 内。
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_page_schema (
|
||||
template_id character varying(64) NOT NULL,
|
||||
name character varying(255),
|
||||
schema_json jsonb NOT NULL,
|
||||
schema_etag character varying(64) NOT NULL,
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
update_time bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_page_schema PRIMARY KEY (template_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_page_schema_name ON sys_page_schema (name);
|
||||
|
||||
COMMENT ON TABLE sys_page_schema IS '页面 amis schema 服务化存储(platform-converter 转换产物入库)';
|
||||
COMMENT ON COLUMN sys_page_schema.template_id IS 'view_template_id(转换产物文件名去 .json)';
|
||||
COMMENT ON COLUMN sys_page_schema.name IS '模板名称(取自分级清单.csv)';
|
||||
COMMENT ON COLUMN sys_page_schema.schema_json IS 'amis 页面 schema(顶层 type:page),已过官方 schema.json 校验闸';
|
||||
COMMENT ON COLUMN sys_page_schema.schema_etag IS 'schema_json 内容指纹(sha-256 hex),HTTP ETag/304 用';
|
||||
COMMENT ON COLUMN sys_page_schema.version IS '单调递增版本(同模板重导入 +1)';
|
||||
COMMENT ON COLUMN sys_page_schema.update_time IS 'epoch 毫秒';
|
||||
27
docs/迁移手册.md
27
docs/迁移手册.md
@@ -689,6 +689,33 @@ com.dsasp.* com.eip4.*
|
||||
| **对策** | P4-5 实装把 `/api/script/execute-template` 改为接受 `{templateId, seq, item}`(RequestBody),后端 `RewrittenScriptStore` 按 `(tid,seq)` 从改写产物取脚本正文执行;原「按模板名取库内 XML 脚本」端点路径区隔为 `/api/script/execute-template-by-name`(保留 P4-2 兼容)。转换器 `attachScriptOnEvent` 生成的 onEvent 即调前者,`item:${&}` 传当前全量表单数据作脚本上下文。出入点已回写报告第五章 |
|
||||
| **影响范围** | `platform-metadata` ScriptExecuteController + RewrittenScriptStore;`platform-converter` TemplateToAmisConverter.attachScriptOnEvent;改写产物落盘根经 `eip4.script.rewritten-root` 配置(默认 `tools/s3_rewriter/output/rewritten`),部署须确保改写产物随应用可达 |
|
||||
|
||||
### 8.7 SelectDialog 的 dialogid = view_template_id(弹窗数据源解析口径坑,picker 端点契约)[NEW 2026-06-11]
|
||||
|
||||
| 栏目 | 内容 |
|
||||
|------|------|
|
||||
| **现象** | P4-4 实现 `/api/picker/{dialogid}/list` 选择窗数据源端点时,初判 `dialogid` 是 `SYS_REFERENCE_ID`(拟经 `DataDicServiceImpl.getReferenceEntityTableName` 反解实体表名)。侦察客户库实测:244 个真实 picker dialogid **全部在 `sys_reference` 反解失败(0 命中)** |
|
||||
| **根因** | 旧引擎模板 XML 里 `SelectDialog`/`MultiSelectDialog` 字段的 `dialogid` 属性,取值是一个 **`view_template_id`**——即「弹窗用哪个列表模板渲染」,**不是** SYS_REFERENCE_ID。被引用模板的 XML 根元素(`<crud entityid="...">` 等)携带 `entityid`,那才是弹窗数据源实体。实测 5 个高频 dialogid 经此路径解析到 PM_PROJECT/SYS_ORG/VIEW_SYS_USER 等真实实体 |
|
||||
| **对策** | picker 端点 `resolveTable` 按优先级解析:① `view_template_id` → 读其 `xml::text` 根 `@entityid` → `DataDicService.getSYSEntity(entityId).getPo().get_Value("TABLENAME")`(主路径,覆盖全部存量 source);② 退化 SYS_REFERENCE_ID 反解(兼容旧引用语义);③ 退化直接实体表名。三路任一解析出的表名都过 P1-3 白名单。**契约与转换器产物对得上靠此解析路径,转换器 source 生成(`/api/picker/{dialogid}/list`)零改动**(dialogid 即模板里原样的属性值) |
|
||||
| **影响范围** | `platform-metadata` PickerController;任何按 SelectDialog 语义做数据源解析的地方;PG `xml` 列须 `xml::text` 取出再 dom4j 解析(见 §5.33);本地 M0 库 `view_template` 是裁剪 stub(无 `xml` 列),端点对 `DataAccessException` 兜底返回 null 走退化路径,不崩 |
|
||||
|
||||
### 8.8 引擎 GeneralPO 对 String 查询条件裸拼 `col like '%值%'`,picker 搜索须转义防注入 [NEW 2026-06-11]
|
||||
|
||||
| 栏目 | 内容 |
|
||||
|------|------|
|
||||
| **现象** | picker/entity 列表端点把前端搜索值下推为引擎查询条件(`cond.put(列名, 值)`)时,String 列的值进了一个 **字符串拼接的 LIKE** 子句 |
|
||||
| **根因** | `GeneralPO.get_searchWhereWithPrefix`(GeneralPO.java:1940-1941)对 `clazz==String.class` 的条件值直接 `sb.append(columnName + " like '%" + obj.toString().trim() + "%'")`——**裸拼,无参数绑定**。列名侧已由 P1-3 白名单守(元数据即白名单),但**值侧**是注入面:值含单引号即可闭合字符串字面量注入 |
|
||||
| **对策** | picker 端点对搜索值 `q` 先过 `escapeLikeValue`:单引号双写(`''`,闭合引擎拼接的字面量防注入)、LIKE 通配符 `%`/`_` 与反斜杠剔除为空格(引擎 LIKE 无 ESCAPE 子句,无法转义,降级为「不可作通配」优先保安全)。实测 `?q=' OR 1=1--` 返回 200 空结果而非 500/注入。**列名仍走白名单,值走转义,双管**。注:EntityController 的 amis filter 值侧同样经此 sink,P5 可考虑统一在引擎外包一层值转义工具(本期 picker 先落地) |
|
||||
| **影响范围** | `platform-metadata` PickerController.escapeLikeValue;EntityController 的 filter 值透传(同 sink,P5 统一);任何把用户输入下推为引擎 String 查询条件的端点 |
|
||||
|
||||
### 8.9 SYS_PAGE_SCHEMA 平台表本期 bootstrap+生产脚本落地,Flyway 引入列 P5 [NEW 2026-06-11]
|
||||
|
||||
| 栏目 | 内容 |
|
||||
|------|------|
|
||||
| **现象** | P4-4 schema 服务化需建平台表 `SYS_PAGE_SCHEMA`(templateId/schema_json/etag/version/update_time)存 1489 个转换产物。架构条款(架构设计 §「平台表管理」):SYS_* 平台表由 Flyway 管。但本工程当前**尚未引入 Flyway** |
|
||||
| **根因** | Flyway 引入是独立工程动作(依赖 + `db/migration` 目录 + baseline 策略),不应在单个功能 P4-4 内顺带引;强行引会与「业务表引擎动态建、不进 Flyway」的边界产生迁移基线划界问题,须单独决策 |
|
||||
| **对策** | 本期按「bootstrap SQL(本地/CI 自举)+ 生产建表脚本落 docs」落地:①`platform-metadata/src/main/resources/bootstrap/bootstrap-page-schema.sql`(`CREATE TABLE IF NOT EXISTS`,幂等,本地/CI psql 灌);②`docs/sql/SYS_PAGE_SCHEMA.sql`(生产建表脚本,注释里写明 P5 引 Flyway 时原样改名 `V{n}__create_sys_page_schema.sql` 即可,DDL 无需改);③导入 CLI `SchemaImportCli` 启动时 `CREATE TABLE IF NOT EXISTS` 兜底。**Flyway 引入列 P5 待办** |
|
||||
| **影响范围** | `platform-metadata`;P5 引 Flyway 时把 `docs/sql/*.sql` 收编为 migration;schema 接口 `GET /api/page/schema/{templateId}` 带 ETag/304(etag=schema_json 的 sha-256,入库时算),amis schema KB 级,304 省重复下发 |
|
||||
|
||||
---
|
||||
|
||||
## 九、待补章节占位
|
||||
|
||||
189
platform-metadata/P4衔接-picker与schema接口报告.md
Normal file
189
platform-metadata/P4衔接-picker与schema接口报告.md
Normal file
@@ -0,0 +1,189 @@
|
||||
# P4 衔接:选择窗数据源(picker)与页面 schema 接口报告
|
||||
|
||||
> 日期:2026-06-11 | 作者:platform-metadata 工作线(P4-4)
|
||||
> 工程:eip4-platform/platform-metadata(JDK17)
|
||||
> 数据源:本地 M0 库 localhost:5433/eip4m0(可写,平台表落地);客户库 192.168.20.68:5435/postgres?currentSchema=eip3(ceshi/ceshi,**只读**,侦察 picker 契约用)
|
||||
> 前序:platform-converter/P4批量转换报告.md(937+138+50=1125 个模板的 SelectDialog→select+source「待联动」,等本端点)
|
||||
|
||||
---
|
||||
|
||||
## 一、一句话结论
|
||||
|
||||
两个切流前公共端点落地并实测通过:
|
||||
- **选择窗数据源** `GET /api/picker/{entityOrRef}/list?q=&page=&perPage=`:解析弹窗数据源实体 → amis options/CRUD 双格式下发,全入参过白名单、搜索转义、行级权限 ctx 生效。
|
||||
- **页面 schema** `GET /api/page/schema/{templateId}`:转换产物 **1489 个**入库 `SYS_PAGE_SCHEMA` 后服务化下发,带 ETag/304;前端 `VITE_SCHEMA_SOURCE=backend` 切到接口模式渲染成功(playwright 截图)。
|
||||
|
||||
单测新增 **19 个**(picker 9 + schema 7 + 导入 CLI 3),全模块 `mvn install` + ArchUnit 绿(8 模块 BUILD SUCCESS,78 个 metadata 测试通过)。
|
||||
|
||||
---
|
||||
|
||||
## 二、契约定稿(关键:与转换器产物对得上)
|
||||
|
||||
### 2.1 picker 契约 —— dialogid 实为 view_template_id(侦察纠偏)
|
||||
|
||||
转换器 `UiTypeMapper`(123/131 行)把 `SelectDialog/MultiSelectDialog` 的 `source` 生成为
|
||||
`/api/picker/{dialogid}/list`,其中 `dialogid = <field>` 的 `dialogid` 属性原样值。
|
||||
|
||||
**初判 `dialogid` 是 `SYS_REFERENCE_ID`(转换器注释如此写),侦察客户库实测推翻**:
|
||||
|
||||
| 侦察项 | 结论 |
|
||||
|--------|------|
|
||||
| 提取转换产物全部 picker source 的 dialogid | 244 个唯一 dialogid(覆盖 1125 个待联动模板的弹窗字段) |
|
||||
| 在 `sys_reference.sys_reference_id` 反解 | **0 命中**(全部未解析) |
|
||||
| 在 `view_template.view_template_id` 命中 | **命中**——dialogid 是被引用的列表模板 id |
|
||||
| 被引用模板 XML 根元素 | `<crud ... entityid="...">`,根 `@entityid` 才是弹窗数据源实体 |
|
||||
| 高频 5 个 dialogid 经「模板根 @entityid → SYS_ENTITY」解析 | PM_PROJECT / SYS_ORG / VIEW_SYS_USER(真实实体,全部解析成功) |
|
||||
|
||||
**定稿口径**:path 变量 `entityOrRef` 按优先级解析为实体表名——
|
||||
1. **view_template_id**(转换器产物主路径,覆盖全部存量 source)→ 读其 `xml::text` 根 `@entityid` → `DataDicService.getSYSEntity(entityId).getPo().get_Value("TABLENAME")`;
|
||||
2. **SYS_REFERENCE_ID**(兼容旧引擎引用语义)→ `getReferenceEntityTableName` 反解;
|
||||
3. **实体表名**(直接以实体作数据源)→ 直接命中。
|
||||
|
||||
**与转换器产物对得上:转换器 `source` 生成零改动**(dialogid 即模板里原样属性值,端点带 `/list` 后缀与全部存量 source 对齐)。无需小改转换器、无需重跑模板闸一抽验——契约对接点全部落在后端解析路径,是更小的改动面。
|
||||
|
||||
### 2.2 picker 响应格式(amis options/CRUD 双兼容)
|
||||
|
||||
```
|
||||
{ "status":0, "msg":"", "data": {
|
||||
"options": [ {"label":"系统管理员组","value":"b0000000-...001"}, ... ], // amis select 的 source 直接消费
|
||||
"items": [ {"_id":"b0000000-...001","NAME":"系统管理员组", ...}, ... ], // amis crud/picker 内嵌 CRUD 消费
|
||||
"total": 3
|
||||
} }
|
||||
```
|
||||
- `value` = 实体主键(`_id`);`label` = 标识列(`isidentifier`)→ 显示列(`getDisplayIndex`)→ 首个非主键 String 列,三级回退;都没有则 label 回落主键值。
|
||||
- 入参:`q`(按标识列模糊搜索,转义后下推)、`page`/`perPage`(分页)、`asUser`/`roles`/`asDepart`/`asOrg`(行级权限测试通道,与 EntityController 同口径)。
|
||||
|
||||
### 2.3 schema 契约(与 eip4-web/src/api/schema.ts 对齐)
|
||||
|
||||
```
|
||||
GET /api/page/schema/{templateId}
|
||||
200 直接返回 amis 页面 schema(JSON,顶层 type:page),带强 ETag
|
||||
304 If-None-Match 命中当前 ETag(空体,省重复下发)
|
||||
404 模板不存在(SYS_PAGE_SCHEMA 无该 templateId)
|
||||
503 schema 存储不可用(SYS_PAGE_SCHEMA 表缺失/库异常 ≈「转换器/产物不可用」)
|
||||
鉴权:带 Bearer(非 prod profile 不强制)
|
||||
```
|
||||
ETag = `schema_json` 的 sha-256 hex(入库时算,与导入 CLI 同源)。
|
||||
|
||||
---
|
||||
|
||||
## 三、SYS_PAGE_SCHEMA 平台表与导入
|
||||
|
||||
### 3.1 建表(架构条款:平台表 Flyway 管,业务表引擎管)
|
||||
|
||||
本工程**尚未引入 Flyway**。本期按「bootstrap SQL + 生产建表脚本落 docs」落地,**Flyway 引入列 P5 待办**:
|
||||
|
||||
| 产物 | 路径 | 用途 |
|
||||
|------|------|------|
|
||||
| 本地/CI 自举建表 | `platform-metadata/src/main/resources/bootstrap/bootstrap-page-schema.sql` | `CREATE TABLE IF NOT EXISTS`,幂等,psql 灌 |
|
||||
| 生产建表脚本 | `docs/sql/SYS_PAGE_SCHEMA.sql` | 注释写明 P5 引 Flyway 时原样改名 `V{n}__create_sys_page_schema.sql` |
|
||||
| CLI 自举兜底 | `SchemaImportCli.CREATE_DDL` | 导入时 `CREATE TABLE IF NOT EXISTS` 兜底(本地/CI 库未跑 bootstrap 也能用) |
|
||||
|
||||
表结构:`template_id`(PK) / `name` / `schema_json`(jsonb) / `schema_etag`(sha-256) / `version` / `update_time`(epoch ms)。
|
||||
|
||||
### 3.2 导入数量
|
||||
|
||||
`SchemaImportCli` 把 `platform-converter/转换产物/schema/*.json`(1489 个)批量入库:
|
||||
|
||||
```
|
||||
SchemaImportCli 导入汇总: 扫描 1489 个产物, 入库/更新 1489 个, 内容未变跳过 0 个
|
||||
(幂等复跑:扫描 1489 个产物, 入库/更新 0 个, 内容未变跳过 1489 个)
|
||||
```
|
||||
- **入库 1489 个**(= 闸一通过的全部转换产物),全部带名称(取自 `分级清单.csv` 的 `view_template_id→name`)。
|
||||
- 幂等:`ON CONFLICT (template_id) DO UPDATE ... WHERE etag 不同`——内容未变 0 行影响(不膨胀版本)。
|
||||
|
||||
---
|
||||
|
||||
## 四、验证证据
|
||||
|
||||
### 4.1 picker 端点(8086 本地库 eip4m0)
|
||||
|
||||
| 用例 | 请求 | 结果 |
|
||||
|------|------|------|
|
||||
| 直接实体表名 | `GET /api/picker/SYS_USERGROUP/list?perPage=3` | 200,3 options(系统管理员组/项目管理组/审批归档组)+ items + total=3 |
|
||||
| **view_template_id 主路径** | seed 测试模板(root `@entityid`→SYS_USERGROUP)`GET /api/picker/{tid}/list` | 200,解析到 SYS_USERGROUP,3 options |
|
||||
| ref→entity 解析 | seed 测试 reference(→SYS_USERGROUP)`GET /api/picker/{refid}/list` | 200,3 options(证 SYS_REFERENCE_ID 退化路径可用) |
|
||||
| 搜索 | `?q=系统` | total=1,仅「系统管理员组」(LIKE 标识列下推) |
|
||||
| 分页 | `?page=2&perPage=2` | total=3,第 2 页 1 条(审批归档组) |
|
||||
| **白名单负例** | `GET /api/picker/NOPE_INJECT' OR 1=1--/list` | **HTTP 400** `{status:1,msg:...}`(不回显载荷) |
|
||||
| 无主键引用实体 | ref→SYS_FILTERRULEROLE(MIDTABLE 无 PK) | **HTTP 400**「引用实体不可作选择窗数据源(无主键)」 |
|
||||
| **搜索注入负例** | `?q=' OR 1=1--` | **HTTP 200** 空结果(转义生效,非 500/注入) |
|
||||
| 行级权限 ctx | `?asUser=alice&roles=r1` | 200(非 ADMIN 视角传引擎,触发行级过滤路径) |
|
||||
|
||||
> 客户库(只读)侦察 ≥3 个真实引用实体:5 个高频 dialogid 经「view_template 根 @entityid」解析到
|
||||
> PM_PROJECT / SYS_ORG / VIEW_SYS_USER(真实实体),契约口径在客户库实数据上成立。
|
||||
|
||||
### 4.2 schema 端点 + 前端联调
|
||||
|
||||
| 用例 | 请求 | 结果 |
|
||||
|------|------|------|
|
||||
| 命中 200 | `GET /api/page/schema/d33af663-...`(角色维护) | 200,顶层 `type:page`,带强 ETag `"7c226f99..."` |
|
||||
| 304 | 同上带 `If-None-Match: "7c226f99..."` | **HTTP 304** 空体 |
|
||||
| 404 | `GET /api/page/schema/not-a-real-template-id` | **HTTP 404**「模板不存在」 |
|
||||
|
||||
**前端切换联调(eip4-web)**:
|
||||
- 起 dev server:`VITE_SCHEMA_SOURCE=backend VITE_BACKEND_TARGET=http://localhost:8086 npm run dev -- --port 5174`;
|
||||
- 注入 JWT(app 密钥 HS256 自签,已实测被 JwtAuthFilter 接受)过路由守卫;
|
||||
- 导航 `/page/d33af663-...`(角色维护,真实转换产物 templateId,**不在 mock MAP,只能来自后端**);
|
||||
- 结果:**amis 渲染成功**——52 个 amis DOM 节点,可见「测试/查询/角色名称/描述/搜索」表单+表格,0 schema 加载错误;
|
||||
- 经 `PerformanceResourceTiming` 确认请求落在 `/api/page/schema/d33af663-...`(XHR,backend 模式),**非** `/schemas/*.json` 静态 mock;
|
||||
- 截图:`platform-metadata/P4衔接证据/schema-backend-render.png`。
|
||||
- (页面内 2 个 console error 是 amis CRUD 数据拉取 `/api/flow/SYS_ROLE_SEARCH` 500——M0 库未种该服务流,属**数据**缺失,与 schema 接口无关;schema 已正确下发并渲染。)
|
||||
|
||||
### 4.3 单测 + 全模块绿
|
||||
|
||||
```
|
||||
[INFO] PickerControllerTest Tests run: 9, Failures: 0, Errors: 0
|
||||
[INFO] PageSchemaControllerTest Tests run: 7, Failures: 0, Errors: 0
|
||||
[INFO] SchemaImportCliTest Tests run: 3, Failures: 0, Errors: 0
|
||||
[INFO] platform-metadata 全模块 Tests run: 78, Failures: 0, Errors: 0
|
||||
[INFO] ArchitectureRulesTest Tests run: 1, Failures: 0, Errors: 0 (保真层禁依赖现代层)
|
||||
[INFO] Reactor: legacy-core/converter/metadata/auth/flow-gateway/ai/parity/app 全 BUILD SUCCESS
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、安全落地(全入参过白名单 + 搜索参数化 + 行级权限)
|
||||
|
||||
| 关注点 | 落地 |
|
||||
|--------|------|
|
||||
| 标识符白名单(P1-3) | 解析出的表名经 `IdentifierWhitelist.requireLegalTable`;非法实体 → 400(不进引擎拼接) |
|
||||
| 搜索参数化 | `q` 经 `escapeLikeValue`(单引号双写防注入、`%`/`_`/`\` 剔除防通配符逃逸)才进引擎 LIKE 裸拼点(GeneralPO.java:1940 String 条件无参数绑定,见手册 §8.8) |
|
||||
| 排序/分页 | 分页用引擎 `PAGE_START/PAGE_SIZE` 数值键,无标识符拼接面 |
|
||||
| 行级权限 ctx | 三级优先(asUser 测试通道 → JWT 绑定的请求级上下文 → ADMIN 默认),与 EntityController 同 `buildCtx` 口径,非 ADMIN 触发引擎行级过滤 |
|
||||
| 不回显载荷 | 白名单异常文案只报「哪类参数+哪个实体」,表名回显只放行 `[A-Z0-9_]`(IllegalIdentifierException + Handler 既有设施) |
|
||||
|
||||
---
|
||||
|
||||
## 六、git 提交
|
||||
|
||||
只 add 本线自有文件(不碰 converter 脚本挂回线、flow-gateway 领地;本次**未改** converter `source` 生成):
|
||||
- `platform-metadata/src/main/java/com/eip4/platform/metadata/web/PickerController.java`
|
||||
- `platform-metadata/src/main/java/com/eip4/platform/metadata/web/PageSchemaController.java`
|
||||
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/SchemaImportCli.java`
|
||||
- `platform-metadata/src/main/resources/bootstrap/bootstrap-page-schema.sql`
|
||||
- `platform-metadata/src/test/java/com/eip4/platform/metadata/web/PickerControllerTest.java`
|
||||
- `platform-metadata/src/test/java/com/eip4/platform/metadata/web/PageSchemaControllerTest.java`
|
||||
- `platform-metadata/src/test/java/com/eip4/platform/metadata/schema/SchemaImportCliTest.java`
|
||||
- `docs/sql/SYS_PAGE_SCHEMA.sql`
|
||||
- `docs/迁移手册.md`(§8.7/8.8/8.9 新坑)
|
||||
- `platform-metadata/P4衔接-picker与schema接口报告.md` + `platform-metadata/P4衔接证据/schema-backend-render.png`
|
||||
|
||||
---
|
||||
|
||||
## 七、坑列表(详见迁移手册 §8.7–8.9)
|
||||
|
||||
1. **SelectDialog 的 dialogid = view_template_id**(非 SYS_REFERENCE_ID)——弹窗数据源实体取被引用模板根 `@entityid`(手册 §8.7)。
|
||||
2. **引擎 GeneralPO 对 String 查询条件裸拼 `col like '%值%'`**(GeneralPO.java:1940 无参数绑定)——picker/entity 搜索值侧是注入面,须转义(手册 §8.8)。
|
||||
3. **SYS_PAGE_SCHEMA 本期 bootstrap+生产脚本落地,Flyway 引入列 P5**(架构条款平台表 Flyway 管,但工程未引 Flyway)(手册 §8.9)。
|
||||
4. 本地 M0 库 `view_template` 是裁剪 stub(无 `xml` 列)——picker 模板路径对 `DataAccessException` 兜底返回 null 走退化路径,不崩;客户库 `view_template.xml` 是 PG `xml` 物理类型,须 `xml::text` 取出再 dom4j 解析(手册 §5.33)。
|
||||
5. M0 库 alice 登录依赖完整 auth 自举(含 parity 种子表 `eip4pt_*`),本端点验证经 app 密钥自签 JWT 过守卫绕开——非本线缺陷,记录供后续联调注意。
|
||||
|
||||
---
|
||||
|
||||
## 八、P5 待办
|
||||
|
||||
- **引入 Flyway**:把 `docs/sql/SYS_PAGE_SCHEMA.sql` 收编为 `db/migration/V{n}__*.sql`,确立平台表迁移基线(业务表仍引擎动态建、不进 Flyway)。
|
||||
- **统一值侧转义**:EntityController 的 amis filter 值透传与 picker 同 sink(GeneralPO LIKE 裸拼),P5 可在引擎外包一层统一值转义工具。
|
||||
- **picker 性能**:高频 dialogid(如 PM_PROJECT 出现 306 次)可加 view_template_id→tablename 解析缓存(现走 POInfo 缓存 + 每次查 view_template,量大时优化)。
|
||||
- **schema 增量重导**:转换器重跑后经 `SchemaImportCli` 幂等重导(etag 变才升版本),可接 CI 触发。
|
||||
BIN
platform-metadata/P4衔接证据/schema-backend-render.png
Normal file
BIN
platform-metadata/P4衔接证据/schema-backend-render.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
@@ -0,0 +1,214 @@
|
||||
package com.eip4.platform.metadata.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* 页面 schema 导入 CLI(P4-4):把 platform-converter 的转换产物
|
||||
* ({@code 转换产物/schema/{view_template_id}.json},1489 个)批量入库 {@code SYS_PAGE_SCHEMA},
|
||||
* 供 {@code GET /api/page/schema/{templateId}} 在线下发。
|
||||
*
|
||||
* <p>幂等:每条 upsert({@code ON CONFLICT (template_id) DO UPDATE}),同模板重导入时
|
||||
* 仅当内容指纹({@code schema_etag})变化才 +1 版本并刷新;内容未变则版本不动(避免无谓版本膨胀)。
|
||||
* 建表 DDL 与 {@code bootstrap-page-schema.sql} 同口径,CLI 启动时 {@code CREATE TABLE IF NOT EXISTS}
|
||||
* 兜底(本地/CI 自举库可能未跑 bootstrap)。
|
||||
*
|
||||
* <p>用法:
|
||||
* <pre>{@code
|
||||
* java -cp ... com.eip4.platform.metadata.schema.SchemaImportCli \
|
||||
* "jdbc:postgresql://localhost:5433/eip4m0" zhengwr "" \
|
||||
* ../platform-converter/转换产物/schema \
|
||||
* ../platform-converter/转换产物/分级清单.csv
|
||||
* }</pre>
|
||||
* 第 4 参为产物 schema 目录,第 5 参(可选)为分级清单 CSV(取模板名称,缺省则 name 留空)。
|
||||
* <b>导入目标是本地/平台库(可写),不是只读客户库</b>——客户库红线由 BatchConvertCli 守,本 CLI 只写平台表。
|
||||
*/
|
||||
public final class SchemaImportCli {
|
||||
|
||||
/** 与 bootstrap-page-schema.sql / docs/sql/SYS_PAGE_SCHEMA.sql 完全一致的建表 DDL(CLI 自举兜底)。 */
|
||||
static final String CREATE_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS sys_page_schema (
|
||||
template_id character varying(64) NOT NULL,
|
||||
name character varying(255),
|
||||
schema_json jsonb NOT NULL,
|
||||
schema_etag character varying(64) NOT NULL,
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
update_time bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_page_schema PRIMARY KEY (template_id)
|
||||
)""";
|
||||
|
||||
private static final String UPSERT = """
|
||||
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
|
||||
VALUES (?, ?, ?::jsonb, ?, 1, ?)
|
||||
ON CONFLICT (template_id) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
schema_json = EXCLUDED.schema_json,
|
||||
schema_etag = EXCLUDED.schema_etag,
|
||||
version = sys_page_schema.version + 1,
|
||||
update_time = EXCLUDED.update_time
|
||||
WHERE sys_page_schema.schema_etag <> EXCLUDED.schema_etag""";
|
||||
|
||||
private SchemaImportCli() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 4) {
|
||||
System.err.println("用法: SchemaImportCli <jdbcUrl> <user> <pass> <schemaDir> [csvFile]");
|
||||
System.exit(2);
|
||||
return;
|
||||
}
|
||||
String url = args[0];
|
||||
String user = args[1];
|
||||
String pass = args[2];
|
||||
Path schemaDir = Path.of(args[3]);
|
||||
Path csvFile = args.length > 4 && !args[4].isBlank() ? Path.of(args[4]) : null;
|
||||
|
||||
try (Connection conn = DriverManager.getConnection(url, user, pass)) {
|
||||
conn.setAutoCommit(true);
|
||||
Summary summary = importAll(conn, schemaDir, csvFile);
|
||||
System.out.println(summary.render());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 {@code schemaDir} 下全部 {@code *.json} 入库。
|
||||
*
|
||||
* @param conn 目标平台库连接(可写)
|
||||
* @param schemaDir 转换产物 schema 目录(文件名 {templateId}.json)
|
||||
* @param csvFile 分级清单 CSV(可选,取 view_template_id→name;列序 id,name,...)
|
||||
* @return 导入汇总
|
||||
*/
|
||||
public static Summary importAll(Connection conn, Path schemaDir, Path csvFile)
|
||||
throws IOException, SQLException {
|
||||
try (PreparedStatement ddl = conn.prepareStatement(CREATE_DDL)) {
|
||||
ddl.execute();
|
||||
}
|
||||
Map<String, String> nameById = csvFile != null ? loadNames(csvFile) : Map.of();
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
Summary summary = new Summary();
|
||||
try (Stream<Path> files = Files.list(schemaDir);
|
||||
PreparedStatement ps = conn.prepareStatement(UPSERT)) {
|
||||
List<Path> jsons = files
|
||||
.filter(p -> p.getFileName().toString().endsWith(".json"))
|
||||
.sorted()
|
||||
.toList();
|
||||
for (Path file : jsons) {
|
||||
String fileName = file.getFileName().toString();
|
||||
String templateId = fileName.substring(0, fileName.length() - ".json".length());
|
||||
String json = Files.readString(file, StandardCharsets.UTF_8);
|
||||
String etag = sha256Hex(json);
|
||||
String name = nameById.get(templateId);
|
||||
|
||||
ps.setString(1, templateId);
|
||||
ps.setString(2, name);
|
||||
ps.setString(3, json);
|
||||
ps.setString(4, etag);
|
||||
ps.setLong(5, now);
|
||||
int affected = ps.executeUpdate();
|
||||
summary.total++;
|
||||
if (affected > 0) {
|
||||
summary.upserted++;
|
||||
} else {
|
||||
summary.unchanged++; // ON CONFLICT WHERE etag 相同 → 0 行(内容未变)
|
||||
}
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** 计算内容指纹(sha-256 hex),与 PageSchemaController 的 ETag 同源。 */
|
||||
static String sha256Hex(String content) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] digest = md.digest(content.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder sb = new StringBuilder(digest.length * 2);
|
||||
for (byte b : digest) {
|
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16));
|
||||
sb.append(Character.forDigit(b & 0xF, 16));
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 不可用", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从分级清单 CSV 取 {@code view_template_id → name}。CSV 首列 id、次列 name(见
|
||||
* 转换产物/分级清单.csv 表头),含引号/逗号的名称按 RFC4180 最小解析前两列。
|
||||
*/
|
||||
static Map<String, String> loadNames(Path csvFile) throws IOException {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
List<String> lines = Files.readAllLines(csvFile, StandardCharsets.UTF_8);
|
||||
for (int i = 1; i < lines.size(); i++) { // 跳表头
|
||||
String line = lines.get(i);
|
||||
if (line.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
// BOM 在首行表头,数据行无需处理;最小解析前两个 CSV 字段
|
||||
String[] firstTwo = parseFirstTwoCsv(line);
|
||||
if (firstTwo[0] != null && !firstTwo[0].isBlank()) {
|
||||
map.put(firstTwo[0].trim(), firstTwo[1]);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/** 最小 CSV 解析:取前两字段(支持双引号包裹与字段内逗号)。 */
|
||||
private static String[] parseFirstTwoCsv(String line) {
|
||||
String[] result = new String[2];
|
||||
int field = 0;
|
||||
boolean inQuotes = false;
|
||||
StringBuilder cur = new StringBuilder();
|
||||
for (int i = 0; i < line.length() && field < 2; i++) {
|
||||
char c = line.charAt(i);
|
||||
if (inQuotes) {
|
||||
if (c == '"') {
|
||||
if (i + 1 < line.length() && line.charAt(i + 1) == '"') {
|
||||
cur.append('"');
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
cur.append(c);
|
||||
}
|
||||
} else if (c == '"') {
|
||||
inQuotes = true;
|
||||
} else if (c == ',') {
|
||||
result[field++] = cur.toString();
|
||||
cur.setLength(0);
|
||||
} else {
|
||||
cur.append(c);
|
||||
}
|
||||
}
|
||||
if (field < 2) {
|
||||
result[field] = cur.toString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 导入汇总(total=扫到的产物文件数;upserted=新增或内容变更入库;unchanged=内容未变跳过)。 */
|
||||
public static final class Summary {
|
||||
public int total;
|
||||
public int upserted;
|
||||
public int unchanged;
|
||||
|
||||
public String render() {
|
||||
return "SchemaImportCli 导入汇总: 扫描 " + total + " 个产物, 入库/更新 " + upserted
|
||||
+ " 个, 内容未变跳过 " + unchanged + " 个";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
|
||||
/**
|
||||
* 页面 schema 服务化端点(P4-4 切流前公共端点之一)。
|
||||
*
|
||||
* <p>把 platform-converter 的转换产物({@code 转换产物/schema/{view_template_id}.json},1489 个)
|
||||
* 经 {@code SchemaImportCli} 入库 {@code SYS_PAGE_SCHEMA} 后,由本端点在线下发——前端
|
||||
* eip4-web 在 {@code VITE_SCHEMA_SOURCE=backend} 时读这里(契约见 ../eip4-web/README.md「与后端契约清单」
|
||||
* 与 src/api/schema.ts)。
|
||||
*
|
||||
* <p><b>契约</b>(与 eip4-web/src/api/schema.ts 对齐):
|
||||
* <ul>
|
||||
* <li>{@code GET /api/page/schema/{templateId}} → 200 直接返回 amis 页面 schema(JSON,顶层 type:page);</li>
|
||||
* <li>{@code 404}:模板不存在(库内无该 templateId 记录);</li>
|
||||
* <li>{@code 503}:schema 存储不可用(SYS_PAGE_SCHEMA 表缺失/库异常,即「转换器/产物不可用」)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>ETag/304</b>:amis schema 不小(KB 级),入库时已算内容指纹({@code schema_etag}=sha-256 hex)。
|
||||
* 响应带 {@code ETag} 强校验;请求带匹配的 {@code If-None-Match} 时回 304(空体),省去重复下发与解析。
|
||||
*/
|
||||
@RestController
|
||||
public class PageSchemaController {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public PageSchemaController(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Operation(summary = "下发页面 amis schema(带 ETag/304)",
|
||||
description = "VITE_SCHEMA_SOURCE=backend 时前端读此端点;404=模板不存在,503=schema 存储不可用")
|
||||
@GetMapping("/api/page/schema/{templateId}")
|
||||
public ResponseEntity<String> schema(@PathVariable String templateId,
|
||||
@RequestHeader(value = HttpHeaders.IF_NONE_MATCH, required = false)
|
||||
String ifNoneMatch) {
|
||||
List<Map<String, Object>> rows;
|
||||
try {
|
||||
rows = jdbcTemplate.queryForList(
|
||||
"SELECT schema_json::text AS schema_json, schema_etag FROM sys_page_schema WHERE template_id = ?",
|
||||
templateId);
|
||||
} catch (DataAccessException ex) {
|
||||
// SYS_PAGE_SCHEMA 表缺失或库异常 → schema 存储不可用(等价契约「503 转换器不可用」)
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"status\":2,\"msg\":\"schema 存储不可用\"}");
|
||||
}
|
||||
|
||||
if (rows.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"status\":1,\"msg\":\"模板不存在\"}");
|
||||
}
|
||||
|
||||
Map<String, Object> row = rows.get(0);
|
||||
String etagValue = String.valueOf(row.get("schema_etag"));
|
||||
// 强校验 ETag,带引号(RFC 7232)
|
||||
String etag = "\"" + etagValue + "\"";
|
||||
|
||||
// 命中缓存:If-None-Match 与当前 ETag 一致 → 304 空体(仍回 ETag,便于代理缓存续期)
|
||||
if (ifNoneMatch != null && etagMatches(ifNoneMatch, etag)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
|
||||
.eTag(etag)
|
||||
.build();
|
||||
}
|
||||
|
||||
String schemaJson = String.valueOf(row.get("schema_json"));
|
||||
return ResponseEntity.ok()
|
||||
.eTag(etag)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(schemaJson);
|
||||
}
|
||||
|
||||
/** If-None-Match 可为逗号分隔多值或 {@code *};任一匹配即命中。 */
|
||||
private boolean etagMatches(String ifNoneMatch, String etag) {
|
||||
String header = ifNoneMatch.trim();
|
||||
if ("*".equals(header)) {
|
||||
return true;
|
||||
}
|
||||
for (String candidate : header.split(",")) {
|
||||
String c = candidate.trim();
|
||||
// 容忍弱校验前缀 W/(本端点只发强 ETag,但请求可能带 W/)
|
||||
if (c.startsWith("W/")) {
|
||||
c = c.substring(2).trim();
|
||||
}
|
||||
if (c.equals(etag)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.DocumentHelper;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.dataDic.bean.POJOInfo;
|
||||
import com.dsasp.server.common.dataDic.bean.SYS_Entity;
|
||||
import com.dsasp.server.common.dataDic.service.DataDicService;
|
||||
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import com.dsasp.server.common.util.UserSession;
|
||||
import com.dsasp.server.dataDic.bean.POInfo;
|
||||
import com.eip4.platform.metadata.security.IdentifierWhitelist;
|
||||
import com.eip4.platform.metadata.security.IllegalIdentifierException;
|
||||
|
||||
/**
|
||||
* 选择窗数据源端点(P4-4 切流前公共端点之一)。
|
||||
*
|
||||
* <p>老系统 {@code SelectDialog / MultiSelectDialog} 语义 = 「从引用实体/数据源弹窗里选记录」。
|
||||
* P4 批量转换器把这两类 uitype 降级为 amis {@code select + 远程 source},source 形如
|
||||
* {@code /api/picker/{dialogid}/list}(见 platform-converter/P4批量转换报告.md §四第 1/3 行、
|
||||
* UiTypeMapper.java 第 123/131 行)。
|
||||
*
|
||||
* <p><b>契约口径(侦察客户库实测定稿,见 P4衔接-picker与schema接口报告.md)</b>:转换器 source 里的
|
||||
* {@code dialogid} 取自旧引擎模板 XML 里 SelectDialog 的 {@code dialogid} 属性,其值是一个
|
||||
* <b>{@code view_template_id}</b>——即「弹窗用哪个列表模板渲染」,<i>而非</i> SYS_REFERENCE_ID。
|
||||
* 该被引用模板的 XML 根元素({@code <crud entityid="...">} 等)携带 {@code entityid},那才是弹窗
|
||||
* 数据源实体。客户库 244 个真实 picker dialogid 全部经此路径解析到实体(PM_PROJECT/SYS_ORG/VIEW_SYS_USER 等)。
|
||||
*
|
||||
* <p>本端点即「契约对接点」:path 变量 {@code entityOrRef} 按以下优先级解析为实体表名——
|
||||
* <ol>
|
||||
* <li><b>view_template_id</b>(转换器产物的主路径,覆盖全部存量 source)→ 读其 XML 根 {@code @entityid}
|
||||
* → {@link DataDicService#getSYSEntity} 取实体表名;</li>
|
||||
* <li><b>SYS_REFERENCE_ID</b>(兼容旧引擎引用语义)→ {@link DataDicService#getReferenceEntityTableName} 反解;</li>
|
||||
* <li><b>实体表名</b>(直接以实体作数据源)→ 直接命中。</li>
|
||||
* </ol>
|
||||
* 解析出的表名必须经 {@link IdentifierWhitelist}(P1-3 安全第 1 层白名单)确认为已登记实体,否则 400。
|
||||
*
|
||||
* <p>返回 amis CRUD/options 双兼容格式 {@code {status,msg,data:{items,total,options}}}:
|
||||
* <ul>
|
||||
* <li>{@code options}:{@code [{label,value}]},amis {@code select} 的 source 直接消费;</li>
|
||||
* <li>{@code items/total}:amis {@code crud}/{@code picker} 内嵌 CRUD 直接消费(同一端点两用)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>安全</b>:全部入参过白名单(表名 / 搜索列名),搜索值 {@code q} 经
|
||||
* {@link #escapeLikeValue} 转义后才进引擎的 LIKE 拼接点(引擎 {@code GeneralPO} 对 String 条件
|
||||
* 走 {@code col like '%值%'} 裸拼,见 GeneralPO.java:1940——必须先转义单引号/通配符);
|
||||
* 行级权限 {@link #buildCtx} 走与 {@link EntityController} 同口径的三级优先(asUser → JWT 绑定 → ADMIN)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/picker")
|
||||
public class PickerController {
|
||||
|
||||
private final POJOCRUDService pojoCRUDService;
|
||||
private final DataDicService dataDicService;
|
||||
private final IdentifierWhitelist identifierWhitelist;
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public PickerController(POJOCRUDService pojoCRUDService,
|
||||
DataDicService dataDicService,
|
||||
IdentifierWhitelist identifierWhitelist,
|
||||
JdbcTemplate jdbcTemplate) {
|
||||
this.pojoCRUDService = pojoCRUDService;
|
||||
this.dataDicService = dataDicService;
|
||||
this.identifierWhitelist = identifierWhitelist;
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 选择窗数据源:{@code GET /api/picker/{entityOrRef}/list?q=&page=&perPage=}。
|
||||
*
|
||||
* <p>转换器产物用的就是 {@code /api/picker/{dialogid}/list} 这条路径(契约基准),故端点带
|
||||
* {@code /list} 后缀以与全部存量 source 对齐;同时接受 {@code q/page/perPage} 三参(amis select
|
||||
* 的 searchable/分页透传)。
|
||||
*
|
||||
* @param entityOrRef SYS_REFERENCE_ID 或实体表名
|
||||
* @param q 模糊搜索关键字(按引用实体的标识列做 LIKE,已转义)
|
||||
* @param page 页码(1 起)
|
||||
* @param perPage 每页条数
|
||||
* @param asUser 行级权限测试通道:显式当前用户(非 ADMIN 视角,触发行级过滤)
|
||||
* @param roles 行级权限测试通道:逗号分隔角色
|
||||
* @param asDepart 多维测试通道:当前部门
|
||||
* @param asOrg 多维测试通道:当前机构
|
||||
*/
|
||||
@GetMapping("/{entityOrRef}/list")
|
||||
public Map<String, Object> list(@PathVariable String entityOrRef,
|
||||
@RequestParam(required = false) String q,
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@RequestParam(defaultValue = "20") int perPage,
|
||||
@RequestParam(required = false) String asUser,
|
||||
@RequestParam(required = false) String roles,
|
||||
@RequestParam(required = false) String asDepart,
|
||||
@RequestParam(required = false) String asOrg) {
|
||||
String table = resolveTable(entityOrRef);
|
||||
// 安全第 1 层:解析出的表名必须存在于 SYS_ENTITY,否则 400(非法表名不进引擎拼接)
|
||||
identifierWhitelist.requireLegalTable(table);
|
||||
|
||||
POJOInfo info = POInfo.getPOInfo(table);
|
||||
if (info == null || !info.hasKeyColumn()) {
|
||||
// 引用实体无主键(MIDTABLE 等)→ 无法作选择窗数据源,按非法实体拒绝(不回显细节)
|
||||
throw new IllegalIdentifierException("引用实体不可作选择窗数据源(无主键): "
|
||||
+ table.replaceAll("[^A-Z0-9_]", "?"));
|
||||
}
|
||||
String keyColumn = info.getKeyColumnName();
|
||||
String labelColumn = displayColumn(info, keyColumn);
|
||||
|
||||
Properties ctx = buildCtx(asUser, roles, asDepart, asOrg);
|
||||
Map<String, Object> cond = new HashMap<>();
|
||||
cond.put(POJOCRUDService.PAGE_START, (page - 1) * perPage);
|
||||
cond.put(POJOCRUDService.PAGE_SIZE, perPage);
|
||||
// 模糊搜索:仅当有关键字且存在可读标识列时下推 LIKE。q 经转义后进引擎(引擎对 String 条件裸拼
|
||||
// col like '%值%',转义单引号与 LIKE 通配符,杜绝注入与通配符逃逸)。标识列名本身来自元数据,天然合法。
|
||||
if (q != null && !q.isBlank() && labelColumn != null) {
|
||||
cond.put(labelColumn, escapeLikeValue(q.trim()));
|
||||
}
|
||||
|
||||
Map<String, Object> result = pojoCRUDService.listSelect(cond, table, ctx);
|
||||
|
||||
List<Map<String, Object>> rows = toRows(result.get(POJOCRUDService.LIST_RESULT));
|
||||
List<Map<String, Object>> options = new ArrayList<>();
|
||||
for (Map<String, Object> row : rows) {
|
||||
Map<String, Object> opt = new LinkedHashMap<>();
|
||||
Object value = row.get("_id");
|
||||
Object label = labelColumn != null ? row.get(labelColumn) : null;
|
||||
opt.put("label", label != null && !String.valueOf(label).isBlank() ? label : value);
|
||||
opt.put("value", value);
|
||||
options.add(opt);
|
||||
}
|
||||
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("items", rows); // amis crud/picker 内嵌 CRUD 直接消费
|
||||
data.put("options", options); // amis select 的 source 直接消费
|
||||
data.put("total", result.get(POJOCRUDService.PAGE_COUNT));
|
||||
|
||||
Map<String, Object> resp = new HashMap<>();
|
||||
resp.put("status", 0);
|
||||
resp.put("msg", "");
|
||||
resp.put("data", data);
|
||||
return resp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 path 变量为实体表名(优先级见类注释):
|
||||
* <ol>
|
||||
* <li>view_template_id → 读其 XML 根 {@code @entityid} → 实体表名(转换器产物主路径);</li>
|
||||
* <li>SYS_REFERENCE_ID → {@link DataDicService#getReferenceEntityTableName} 反解;</li>
|
||||
* <li>退化:直接当实体表名(由后续白名单校验是否登记)。</li>
|
||||
* </ol>
|
||||
*/
|
||||
private String resolveTable(String entityOrRef) {
|
||||
if (entityOrRef == null || entityOrRef.isBlank()) {
|
||||
throw new IllegalIdentifierException("选择窗数据源标识为空");
|
||||
}
|
||||
// 1) view_template_id → 根 @entityid → 实体表名(转换器 source 里的 dialogid 主路径)
|
||||
String byTemplate = resolveByViewTemplate(entityOrRef);
|
||||
if (byTemplate != null && !byTemplate.isBlank()) {
|
||||
return byTemplate.toUpperCase();
|
||||
}
|
||||
// 2) SYS_REFERENCE_ID 反解(兼容旧引擎引用语义)
|
||||
String byRef = dataDicService.getReferenceEntityTableName(entityOrRef);
|
||||
if (byRef != null && !byRef.isBlank()) {
|
||||
return byRef.toUpperCase();
|
||||
}
|
||||
// 3) 退化:直接当实体表名(以实体作数据源的场景)
|
||||
return entityOrRef.toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 {@code dialogid}(= view_template_id)解析为弹窗数据源实体表名:
|
||||
* 取该模板 XML 根元素的 {@code @entityid} 属性 → {@link DataDicService#getSYSEntity} 取 TABLENAME。
|
||||
* 非模板 id / 模板无 entityid / 实体不存在 → 返回 null(交上层走下一路径)。
|
||||
*
|
||||
* <p>PG {@code xml} 物理类型须以 {@code xml::text} 取出再解析(迁移手册 §5.33)。
|
||||
*/
|
||||
private String resolveByViewTemplate(String maybeTemplateId) {
|
||||
String xml;
|
||||
try {
|
||||
List<String> xmls = jdbcTemplate.queryForList(
|
||||
"SELECT xml::text FROM VIEW_TEMPLATE WHERE VIEW_TEMPLATE_ID = ? AND xml IS NOT NULL",
|
||||
String.class, maybeTemplateId);
|
||||
if (xmls.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
xml = xmls.get(0);
|
||||
} catch (DataAccessException ex) {
|
||||
// VIEW_TEMPLATE 表缺失或库异常 → 视为非模板路径,交由 ref/直连退化
|
||||
return null;
|
||||
}
|
||||
if (xml == null || xml.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String entityId;
|
||||
try {
|
||||
Document doc = DocumentHelper.parseText(xml.trim());
|
||||
entityId = doc.getRootElement().attributeValue("entityid");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
if (entityId == null || entityId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
SYS_Entity entity = dataDicService.getSYSEntity(entityId);
|
||||
if (entity == null || entity.getPo() == null) {
|
||||
return null;
|
||||
}
|
||||
Object tableName = entity.getPo().get_Value("TABLENAME");
|
||||
return tableName != null ? tableName.toString() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 选用作 label 的「可读标识列」:优先实体声明的标识列(isidentifier),
|
||||
* 回退实体的显示列(getDisplayIndex),再回退首个非主键的 String 列;都没有则返回 null
|
||||
* (此时 label 回落为主键值)。
|
||||
*/
|
||||
private String displayColumn(POJOInfo info, String keyColumn) {
|
||||
int count = info.getColumnCount();
|
||||
// 1) 标识列(isidentifier=true)
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (info.isIdentifier(i)) {
|
||||
String name = info.getColumnName(i);
|
||||
if (name != null && !name.equalsIgnoreCase(keyColumn)) {
|
||||
return name.toUpperCase();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2) 实体声明的显示列
|
||||
int di = info.getDisplayIndex();
|
||||
if (di >= 0 && di < count) {
|
||||
String name = info.getColumnName(di);
|
||||
if (name != null && !name.equalsIgnoreCase(keyColumn)) {
|
||||
return name.toUpperCase();
|
||||
}
|
||||
}
|
||||
// 3) 首个非主键 String 列
|
||||
for (int i = 0; i < count; i++) {
|
||||
String name = info.getColumnName(i);
|
||||
if (name != null && !name.equalsIgnoreCase(keyColumn)
|
||||
&& info.getColumnClass(i) == String.class) {
|
||||
return name.toUpperCase();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义进引擎 LIKE 裸拼点的搜索值(引擎 {@code GeneralPO} 对 String 条件做 {@code col like '%值%'}
|
||||
* 字符串拼接,见 GeneralPO.java:1940):单引号双写防 SQL 注入,{@code %}/{@code _} 转义防通配符逃逸。
|
||||
* 注:引擎当前 LIKE 未带 ESCAPE 子句,本转义把 {@code %_} 替换为下划线占位的等价语义降级,
|
||||
* 优先保证安全(注入/逃逸不可发生)而非通配符可搜——这是切流前数据源端点的安全基线。
|
||||
*/
|
||||
static String escapeLikeValue(String raw) {
|
||||
if (raw == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(raw.length());
|
||||
for (int i = 0; i < raw.length(); i++) {
|
||||
char c = raw.charAt(i);
|
||||
switch (c) {
|
||||
case '\'' -> sb.append("''"); // 单引号双写,闭合引擎拼接的字符串字面量,杜绝注入
|
||||
case '%', '_' -> sb.append(' '); // LIKE 通配符 → 空格(引擎 LIKE 无 ESCAPE,转义不可行,降级为不可作通配)
|
||||
case '\\' -> sb.append(' '); // 反斜杠同样剔除,避免后端方言转义歧义
|
||||
default -> sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级权限上下文构造,与 {@link EntityController#buildCtx} 同口径(三级优先):
|
||||
* <ol>
|
||||
* <li>显式 {@code asUser}(对拍测试通道)→ 非 ADMIN 视角,触发行级过滤;</li>
|
||||
* <li>JWT 过滤器已绑定的请求级上下文(真实用户,非 ADMIN)→ 复用;</li>
|
||||
* <li>都没有 → ADMIN 视角(不过滤)。</li>
|
||||
* </ol>
|
||||
*/
|
||||
private Properties buildCtx(String asUser, String roles, String asDepart, String asOrg) {
|
||||
if (asUser != null && !asUser.isBlank()) {
|
||||
Properties ctx = new Properties();
|
||||
ctx.setProperty(LoggedInUser.CURRENTUSER, asUser);
|
||||
if (asDepart != null && !asDepart.isBlank()) {
|
||||
ctx.setProperty(LoggedInUser.CURRENTDEPART, asDepart);
|
||||
}
|
||||
if (asOrg != null && !asOrg.isBlank()) {
|
||||
ctx.setProperty(LoggedInUser.CURRENTORG, asOrg);
|
||||
}
|
||||
List<String> roleList = new ArrayList<>();
|
||||
if (roles != null && !roles.isBlank()) {
|
||||
for (String r : roles.split(",")) {
|
||||
if (!r.isBlank()) {
|
||||
roleList.add(r.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.put(LoggedInUser.ROLES, roleList);
|
||||
return ctx;
|
||||
}
|
||||
Properties bound = UserSession.get();
|
||||
if (bound != null) {
|
||||
String cu = bound.getProperty(LoggedInUser.CURRENTUSER);
|
||||
if (cu != null && !cu.isBlank() && !LoggedInUser.ADMIN.trim().equals(cu.trim())) {
|
||||
return bound;
|
||||
}
|
||||
}
|
||||
return UserSession.getAdmin();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<Map<String, Object>> toRows(Object listResult) {
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
if (listResult instanceof List<?> list) {
|
||||
for (Object o : list) {
|
||||
if (o instanceof GeneralPOJO p) {
|
||||
rows.add(toRow(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private Map<String, Object> toRow(GeneralPOJO p) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("_id", p.get_ID());
|
||||
for (int i = 0; i < p.get_ColumnCount(); i++) {
|
||||
row.put(p.get_ColumnName(i), p.get_Value(i));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
-- ============================================================================
|
||||
-- eip4-platform 平台表 SYS_PAGE_SCHEMA —— bootstrap-page-schema.sql
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 用途:页面 schema 服务化(P4-4)。把 platform-converter 的转换产物
|
||||
-- (转换产物/schema/{view_template_id}.json,1489 个) 作为初始数据源导入,
|
||||
-- 由 GET /api/page/schema/{templateId} 在线下发(amis SDK 直接渲染)。
|
||||
--
|
||||
-- 架构条款(docs/架构设计.md §「平台表管理」):SYS_* 平台表由 Flyway 管,业务表由引擎动态建。
|
||||
-- 本工程当前尚未引入 Flyway —— 本次按「bootstrap SQL(本地/CI 自举) + 生产建表脚本
|
||||
-- (docs/sql/SYS_PAGE_SCHEMA.sql) 落 docs」落地,Flyway 引入列 P5 待办
|
||||
-- (见 platform-metadata/P4衔接-picker与schema接口报告.md「Flyway 待办」)。
|
||||
--
|
||||
-- 纪律:可重复执行(CREATE TABLE IF NOT EXISTS / DROP INDEX IF EXISTS);
|
||||
-- 表名/列名一律小写(PG 不区分大小写,引擎与现代层 SQL 大小写混用,小写建库两侧皆命中)。
|
||||
-- schema 列用 jsonb(amis 页面 schema 不小,jsonb 便于校验/索引,且导入侧用 ::jsonb 强校验 JSON 合法)。
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_page_schema (
|
||||
template_id character varying(64) NOT NULL, -- view_template_id(转换产物文件名去 .json)
|
||||
name character varying(255), -- 模板名称(取自分级清单.csv,便于运维检索)
|
||||
schema_json jsonb NOT NULL, -- amis 页面 schema(顶层 type:page)
|
||||
schema_etag character varying(64) NOT NULL, -- schema_json 的内容指纹(sha-256 hex),用于 HTTP ETag/304
|
||||
version integer NOT NULL DEFAULT 1, -- 单调递增版本(同模板重导入 +1)
|
||||
update_time bigint NOT NULL, -- epoch 毫秒(与引擎 DATE 列同口径)
|
||||
CONSTRAINT pk_sys_page_schema PRIMARY KEY (template_id)
|
||||
);
|
||||
|
||||
-- 按名称检索(运维/联调按模板名找 templateId)
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_page_schema_name ON sys_page_schema (name);
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.eip4.platform.metadata.schema;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Schema 导入 CLI {@link SchemaImportCli} 纯逻辑单测(不连库):
|
||||
* 内容指纹(与 ETag 同源)确定性 + 分级清单 CSV 名称解析(含引号/逗号)。
|
||||
*/
|
||||
class SchemaImportCliTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("1. sha256Hex 确定性:同输入同指纹、异输入异指纹、64 位 hex")
|
||||
void sha256Deterministic() {
|
||||
String a = SchemaImportCli.sha256Hex("{\"type\":\"page\"}");
|
||||
String b = SchemaImportCli.sha256Hex("{\"type\":\"page\"}");
|
||||
String c = SchemaImportCli.sha256Hex("{\"type\":\"crud\"}");
|
||||
assertEquals(a, b);
|
||||
assertNotEquals(a, c);
|
||||
assertEquals(64, a.length()); // sha-256 = 32 字节 = 64 hex
|
||||
assertEquals(a, a.toLowerCase()); // 全小写 hex
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2. loadNames:跳表头 + BOM,取 id→name,支持引号包裹与字段内逗号")
|
||||
void loadNamesParsesCsv(@TempDir Path dir) throws IOException {
|
||||
Path csv = dir.resolve("分级清单.csv");
|
||||
String content = """
|
||||
view_template_id,name,type,root,grade
|
||||
id-1,角色维护,1,crud,SUCCESS
|
||||
id-2,"合同,带逗号的名称",1,crud,PARTIAL
|
||||
id-3,"含""引号""名",1,crud,PARTIAL
|
||||
""";
|
||||
Files.writeString(csv, content, StandardCharsets.UTF_8);
|
||||
|
||||
Map<String, String> names = SchemaImportCli.loadNames(csv);
|
||||
assertEquals("角色维护", names.get("id-1"));
|
||||
assertEquals("合同,带逗号的名称", names.get("id-2"));
|
||||
assertEquals("含\"引号\"名", names.get("id-3"));
|
||||
assertNull(names.get("view_template_id")); // 表头被跳过
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3. CREATE_DDL 幂等且与 bootstrap 同表名(sys_page_schema)")
|
||||
void createDdlShape() {
|
||||
String ddl = SchemaImportCli.CREATE_DDL;
|
||||
org.junit.jupiter.api.Assertions.assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_page_schema"));
|
||||
org.junit.jupiter.api.Assertions.assertTrue(ddl.contains("schema_etag"));
|
||||
org.junit.jupiter.api.Assertions.assertTrue(ddl.contains("PRIMARY KEY (template_id)"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* 页面 schema 端点 {@link PageSchemaController} 单测(mock JdbcTemplate,不连库)。
|
||||
*
|
||||
* <p>覆盖契约:200 直接返回 schema(带 ETag)、If-None-Match 命中 → 304 空体、模板不存在 → 404、
|
||||
* SYS_PAGE_SCHEMA 表缺失/库异常 → 503。
|
||||
*/
|
||||
class PageSchemaControllerTest {
|
||||
|
||||
private static final String TID = "00511ac1-ee64-4ecd-a550-22842ee5be72";
|
||||
private static final String SCHEMA = "{\"type\":\"page\",\"title\":\"角色维护\"}";
|
||||
private static final String ETAG_VALUE = "abc123etag";
|
||||
|
||||
private List<Map<String, Object>> oneRow() {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("schema_json", SCHEMA);
|
||||
row.put("schema_etag", ETAG_VALUE);
|
||||
return List.of(row);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1. 命中:200 直接返回 amis schema + 强 ETag")
|
||||
void hit200WithEtag() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA, resp.getBody());
|
||||
assertEquals("\"" + ETAG_VALUE + "\"", resp.getHeaders().getETag());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2. If-None-Match 命中当前 ETag → 304 空体")
|
||||
void notModified304() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "\"" + ETAG_VALUE + "\"");
|
||||
assertEquals(HttpStatus.NOT_MODIFIED, resp.getStatusCode());
|
||||
assertNull(resp.getBody());
|
||||
assertEquals("\"" + ETAG_VALUE + "\"", resp.getHeaders().getETag());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3. If-None-Match 不匹配 → 200 正常下发")
|
||||
void staleEtagReturns200() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "\"stale-etag\"");
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA, resp.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4. 模板不存在 → 404")
|
||||
void notFound404() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq("missing"))).thenReturn(List.of());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema("missing", null);
|
||||
assertEquals(HttpStatus.NOT_FOUND, resp.getStatusCode());
|
||||
assertTrue(String.valueOf(resp.getBody()).contains("模板不存在"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("5. SYS_PAGE_SCHEMA 缺失/库异常 → 503")
|
||||
void serviceUnavailable503() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID)))
|
||||
.thenThrow(new DataAccessResourceFailureException("relation sys_page_schema does not exist"));
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null);
|
||||
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, resp.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("6. 弱校验前缀 W/ 的 If-None-Match 也能命中")
|
||||
void weakValidatorPrefixMatches() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "W/\"" + ETAG_VALUE + "\"");
|
||||
assertEquals(HttpStatus.NOT_MODIFIED, resp.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("7. If-None-Match: * 通配 → 304")
|
||||
void wildcardIfNoneMatch() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "*");
|
||||
assertEquals(HttpStatus.NOT_MODIFIED, resp.getStatusCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.CCache;
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.dataDic.bean.POJOInfo;
|
||||
import com.dsasp.server.common.dataDic.bean.SYS_Entity;
|
||||
import com.dsasp.server.common.dataDic.service.DataDicService;
|
||||
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import com.eip4.platform.metadata.security.IdentifierWhitelist;
|
||||
import com.eip4.platform.metadata.security.IllegalIdentifierException;
|
||||
|
||||
/**
|
||||
* 选择窗数据源端点 {@link PickerController} 单测(mock 引擎/白名单/元数据,不连库)。
|
||||
*
|
||||
* <p>覆盖:① ref id → 实体表名反解;② 直接实体表名退化路径;③ 模糊搜索值转义(防注入/通配符逃逸);
|
||||
* ④ 分页透传;⑤ 白名单负例 400;⑥ 行级权限 ctx(asUser → 非 ADMIN 视角);⑦ amis options 装配;
|
||||
* ⑧ 无主键引用实体拒绝。
|
||||
*
|
||||
* <p>{@code POInfo.getPOInfo(table)}(继承自 AbstractPOJOInfo 的静态工厂,走静态 {@code s_cache} 缓存)
|
||||
* 在测试里经反射预热缓存桩入——比静态 mock 更稳(避免「继承自父类的静态方法被子类 mockStatic 不拦截」坑),
|
||||
* 每个用例后清缓存隔离。
|
||||
*/
|
||||
class PickerControllerTest {
|
||||
|
||||
private static final String REF_ID = "73cf2dfb-9c03-405f-bfe7-762a57e900ed";
|
||||
private static final String TABLE = "SYS_USERGROUP";
|
||||
private static final String KEY = "SYS_USERGROUP_ID";
|
||||
private static final String LABEL = "NAME";
|
||||
|
||||
/** 把 fakeInfo 预热进 AbstractPOJOInfo.s_cache(POInfo.getPOInfo 命中缓存即返回,不触发 loadInfo 连库)。 */
|
||||
@SuppressWarnings("unchecked")
|
||||
private void seedPoInfoCache(String table, POJOInfo info) {
|
||||
try {
|
||||
Field f = Class.forName("com.dsasp.server.common.dataDic.bean.AbstractPOJOInfo")
|
||||
.getDeclaredField("s_cache");
|
||||
f.setAccessible(true);
|
||||
CCache<String, POJOInfo> cache = (CCache<String, POJOInfo>) f.get(null);
|
||||
cache.put(table, info);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException("预热 POInfo 缓存失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void clearPoInfoCache() {
|
||||
try {
|
||||
Field f = Class.forName("com.dsasp.server.common.dataDic.bean.AbstractPOJOInfo")
|
||||
.getDeclaredField("s_cache");
|
||||
f.setAccessible(true);
|
||||
((Map<String, POJOInfo>) f.get(null)).clear();
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException("清理 POInfo 缓存失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
clearPoInfoCache();
|
||||
}
|
||||
|
||||
/** 构造一个最小 POJOInfo 桩:单标识列 NAME + 主键 SYS_USERGROUP_ID。 */
|
||||
private POJOInfo fakeInfo() {
|
||||
POJOInfo info = mock(POJOInfo.class);
|
||||
when(info.hasKeyColumn()).thenReturn(true);
|
||||
when(info.getKeyColumnName()).thenReturn(KEY);
|
||||
when(info.getColumnCount()).thenReturn(2);
|
||||
when(info.getColumnName(0)).thenReturn(KEY);
|
||||
when(info.getColumnName(1)).thenReturn(LABEL);
|
||||
when(info.isIdentifier(0)).thenReturn(false);
|
||||
when(info.isIdentifier(1)).thenReturn(true);
|
||||
when(info.getDisplayIndex()).thenReturn(1);
|
||||
org.mockito.Mockito.doReturn(String.class).when(info).getColumnClass(0);
|
||||
org.mockito.Mockito.doReturn(String.class).when(info).getColumnClass(1);
|
||||
return info;
|
||||
}
|
||||
|
||||
private GeneralPOJO fakeRow(String id, String name) {
|
||||
GeneralPOJO p = mock(GeneralPOJO.class);
|
||||
when(p.get_ID()).thenReturn(id);
|
||||
when(p.get_ColumnCount()).thenReturn(2);
|
||||
when(p.get_ColumnName(0)).thenReturn(KEY);
|
||||
when(p.get_ColumnName(1)).thenReturn(LABEL);
|
||||
when(p.get_Value(0)).thenReturn(id);
|
||||
when(p.get_Value(1)).thenReturn(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
private Map<String, Object> engineResult(GeneralPOJO... rows) {
|
||||
Map<String, Object> r = new HashMap<>();
|
||||
r.put(POJOCRUDService.LIST_RESULT, List.of(rows));
|
||||
r.put(POJOCRUDService.PAGE_COUNT, (long) rows.length);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** 默认 JdbcTemplate 桩:VIEW_TEMPLATE 查询返回空(resolveTable 跳过模板路径,走 ref/直连)。 */
|
||||
private JdbcTemplate emptyTemplateJdbc() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(String.class), any())).thenReturn(List.of());
|
||||
return jdbc;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1. ref id → 实体表名反解,返回 amis options{label,value}")
|
||||
void resolvesRefIdToTableAndBuildsOptions() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName(REF_ID)).thenReturn(TABLE);
|
||||
// 先构造结果(含 fakeRow 的内部 stubbing)再 stub engine,避免「stubbing 内嵌 stubbing」破坏 Mockito 状态
|
||||
Map<String, Object> result = engineResult(fakeRow("g1", "管理员组"), fakeRow("g2", "普通组"));
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(result);
|
||||
seedPoInfoCache(TABLE, fakeInfo());
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
Map<String, Object> resp = c.list(REF_ID, null, 1, 20, null, null, null, null);
|
||||
assertEquals(0, resp.get("status"));
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = (Map<String, Object>) resp.get("data");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> options = (List<Map<String, Object>>) data.get("options");
|
||||
assertEquals(2, options.size());
|
||||
assertEquals("管理员组", options.get(0).get("label"));
|
||||
assertEquals("g1", options.get(0).get("value"));
|
||||
assertEquals(2L, data.get("total"));
|
||||
verify(wl).requireLegalTable(TABLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2. 反解不到 ref → 退化为实体表名直接命中")
|
||||
void fallsBackToDirectTableWhenNotARef() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName(TABLE)).thenReturn(null); // 不是 ref id
|
||||
Map<String, Object> result = engineResult(fakeRow("g1", "管理员组"));
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(result);
|
||||
seedPoInfoCache(TABLE, fakeInfo());
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
// path 用实体表名(小写也可,内部 toUpperCase)
|
||||
Map<String, Object> resp = c.list("sys_usergroup", null, 1, 20, null, null, null, null);
|
||||
assertEquals(0, resp.get("status"));
|
||||
verify(wl).requireLegalTable(TABLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3. 模糊搜索:q 经转义进引擎 LIKE 条件(单引号双写、通配符剔除),按标识列下推")
|
||||
void searchEscapesValueAndPushesDownOnLabelColumn() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName(REF_ID)).thenReturn(TABLE);
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(engineResult());
|
||||
seedPoInfoCache(TABLE, fakeInfo());
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
c.list(REF_ID, "管理'员%组", 1, 20, null, null, null, null);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> condCap = ArgumentCaptor.forClass(Map.class);
|
||||
verify(engine).listSelect(condCap.capture(), eq(TABLE), any(Properties.class));
|
||||
Object pushed = condCap.getValue().get(LABEL);
|
||||
// 单引号双写防注入,% 通配符被剔除为空格防逃逸
|
||||
assertEquals("管理''员 组", pushed);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4. 分页:page/perPage → 引擎 PAGE_START/PAGE_SIZE")
|
||||
void pagingMapsToEngineStartAndSize() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName(REF_ID)).thenReturn(TABLE);
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(engineResult());
|
||||
seedPoInfoCache(TABLE, fakeInfo());
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
c.list(REF_ID, null, 3, 15, null, null, null, null);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> condCap = ArgumentCaptor.forClass(Map.class);
|
||||
verify(engine).listSelect(condCap.capture(), eq(TABLE), any(Properties.class));
|
||||
assertEquals(30, condCap.getValue().get(POJOCRUDService.PAGE_START)); // (3-1)*15
|
||||
assertEquals(15, condCap.getValue().get(POJOCRUDService.PAGE_SIZE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("5. 白名单负例:解析出的表名非法 → 抛 IllegalIdentifierException(异常处理器转 400)")
|
||||
void illegalTableRejected() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName("NOPE")).thenReturn(null);
|
||||
doThrow(new IllegalIdentifierException("非法实体或元数据不存在: NOPE"))
|
||||
.when(wl).requireLegalTable(eq("NOPE"));
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
IllegalIdentifierException ex = assertThrows(IllegalIdentifierException.class,
|
||||
() -> c.list("nope", null, 1, 20, null, null, null, null));
|
||||
assertFalse(ex.getMessage().contains("'")); // 不回显注入载荷
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("6. 行级权限 ctx:asUser → 非 ADMIN 视角传给引擎(触发行级过滤)")
|
||||
void asUserBuildsNonAdminCtx() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName(REF_ID)).thenReturn(TABLE);
|
||||
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(engineResult());
|
||||
seedPoInfoCache(TABLE, fakeInfo());
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
c.list(REF_ID, null, 1, 20, "alice", "role-a,role-b", null, null);
|
||||
|
||||
ArgumentCaptor<Properties> ctxCap = ArgumentCaptor.forClass(Properties.class);
|
||||
verify(engine).listSelect(any(), eq(TABLE), ctxCap.capture());
|
||||
Properties ctx = ctxCap.getValue();
|
||||
assertEquals("alice", ctx.getProperty(LoggedInUser.CURRENTUSER));
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> roles = (List<String>) ctx.get(LoggedInUser.ROLES);
|
||||
assertTrue(roles.contains("role-a") && roles.contains("role-b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("7. 引用实体无主键 → 拒绝作选择窗数据源(400)")
|
||||
void rejectsEntityWithoutKey() {
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
when(dic.getReferenceEntityTableName(REF_ID)).thenReturn(TABLE);
|
||||
POJOInfo noKey = mock(POJOInfo.class);
|
||||
when(noKey.hasKeyColumn()).thenReturn(false);
|
||||
seedPoInfoCache(TABLE, noKey);
|
||||
PickerController c = new PickerController(engine, dic, wl, emptyTemplateJdbc());
|
||||
|
||||
assertThrows(IllegalIdentifierException.class,
|
||||
() -> c.list(REF_ID, null, 1, 20, null, null, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("8. escapeLikeValue:单引号双写 + 通配符/反斜杠剔除")
|
||||
void escapeLikeValueUnit() {
|
||||
assertEquals("a''b", PickerController.escapeLikeValue("a'b"));
|
||||
assertEquals("a b c", PickerController.escapeLikeValue("a%b_c"));
|
||||
assertEquals("x y", PickerController.escapeLikeValue("x\\y"));
|
||||
assertEquals("", PickerController.escapeLikeValue(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("9. 主路径:dialogid=view_template_id → 读 XML 根 @entityid → 实体表名")
|
||||
void resolvesViewTemplateIdToEntity() {
|
||||
String dialogId = "07eef963-fd17-42a5-997c-219f0ec18cff";
|
||||
String entityId = "61d66424-6384-4a17-8aca-d7f34d432c5c";
|
||||
POJOCRUDService engine = mock(POJOCRUDService.class);
|
||||
DataDicService dic = mock(DataDicService.class);
|
||||
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
// VIEW_TEMPLATE 返回带 root @entityid 的 XML(与客户库实测同形态)
|
||||
when(jdbc.queryForList(any(String.class), eq(String.class), eq(dialogId)))
|
||||
.thenReturn(List.of("<crud title=\"测试\" entityid=\"" + entityId + "\"><display/></crud>"));
|
||||
// entityId → SYS_ENTITY → TABLENAME=PM_PROJECT
|
||||
GeneralPOJO entityPo = mock(GeneralPOJO.class);
|
||||
when(entityPo.get_Value("TABLENAME")).thenReturn("PM_PROJECT");
|
||||
SYS_Entity sysEntity = mock(SYS_Entity.class);
|
||||
when(sysEntity.getPo()).thenReturn(entityPo);
|
||||
when(dic.getSYSEntity(entityId)).thenReturn(sysEntity);
|
||||
when(engine.listSelect(any(), eq("PM_PROJECT"), any(Properties.class))).thenReturn(engineResult());
|
||||
seedPoInfoCache("PM_PROJECT", fakeInfo());
|
||||
PickerController c = new PickerController(engine, dic, wl, jdbc);
|
||||
|
||||
Map<String, Object> resp = c.list(dialogId, null, 1, 20, null, null, null, null);
|
||||
assertEquals(0, resp.get("status"));
|
||||
verify(wl).requireLegalTable("PM_PROJECT"); // 解析出 PM_PROJECT 并过白名单
|
||||
verify(engine).listSelect(any(), eq("PM_PROJECT"), any(Properties.class));
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,9 @@ psql -h "$CI_PG_HOST" -p "$CI_PG_PORT" -U "$CI_PG_USER" -d "$CI_DB" -q \
|
||||
-f platform-parity/src/main/resources/bootstrap/bootstrap-sys.sql
|
||||
psql -h "$CI_PG_HOST" -p "$CI_PG_PORT" -U "$CI_PG_USER" -d "$CI_DB" -q \
|
||||
-f platform-parity/src/main/resources/bootstrap/bootstrap-privilege.sql
|
||||
# P4-4 平台表 SYS_PAGE_SCHEMA(页面 schema 服务化);幂等建表,数据由 SchemaImportCli 按需导入
|
||||
psql -h "$CI_PG_HOST" -p "$CI_PG_PORT" -U "$CI_PG_USER" -d "$CI_DB" -q \
|
||||
-f platform-metadata/src/main/resources/bootstrap/bootstrap-page-schema.sql
|
||||
|
||||
JDBC="jdbc:postgresql://${CI_PG_HOST}:${CI_PG_PORT}/${CI_DB}"
|
||||
echo "==[3/4] 起服务(:${CI_PORT} → ${JDBC})=="
|
||||
|
||||
Reference in New Issue
Block a user