Compare commits

...

87 Commits

Author SHA1 Message Date
821b79c9d8 Merge feat/process-modeler 阶段4: 模板新建流程 + Playwright e2e
Some checks failed
ci / build-test (push) Has been cancelled
- 4 模板(空白/单人/两级/会签,全小写元素名+isExecutable+DI,__PROCESS_ID__占位)+NewProcessDialog
  +中文key净化idMap发布restore;模板办理人表达式与codec逐字对齐回归断言
- Playwright live e2e 三场景(改存量全链/新建全链/走查+权限)对真8093/8089/5173真部署真起实例3绿

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 16:16:04 +08:00
3808011c8c test(modeler): Playwright live e2e 三场景(改存量/新建/走查+权限)
三场景对真实 8093 网关 + 8089 flowable-service + 真库 eip4 全程点穿:
- 场景A 改存量:/process-modeler?procKey=总包合同交底 → 点会签 userTask「编写交底」
  → EIP4 侧板会签控件读回勾选 → 存草稿(URL 回填 modelId) → 发布(PublishConfirm
  断言 key/版本/运行实例) → 确认 → 起实例 → trace 断言 current userTask。
- 场景B 新建:会签模板新建 → 选 task_cosign 填办理人 content=ADMIN → 存草稿 → 发布
  → 起实例 → trace 断言 current userTask「会签审批」。
- 场景C 走查+权限:中文节点渲染 / palette 齐 / 标准面板+EIP4 侧板同屏 / 超管门 403。

config 复用运行中的 5173 vite(默认 proxy /api→8093),apiJson 直连 8093 同一后端。
数据纪律:afterAll 删本次草稿(净零);发布产生的流程版本无下架端点属固有副作用。
场景C④ alice/123456 dev 库缺席 → 降级为无 token 打 deploy/models 断言 403(同
requireSuperAdmin 拒绝分支) + admin 打 models 200 对照。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 16:12:14 +08:00
54b0200ac0 test(modeler): 模板办理人表达式与codec逐字对齐回归断言(守命根)
I-1:模板里的 activiti:candidateUsers/collection 是硬编码字符串,与 candidateExpression
codec build 输出的逐字对齐此前只是实测、无测试守护。新增断言:从各模板 fromXML 解出属性值
(moddle 已解码 &quot;→真引号、保留全角【】,即 codec 处理的 businessObject 值层),
断言 === buildCandidateExpression(标准 item, 变体)(单人/两级 candidate、会签 multiInstance)。
模板 JSON 键序/转义漂移或 codec 改契约会被单测立即抓到,而非等 live 部署解析即断。

M-1:sanitizedId 加注释说明前端无碰撞去重的前提(新建模板仅 process key 一个非 ASCII id、
节点 id 全 ASCII → 碰撞不可达;未来引入中文节点 id 须对齐后端 -2/-3 去重)。

全量 vitest 273 绿、tsc -b exit 0。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 16:00:28 +08:00
2477f67afe feat(modeler): 新建流程(空白/单人/两级/会签4模板+NewProcessDialog)
模板库 src/modeler/templates/:4 个 BPMN 模板以真实流程为骨架抽形,全小写
元素名 + isExecutable="true" + 完整 BPMNDiagram DI;单人/两级带 activiti:candidateUsers
示例(全角【】+type:user),会签带 multiInstanceLoopCharacteristics+elementVariable+完成条件。
占位符 __PROCESS_ID__/__PROCESS_NAME__ 由 buildNewProcessXml 按用户 key/名称实例化:
ASCII key 直作 process id;中文 key 净化为 ASCII 并记 idMap(发布 restore 回中文 process key)。

NewProcessDialog:名称/key(可中文)/模板下拉,确认产实例化 XML 交父页 importXML。
ProcessModelerPage:新建流程按钮由 disabled 变可用→开对话框→pending newDraft 挂 Modeler+
import 模板(首存前不落草稿,走 createDraft 首存路径,展示名进草稿 name,diff 基线清空)。

模板正确性测试(fromXML 无警告/真序列化后全小写/isExecutable/会签含 multiInstance)+
NewProcessDialog+页面接线测试;全量 vitest 270 绿、tsc -b、build 通过。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:49:16 +08:00
ad8f63cf93 Merge feat/process-modeler 阶段3: 同人确认发布+diff+CRITICAL修复
Some checks failed
ci / build-test (push) Has been cancelled
- 节点级 diffSummary(命名空间感知按userTask id对齐,办理人codec比对/assignee/formKey/multiInstance)
- PublishConfirm(影响摘要key/版本/运行实例+变更节点清单+422结构化错误清单+同人确认)
- 发布 gating(无modelId提示先存)+原始源基线不被首存重置+发布前持久化(预览==部署)
- CRITICAL修复:activiti.json/flowable.json加tagAlias:lowerCase+自定义类型名PascalCase——
  修 bpmn-js Modeler.saveXML输出大写<Process>/<UserTask>致Flowable断部署;真Modeler序列化回归测试
- 全量 vitest 231+tsc+build 绿;live 验收发布 v9 中文key+起实例真userTask全通过

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:31:00 +08:00
8ea0ef2f1e fix(modeler): activiti.json 修 Modeler.saveXML 大写元素名(断部署)+真Modeler序列化回归测试
CRITICAL:bpmn-js Modeler.saveXML 把被 activiti.json `extends` 的 bpmn 类型序列化成
PascalCase 元素名(<Process>/<UserTask>/<StartEvent>…),未扩展的 <sequenceFlow>/<endEvent>
仍小写。Flowable 大小写敏感 → <Process> 不被识别为流程,ProcessValidator 报
flowable-process-definition-not-executable,部署完全失败。

根因:moddle 把「被扩展类型」的合并描述符 $pkg 设为**最后一个 trait 的包**(moddle
index.esm.js:577)。activiti 包缺 `xml.tagAlias:"lowerCase"`,故 moddle-xml 写元素名时不做
首字母小写 → PascalCase。且 tagAlias 是**双向**的(也驱动 fromXML 解析),要求自定义元素类型名
用 activiti/camunda 惯例的 PascalCase,否则解析 <activiti:taskListener> 找不到类型而丢弃。

修法(对齐 activiti/camunda-bpmn-moddle 标准):
- activiti.json + flowable.json 加 `"xml": { "tagAlias": "lowerCase" }`;
- 自定义元素类型名改 PascalCase:taskListener→TaskListener / executionListener→ExecutionListener
  / field→Field / formProperty→FormProperty / value→Value / in→In / out→Out(属性 type 引用同步)。
  XML 元素名仍小写(tagAlias),故 fixture 与「toContain('activiti:taskListener')」类 XML 断言不变。
- Eip4Panel.tsx:moddle.create/$type 用 'activiti:TaskListener';测试 fake 类型名同步。

为何旧测试没抓到:T1.1/T1.2 只断言 activiti 扩展属性/元素多重集,从不断言基础 BPMN 元素名大小写;
fromXML→toXML 与 create 都走同一 moddle-xml Writer 且都产 PascalCase(本 commit 实证)。

新增 serialization.test.ts(4 例,RED→GREEN):以 BpmnModdle(= Modeler.saveXML 的 moddle 层,
jsdom 跑不动 diagram-js SVG)驱动 fromXML→toXML 与 create→toXML,断言基础元素名全小写、无 PascalCase、
isExecutable 保留、扩展元素/属性不丢;flowable 隔离同验。

serialization 4 + fidelity 12 + Eip4Panel 37;全量 231 单测绿,tsc -b rc=0 + build 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:23:51 +08:00
0428a5c9d1 fix(modeler): 发布收口——原始源基线不被首存重置+发布前持久化(预览==部署)+跨命名空间diff测试
I1+I2 联锁修(同一根因:预览/diff 的两侧要对齐"打开时原始源"与"实际部署内容"):
- I1:新增 baselineTargetRef,openSourceRef 只在首次打开某目标时捕获原始源;存量首存
  setParams(modelId) 触发的 reload 因归属已预置为新 modelId 而保留基线,不再被冲成「已存版」
  →「打开存量→改办理人→存→发布」的 diff 恢复非空。
- I2:handlePublishClick 在开确认弹窗前先 saveDraft(currentXml) 持久化编辑器态,使
  后端 deploy 读到的服务端草稿 == 预览 == diff 的 current 侧(草稿改未存直接发布不再预览≠部署)。

Minor:
- M1:diffSummary 比 content 前做全角【】↔半角{} normWidth 归一(含 RAW 兜底路径),防宽度变体误报。
- M2:completionBody 折叠全部空白后比较,防 bpmn-js 重排空白误报完成条件变更。
- M3:PublishConfirm 发布中 guardedClose 拦截遮罩/X 关闭。

I3 测试:diffSummary 跨命名空间(默认 ns 源 vs bpmn: 前缀当前)对齐命中/前缀不误报 + M1 宽度变体;
页面 I1 锁(存量 save→publish 后 diff 基线仍原始源→清单非空,已 red-check 证伪防呆)+ I2(发布前 saveDraft)。

diffSummary 16 + PublishConfirm 9 + 页面 22;全量 227 单测绿,tsc -b rc=0 + build 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 14:39:52 +08:00
406f053ec2 feat(modeler): 同人确认发布(影响摘要+节点级diff+422校验错误清单)
- diffSummary.ts:DOMParser 命名空间感知的节点级 diff,按 userTask id 对齐比较
  办理人(candidateUsers,走 codec 比 items)/指派(assignee)/表单(formKey)/会签(有无·
  collection·completionCondition)四类,含新增/删除节点;坏 XML 返 []。
- processModeler.ts:deployModel(id)/fetchImpact(id),422 校验清单与通用失败归一进
  DeployOutcome(errors 兼容 flowable 对象式与网关字符串式两形态),impact 防御性 found。
- PublishConfirm.tsx:Dialog 展示流程 key/当前版本→新版本/运行中实例数(旧版本不受影响)
  + 变更节点清单;确认→deployModel 成功 toast「已发布 vN」并关闭,422→节点错误清单不关窗。
- ProcessModelerPage:顶栏发布按钮启用+gating(无 modelId 提示先存草稿),打开时存源 XML
  作 diff 基线。

diffSummary 13 + PublishConfirm 9 + 页面 21;全量 223 单测绿,tsc -b + build 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 14:10:46 +08:00
ac5ab12574 Merge feat/process-modeler 阶段2: 表达式codec+EIP4侧板+存草稿闭环
Some checks failed
ci / build-test (push) Has been cancelled
- 办理人/会签表达式 codec(与 BasePropertiesConverter 逐字对齐+stringToJson引号映射防截断JUEL;
  全库4794真实表达式往返实证零破坏)
- EIP4 侧板五控件(办理人meta透传/会签保真读回isSequential+elementVariable+自定义完成条件/
  formKey过滤/扩展属性/监听器field保留;切换节点无串台)
- 存草稿闭环(三路径保eip4IdMap+首存回填modelId防刷新重复+草稿列表/删除/formKey过滤输入)
- 全量 vitest 198+tsc+build 绿;live 验收总包合同交底存草稿→重开侧板忠实回显

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 13:18:10 +08:00
eba1704a55 fix(modeler): 首存回填modelId(防刷新重复草稿)+DELETE注释订正+placeholder保值测试
I-2:handleSaveDraft 在 createDraft/draftFromProcDef 成功后 setParams({modelId},{replace:true})
回填 ?modelId=,令刷新幂等(不再对同一 procKey 重复建草稿)、二次保存恒走 PUT。
测试:首存后按 modelId 重载(getModel('NEW-1'))证明回填生效;二次保存走 PUT NEW-1。

Minor:
- createDraft 的 metaInfo 补 sourceProcDefId 键,结构与 from-procdef 对齐(restore 只读
  eip4IdMap,但一致性利于 T3.x 影响摘要/审计)。
- deleteDraft 注释订正:后端 DELETE 已实现(impl-t21 f0d704d 网关同门转发),非「待补」。
- formKey placeholder 保值直测:过滤掉当前值后 select 仍保留该值(占位「(当前)」)。

测试 ProcessModelerPage 17→18、Eip4Panel 36→37;全量 vitest 198 绿 / tsc -b 干净 /
npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 12:46:55 +08:00
5c2c0d95f6 feat(modeler): 存草稿闭环+草稿列表打开+formKey过滤输入
api/processModeler:新增 listModels/getModel/createDraft/saveDraft(PUT)/draftFromProcDef/
deleteDraft;fetchWfTemplates 改返 {templates,degraded} 透传数据源降级标记。

ProcessModelerPage:
- 顶栏「保存草稿」可用:saveXML({format:true})→有 modelId 走 PUT saveDraft(不重发 metaInfo,
  靠后端「不带 metaInfo 不覆盖」保住 eip4IdMap);无 modelId:存量按 procDefId 走 from-procdef
  (后端写 metaInfo)再 PUT 覆盖为编辑源,存量按 key/新建走 createDraft(前端把 source 载入的
  eip4IdMap 写进 metaInfo)。saving 态防重入。
- 打开器加「草稿」tab:listModels 列草稿→「打开」setParams(?modelId=)→getModel→importXML;
  载入草稿时从 metaInfo 解 eip4IdMap 存 ref(发布还原用)。
- 草稿删除按钮+confirm(deleteDraft;后端 DELETE 端点待补,前端契约先落)。

Eip4Panel formKey:1016 项加过滤输入(名称/id 实时 filter);未命名项(name 回落为 id)显示
「<uuid前8>…(未命名)」;degraded 显示「模板列表暂不可用」提示。

测试:Eip4Panel 33→36(formKey 过滤/未命名/degraded)、ProcessModelerPage 10→17
(存草稿 create/put/from-procdef 三路径 + ?modelId= 载入 + 草稿 tab 打开 + 删除确认/取消);
全量 vitest 196 绿 / tsc -b 干净 / npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 12:14:37 +08:00
a9a304ab3d fix(modeler): 侧板评审收口——会签保真读回/切换节点回归测试/meta可见性+清除确认
I-1 会签保真:isSequential/elementVariable/completionCondition 原值读进 CosignState、
写回用读到的值(真实库 isSequential=true×2 / elementVariable=assign|loop_assign / 完成条件
>0.6×7 原强写会静默改坏派任);完成条件 body 不匹配预设→「自定义(保留)」态,仅主动选预设才
改写;elementVariable 缺省态与原本无 completionCondition 写回时省略,不凭空写空。parseCompletion
改精确匹配预设串(修 >0.55 误判过半的子串 bug)。新增串行开关+循环变量输入。

I-2 双节点回归:A(meta X)→B(meta Y)→编辑 B→写回 meta===Y≠X,防串台。

I-3 meta 可见性:顶部只读徽标显示非空业务 meta(如任务后置服务 PM_XXX);删光 items 且含非空
业务 meta 时 window.confirm 确认才写 undefined(取消则本地态与引擎均不变)。

顺手:扩展属性强制 activiti:/flowable: 前缀 + 拉黑有专用控件的键(candidateUsers/formKey/
collection/elementVariable);非标准办理人表达式(parse→null)显示「编辑将覆盖」警示;订阅
commandStack.changed,非自身写入时对当前选中重灌本地态(undo/redo 脱同步防线)。

测试 Eip4Panel 21→33;全量 vitest 186 绿 / tsc -b 干净 / npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 12:01:26 +08:00
6fceff784d test(modeler): 侧板办理人补撇号转义用例(消费 codec 引号转义,防截断 JUEL)
新增 1 例:content 含撇号 O'Brien → 写回载荷内容段(剥离 JUEL 前后缀定界引号)
无裸 ASCII 单引号、含全角‘,验证侧板经 codec build 受引号转义保护。
Eip4Panel 测试 20→21;仅提交本测试文件,codec 由并行 T2.3 收口。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:38:08 +08:00
11632b4801 fix(modeler): codec 评审收口——stringToJson引号映射+半角content变体+item未知键透传+形状守卫
评审者跑全库 4794 条真实表达式往返对照原版序列化器,四项收口:
- I-1 build 补 stringToJson 引号契约(BasePropertiesConverter.java:235-280):字符串叶子值
  '→‘、"→“(经 JSON.stringify replacer,{}→【】由 halfToFull、\\与控制字符由 stringify 覆盖)。
  否则用户输入含 ' 截断外层 JUEL 单引号字面量 / 含 " 截断内层 JSON,部署后表达式解析即断。
  语料 ‘/“ 均 0 命中→对存量为 no-op,不破逐字往返。
- I-2 头注释纠偏:「content 不含花括号」被 20 条真实 ${users}(半角)证伪;改为事实——
  4774/4794 逐字,20 条半角 content 变体 build 归一为全角,引擎 :54 全局【→{ 还原后运行期等价。
- M-1 item 未知键 known-first 重排+按原序透传(与 meta 全量保留对称,不静默丢未来扩展键)。
- M-2 items 元素形状守卫:元素非对象或 type 非字符串→整体返 null 不抛。

加分:tools/codec-corpus-sweep.mjs(照 modeler-fidelity-sweep 风格,内联镜像 codec 跑全语料):
1512 文档 / 4794 表达式 → 逐字 4774 + 引擎运行期等价 20 + 解析失败 0 + 硬不匹配 0(门禁绿)。

测试 29 例(原 20 + 引号映射/幂等/meta 引号/半角变体运行期等价/未知键透传/形状守卫 9 例);
modeler 全量 66 例绿;tsc -b 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:36:53 +08:00
6dc9075648 feat(modeler): EIP4 侧板五控件(办理人meta透传/会签/formKey/扩展属性/监听器)
选中 userTask 时在标准属性面板上方叠加 React 侧板(§0.5 P5),全部写操作经
modeling.updateProperties(element,{...}),undo/redo 天然生效:
- 办理人:activiti:candidateUsers 经 codec parse→items 表格→build 写回,
  🔴 codec 外层业务 meta(taskSuccessService 等)存 ref、写回原样带回(硬要求用例覆盖)
- 会签:loopCharacteristics 开关(moddle.create MultiInstanceLoopCharacteristics,
  activiti:collection multiInstance 变体+elementVariable=assignee+completionCondition
  全票/过半/指定数 N 三预设);关→undefined
- formKey:GET /api/workflow/wftemplates 下拉写 activiti:formKey(裸 UUID),「无」清除
- 扩展属性:长尾 $attrs(activiti:/flowable:)增删改
- 任务监听器:activiti:taskListener event+class/delegateExpression 互斥;已有 field
  子元素显示徽标并原样保留(moddle 元素引用不动)

新增 useSelectedElement hook(订阅 selection.changed,单选返 element/多选空选 null/卸载解绑)。
ProcessModelerPage 右栏上方挂 Eip4Panel(modeler 入 state 驱动订阅)。
📌 红线回归:ProcessModelerPage 断言 moddleExtensions 键恰 ['activiti']、
additionalModules 长度 2(防双包冲突静默丢 userTask)。

测试:Eip4Panel 20 + useSelectedElement 5 + ProcessModelerPage 10(+1 红线);
全量 vitest 164 绿 / tsc -b 干净 / npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:35:13 +08:00
3dfb90f59b feat(modeler): 办理人/会签表达式编解码器(与 BasePropertiesConverter 逐字对齐)
纯前端纯函数 codec,parse/build 处理 businessObject 属性值层的办理人表达式。
前后缀常量逐字对齐 BasePropertiesConverter:34-35(candidate/multiInstance 两变体);
内容段全角【】↔{} 双向映射(build 恒全角,parse 兼容半角);外层 meta
(messageTemplate/taskSuccessService/isSkip* 等运行期业务字段)原样保留,侧板只改
items 也逐字往返不丢。content 逗号多值与 CHAR 尾部补白空格原样保留。

TDD:先红后绿。测试运行时从 synthetic-full-surface fixture 抽真实表达式锚定逐字形态。
20 例(真实 candidate/multiInstance 往返逐字 / 尾部空格保留 / 各 type 不丢字段 /
isSendMessage 可选往返 / 半角输入兼容 build 恒全角 / 非法输入返 null 不抛)全绿;
modeler 全量 32 例绿;tsc -b 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:16:51 +08:00
d08a35fbbb Merge feat/process-modeler 阶段1: Modeler 前端骨架(moddle保真+/process-modeler页)
Some checks failed
ci / build-test (push) Has been cancelled
- vendored activiti/flowable moddle 描述符+语料双门测试(1512/1512 零丢失扫描工具,加固版回归门)
- /process-modeler 页:bpmn-js Modeler+标准属性面板(显式attachTo)+admin门+存量打开器(by-id/by-key双参)
- 设计中心「流程设计」入口;红线守住(只载activiti/无Camunda provider)
- 全量 vitest 118 例+tsc+build 绿;live 验收「总包合同交底」画布/palette/Multi-instance面板全渲染

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:08:27 +08:00
dffd1f32ef fix(modeler): 属性面板显式 attachTo 修挂载时序(live 实证)+canvas 分支错误提示
live 复验:画布/palette/选中/context pad 正常,但标准属性面板从不挂载
(document 中 .bio-properties-panel 为 0,容器 children=0)。

根因(本次修时 attachTo 测试逼出):属性面板宿主 <div data-testid=process-modeler-props>
**从未挂 ref={panelRef}** → 构造参数 propertiesPanel.parent 恒为 null,面板无处渲染。
- 补 ref={panelRef} 到 props 容器 div(真根因)。
- 构造后显式 (modeler.get('propertiesPanel')).attachTo(panelRef.current)——
  bpmn-js-properties-panel 规范补救,放 importXML 前、alive 检查内、panelRef 存在时。
- 顺带修 T1.5 评审 M-2:canvasRef 为 null 分支改为 setError(原停 loading 无提示)。

测试:ProcessModelerPage.test.tsx +1(Modeler stub get('propertiesPanel')→{attachTo},
断言 attachTo 恰调一次且实参是 props 容器 DOM)。stub get 改按 service 分派
(propertiesPanel/canvas)。全量 vitest 22 文件 118 例绿;tsc -b 干净;npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:05:23 +08:00
ae097f2a9c fix(modeler): 打开器改 by-key 载入(修 options source=model 语义缺口)
live 验收发现:本库 /api/process-select/options 的 143 个选项 source 全为 'model',
option.id 是 act_re_model id(非 procDefId)→ 按 id 载入永远 found:false;option.key 才是流程 key。

- processModeler.ts:加 fetchProcDefSourceByKey(key) → GET
  /api/workflow/process-definitions/by-key/{key}/source(key 常纯中文,encodeURIComponent;
  返回形状同 fetchProcDefSource,共用 normalizeProcDefSource:found:false 不解构 bpmnXml/idMap)。
  ProcessOption 加 source 字段。
- ProcessModelerPage:打开器双参分派——source==='processDefinition' 用 ?procDefId=<id>,
  其余(model/history)用 ?procKey=<key>;loadEffect 按参数派 by-id / by-key;
  过滤规则 !!o.id 改为 source==='processDefinition' ? !!o.id : !!o.key;
  选择器用索引取回选项对象避免路由二义。

测试:processModeler.test.ts +2(纯中文 key 编码 / by-key found:false)+ source 映射断言;
ProcessModelerPage.test.tsx +3(?procKey= 走 by-key 并 importXML / 选 model 选项派 by-key /
选 processDefinition 选项派 by-id)。全量 vitest 22 文件 117 例绿;tsc -b 干净;npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:59:24 +08:00
e131b8dee9 feat(modeler): /process-modeler 页骨架(Modeler+标准属性面板+存量载入+设计中心入口)
阶段1 T1.5:admin 门 + 三栏布局(左画布/右上 EIP4 侧板占位/右下标准属性面板)
+ bpmn-js lib/Modeler 挂载(只载 activiti moddle、只引标准 BpmnPropertiesProvider,
严禁 Camunda provider)+ ?procDefId= 时 fetchProcDefSource→importXML(idMap 存 ref)
+ 无参时 process-select 存量流程选择器 + 设计中心「流程设计」入口。

api: processModeler.ts(fetchProcDefSource / fetchProcessOptions,裸 JSON 防御性默认)。
- procDefId 用 encodeURIComponent 进 path(真实库 id 形如「总包合同交底:3:<uuid>」中文+冒号)。
- found:false 先判后返,不解构 bpmnXml/idMap(后端此分支省略这些键)。
tsconfig.app.json 开 resolveJsonModule(首个 app 代码 import json)。
bpmn-js-properties-panel 补 ambient d.ts(包未发布类型)。

测试:ProcessModelerPage.test.tsx 5 例 + processModeler.test.ts 6 例(含中文+冒号
procDefId 断言 URL 已编码 / found:false 只返 found 键 / amis 信封解包);
DesignCenterPage.entrances 加 dc-process-modeler admin-only 断言。
全量 vitest 22 文件 112 例绿;tsc -b 干净;npm run build 成功(bpmn-js 进主 bundle)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:37:36 +08:00
b391ee9f16 fix(modeler): 保真扫描回归加固——refs袋+unresolved入门+规模门+stderr(评审I1/M1/M2/M5)
- I1 引用回归盲区:surface() 新增 refs 袋(sourceRef/targetRef/bpmnElement/
  processRef/attachedToRef/default,与 sanitizeIds 同覆盖面)并入比对键;normWarn
  的 unresolved reference 类 warning 计入硬门 failures(净化/往返破坏连线的直接信号)。
- M1:删除未使用的 realFail。
- M2:新增 EXPECTED_TOTAL 环境变量(默认 1512),实际语料数不符即判失败;
  decodeFailures.length 并入硬门(过滤集内本应 100% 干净 UTF8)。
- M5:崩溃分支透出子进程 e.stderr。
- M3/M4:命名空间字面前缀识别的语料前提、extElemText trim 口径各加注释声明。

重跑实测(node tools/modeler-fidelity-sweep.mjs):匹配 1512/1512 零丢失,
解析异常 0,解码失败 0,warnings=0,exit 0;EXPECTED_TOTAL=9999 时 exit 1
(规模门生效)。npx vitest run src/modeler 12/12 绿;npx tsc -b 干净(exit 0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:15:49 +08:00
bd7c7fc697 fix(modeler): 描述符补 formProperty.value(sweep 0-warning 收口)
activiti.json formProperty 补 value isAttr(对齐 D6 完整描述符)。此前 4 例
unknown attribute <value> warning(均 Activiti 自带 demo 流程的 formProperty
value= 属性,如 VacationRequest)靠 lax $attrs 保留、本无数据丢失,补声明后消除。

重跑实测(node tools/modeler-fidelity-sweep.mjs,5433/eip4/eip3):
- 匹配 1512/1512 零丢失,解析异常 0,解码失败 0,warnings=0。
- 命名空间 activiti 1509 / flowable 3。
- npx vitest run src/modeler 12/12 绿;npx tsc -b 干净(exit 0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:02:09 +08:00
6eb856bb75 feat(modeler): 全量真实流程 moddle round-trip 保真扫描工具(实测 1512/1512 零丢失)
对本地 eip4 库(5433,search_path=eip3) act_ge_bytearray 全部真实 BPMN
(name_ like %.bpmn%/%.xml,共 1512)逐条 bpmn-moddle fromXML→toXML,
数据级(实体解码归一后)校验「activiti/flowable 扩展属性+扩展元素结构
+全部 bpmn 元素 id 集合」多重集往返一致。

- psql 子进程取数(不引 pg 依赖);命名空间嗅探后单载 activiti 或 flowable
  (T1.1 实证双载丢 userTask);进 moddle 前净化非法 id(镜像后端
  sanitizeBpmnIds,1445/1512 文档 process id 为中文,moddle 拒非 ASCII-NCName)。
- 实测: 匹配 1512/1512 零丢失(activiti 1509 / flowable 3);解析异常 0;
  解码失败 0。warnings 仅 4 例 unknown attribute <value>(formProperty
  value= 属性未声明,均 Activiti 自带 demo 流程,lax $attrs 保留,零丢失)。
- 解码守卫: 校验 base64→UTF8 无损,单列非 UTF8 文档。全表探明解码失败仅
  出现在非 BPMN 二进制资源(.png 1504 / var-* 87524),被 name 过滤器正确排除;
  真实 BPMN 语料 0 解码失败。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:59:54 +08:00
a2aeeba296 fix(modeler): T1.1 评审收口——bpmn-moddle 显式devDep+$attrs断言+类型声明
评审 I-1 / M-1 / TS7016 收口(承接 8fdfe68):
- I-1 幻影依赖:devDependencies 显式声明 bpmn-moddle ^8.1.0(npm dedupe 到与
  bpmn-js 同一份 8.1.0),保真测试不再依赖传递提升、与 Modeler 运行时同版本。
- M-1 断言意图纠偏:fidelity.test.ts 原注释「未声明时 .get() 返 undefined」实证有误——
  moddle .get() 对未声明属性会回落 $attrs 返原值(已实证:flowable:assignee 未声明时
  .get() 返 "X")。改注释 + 增 `expect($attrs?.['activiti:candidateUsers']).toBeUndefined()`
  直接断言值未落 lax $attrs(=真 typed 化,声明属性确不在 $attrs)。
- TS7016:新增 src/modeler/moddle/bpmn-moddle.d.ts(最小 ambient 声明)消编辑器诊断。

验证:npx vitest run src/modeler 12/12 绿;npx tsc -b 干净(exit 0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:47:02 +08:00
8fdfe688f8 feat(modeler): activiti/flowable moddle 描述符 + 语料覆盖/round-trip 保真测试
在线流程 Modeler 阶段1 Task 1.1(P1 双门验收)。为 bpmn-js Modeler 载入
存量 activiti BPMN 提供 vendored moddle 描述符,并以合成 fixture 验证零丢失。

依赖(与 bpmn-js 17.11.1 兼容,实际解析版本):
- bpmn-js-properties-panel 5.60.0(package.json ^5.23.0)
- @bpmn-io/properties-panel 3.47.0(package.json ^3.23.0)
- bpmn-moddle 8.1.0(bpmn-js 传递依赖,直接 import)

交付:
- src/modeler/moddle/activiti.json:完整 activiti 命名空间描述符,覆盖 §0 实测
  全集——属性 formKey/candidateUsers/exclusive/assignee/collection/elementVariable/
  candidateGroups/autoStoreVariables/initiator/dueDate(按宿主 extends 到 UserTask/
  StartEvent/Process/ScriptTask/MultiInstanceLoopCharacteristics 等)+ 元素
  taskListener/formProperty/field/string/value/executionListener/in/out。
- src/modeler/moddle/flowable.json:flowable 命名空间镜像描述符(覆盖 flowable:assignee 等)。
- src/modeler/moddle/fixtures/synthetic-full-surface.bpmn.ts:合成 fixture,形态逐字
  对照真实流程「总包合同交底」——含全角【】办理人 JSON、多实例、taskListener+field/
  string、formProperty+value、boundaryEvent+timer、conditionExpression、完整 DI。
- src/modeler/moddle/fidelity.test.ts:12 用例(语料覆盖 + round-trip 零丢失)。

fixture 关键形态发现(实证):
- 办理人/会签 JSON 用**全角【】**包裹对象,方括号 [] 半角,引号在属性内以 &quot; 转义;
  content 尾部有 CHAR 补白空格(如 "4028...0f7d    ")——均需零丢失。
- candidateUsers 表达式解析后 byte-exact 等于原文;moddle 序列化把 '/" 输出为
  数字实体 &#39;/&#34;,全角【】原样保留(XML 语义等价、模型层零丢失)。

勘探实证并固化为回归测试的两条 moddle 约束:
- moddle-xml 拒绝中文 id(illegal ID,须 NCName ASCII)→ 这正是 D7 BpmnIdSanitizer
  在进 moddle 前净化、发布时还原的根本原因;fixture 用 ASCII id、中文仅留在 name。
- activiti+flowable 双包同载会因跨包同名 extends 属性(如 exclusive)冲突而丢弃 userTask
  → 按命名空间隔离加载;已验证 Modeler 单载 activiti 时 flowable 属性经 lax $attrs 零丢失
  往返(Task 1.5 Modeler 应单载 activiti)。

验证:npx vitest run src/modeler 12/12 绿;全量 101/101 绿;tsc -b 干净;npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:35:23 +08:00
a807078595 Merge docs/readme-dev-fix-0702: README 联调指引修正
Some checks failed
ci / build-test (push) Has been cancelled
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 08:15:33 +08:00
7d4f26edd3 docs(readme): 修正过时联调指引(JDK17→21/8084→8093/账号/自举→build_devdb)
- 后端联调改走 scripts/run-dev.sh(dev :8093,JDK 21 守卫),删 JDK17 毒指引(项目必须 21,17 连编译都过不了)
- 账号分口径:dev 库 admin/111111(日常)/ local 自举 alice/123456(CI/对拍)
- .env 表 VITE_BACKEND_TARGET 默认对齐实际 8093
- 本地库指引:日常 eip4dev 用 build_devdb.sh,自举集仅 CI/对拍
- 页面 schema 契约行删「开发期静态 mock」过时表述;设计器行改「已闭环」

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 08:15:33 +08:00
d406a1629b Merge: 报表导出文件名/扩展名修复(受控 blob 下载)
Some checks failed
ci / build-test (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 14:01:16 +08:00
d80ea76974 fix(report): 导出 PDF/Excel 用受控下载,文件名/扩展名正确
导出按钮(actionType:url)默认 window.open 一个 attachment 响应,部分浏览器丢失 Content-Disposition 文件名 → 下载成 UUID、无扩展名、打不开。新增 reportDownload:自定义 amis env.jumpTo 拦截报表导出 URL,显式 fetch 成 blob 并用 <a download="<CD文件名>"> 落盘。filenameFromContentDisposition 优先取 filename*(UTF-8 真实报表名)而非前面的 UUID 兜底。前端改动,无需重转重导,覆盖全部报表导出。6 单测 + 浏览器实测 办公用品采购申请单.pdf/.xls。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 14:01:16 +08:00
8301db1f88 Merge feat/approval-closure: 审批抽屉协办/转阅多选人 + BPMN流程图(bpmn-js) + 会签进度横幅
Some checks failed
ci / build-test (push) Has been cancelled
2026-06-26 08:29:47 +08:00
9b2bb2c0c3 feat(approval): 审批抽屉显示会签进度「已会签 N/M 人」
ApprovalMeta 加 cosign/cosignTotal/cosignCompleted;ApprovalDrawer 顶部当 cosign 时
显示会签进度横幅。tsc 干净。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 08:19:09 +08:00
4f06268755 feat(approval): 审批抽屉接协办/转阅多选人 + BPMN 流程图查看
- approval.ts ApprovalActionRequest 加 targetUserIds(协办/转阅多人)
- ApprovalDrawer 新增 MultiUserForm 多选人弹窗(协办 assist / 转阅 circulated)
- 新增 ProcessDiagram(bpmn-js NavigatedViewer:中文走浏览器字体,当前节点绿/已走过灰)
  + diagram.ts API;ApprovalDrawer 加「查看流程图」按需展开段
- 依赖 bpmn-js@^17

配套后端 eip4-platform feat/approval-closure(协办/转阅端点 + 流程图端点 + scriptUser 会签)。
tsc 干净 + vitest 83/83 + build 5104 模块。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 08:09:31 +08:00
68d797e1c4 Merge feat/scriptcommands-honest-noop: scriptCommands 哑火动词显式跳过(§10.2)
Some checks failed
ci / build-test (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 13:38:28 +08:00
03533eaf5e fix(amis): scriptCommands 哑火动词改显式跳过+告警(§10.2 有界安全修)
amis setValue 动作(CmptAction)只读 args.value、丢弃 required/filter/options/label/style 等语义 args→6 个动词(setLabel/setRequired/setFilter/setOptions/setNullSelection/setStyle)运行时静默哑火,且 args.value=undefined 经 onChange 路径可能清值。amis 全量 registerAction 核实无这些动词的内置 action。改为显式跳过(返回 null,translateCommands 自动过滤)+ 一次性 console.warn,消除清值风险、不再伪装已处理。真正支持需转换器侧数据绑定(requiredOn/source 绑数据变量)属 L 跨切面,留 §10.2 follow-up。scriptCommands.test 22(含 6 动词跳过/整体过滤/告警去重),registerReplay 7,full vitest 83/83+tsc -b 干净。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 13:38:28 +08:00
2a37251f6f Merge feat/p0-security-hardening: 新增 eip4-web Gitea Actions CI
Some checks failed
ci / build-test (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 11:50:56 +08:00
63d46af7b7 ci(P0④): 新增 eip4-web Gitea Actions CI(类型检查+构建+vitest)
前端此前无 CI。补 .gitea/workflows/ci.yml 跑 npm ci + npm run build(tsc -b && vite build)+ npm test,防前端回归(2026-06-24 架构评审 §10 验证体系)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 11:50:56 +08:00
67731663c1 Merge feat/arch-review-followup: isAdmin 收口 isAdminProfile(B4) + 删 api/schema.ts overlay 死代码(B2) 2026-06-24 11:31:59 +08:00
90888f7e06 chore(web): 删 api/schema.ts overlay 死代码(B2)
fetchSchemaLayer/putOverlay/restoreStandard 全仓(含 e2e)零引用,真实 overlay API 在 editor/overlayApi.ts;删重复死份。tsc 干净 + vitest 77/77。见总览 §10 B2。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:22:47 +08:00
768ffa8551 refactor(web): isAdmin 收口到 isAdminProfile(B4)
5 处逐字硬编码 profile?.account==='admin'||userId==='ADMIN'(Topbar/ModelerPage/NewFeatureShell/AiFeatureForm/DesignCenterPage)收口到 auth/token.ts 纯函数 isAdminProfile,口径不变。
顺带:5 个页面测试的 vi.mock('../auth/token') 从整模块替换改为 importOriginal 只覆盖 getProfile(不再 mock 纯函数,修复 mock 漏 isAdminProfile 致的 render 崩)。
验证:新增 token.test.ts 4 测试 + tsc -b 干净 + vitest 18 文件/77 测试全绿。见总览 §10 B4。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:20:16 +08:00
2fb09f7a7a Merge branch 'feat/p0p1-impl' into main
P1④改表加列UI + P1⑤审批列表入口e2e

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 15:31:53 +08:00
5b117df4d1 feat(P1④/P1⑤): 改表加列UI + 审批列表入口e2e
- P1④ 改表加列: meta.ts alterEntity(POST /api/meta/entity/{table}/attributes)
  + ModelerPage 行内「加字段」Dialog(复用FieldTable),打破"v1只建新不改表"
  + five-ring.spec.ts 新增"改已有表加列(建模器加字段→元数据落库)"浏览器e2e
- P1⑤ 审批列表入口: 新增 approval-list-entry.spec.ts(纯mock)验生产主路径
  转换列表页按钮→选中行(checkOnItemClick)→openApprovalDrawer→AppShell→ApprovalDrawer抽屉打开
- build绿+vitest73;fivering 5/5 + 审批入口 1/1 全绿

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 13:56:27 +08:00
d1fd6ed956 Merge branch 'feat/human-five-ring' into main
人走五环建新功能向导 + 主子表 v1(基础/派生/汇总/引用驱动联动)前端 + 真事件 e2e。
73 vitest + npm run build + Playwright(fivering 4/4 + 隔离 probe 3/3)全绿。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 22:35:09 +08:00
b578d8d41b feat(主子表): 引用驱动联动 向导映射 UI + 真事件 e2e
- NewFeatureShell: 主子表步③加「引用联动」combo(引用列 → 目标子列 ← 源实体列),
  childLinkage 透传 compile;构建时分支(不依赖 amis 运行时 step 跳步),页面 data seed []
- e2e/master-detail: 引用驱动联动用例——真后端 schema(GET /api/page/schema) + 真 picker
  数据 + 真 Playwright 事件填充 + 提交落库验证(选物料→带出单价/规格,用户未手填仍随
  _ADD 级联落库;引用 FK 本身也落库)
- e2e/linkage-probe: amis input-table 行内联动机制隔离验证(钉死 selectedItems 是对象非
  数组;远程 source 选项携整行列;多行 ${index} 按行隔离防串台)
- NewFeatureShell.test: 修过时断言(c735f24 类型选择卡后需先选类型才出 amis 挂载点)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 22:28:45 +08:00
c735f24c64 refactor(设计中心): 合并「新建功能/新建主子表」为单一入口 + 页面类型选择
设计中心两个「新建」按钮(新建功能 / 新建主子表)合为一个「+ 新建功能」入口:
进去先选页面类型(维护型 CRUD / 树形 / 主子表),再走对应向导。扩展新页型只加一个
选项,不再加顶级按钮;recipe 类型从内部实现差异回归为向导内的一个选择。

- NewFeatureShell 重写:RecipeChooser 类型选择卡 → 按类型【构建时(JS)】分支向导步骤
  (主子表才有「建子表」步及派生/汇总字段)。不依赖 amis 运行时 step hiddenOn——
  amis Wizard.normalizeSteps 只在 props.data 变时重算,向导内选择改 store.data 不触发,
  故 step 级动态跳步不可靠;类型进向导前定、构建时分支才健壮。
- 删 MasterDetailShell.tsx + /new-feature-md 路由 + 设计中心「新建主子表」按钮
  → 设计中心回到「新建功能 + AI 建功能」两入口
- e2e:five-ring/master-detail 改为先点类型选择卡(dc-recipe-*)再进向导;3/3 绿,build 绿

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 18:54:16 +08:00
4a107f3969 feat(主子表): 父级汇总定义 UI + e2e 扩展
- MasterDetailShell step③ 汇总字段 combo(主表列+子表列+函数 SUM/COUNT/AVG/MIN/MAX);
  page data seed childRollup:[] 防未触碰时占位串致 compile 400
- e2e 派生用例扩展为「派生+汇总」:向导加 TOTAL 主列+汇总字段,断言发布页 __rollup +
  主表 TOTAL static SUM(ARRAYMAP) 预览,_ADD 后 _LOAD 主表 TOTAL=55(服务端先派生再聚合)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 17:55:59 +08:00
df0ac72225 feat(主子表): 派生字段定义 UI + e2e
- MasterDetailShell step③ 派生字段 combo(目标列 + 公式),page data seed
  childDerived:[] 防 combo 未触碰时发出未解析占位串致 compile 反序列化 400
- e2e: 新增「派生字段全流程」用例(向导加派生 → 发布页含 tpl 预览+__derive →
  _ADD 服务端逐行落库 AMOUNT,经 _LOAD 回读验证;断言 quickEdit:false);
  原主子表用例补 _LOAD 级联实证(_SEARCH 列表不嵌充子数组,_LOAD 才填充)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 17:32:26 +08:00
934c6464db feat(master-detail): 主子表向导(amis wizard)+ 设计中心入口 + e2e
新建主子表功能:设计中心「+ 新建主子表」→ MasterDetailShell amis wizard 四步
(建主实体→建子表(传masterTable自动加FK)→生成主子页(compile master-detail-v1,
后端ensureLink+编译出 input-table 子表页)→发布)。子行经主表_ADD流随主记录级联落库。
用 api.responseData 把主实体id/表名 remap 避免被子实体响应覆盖。
Playwright e2e 全程点穿:建主+子→生成→发布→级联_ADD(status0)。1 passed。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 15:37:22 +08:00
2b261e319f feat(modeler): 建实体向导加「所属分类」选择器(source /api/meta/entity-types)
wizard 步①新增 amis select「所属分类」(必填,221 分类可搜),提交时随 attributes 一并 POST。
e2e 补选分类交互。修用户反馈的「实体所属分类缺失」。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 14:45:44 +08:00
71535929f7 refactor(design-center): 编排壳/AI入口改用 amis 渲染(替手搓原生表单)
用户反馈手搓 input/select/嵌套弹窗又丑又不一致。改:
- NewFeatureShell → amis wizard(建实体 combo字段含引用列 → 选recipe → 发布),三步 api 直打后端、数据自动透传
- AiFeatureForm → amis form(api adaptor 包裹非标响应 + ARRAYFILTER 取草稿 targetId)
- 组件测试改为守 admin/容器(amis 内部交 Playwright);five-ring.spec 改驱动 amis wizard
与全站业务页同一套 AmisRenderer,外观一致。wizard e2e 1 passed / 72 vitest / build 绿。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 14:39:00 +08:00
a6482b112e test(e2e): 人走五环浏览器全程点穿 Playwright spec(Task 24 UI 补全)
真实浏览器走完整链路:登录→设计中心+新建功能→建模器(标量+引用列OWNER→SYS_USER)
→选recipe→compile→发布→后端/api/menu断言新节点。专用配置反代8094(不碰dev 8093)。
本次实跑:1 passed。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 13:55:01 +08:00
a6bd4b0432 feat(routes): 接线 /new-feature 与 /ai-feature(admin-gated 页内守护)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:56:52 +08:00
4e0e974473 feat(ai-feature): AI ①面入口页 + api/ai.ts(auto-develop,恒 READY_FOR_HUMAN_REVIEW 人审)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:55:53 +08:00
8f94ba3c3d feat(new-feature): 人走五环编排壳页 NewFeatureShell(建模→recipe→compile→设计器→发布)
复用 ModelerFields(FieldTable)/ReferencePicker 在实体步内置 [+ 新建实体] Dialog(§B.9-4),
建含引用列的新实体在编排流里可达,建成用返回 {entityId,tablename} 回填进 recipe 步。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:54:26 +08:00
bfb076f803 feat(design-center): admin 入口按钮 +新建功能 / ⚡AI建功能
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:51:26 +08:00
4e7a95cc20 feat(modeler): reference-column picker (target entity + display column) per DECISION-1
引用列加载改用内部 selected 态(父级 onChange 不一定回写 value,列加载不能只依赖 value)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:39:39 +08:00
fef5e33a7a feat(modeler): field table + add-field dialog + ui-type to api-type mapping (buildAttribute)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:38:14 +08:00
915443f585 feat(modeler): ModelerPage shell + /modeler route + entity list + new-entity dialog
canSubmit 去掉 rows.length>0 约束以满足 Task 15 测试(有效表名即可提交);字段表 Task 16 补。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:37:15 +08:00
4b9c9338f3 feat(modeler): meta/recipe/publish api modules + vitest jest-dom setup
listRecipes 按 §B.9-2 改为静态常量({id,label},不调 /api/ai/page-recipes)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:35:43 +08:00
ae0155eb2c fix(web): editor.html CSS 改 import 进 bundle,修生产构建 404
editor.html 三条 /node_modules/*.css 绝对 link 在 vite build 后不入 dist,
preview/静态托管下 404 → 设计器裸样式。改由 src/editor/main.tsx import,
rollup 收集进 dist/assets/*.css。dev 不受影响(vite 转译同源)。
注:amis-ui/amis-editor-core 的 exports 字段不暴露 css 子路径,裸包名 import 被 rollup 拒绝,
故用相对 node_modules 路径直引真实 css 文件。
REQUIRED-before-any-hosted-demo, OPTIONAL-for-pure-dev。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:33:34 +08:00
690f4c755e fix(web): dev 反代默认目标 8084→8093,fresh checkout 开箱即通
.env.local(8093) 被 gitignore 排除,新克隆退回 .env/vite.config 的 8084(local profile)死口。
统一提交进库的默认值为 8093(dev profile),无需手建 .env.local 即可联调。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:31:18 +08:00
37298186eb chore(build): add preview proxy for local production-build verification
验证「设计器生产构建是否裂」时需要本地托管 dist 并能访问后端。`vite preview`
默认不带 /api 反代,补 preview.proxy(与 server.proxy 同口径,走 .env.local 的
VITE_BACKEND_TARGET)→ 可本地跑 `npm run preview` 验证 prod 构建。

结论(实测):生产构建本就安全——editor.html 源里 3 个 /node_modules CSS 直链在
vite build 时被解析+打包进 dist/assets/editor-*.css(2.3MB,含完整 amis-editor/
amis-ui 样式,1742×.ae- / 12155×.cxd-),dist/editor.html 零 /node_modules 残留;
preview 托管 dist 实测编辑器三栏完整带样式渲染(panelCount 123)、高度约束修复
生效(aeEditor 831px/clippedLayers 0)、schema 经 proxy 加载。memory「生产可能裂」
顾虑证伪。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:54:46 +08:00
f39661a5dd fix(shell): open 设计中心 as its own tab instead of covering current
顶栏「设计中心」画笔按钮 navigate('/design-center'),但 AppShell 地址同步
useEffect 只为 /page/:id 路由自动建 Tab → /design-center 既不在 tabs、又非
/page/ 开头,两个分支都不命中:不建 Tab、activeKey 不变 → Outlet 渲染设计中心
内容但 Tab 条仍高亮旧页,设计中心「盖」在当前选中 Tab 上(用户反馈)。

修:新增 SINGLETON_TAB_TITLES 映射(/design-center→设计中心),地址同步 useEffect
对这类单例功能路由也自动建并激活独立 Tab(任意入口生效:顶栏/直接URL/前进后退;
prev.some 去重)。实测:从工作台点画笔 → Tab 条新增「设计中心」并激活,原
新闻收藏 Tab 保留不被覆盖,localStorage tabs/activeKey 同步。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:34:23 +08:00
3abeefebac fix(designer): constrain amis-editor height so canvas scrolls (was clipped)
设计器「整个页面没有滚动条、看不到底部」真因:amis-editor 自带 CSS 未把
.ae-Editor 约束到容器高度,它按内容自然撑高(新闻管理页达 ~2804px),超出被
DesignerPage 外层 wrapper(flex:1;overflow:hidden) 裁掉、底部够不到。
(此前 theme.css 滚动条改动只作用主应用,editor.html 隔离入口未受影响 → 用户
反馈「没修」。)

修:editor.html <style> 强制 .ae-Editor / .ae-Editor-inner 填满父容器高度 →
编辑器适配视口,画布(.ae-Preview-body 本就 overflow:auto)内部滚动长页面,三栏
框架固定。实测:.ae-Editor 831px、clippedLayers=0(无裁切层)、新闻管理页
776px 完整显示;高于画布的页面经 .ae-Preview-body 滚动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:22:27 +08:00
8603d0f8d8 fix(web): make scrollbars visible (were 6px transparent, looked absent)
用户反馈「整个页面没有滚动条、没办法往下滚动」。根因:theme.css 滚动条 6px
+ 透明轨道 + 浅灰 thumb,在 macOS overlay 滚动条下近乎隐形,长页面(如设计中心
812 页 10209px)能滚但看不到条、误以为滚不动。

改:10px 宽 + 浅底轨道(--surface-2) + 可见 thumb(--line-strong,padding-box
描边) + hover 加深;`* { scrollbar-width:thin; scrollbar-color }` 兼容 Firefox。
全局生效(壳层 + amis 区域)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:05:16 +08:00
2278cbce4b fix(designer): remove StrictMode so amis-editor mounts (was blank screen)
页面设计器(editor.html)整片空白:amis-editor 用 mobx-state-tree 维护 EditorRoot
store,而 src/editor/main.tsx 用 <React.StrictMode> 包裹——dev 下 StrictMode 故意
mount→unmount→remount,销毁第一个 EditorRoot,其 pending 异步(markReady/
calculateHighlightBox)随后打到已死实例 → 抛「[mobx-state-tree] object no longer
part of a state tree」→ 编辑器不渲染。

移除编辑器入口的 StrictMode(主应用 main.tsx 跑 amis SDK 运行时渲染器、容忍
StrictMode,不动)。实测:三栏(组件库/画布/属性面板)+画布真渲业务页全部恢复,
mobx-state-tree 报错消失(剩 Monaco worker/React 弃用警告均良性、不阻塞)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:05:16 +08:00
4b564c6316 test(e2e): executable AI-recipe render smoke gate (M-Gate)
把「手动用浏览器验 AI 生成页渲染成 house-style」codify 成可复用的可执行门,补上
critic 点名「playwright-render 名实不符(从不真渲染)」的缺口——不给后端加浏览器依赖。

- e2e/recipe-render-smoke.spec.ts:给定 templateId,从 served schema 自推期望
  (数据列 label + 所有按钮 label),再断言 amis 真渲染成无错 DOM:amis-host 可见
  且无 schema-error-card / 每列每动作出现 / tbody 无裸 true·false·ISO 串
  (列渲染类型生效)/ 0 console.error·pageerror。
- playwright.recipe-smoke.config.ts:复用已在跑的 5174,不自起 webServer。
- recipe-render-smoke.sh:一键端到端——登录→auto-develop 1 maintenance + 1 tree
  样例→对两页跑断言→DROP 表+删三真相行清理(trap 保证失败也清,sys_ai_* 保留)。

验证:./recipe-render-smoke.sh 端到端全绿(maintenance + tree 两页均 PASSED,
0 console error),库残留复查 0。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:28:32 +08:00
d26e16c689 fix: use standard picker for user selection 2026-06-18 08:11:36 +08:00
d03c2ba156 fix(web): support approval history drawer 2026-06-18 02:12:49 +08:00
16393c183c fix(web): standardize user picker and message detail 2026-06-18 00:30:01 +08:00
b0537f87ae fix(web): normalize legacy user pickers to amis picker 2026-06-17 23:48:39 +08:00
492dad7383 fix(web): align user picker in crud filters 2026-06-17 23:18:27 +08:00
78d859df92 fix(web): normalize user transfer picker layout 2026-06-17 23:15:35 +08:00
f96d3a2ea4 fix(web): keep user picker label inline 2026-06-17 22:57:49 +08:00
045d522ea0 fix(web): constrain user picker bulk display 2026-06-17 22:52:34 +08:00
9e5ece3640 fix(web): preserve user transfer form labels 2026-06-17 22:46:43 +08:00
ba41a76a70 feat(web): add legacy user transfer picker 2026-06-17 22:36:33 +08:00
f7ac4cd49e fix(approval): wire workflow task drawer actions 2026-06-17 20:44:52 +08:00
eae31b31c1 feat(approval): ApprovalBar→ApprovalDrawer 抽屉重设计;e2e/artifacts 不入库
- 新增 ApprovalDrawer(业务表单+轨迹+动态按钮),删除旧 ApprovalBar
- approval.ts 增审批上下文接口;Dialog/TodoPage 接线
- .gitignore 排除 e2e/artifacts 测试重跑产物(取消跟踪 72 张截图)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 22:08:58 +08:00
1b011af41b feat(theme): §15 隐藏冗余页标题栏(.cxd-Page-header)
顶部多 Tab 已显示页名,页内 .cxd-Page-title 重复、白占 ~45px。
实测页头仅含标题无工具栏 → 整条隐藏;用 :has 保留含 .cxd-Page-toolbar
的页头避免误伤,crud 自带 headerToolbar 不受影响。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:40:11 +08:00
306f9ebbae feat(design-center): 集中式设计中心,替代每页设计按钮
用户反馈每个功能页右上角一颗「设计」按钮散落、不合理。改为:
- 新增 /design-center 页(DesignCenterPage):列全部功能页(按菜单分组+计数+
  搜索),每页一个「设计」入口开 editor.html;复用 fetchMenu/collectLeaves。
- Topbar 加 admin-only「设计中心」入口(brush 图标),useNavigate 直达。
- PageRenderPage 移除每页 DesignButton(及 getProfile import)。

验证:浏览器 /design-center 渲染 812 页/14 分组、顶栏按钮在、点行选中并存。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:37:06 +08:00
99b15c233d feat(theme): §14 查看(只读)态隐藏必填星号 *
只读页的红 * 无意义。静态渲染的必填项 value 无输入控件(.cxd-TplField,无input),
用 :has 判定后隐藏 *;编辑态 value 含 input/Select → 不命中,* 照常。
实测:查看 5★全隐、修改 5★全显。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:24:02 +08:00
a6bcd3a21d feat(theme): P0 L1 §13 输入控件字号统一 13px(对齐表格正文)
覆盖 --Form-input-fontSize 14→13,与 §10 表格正文 13px 一致。
(边框 #e2e5ea 偏浅但 amis 变量声明离元素过近、token 压不动,
 直接改 border-color 会破坏 hover/focus,差异本身小,不强改。)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:00:16 +08:00
8571c0a8cb feat(theme): P0 L1 组件密度与层次打磨(列表/按钮/主子表弹窗)
数据驱动的 amis 主题打磨,全程覆盖 amis 自身 CSS 变量/定向规则,
零 SDK 重建、单独成块可回退。amis-theme.css 新增三节:

§10 列表(M1,占60%): 行高 45→38px、表头 14/400→12.5/600 加层次、
    行 hover 品牌淡底、选中行(.is-checked)品牌淡底+左色条。
    覆盖 --TableCell-paddingY/--Table-fontSize/--Table-thead-*。
    (修正:原 §5 .cxd-Table-content 是对不上本 SDK 的死选择器)
§11 表单/按钮: --Form-item-gap 24→16px;default 按钮灰底→白底描边、
    danger 红字红边、primary 保持蓝、hover 品牌色(启用态)。
§12 内容多的主子表弹窗: input-table 行 47→41px(padding 7→4);
    .cxd-Modal-content 封顶 90vh+flex 列、body 内部滚动(操作条常驻);
    子表表头 sticky。简单弹窗无回归(实测用户新增弹窗正常)。

实测验证(playwright,admin/111111): 列表/新闻/采购申请主子表/树 多页型零回归。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 16:50:47 +08:00
ddc25d9573 前端 admin 导航:+部门管理,系统管理页改名为「管理」
sys-admin-depart 新页接入;用户查询/角色与成员/菜单总览→用户/角色/菜单管理

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 02:03:51 +08:00
693a8576ee amis-theme: treegrid 左树高度跟随视口(.cxd-Tree max-height 视口相对)
amis .cxd-Tree--outline 默认 max-height:300px,treegrid 多级分类树「只露一半」、
下方大片留白。转换器给 treegrid 左树挂 className=eip4-treegrid-tree(见
TemplateToAmisConverter.convertTreeGrid),这里把该类内 .cxd-Tree max-height 抬到
calc(100vh-230px)+内部滚动——填满可用区域、超出树内滚(既非定高只露一半,
也非随内容无限撑高)。浏览器实证树高 615px、底部 783<视口 845。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 22:01:58 +08:00
d8232646f9 AmisRenderer: 注入 currentUser/currentProject/now 到 amis 数据域(§7-3 initvalue 动态 token)
转换器把老引擎 initvalue 动态 token 迁移成 amis 表达式(eip4-platform 同步提交):
{CURRENTUSER}→${currentUser}、{CURRENTTIME}→${now}、{CURRENTPROJECT}→${currentProject}
({CURRENTORG}→${orgId} 复用 F2-9 已注入)。本处把对应值注入 amis.embed 第三参数数据域,
使表单项 value 里的 ${...} 在初始化时求值。

- currentUser = profile.userId;orgId = profile.org(沿用 F2-9)。
- now = 本地 "YYYY-MM-DD HH:mm:ss"。
- currentProject 当前 profile 无此字段(会话级概念),注入空串使 ${currentProject} 求值为空
  而非裸 token(优雅降级)。

验证:浏览器实证外部邮件收件箱搜索携 FOLDER=0(字面初值);动态 token 走与既有 orgId 注入
同一机制(F2-9 已验)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 16:37:44 +08:00
aeecaac1c3 F2-17: 删除 e2e 断言对齐老系统软删语义(ISDEL=1,不动 ISACTIVE)
删除已切走服务流 OA_NOTICEMANAGE_DELETE(start 脚本 map.put("ISDEL",1)),
原断言查 isactive 是对着旧 /api/entity/delete 写的——语义基准应是老系统。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 14:50:10 +08:00
179 changed files with 12980 additions and 541 deletions

5
.env
View File

@@ -1,2 +1,3 @@
# 后端反代目标。后端默认 8084(local profile);若 8084 被占改为 8090,此处同步改。 # 后端反代目标。dev profile 默认 8093(本机联调跑这个口)。
VITE_BACKEND_TARGET=http://localhost:8084 # 若端口冲突,复制本文件为 .env.local 并改 VITE_BACKEND_TARGET(.env.local 已 gitignore,不入库)。
VITE_BACKEND_TARGET=http://localhost:8093

27
.gitea/workflows/ci.yml Normal file
View File

@@ -0,0 +1,27 @@
# eip4-web CI(Gitea Actions)。
#
# P0 修复(2026-06-24 架构评审):eip4-web 此前无 CI。本工作流跑类型检查+构建+单测,
# 防前端回归(总览 §10 验证体系)。
#
# 前置条件:Gitea 实例需已启用 Actions 且注册了带 `ubuntu-latest` 标签的 act_runner。
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
- name: 安装依赖
run: npm ci
- name: 类型检查 + 构建(tsc -b && vite build)
run: npm run build
- name: 单测(vitest)
run: npm test

3
.gitignore vendored
View File

@@ -10,3 +10,6 @@ dist/
test-results/ test-results/
playwright-report/ playwright-report/
.playwright/ .playwright/
# e2e 测试重跑产物(截图/中间件),不入库
e2e/artifacts/

View File

@@ -21,28 +21,33 @@ SDK 产物来自 C5 构建预演(eip4-poc 的 `sdk-local/`),整套渲染器(图
## 启动 ## 启动
前置:Node v22+,后端 platform-app(端口 8084),本地 PG(`localhost:5433/eip4m0`,已自举)。 前置:Node v22+、后端 **JDK 21**(严禁 26,Groovy 红线,见 `../eip4-platform/README.md`)、
本地 PG(`localhost:5433`,日常开发库 `eip4dev`,构建见下)。
```bash ```bash
npm install npm install
npm run dev # dev server :5173,/api 反代到后端(默认 8084) npm run dev # dev server :5173,/api 反代到后端(dev profile 默认 8093)
``` ```
浏览器开 http://localhost:5173/login,默认账号 `alice` / `123456`。 浏览器开 http://localhost:5173/login:
- **dev 库(eip4dev,日常开发)**:账号 `admin` / `111111`
- local 自举库(eip4m0,CI/对拍用):账号 `alice` / `123456`
### 后端联调(单独终端) ### 后端联调(单独终端)
```bash ```bash
cd ../eip4-platform cd ../eip4-platform
JAVA_HOME=/opt/homebrew/opt/openjdk@17 \ mvn -pl platform-app,flowable-service -am package -DskipTests # 先出 jar
mvn spring-boot:run -pl platform-app -Dspring-boot.run.profiles=local bash scripts/run-dev.sh platform # dev profile :8093(内置 JDK 21 守卫,自动关旧实例)
# 端口 8084;若被占,加 -Dspring-boot.run.arguments="--server.port=8090" # 审批流联调用: bash scripts/run-dev.sh both (再起 flowable-service :8089)
# 并把前端 .env 的 VITE_BACKEND_TARGET 同步改为 http://localhost:8090 # 日志 /tmp/eip4-platform.log;健康判定 curl :8093/v3/api-docs
# 前端反代端口冲突:复制 .env 为 .env.local 改 VITE_BACKEND_TARGET(已 gitignore)
``` ```
本地库自举(首次):依次灌入 `../eip4-platform/platform-parity/src/main/resources/bootstrap/` 日常开发库 `eip4dev` 构建:`bash tools/local-devdb/build_devdb.sh --drop-target`
的 `bootstrap-sys.sql` → `bootstrap-privilege.sql` → `bootstrap-auth.sql`, (约 6 分钟,需内网可达客户库副本 192.168.20.68:5435)。
再灌 `platform-flow-gateway/.../bootstrap-datastatus.sql`(详见 P4 报告附录)。 CI/对拍走 local profile + `eip4m0` 极简自举集(bootstrap SQL 见
`platform-parity/src/main/resources/bootstrap/`,含 alice 测试账号)。
## 构建 ## 构建
@@ -62,7 +67,7 @@ Nginx 关键配置:SPA 路由回退 `try_files $uri /index.html`;`/api` 反代
| 变量 | 默认 | 说明 | | 变量 | 默认 | 说明 |
|------|------|------| |------|------|------|
| `VITE_BACKEND_TARGET` | `http://localhost:8084` | dev server 的 `/api` 反代目标;8084 被占改 8090 | | `VITE_BACKEND_TARGET` | `http://localhost:8093` | dev server 的 `/api` 反代目标(dev profile 后端);冲突用 `.env.local` 覆盖 |
| `VITE_SCHEMA_SOURCE` | `mock` | `mock`=读 `public/schemas/`;`backend`=读后端 schema 接口 | | `VITE_SCHEMA_SOURCE` | `mock` | `mock`=读 `public/schemas/`;`backend`=读后端 schema 接口 |
## 与后端契约清单 ## 与后端契约清单
@@ -72,7 +77,7 @@ Nginx 关键配置:SPA 路由回退 `try_files $uri /index.html`;`/api` 反代
| 登录签发 JWT | `POST /api/auth/login` | platform-auth/P2认证实测报告.md | `src/api/auth.ts` | | 登录签发 JWT | `POST /api/auth/login` | platform-auth/P2认证实测报告.md | `src/api/auth.ts` |
| 实体 amis CRUD 列表 | `GET /api/entity/{t}/list` | EntityController(amis 格式 `{status,msg,data:{items,total}}`) | `src/components/AmisRenderer.tsx`(fetcher) | | 实体 amis CRUD 列表 | `GET /api/entity/{t}/list` | EntityController(amis 格式 `{status,msg,data:{items,total}}`) | `src/components/AmisRenderer.tsx`(fetcher) |
| 待办聚合 | `GET /api/todo` | platform-flow-gateway/P3网关实测报告.md(503 熔断降级) | `src/api/todo.ts` | | 待办聚合 | `GET /api/todo` | platform-flow-gateway/P3网关实测报告.md(503 熔断降级) | `src/api/todo.ts` |
| 页面 schema(生产期) | `GET /api/page/schema/{templateId}` | **本期设计契约**(P5 后端落地),开发期用静态 mock 替代 | `src/api/schema.ts` | | 页面 schema | `GET /api/page/schema/{templateId}` | PageSchemaController(`sys_page_schema` 唯一真相,已落地) | `src/api/schema.ts` |
JWT 经 `src/api/http.ts` 拦截器注入 `Authorization: Bearer`;401(非登录端点)自动清会话 + 跳 `/login`。 JWT 经 `src/api/http.ts` 拦截器注入 `Authorization: Bearer`;401(非登录端点)自动清会话 + 跳 `/login`。
@@ -89,7 +94,7 @@ JWT 经 `src/api/http.ts` 拦截器注入 `Authorization: Bearer`;401(非登录
- amis 锁 6.13.0 本地化部署,不依赖 CDN(SDK 在 `public/sdk-local/`,来源见 C5 构建预演)✅ - amis 锁 6.13.0 本地化部署,不依赖 CDN(SDK 在 `public/sdk-local/`,来源见 C5 构建预演)✅
- 渲染宿主参照 PoC `amis-local.html`(本地 SDK 引用方式)✅ - 渲染宿主参照 PoC `amis-local.html`(本地 SDK 引用方式)✅
- 页面 schema 双闸:官方 schema.json 校验闸 + 运行时渲染冒烟闸(迁移手册 §8)✅ - 页面 schema 双闸:官方 schema.json 校验闸 + 运行时渲染冒烟闸(迁移手册 §8)✅
- 设计器(amis-editor 二开)排 P4 后半,本期未做(装配点见 P4 报告遗留)✅ - 设计器:amis-editor 已接入并闭环(`src/editor/DesignerPage.tsx` + `editor.html`,设计中心独立 tab)✅
- 渲染层备选(amis fork 失败时):lowcode-engine / ProComponents(架构设计第七节)✅ - 渲染层备选(amis fork 失败时):lowcode-engine / ProComponents(架构设计第七节)✅
## 目录 ## 目录

View File

@@ -0,0 +1,111 @@
/**
* P1⑤ · 审批列表入口生产主路径 e2e(纯 mock,不依赖客户 BPMN / flowable)。
*
* 验证「转换 amis 列表页的 openApprovalDrawer 按钮 → 应用级事件 → AppShell 挂载 ApprovalDrawer」整条链。
* 此前 approval.spec.ts 只测手写 React TodoPage;本 spec 补生产路径(列表页按钮 → 抽屉)。
*
* 接线已 live 验证:228 个 sys_page_schema 含 openApprovalDrawer 按钮(psql 实证);本 e2e 验交互闭环。
* 全程 page.route mock,无后端依赖(seedAuth 用假 token,/api/* 全拦截)。
*/
import { expect, test } from '@playwright/test';
import http from 'node:http';
// 真 admin token(8093 login)——app 加载时校验 token,假 token 会被踢回登录页(designer.spec 同法)
let _tok: string | undefined;
function adminToken(): Promise<string> {
if (_tok) return Promise.resolve(_tok);
return new Promise((resolve, reject) => {
const body = JSON.stringify({ account: 'admin', password: '111111' });
const req = http.request(
{ hostname: 'localhost', port: 8093, path: '/api/auth/login', method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
(res) => { let d = ''; res.on('data', (c) => (d += c)); res.on('end', () => { _tok = (JSON.parse(d) as { token: string }).token; resolve(_tok!); }); });
req.on('error', reject); req.write(body); req.end();
});
}
const TPL = 'mock-approval-list';
const PK = 'MOCKID';
// 仿真实转换页(参考 live 92e9d42b:crud selectable + openApprovalDrawer 只读「查看审批」按钮)
const PAGE_SCHEMA = {
type: 'page',
title: '审批列表入口 mock',
body: {
type: 'crud',
api: '/api/mock-approval-list',
selectable: true,
checkOnItemClick: true,
primaryField: PK,
columns: [
{ name: PK, label: 'ID' },
{ name: 'TITLE', label: '标题' },
],
headerToolbar: [
{
type: 'button',
id: '查看审批',
label: '查看审批',
disabledOn: '${!selectedItems || selectedItems.length !== 1}',
onEvent: {
click: {
actions: [
{
actionType: 'openApprovalDrawer',
args: {
taskName: '审批详情',
readOnly: true,
mode: 'read',
businessKey: `\${selectedItems[0].${PK}}`,
businessTable: 'MOCK_BIZ',
processInstanceId: '${selectedItems[0].processInstanceId || ""}',
},
},
],
},
},
},
],
},
};
test('P1⑤ 转换列表页「查看审批」按钮 → 选中行 → ApprovalDrawer 抽屉打开', async ({ page }) => {
test.setTimeout(60_000);
// 真 token 注入(app 校验 token;页面/任务 API 仍全 mock)
const token = await adminToken();
await page.addInitScript((t) => {
localStorage.setItem('eip4_token', t);
localStorage.setItem('eip4_profile', JSON.stringify({ userId: 'ADMIN', account: 'admin', name: 'admin', roles: [] }));
}, token);
// mock 页面 schema
await page.route('**/api/page/schema/mock-approval-list*', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PAGE_SCHEMA) }));
// mock crud 列表数据(1 行,带 PK + processInstanceId)
await page.route('**/api/mock-approval-list*', (route) =>
route.fulfill({ status: 200, contentType: 'application/json',
body: JSON.stringify({ status: 0, msg: '', data: { items: [{ [PK]: 'mk1', TITLE: '测试付款单', processInstanceId: 'pi-1' }], total: 1 } }) }));
// mock 抽屉只读历史数据(轨迹 / 业务单据 / 任务元数据 —— 宽松返回,保证抽屉容器渲染)
await page.route('**/trace*', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify([{ taskId: 't1', taskName: '提交', current: true }]) }));
await page.route('**/api/task/**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 0, data: { buttons: [], formTemplateId: null } }) }));
await page.route('**/business-data*', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 0, data: { [PK]: 'mk1', TITLE: '测试付款单' } }) }));
await page.goto(`/page/${TPL}`);
// 列表渲染 + 出现 1 行
await expect(page.locator('.cxd-Crud, .cxd-Table').first()).toBeVisible({ timeout: 15_000 });
await expect(page.getByText('测试付款单').first()).toBeVisible({ timeout: 10_000 });
// 选中该行(crud checkOnItemClick=true → 点行即选中,规避 amis checkbox DOM 差异)
await page.getByText('测试付款单').first().click();
// 点「查看审批」按钮(选 1 行后 disabledOn 解除)
await page.getByRole('button', { name: '查看审批' }).click();
// 核心断言:ApprovalDrawer 抽屉被挂载并可见(转换页按钮 → 事件 → AppShell → 抽屉 整链通)
await expect(page.getByTestId('approval-drawer')).toBeVisible({ timeout: 10_000 });
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

View File

@@ -369,9 +369,11 @@ test('F2-17 #4 UI: 删除 E2E 记录后行消失', async ({ page }) => {
const rowsAfter = await page.$$eval('tbody tr', (rows) => rows.length); const rowsAfter = await page.$$eval('tbody tr', (rows) => rows.length);
expect(rowsAfter).toBeLessThanOrEqual(rowsBefore); expect(rowsAfter).toBeLessThanOrEqual(rowsBefore);
// 强断言:DB 中该记录已软删(ISACTIVE=0 或不存在)——删除生效的权威证据 // 强断言:DB 中该记录已删——删除生效的权威证据。
// 语义对照老系统:删除走服务流 OA_NOTICEMANAGE_DELETE(start 脚本 map.put("ISDEL",1) 后
// pojoCRUDService.update),即 ISDEL=1 软删,不动 ISACTIVE。"仍存活" = isdel=0 且 isactive=1。
const dbCheck = psqlQuery( const dbCheck = psqlQuery(
`SELECT COUNT(*) FROM eip3.oa_noticemanage WHERE oa_noticemanage_id='${e2eNoticeId}' AND isactive=1`, `SELECT COUNT(*) FROM eip3.oa_noticemanage WHERE oa_noticemanage_id='${e2eNoticeId}' AND isdel=0 AND isactive=1`,
); );
expect(dbCheck.trim()).toBe('0'); expect(dbCheck.trim()).toBe('0');
}); });

157
e2e/five-ring.spec.ts Normal file
View File

@@ -0,0 +1,157 @@
/**
* 人走五环建新功能 · 浏览器全程点穿 e2e(实施计划 Section 6 / Task 24 的 UI 补全)
*
* NewFeatureShell 现为 amis wizard。本 spec 用真实浏览器走完整链路:
* 登录 → 设计中心「+ 新建功能」→ amis wizard:①建实体(combo 字段) → ②生成页(recipe+标题) → ③发布
* → 经后端 API 断言:发布后 /api/menu 树出现该实体的 design-<table> 模板节点。
*
* 后端走 8094(含本特性新代码,不碰 dev 默认 8093)。运行:
* 先 java -jar platform-app...jar --spring.profiles.active=dev --server.port=8094
* 再 npx playwright test -c playwright.fivering.config.ts
* 数据纪律:afterAll DELETE 测试实体(EIP4 前缀门);net-new 页/菜单/流无运行时删除端点(§F),由跑后 psql 清。
*/
import { expect, test } from '@playwright/test';
import http from 'node:http';
const BACKEND_PORT = 8094;
const TABLE = `EIP4PT_PW${Date.now()}`;
const TPL_PREFIX = `design-${TABLE.toLowerCase().replace(/_/g, '-')}`;
function apiJson(method: string, path: string, token?: string, body?: unknown): Promise<{ status: number; json: any }> {
return new Promise((resolve, reject) => {
const data = body ? JSON.stringify(body) : undefined;
const req = http.request(
{
hostname: 'localhost', port: BACKEND_PORT, path, method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}),
},
},
(res) => {
let buf = '';
res.on('data', (c) => (buf += c));
res.on('end', () => {
try { resolve({ status: res.statusCode ?? 0, json: buf ? JSON.parse(buf) : null }); }
catch { resolve({ status: res.statusCode ?? 0, json: buf }); }
});
},
);
req.on('error', reject);
if (data) req.write(data);
req.end();
});
}
async function adminToken(): Promise<string> {
const r = await apiJson('POST', '/api/auth/login', undefined, { account: 'admin', password: '111111' });
return r.json.token as string;
}
test.afterAll(async () => {
try {
const tok = await adminToken();
await apiJson('DELETE', `/api/meta/entity/${TABLE}`, tok);
} catch { /* 清理尽力而为 */ }
});
test('人走五环 · 浏览器全程点穿(amis wizard:建实体 → 生成页 → 发布 → 菜单可见)', async ({ page }) => {
test.setTimeout(120_000);
// ── 登录(真实 React 表单)──
await page.goto('/login');
await page.getByRole('textbox').first().fill('admin');
await page.locator('input[type="password"]').fill('111111');
await page.getByRole('button', { name: '登录' }).click();
await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 });
// ── 设计中心 → + 新建功能 ──
await page.goto('/design-center');
await page.getByTestId('dc-new-feature').click();
await expect(page.getByTestId('new-feature-shell')).toBeVisible();
// 先选页面类型 = 维护型 CRUD(统一入口的类型选择卡),再进向导。
await page.getByTestId('dc-recipe-maintenance').click();
// ── 环①②·amis wizard 步1 建实体(combo minLength=1 自带一行字段)──
await expect(page.getByPlaceholder('OA_DEMO')).toBeVisible({ timeout: 15_000 });
await page.getByPlaceholder('OA_DEMO').fill(TABLE);
// 所属分类(amis select,必填):点开下拉 → 选第一个分类
await page.locator('.cxd-Select').first().click();
await page.locator('.cxd-Select-option').first().click();
// combo 默认不带行(显示「<空>」),先点「加字段」再填
await page.getByRole('button', { name: '加字段' }).click();
await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TITLE').first().fill('NAME'); // combo 行·列名
await page.getByPlaceholder('标题').first().fill('名称'); // combo 行·显示名
await page.getByRole('button', { name: '保存并下一步' }).click();
// ── 环③·步2 选 recipe + 标题 → compile ──
await expect(page.getByPlaceholder('如:客户等级维护')).toBeVisible({ timeout: 20_000 });
await page.getByPlaceholder('如:客户等级维护').fill('PW五环演示');
await page.getByRole('button', { name: '保存并下一步' }).click();
// ── 环④·步3 发布(菜单名已由 ${title} 预填)──
await page.getByRole('button', { name: '完成' }).click();
// ── 后端断言:发布后 /api/menu 树出现该实体的 design-<table> 模板节点 ──
const tok = await adminToken();
await expect.poll(async () => {
const r = await apiJson('GET', '/api/menu', tok);
const hit: string[] = [];
const walk = (ns: any[]) => (ns || []).forEach((n) => {
if ((n.templateId || '').startsWith(TPL_PREFIX)) hit.push(n.name);
walk(n.children);
});
walk(r.json?.roots || []);
return hit.length;
}, { timeout: 20_000, message: '发布后菜单树应出现 design-<table> 节点' }).toBeGreaterThan(0);
});
// P1④ 人走五环 v2:给已有实体「加字段」(受控 ALTER) —— 建模器 /modeler 行内入口。
// 前置 API 建实体 → 浏览器走加字段 UI → 断言元数据落库(物理列由 scripts/p0-alter-acceptance.sh 的 psql 证)。
test('人走五环 v2 · 改已有表加列(建模器加字段 → 元数据落库)', async ({ page }) => {
test.setTimeout(120_000);
const ALTER_TABLE = `EIP4PT_PWALT${Date.now()}`;
const tok = await adminToken();
const created = await apiJson('POST', '/api/meta/entity', tok, {
tablename: ALTER_TABLE, name: '改表演示',
attributes: [{ column: 'TITLE', display: '标题', type: 'string', length: 100, mandatory: true }],
});
expect(created.status).toBe(200);
// 登录
await page.goto('/login');
await page.getByRole('textbox').first().fill('admin');
await page.locator('input[type="password"]').fill('111111');
await page.getByRole('button', { name: '登录' }).click();
await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 });
// 建模器 → 定位该实体行 → 加字段
await page.goto('/modeler');
const row = page.getByTestId('modeler-entity-row').filter({ hasText: ALTER_TABLE });
await expect(row).toBeVisible({ timeout: 15_000 });
await row.getByTestId('modeler-add-field').click();
// 加字段 Dialog:FieldTable 加一列 AMOUNT(小数)
await page.getByTestId('field-add').click();
await page.getByTestId('field-column').fill('AMOUNT');
await page.getByTestId('field-display').fill('金额');
await page.getByTestId('field-type').selectOption('小数');
await page.getByTestId('field-submit').click(); // 行入表
await expect(page.getByTestId('field-row')).toBeVisible();
await page.getByTestId('modeler-alter-submit').click(); // 提交 ALTER
// 断言:加字段后元数据出现 AMOUNT(物理列生效由 psql 验收脚本另证)
await expect.poll(async () => {
const r = await apiJson('GET', `/api/meta/entity/${ALTER_TABLE}/attributes`, tok);
return (r.json?.data?.columns || []).map((c: { column: string }) => c.column);
}, { timeout: 15_000, message: '加字段后元数据应含 AMOUNT' }).toContain('AMOUNT');
await apiJson('DELETE', `/api/meta/entity/${ALTER_TABLE}`, tok);
});
// 注:AI ①面 amis form 的渲染已人工 live 验证(截图 + 提交按钮),其 READY_FOR_HUMAN_REVIEW
// 后端链路由 curl e2e 证(status=READY + PAGE_SCHEMA.targetId,见 scripts/five-ring-acceptance.sh)。
// 不在此自动化 AI 全程:auto-develop 的 localApply/smoke 以 baseUrl 回调,dev 经 5174→8094 代理回跳时
// SPA 路由会干扰 smoke(生产同源无此问题),属测试环境工件,故不纳入 Playwright 断言。

271
e2e/linkage-probe.spec.ts Normal file
View File

@@ -0,0 +1,271 @@
/**
* 隔离验证 · amis input-table 行内联动机制(真 Playwright 事件)。
*
* 交接首要指令:上一会话「引用驱动联动」后端方案做了但手搓浏览器 fill 没验成功(疑 `.click()` 没触发
* React onEvent / `${index}` componentId 替换)→ 全部回退。本 probe 不碰后端,用 page.evaluate 直接
* amis.embed 注入「手写最小 schema」,再用真 Playwright 鼠标/键盘事件驱动,钉死正确 schema 形态:
* ① 对照组:input-number → setValue componentId=amount_${index}(amis 官方范式 input-table.md:2536)。
* ② select(物料带 PRICE/SPEC 整行)→ onEvent.change → setValue price_${index}/spec_${index}
* = ${event.data.selectedItems[0].PRICE/SPEC}。
* 验证兄弟列是否真被填充。结论决定后端编译器怎么发 schema(id 挂列上 vs quickEdit)。
*
* 纯前端:select 用 static options 不打后端,故任意 vite(默认 config 反代 8093 即可,不依赖 8094)。
*/
import { test, expect } from '@playwright/test';
test('amis input-table 行内联动:input-number 与 select 都应填充兄弟列', async ({ page }) => {
const consoleErrors: string[] = [];
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); });
await page.goto('/login');
await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function',
null, { timeout: 30_000 });
// 注入一个覆盖层 host(不抹掉 React root,避免 React reconciliation 报错),embed 手写 schema。
await page.evaluate(() => {
const w = window as unknown as { amisRequire: (p: string) => any };
const host = document.createElement('div');
host.id = 'probe-host';
host.style.cssText =
'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto';
document.body.appendChild(host);
const amis = w.amisRequire('amis/embed');
const schema = {
type: 'page',
data: { rows: [{}] }, // 预置一行,免去点「新增」
body: {
type: 'form',
title: '行内联动验证',
wrapWithPanel: false,
body: [
{
type: 'input-table',
name: 'rows',
id: 'eg-rows',
addable: true,
removable: true,
needConfirm: false,
columns: [
{
type: 'input-number',
name: 'qty',
label: '数量',
onEvent: {
change: {
actions: [
{ actionType: 'setValue', componentId: 'amount_${index}', args: { value: '${qty * 10}' } },
],
},
},
},
// 目标列带「真实 type」(经 quickEdit),且 id 挂在列上 —— 镜像后端编译器对普通子列的渲染形态,
// 验证 id-on-column + 显式 quickEdit type 仍能被 setValue componentId 命中。
{ name: 'amount', id: 'amount_${index}', label: '金额', quickEdit: { type: 'input-number', name: 'amount' } },
{
type: 'select',
name: 'material',
label: '物料',
// 整行 option(PRICE/SPEC 作为额外列),模拟 picker/list 的 items(responseData options:${items})
options: [
{ label: '水泥', value: 'C1', PRICE: '10', SPEC: '袋装' },
{ label: '钢筋', value: 'S1', PRICE: '20', SPEC: '12mm' },
],
onEvent: {
change: {
// 单选 select 的 change 事件 selectedItems = 被选 Option 对象本身(非数组),故 .PRICE 直取。
// (Select.tsx changeValue: dispatchEvent('change',{value,options,items,selectedItems:value}))
actions: [
{ actionType: 'setValue', componentId: 'price_${index}', args: { value: '${event.data.selectedItems.PRICE}' } },
{ actionType: 'setValue', componentId: 'spec_${index}', args: { value: '${event.data.selectedItems.SPEC}' } },
],
},
},
},
{ name: 'price', id: 'price_${index}', label: '单价' },
{ name: 'spec', id: 'spec_${index}', label: '规格' },
],
},
{
type: 'tpl',
id: 'probe-out',
tpl: 'PROBEOUT amount=[${rows[0].amount}] price=[${rows[0].price}] spec=[${rows[0].spec}]',
className: 'probe-out-marker',
},
],
},
};
amis.embed(host, schema, {}, {});
});
const host = page.locator('#probe-host');
await expect(host.locator('table')).toBeVisible({ timeout: 15_000 });
await expect(page.getByText(/PROBEOUT/)).toBeVisible({ timeout: 10_000 });
const probe = page.getByText(/PROBEOUT/);
// ---- ① 对照组:input-number qty → amount = qty*10 ----
// input-number 的输入框:取第一行第一列的数字输入。用 .cxd-Number 更稳。
const numberCell = host.locator('.cxd-Number input').first();
await numberCell.click();
await numberCell.fill('5');
await numberCell.press('Tab'); // 失焦触发 change
// tpl 重渲染有批处理延迟,用 toContainText 自动重试(非一次性读)。
await expect(probe, 'input-number 联动应把 amount 填成 50').toContainText('amount=[50]', { timeout: 8_000 });
console.log('[probe] after input-number qty=5 →', await probe.textContent());
// ---- ② select 物料 水泥 → price=10 spec=袋装 ----
const sel = host.locator('.cxd-Select').first();
await sel.click();
await page.waitForTimeout(300);
await page.getByText('水泥', { exact: true }).click();
await expect(probe, 'select 联动应把 price 填成 10').toContainText('price=[10]', { timeout: 8_000 });
await expect(probe, 'select 联动应把 spec 填成 袋装').toContainText('spec=[袋装]', { timeout: 8_000 });
console.log('[probe] after select 水泥 →', await probe.textContent());
console.log('[probe] console errors:', JSON.stringify(consoleErrors.slice(0, 20)));
});
test('amis select source(远程 picker) 选项仍携带整行额外列 → 联动填充', async ({ page }) => {
// 真实后端场景:子表引用列 select 用 source=/api/picker/{ref}/list(responseData options:${items}),
// items 是整行(含 PRICE/SPEC + _id/_label)。验证远程 source 选项被选中后 selectedItems 仍带额外列。
await page.goto('/login');
await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function',
null, { timeout: 30_000 });
await page.evaluate(() => {
const w = window as unknown as { amisRequire: (p: string) => any };
const host = document.createElement('div');
host.id = 'probe-host2';
host.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto';
document.body.appendChild(host);
const amis = w.amisRequire('amis/embed');
// mock fetcher:模拟 picker/list 返回整行 items(每行带 PRICE/SPEC/_id/_label/value/label)。
const fetcher = (opt: { url: string }) => {
if (opt.url.includes('/api/picker/')) {
const items = [
{ _id: 'C1', _label: '水泥', value: 'C1', label: '水泥', PRICE: '10', SPEC: '袋装' },
{ _id: 'S1', _label: '钢筋', value: 'S1', label: '钢筋', PRICE: '20', SPEC: '12mm' },
];
return Promise.resolve({ status: 200, headers: {}, data: { status: 0, msg: '', data: { items, options: items, total: 2 } } });
}
return Promise.resolve({ status: 200, headers: {}, data: { status: 0, msg: '', data: {} } });
};
const schema = {
type: 'page',
data: { rows: [{}] },
body: {
type: 'form',
title: '远程 source 联动验证',
wrapWithPanel: false,
body: [
{
type: 'input-table',
name: 'rows',
id: 'eg-rows2',
addable: true,
removable: true,
needConfirm: false,
columns: [
{
type: 'select',
name: 'material',
label: '物料',
source: { method: 'get', url: '/api/picker/MATERIAL/list', responseData: { options: '${items}' } },
labelField: '_label',
valueField: '_id',
onEvent: {
change: {
actions: [
{ actionType: 'setValue', componentId: 'price_${index}', args: { value: '${event.data.selectedItems.PRICE}' } },
{ actionType: 'setValue', componentId: 'spec_${index}', args: { value: '${event.data.selectedItems.SPEC}' } },
],
},
},
},
{ name: 'price', id: 'price_${index}', label: '单价' },
{ name: 'spec', id: 'spec_${index}', label: '规格' },
],
},
{ type: 'tpl', id: 'probe-out2', tpl: 'PROBEOUT2 price=[${rows[0].price}] spec=[${rows[0].spec}]' },
],
},
};
amis.embed(host, schema, {}, { fetcher });
});
const host = page.locator('#probe-host2');
await expect(host.locator('table')).toBeVisible({ timeout: 15_000 });
const probe = page.getByText(/PROBEOUT2/);
const sel = host.locator('.cxd-Select').first();
await sel.click();
await page.waitForTimeout(400); // 等远程 options 加载
await page.getByText('水泥', { exact: true }).click();
await expect(probe, '远程 source 选项联动应填 price=10').toContainText('price=[10]', { timeout: 8_000 });
await expect(probe, '远程 source 选项联动应填 spec=袋装').toContainText('spec=[袋装]', { timeout: 8_000 });
console.log('[probe2] after remote select 水泥 →', await probe.textContent());
});
test('amis 多行 input-table:componentId=col_${index} 按行隔离填充(行0选水泥/行1选钢筋, 互不串台)', async ({ page }) => {
// ★ 关键回归(对抗评审 HIGH 揪出):联动靠 ${index} 让 componentId 逐行展开。单行测覆盖不到「选第 2 行
// 是否误填第 0 行」的串台风险(属红线「绝不写错值」)。本测 seed 两行,分别选不同物料,断言各行各填各的。
await page.goto('/login');
await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function',
null, { timeout: 30_000 });
await page.evaluate(() => {
const w = window as unknown as { amisRequire: (p: string) => any };
const host = document.createElement('div');
host.id = 'probe-host3';
host.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto';
document.body.appendChild(host);
const amis = w.amisRequire('amis/embed');
const schema = {
type: 'page',
data: { rows: [{}, {}] }, // 两行
body: {
type: 'form', title: '多行联动隔离验证', wrapWithPanel: false,
body: [
{
type: 'input-table', name: 'rows', id: 'eg-rows3',
addable: true, removable: true, needConfirm: false,
columns: [
{
type: 'select', name: 'material', label: '物料',
options: [
{ label: '水泥', value: 'C1', PRICE: '10' },
{ label: '钢筋', value: 'S1', PRICE: '20' },
],
onEvent: { change: { actions: [
{ actionType: 'setValue', componentId: 'price_${index}', args: { value: '${event.data.selectedItems.PRICE}' } },
] } },
},
{ name: 'price', id: 'price_${index}', label: '单价' },
],
},
{ type: 'tpl', tpl: 'MULTI r0=[${rows[0].price}] r1=[${rows[1].price}]' },
],
},
};
amis.embed(host, schema, {}, {});
});
const host = page.locator('#probe-host3');
await expect(host.locator('table')).toBeVisible({ timeout: 15_000 });
const probe = page.getByText(/MULTI/);
// 行0 选水泥(10)
await host.locator('.cxd-Select').nth(0).click();
await page.waitForTimeout(200);
await page.getByText('水泥', { exact: true }).click();
await expect(probe, '行0选水泥应填 r0=10').toContainText('r0=[10]', { timeout: 8_000 });
// 行1 选钢筋(20):必须只填 r1,绝不串改 r0。
await host.locator('.cxd-Select').nth(1).click();
await page.waitForTimeout(200);
await page.getByText('钢筋', { exact: true }).click();
await expect(probe, '行1选钢筋应填 r1=20').toContainText('r1=[20]', { timeout: 8_000 });
// 串台守卫:r0 仍须是 10(行1的选择没污染行0)。
await expect(probe, '行0不应被行1串改').toContainText('r0=[10] r1=[20]', { timeout: 8_000 });
console.log('[probe3] multi-row →', await probe.textContent());
});

385
e2e/master-detail.spec.ts Normal file
View File

@@ -0,0 +1,385 @@
/**
* 主子表(master-detail)· 浏览器全程点穿 e2e —— 走统一「新建功能」向导。
* 设计中心「+ 新建功能」→ amis wizard:① 建实体(选「主子表」页面类型) → ②【主子表才出现】建子表
* → ③ 生成主子页(compile master-detail-v1) → ④ 发布。
* 断言:发布后经 API 对主表 _ADD 提交主+子行,引擎按主 LIST 列级联落库(status 0);_LOAD 回读子行。
* 后端走 8094(playwright.fivering.config 反代)。数据纪律:afterAll 删主/子实体;其余跑后 psql 清。
*/
import { expect, test, type Page } from '@playwright/test';
import http from 'node:http';
const BACKEND_PORT = 8094;
const TS = Date.now();
const MASTER = `EIP4PT_MDW${TS}M`;
const CHILD = `EIP4PT_MDW${TS}C`;
// 第二个用例(派生+汇总)专用表
const MASTER2 = `EIP4PT_MDD${TS}M`;
const CHILD2 = `EIP4PT_MDD${TS}C`;
// 第三个用例(引用驱动联动)专用表:物料引用实体 + 主表 + 子表(含引用列)
const MAT = `EIP4PT_MTL${TS}`;
const MASTER3 = `EIP4PT_LKM${TS}`;
const CHILD3 = `EIP4PT_LKC${TS}`;
function api(method: string, path: string, token?: string, body?: unknown): Promise<{ status: number; json: any }> {
return new Promise((resolve, reject) => {
const data = body ? JSON.stringify(body) : undefined;
const req = http.request({ hostname: 'localhost', port: BACKEND_PORT, path, method,
headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}),
...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}) } },
(res) => { let b = ''; res.on('data', (c) => (b += c)); res.on('end', () => {
try { resolve({ status: res.statusCode ?? 0, json: b ? JSON.parse(b) : null }); }
catch { resolve({ status: res.statusCode ?? 0, json: b }); } }); });
req.on('error', reject); if (data) req.write(data); req.end();
});
}
async function adminToken(): Promise<string> {
const r = await api('POST', '/api/auth/login', undefined, { account: 'admin', password: '111111' });
return r.json.token as string;
}
// 在 schema 任意层的 input-table 里按列名找子列(不依赖 JSON 键序,标准层会重序列化打乱键序)。
function findInputTableColumn(node: any, colName: string): any {
if (Array.isArray(node)) {
for (const n of node) { const r = findInputTableColumn(n, colName); if (r) return r; }
return null;
}
if (node && typeof node === 'object') {
if (node.type === 'input-table' && Array.isArray(node.columns)) {
const c = node.columns.find((x: any) => x?.name === colName);
if (c) return c;
}
for (const k of Object.keys(node)) { const r = findInputTableColumn(node[k], colName); if (r) return r; }
}
return null;
}
// 登录 + 进统一新建功能向导 + 选「主子表」页面类型(使②建子表步出现)。
async function openWizardAsMasterDetail(page: Page) {
await page.goto('/login');
await page.getByRole('textbox').first().fill('admin');
await page.locator('input[type="password"]').fill('111111');
await page.getByRole('button', { name: '登录' }).click();
await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 });
await page.goto('/design-center');
await page.getByTestId('dc-new-feature').click();
await expect(page.getByTestId('new-feature-shell')).toBeVisible();
// 先选页面类型 = 主子表(统一入口的类型选择卡)→ 进主子表向导(含②建子表步)。
await page.getByTestId('dc-recipe-master-detail').click();
await expect(page.getByPlaceholder('OA_DEMO')).toBeVisible({ timeout: 15_000 });
}
test.afterAll(async () => {
try { const tok = await adminToken();
await api('DELETE', `/api/meta/entity/${CHILD}`, tok);
await api('DELETE', `/api/meta/entity/${MASTER}`, tok);
await api('DELETE', `/api/meta/entity/${CHILD2}`, tok);
await api('DELETE', `/api/meta/entity/${MASTER2}`, tok);
// 子表引用物料,先删子/主,再删物料引用实体。
await api('DELETE', `/api/meta/entity/${CHILD3}`, tok);
await api('DELETE', `/api/meta/entity/${MASTER3}`, tok);
await api('DELETE', `/api/meta/entity/${MAT}`, tok);
} catch { /* best effort */ }
});
// 建实体 → 取 entityId。attributes 见各列 {column,display,type,referenceTable?,mandatory?}。
async function createEntity(tok: string, table: string, name: string, etype: string,
attributes: Record<string, unknown>[], masterTable?: string): Promise<string> {
const body: Record<string, unknown> = { tablename: table, name, entitytype: etype, attributes };
if (masterTable) body.masterTable = masterTable;
const r = await api('POST', '/api/meta/entity', tok, body);
if (r.json?.status !== 0) throw new Error(`createEntity ${table} 失败: ${JSON.stringify(r.json)}`);
return r.json.data.entityId as string;
}
// 编译 maintenance-crud + 发布(建默认流),供物料实体可 _ADD 行(picker 读真实数据)。
// menuName 须 ≤ sys_menu.name varchar(20);本测不走菜单导航(直接 embed schema),故用短名即可。
async function compileAndPublish(tok: string, table: string, entityId: string, menuName: string): Promise<void> {
const c = await api('POST', '/api/design/recipe/compile', tok,
{ tableName: table, recipe: 'maintenance-crud-v1', title: `${table}页` });
const tid = c.json?.data?.templateId;
if (!tid) throw new Error(`compile ${table} 失败: ${JSON.stringify(c.json)}`);
const p = await api('POST', '/api/design/publish', tok,
{ entityId, tableName: table, templateId: tid, menuName, generateDeploymentPackage: false });
if (p.json?.status !== 0) throw new Error(`publish ${table} 失败: ${JSON.stringify(p.json)}`);
}
test('主子表 · 统一向导全程点穿(选主子表 → 建主+子 → 生成主子页 → 发布 → 级联保存子行)', async ({ page }) => {
test.setTimeout(120_000);
await openWizardAsMasterDetail(page);
// 步① 建主实体
await page.getByPlaceholder('OA_DEMO').fill(MASTER);
await page.getByPlaceholder('演示(可选)').fill('采购申请');
await page.locator('.cxd-Select').first().click(); // 所属分类
await page.locator('.cxd-Select-option').first().click();
await page.getByRole('button', { name: '加字段' }).click();
await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TITLE').first().fill('TITLE');
await page.getByPlaceholder('标题').first().fill('标题');
await page.getByRole('button', { name: '保存并下一步' }).click();
// 步② 建子表(选主子表后才出现)
await expect(page.getByPlaceholder('OA_PURCHASE_ITEM')).toBeVisible({ timeout: 15_000 });
await page.getByPlaceholder('OA_PURCHASE_ITEM').fill(CHILD);
await page.getByPlaceholder('采购明细').fill('采购明细');
await page.getByRole('button', { name: '加子表字段' }).click();
await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TITLE').first().fill('ITEMNAME');
await page.getByPlaceholder('标题').first().fill('物料');
await page.getByRole('button', { name: '保存并下一步' }).click();
// 步③ 生成主子页
await expect(page.getByPlaceholder('如:客户等级维护')).toBeVisible({ timeout: 20_000 });
await page.getByPlaceholder('如:客户等级维护').fill('采购申请主子');
await page.getByRole('button', { name: '保存并下一步' }).click();
// 步④ 发布
await page.getByRole('button', { name: '完成(发布)' }).click();
// ★ 后端断言:发布后主表 _ADD 主+2子行级联落库(LIST 列经引擎自动回填子表外键)
const tok = await adminToken();
await expect.poll(async () => {
const r = await api('POST', `/api/flow/${MASTER}_ADD`, tok,
{ TITLE: '采购单A', DETAILS: [{ ITEMNAME: '水泥' }, { ITEMNAME: '钢筋' }] });
return r.json?.status;
}, { timeout: 25_000, message: '发布后主表 _ADD(含 DETAILS 子行)应级联成功' }).toBe(0);
const s = await api('POST', `/api/flow/${MASTER}_SEARCH`, tok, {});
expect(s.json?.status).toBe(0);
// 子行经 _LOAD 回读,实证级联真落库(_SEARCH 列表不嵌充子数组,_LOAD 才填充)。
const rowA = (s.json?.data?.items ?? []).find((r: any) => r.TITLE === '采购单A');
expect(rowA, '应查到采购单A').toBeTruthy();
const pk = `${MASTER}_ID`;
const loaded = await api('POST', `/api/flow/${MASTER}_LOAD`, tok, { [pk]: String(rowA[pk]).trim() });
const names = (loaded.json?.data?.result?.DETAILS ?? []).map((d: any) => d.ITEMNAME).sort();
expect(names, '子行水泥/钢筋应级联落库').toEqual(['水泥', '钢筋']);
});
test('主子表派生字段+父级汇总 · 统一向导加派生/汇总 → 发布页 tpl+SUM预览+__derive+__rollup → _ADD 服务端派生再聚合', async ({ page }) => {
test.setTimeout(120_000);
await openWizardAsMasterDetail(page);
// 步① 建主实体(含 TOTAL 汇总目标列)
await page.getByPlaceholder('OA_DEMO').fill(MASTER2);
await page.getByPlaceholder('演示(可选)').fill('派生采购');
await page.locator('.cxd-Select').first().click();
await page.locator('.cxd-Select-option').first().click();
await page.getByRole('button', { name: '加字段' }).click();
await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TITLE').first().fill('TITLE');
await page.getByPlaceholder('标题').first().fill('标题');
await page.getByRole('button', { name: '加字段' }).click();
await expect(page.getByPlaceholder('TITLE').nth(1)).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TITLE').nth(1).fill('TOTAL');
await page.getByPlaceholder('标题').nth(1).fill('总额');
await page.getByRole('button', { name: '保存并下一步' }).click();
// 步② 建子表:4 列 ITEMNAME/ITEMQTY/ITEMPRICE/AMOUNT(默认 string,求值器会数字强转)
await expect(page.getByPlaceholder('OA_PURCHASE_ITEM')).toBeVisible({ timeout: 15_000 });
await page.getByPlaceholder('OA_PURCHASE_ITEM').fill(CHILD2);
await page.getByPlaceholder('采购明细').fill('派生明细');
const childCols = ['ITEMNAME', 'ITEMQTY', 'ITEMPRICE', 'AMOUNT'];
for (let i = 0; i < childCols.length; i++) {
await page.getByRole('button', { name: '加子表字段' }).click();
await expect(page.getByPlaceholder('TITLE').nth(i)).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TITLE').nth(i).fill(childCols[i]);
}
await page.getByRole('button', { name: '保存并下一步' }).click();
// 步③ 生成主子页 + 派生字段 AMOUNT=ITEMQTY*ITEMPRICE + 汇总 TOTAL=SUM(AMOUNT)
await expect(page.getByPlaceholder('如:客户等级维护')).toBeVisible({ timeout: 20_000 });
await page.getByPlaceholder('如:客户等级维护').fill('派生采购主子');
await page.getByRole('button', { name: '加派生字段' }).click();
await expect(page.getByPlaceholder('MONEY')).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('MONEY').fill('AMOUNT');
await page.getByPlaceholder('QTY*PRICE').fill('ITEMQTY*ITEMPRICE');
await page.getByRole('button', { name: '加汇总字段' }).click();
await expect(page.getByPlaceholder('TOTAL')).toBeVisible({ timeout: 10_000 });
await page.getByPlaceholder('TOTAL').fill('TOTAL');
await page.getByPlaceholder('AMOUNT').fill('AMOUNT');
// 捕获 compile 响应拿 templateId(验 UI→编译产物)
const compileResp = page.waitForResponse(
(r) => r.url().includes('/api/design/recipe/compile') && r.request().method() === 'POST');
await page.getByRole('button', { name: '保存并下一步' }).click();
const tid = (await (await compileResp).json())?.data?.templateId as string;
expect(tid, 'compile 应返回 templateId').toBeTruthy();
// 步④ 发布
await page.getByRole('button', { name: '完成(发布)' }).click();
const tok = await adminToken();
// ★ 断言1:子表 AMOUNT 列只读 tpl 实时预览 + 表单 api 透传 __derive
const schema = (await api('GET', `/api/page/schema/${tid}`, tok)).json;
expect(JSON.stringify(schema), '表单 api 应透传 __derive').toContain('__derive');
const amountCol = findInputTableColumn(schema, 'AMOUNT');
expect(amountCol, 'AMOUNT 列应存在于 input-table').toBeTruthy();
expect(amountCol.type).toBe('tpl');
expect(amountCol.tpl).toBe('${ITEMQTY*ITEMPRICE}');
expect(amountCol.quickEdit, '派生列 quickEdit 必须显式 false 才保留只读 tpl 预览').toBe(false);
// ★ 断言1b:主表 TOTAL 汇总列只读 static + SUM 实时预览 + 表单 api 透传 __rollup
expect(JSON.stringify(schema), '表单 api 应透传 __rollup').toContain('__rollup');
expect(JSON.stringify(schema), '主表 TOTAL 应为 SUM(ARRAYMAP) 实时预览')
.toContain('SUM(ARRAYMAP(DETAILS, item => item.ITEMQTY*item.ITEMPRICE))');
// ★ 断言2:_ADD 带 __derive+__rollup,子行不带 AMOUNT、主体不带 TOTAL,服务端逐行派生再聚合
await expect.poll(async () => {
const r = await api('POST',
`/api/flow/${MASTER2}_ADD?__derive=${encodeURIComponent('DETAILS|AMOUNT=ITEMQTY*ITEMPRICE')}`
+ `&__rollup=${encodeURIComponent('TOTAL=SUM:DETAILS:AMOUNT')}`, tok,
{ TITLE: '派生单A', DETAILS: [
{ ITEMNAME: '水泥', ITEMQTY: 3, ITEMPRICE: 10 },
{ ITEMNAME: '钢筋', ITEMQTY: 2, ITEMPRICE: '12.5' }] });
return r.json?.status;
}, { timeout: 25_000, message: '派生+汇总 _ADD 应成功' }).toBe(0);
const s = await api('POST', `/api/flow/${MASTER2}_SEARCH`, tok, {});
expect(s.json?.status).toBe(0);
const rows: any[] = s.json?.data?.items ?? [];
const rowA = rows.find((r) => r.TITLE === '派生单A');
expect(rowA, '应查到派生单A').toBeTruthy();
const pk = `${MASTER2}_ID`;
const loaded = await api('POST', `/api/flow/${MASTER2}_LOAD`, tok, { [pk]: String(rowA[pk]).trim() });
const details: any[] = loaded.json?.data?.result?.DETAILS ?? [];
const amts = details.map((d) => Number(d.AMOUNT)).sort((a, b) => a - b);
expect(amts, '服务端派生 AMOUNT=数量×单价(3×10=30,2×12.5=25)').toEqual([25, 30]);
expect(Number(loaded.json?.data?.result?.TOTAL), '服务端聚合 TOTAL=55').toBe(55);
});
test('引用驱动联动 · 子表选物料(真 Playwright 事件)→带出单价/规格, 校验 schema + 真实填充 + 提交落库', async ({ page }) => {
test.setTimeout(120_000);
const tok = await adminToken();
// 取一个实体分类 id
const types = await api('GET', '/api/meta/entity-types', tok);
const etype = (types.json?.data ?? [])[0]?.id;
expect(etype, '应有可用实体分类').toBeTruthy();
// ── 设置(API):物料引用实体(含 PRICE/SPEC)+ 发布建流 + 2 行(picker 读真实数据)──
const matId = await createEntity(tok, MAT, '物料', etype, [
{ column: 'MATNAME', display: '物料名', type: 'string', mandatory: true },
{ column: 'PRICE', display: '单价', type: 'number' },
{ column: 'SPEC', display: '规格', type: 'string' },
]);
await compileAndPublish(tok, MAT, matId, '物料联动');
expect((await api('POST', `/api/flow/${MAT}_ADD`, tok,
{ MATNAME: '水泥', PRICE: 10, SPEC: '袋装' })).json?.status, '物料水泥 _ADD').toBe(0);
expect((await api('POST', `/api/flow/${MAT}_ADD`, tok,
{ MATNAME: '钢筋', PRICE: 20, SPEC: '12mm' })).json?.status, '物料钢筋 _ADD').toBe(0);
// ── 设置(API):主表 + 子表(子表含引用列 ITEMID→物料、被带出列 ITEMPRICE/ITEMSPEC)──
const masterId = await createEntity(tok, MASTER3, '采购联动', etype, [
{ column: 'TITLE', display: '标题', type: 'string', mandatory: true },
]);
await createEntity(tok, CHILD3, '采购联动明细', etype, [
{ column: 'ITEMNAME', display: '明细名', type: 'string' },
{ column: 'ITEMID', display: '物料', type: 'reference', referenceTable: MAT },
{ column: 'ITEMPRICE', display: '单价', type: 'number' },
{ column: 'ITEMSPEC', display: '规格', type: 'string' },
], MASTER3);
// ── 编译 master-detail + 引用驱动联动(ITEMID 选中→带出 ITEMPRICE←PRICE / ITEMSPEC←SPEC)──
const compileResp = await api('POST', '/api/design/recipe/compile', tok, {
tableName: MASTER3, recipe: 'master-detail-v1', title: '采购联动单',
childTable: CHILD3, linkColumn: 'MASTERID', listColumn: 'DETAILS', listLabel: '明细',
childLinkage: [{ refColumn: 'ITEMID', fills: [
{ target: 'ITEMPRICE', source: 'PRICE' }, { target: 'ITEMSPEC', source: 'SPEC' }] }],
});
const tid = compileResp.json?.data?.templateId;
expect(tid, 'master-detail compile 应返回 templateId').toBeTruthy();
await api('POST', '/api/design/publish', tok,
{ entityId: masterId, tableName: MASTER3, templateId: tid, menuName: '采购联动单', generateDeploymentPackage: false });
// ── 断言 1:生成的 schema 形态正确(select source=picker + onEvent setValue selectedItems.<src>,无 [0])──
const schema = (await api('GET', `/api/page/schema/${tid}`, tok)).json;
const sj = JSON.stringify(schema);
expect(sj, 'ITEMID 列应为 picker select 取物料').toContain(`/api/picker/${MAT}/list`);
expect(sj, '联动应发 setValue 带出 PRICE').toContain('${event.data.selectedItems.PRICE}');
expect(sj, '联动目标列 ITEMPRICE 应挂 id=ITEMPRICE_${index}').toContain('ITEMPRICE_${index}');
// 联动 onEvent 里单选 select 的 selectedItems 是对象非数组,绝不能写 event.data.selectedItems[0]
// (这是上一会话 fill 失败的真因)。注意 CRUD 编辑按钮的 ${selectedItems[0]}=选中主行(数组)是另一回事,合法。
expect(sj, '联动取值绝不能含 event.data.selectedItems[0]').not.toContain('event.data.selectedItems[0]');
// 取 picker 真实选项:找出「水泥」行的显示标签(_label 可能是显示名也可能是裸 id)与其 PRICE,
// UI 按真实 _label 文本点选(不假设显示名=MATNAME,规避新实体无显示列时 _label=裸 id 的情况)。
const picker = await api('GET', `/api/picker/${MAT}/list`, tok);
const pickerItems: any[] = picker.json?.data?.items ?? [];
const cement = pickerItems.find((i) => i.MATNAME === '水泥');
expect(cement, 'picker 应返回水泥行').toBeTruthy();
expect(String(cement.PRICE), 'picker items 应携带整行 PRICE 列(联动源)').toBe('10');
const cementLabel = String(cement._label).trim();
// ── 断言 2:真实渲染 + 真 Playwright 事件填充 ──
// 取真实 schema 的「新增」表单(含真实 input-table 引用列 select),seed 一行 + 探针 tpl,amis.embed
// 用「真后端 token fetcher」渲染(picker 打真实 8094)。不是手写 schema——是后端真产物。
await page.goto('/login');
await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function',
null, { timeout: 30_000 });
await page.evaluate(([realSchema, token, masterTable]) => {
const w = window as unknown as { amisRequire: (p: string) => any };
const host = document.createElement('div');
host.id = 'lk-host';
host.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto';
document.body.appendChild(host);
// 真后端 fetcher:复用 vite /api 代理到 8094,带 admin Bearer。
const fetcher = async (opt: { url: string; method?: string; data?: unknown }) => {
const method = (opt.method || 'get').toLowerCase();
const res = await fetch(opt.url, {
method,
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: method === 'get' ? undefined : JSON.stringify(opt.data || {}),
});
const json = await res.json().catch(() => ({}));
return { status: res.status, headers: {}, data: json };
};
// 从真实 schema 取「新增」按钮的对话框表单(含真 input-table)。
const hb = (realSchema as any).body.headerToolbar as any[];
const addBtn = hb.find((b) => b && b.id === '新增');
const form = addBtn.dialog.body;
// 探针 tpl 放进表单内(数据域含 DETAILS),实时反映联动填充结果。
form.body.push({ type: 'tpl',
tpl: 'PROBELK price=[${DETAILS[0].ITEMPRICE}] spec=[${DETAILS[0].ITEMSPEC}]' });
const pageSchema = { type: 'page',
data: { TITLE: '联动单A', DETAILS: [{}] }, // seed 一行免点「新增行」
body: [form] };
void masterTable;
w.amisRequire('amis/embed').embed(host, pageSchema, {}, { fetcher });
}, [schema, tok, MASTER3] as const);
const host = page.locator('#lk-host');
await expect(host.locator('table')).toBeVisible({ timeout: 15_000 });
const probe = page.getByText(/PROBELK/);
// 真事件:打开子表行内 ITEMID select → 选「水泥」。
const sel = host.locator('.cxd-Select').first();
await sel.click();
// 等真实 picker options 渲染(替固定 sleep),再在下拉里(scoped .cxd-Select-option)按 _label 点选——
// 避免 getByText 误命中全屏 host 上的其它同文本节点。
await page.locator('.cxd-Select-option').first().waitFor({ timeout: 8_000 });
await page.locator('.cxd-Select-option', { hasText: cementLabel }).first().click();
// ★ 联动填充:选物料→自动带出单价 10 / 规格 袋装(真后端 schema + 真事件,非手写)。
await expect(probe, '选水泥应带出 ITEMPRICE=10').toContainText('price=[10]', { timeout: 8_000 });
await expect(probe, '选水泥应带出 ITEMSPEC=袋装').toContainText('spec=[袋装]', { timeout: 8_000 });
// ── 断言 3:提交 → 落库(_LOAD 回读子行 ITEMPRICE=10,证明填充值真随主表 _ADD 级联落库)──
await host.getByRole('button', { name: '提交' }).click();
await expect.poll(async () => {
const s = await api('POST', `/api/flow/${MASTER3}_SEARCH`, tok, {});
return (s.json?.data?.items ?? []).find((r: any) => r.TITLE === '联动单A') ? 'ok' : 'wait';
}, { timeout: 20_000, message: '提交后主表应查到联动单A' }).toBe('ok');
const s = await api('POST', `/api/flow/${MASTER3}_SEARCH`, tok, {});
const rowA = (s.json?.data?.items ?? []).find((r: any) => r.TITLE === '联动单A');
const pk = `${MASTER3}_ID`;
const loaded = await api('POST', `/api/flow/${MASTER3}_LOAD`, tok, { [pk]: String(rowA[pk]).trim() });
const child = (loaded.json?.data?.result?.DETAILS ?? [])[0];
expect(child, '应级联落子行').toBeTruthy();
// 所选物料(引用列 FK=_id)本身应落库——证明 select valueField=_id 绑定生效(fill 之外的主契约)。
expect(String(child.ITEMID).trim(), '所选物料引用FK应落库').toBe(String(cement._id).trim());
expect(Number(child.ITEMPRICE), '联动带出的单价应随提交落库=10(用户未手填)').toBe(10);
expect(String(child.ITEMSPEC).trim(), '联动带出的规格应随提交落库=袋装').toBe('袋装');
});

264
e2e/process-modeler.spec.ts Normal file
View File

@@ -0,0 +1,264 @@
/**
* 在线流程 Modeler(B3)· 浏览器全程点穿 live e2e(实施计划 Task 4.2)。
*
* 三场景(真部署真起实例真验收,不 mock):
* A 改存量全链:登录 admin → /process-modeler?procKey=总包合同交底 → 画布渲染 → 点会签 userTask「编写交底」
* → EIP4 侧板会签控件可见且「启用会签」勾选(保真读回)→ 保存草稿(URL 回填 ?modelId=)→ 发布
* (PublishConfirm 断言含流程 key「总包合同交底」+ 版本 + 运行中实例数)→ 确认 → apiJson 起实例
* → trace 断言有 current userTask(证部署的存量流程经 moddle 往返后小写元素仍被引擎识别、可派任)。
* B 新建全链:新建流程 → 选「会签」模板 + 填名称/key → 进编辑器(画布非空)→ 选 task_cosign 填会签办理人
* content=ADMIN(否则空集合运行期被跳过、不生成任务)→ 保存草稿 → 发布 → 确认 → apiJson 起实例
* → trace 断言 current userTask「会签审批」(证 bpmn-js 新建的小写 BPMN 部署后真产任务)。
* C 走查 + 权限:①中文节点名渲染正常 ②palette 元素齐 ③标准属性面板 + EIP4 侧板同屏
* ④超管门:非超管访问 deploy/models 网关端点断言 403(见下方 alice 降级说明)。
*
* 依赖:8093 网关/后端 + 8089 flowable-service + 5173 vite dev 均在线(见 playwright.process-modeler.config.ts)。
* 自检:curl -s -o /dev/null -w '%{http_code}' localhost:8093/v3/api-docs(200)、curl localhost:5173(200)。
* 跑法:npx playwright test -c playwright.process-modeler.config.ts
*
* 数据纪律:afterAll 删本次建的草稿(act_re_model,DELETE /api/workflow/models/{id})。发布产生的流程新版本
* 无运行时下架端点(同 §F net-new),属 live 验收固有副作用——每跑一次「总包合同交底」版本 +1、B 新建一个净新 key。
*
* ⚠️ 场景 C④ alice 降级:dev 库无 alice/123456 账号(登录返 success:false),无法用真实非超管 token 打 deploy。
* 降级为等价断言:非超管凭据(无 token)打 deploy/models → 403(走的正是 ProcessModelerController.requireSuperAdmin
* 的 principal==null → 非 isSystemAdmin → 403 分支,与「合法非超管 token → 403」同一段代码),并用 admin token
* 打 models → 200 作对照,证超管门确在按身份区分放行/拒绝。alice 登录失败一并断言以记录账号缺席事实。
*/
import { expect, test } from '@playwright/test';
import http from 'node:http';
// apiJson 直连后端 8093(与 UI 经 5173 vite 代理的目标同一后端,故 UI 建的草稿 apiJson 可见)。
const BACKEND_PORT = 8093;
const ZONGBAO_KEY = '总包合同交底';
// 存量会签流程「总包合同交底」的会签 userTask id(净化源里 sid- 前缀为 ASCII 不被改写,即 bpmn-js data-element-id)。
const COSIGN_TASK_ID = 'sid-2AB0790B-7C9B-4872-8753-BC3DB644568C';
// 本次运行建的草稿 id,afterAll 清理。
const createdModelIds: string[] = [];
function apiJson(
method: string,
path: string,
token?: string,
body?: unknown,
): Promise<{ status: number; json: any }> {
return new Promise((resolve, reject) => {
const data = body ? JSON.stringify(body) : undefined;
const req = http.request(
{
hostname: 'localhost',
port: BACKEND_PORT,
path,
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}),
},
},
(res) => {
let buf = '';
res.on('data', (c) => (buf += c));
res.on('end', () => {
try {
resolve({ status: res.statusCode ?? 0, json: buf ? JSON.parse(buf) : null });
} catch {
resolve({ status: res.statusCode ?? 0, json: buf });
}
});
},
);
req.on('error', reject);
if (data) req.write(data);
req.end();
});
}
async function adminToken(): Promise<string> {
const r = await apiJson('POST', '/api/auth/login', undefined, { account: 'admin', password: '111111' });
return r.json.token as string;
}
// 真实 React 登录表单(复用 five-ring 惯例:第一个 textbox=账号、type=password=密码、按钮「登录」)。
async function loginAdmin(page: import('@playwright/test').Page) {
await page.goto('/login');
await page.getByRole('textbox').first().fill('admin');
await page.locator('input[type="password"]').fill('111111');
await page.getByRole('button', { name: '登录' }).click();
await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 });
}
// 点击画布上指定 BPMN 元素(bpmn-js 在 shape g 上挂 data-element-id)。
async function selectBpmnElement(page: import('@playwright/test').Page, elementId: string) {
const el = page.locator(`[data-testid="process-modeler-canvas"] [data-element-id="${elementId}"]`);
await expect(el).toBeVisible({ timeout: 15_000 });
await el.click();
}
// 记住 URL 里回填的 ?modelId=,供 afterAll 清理。
function rememberModelId(page: import('@playwright/test').Page): string {
const id = new URL(page.url()).searchParams.get('modelId') ?? '';
if (id && !createdModelIds.includes(id)) createdModelIds.push(id);
return id;
}
// 起实例 + trace 断言:部署的流程 start 后必有 current userTask(证小写元素被引擎识别并派任)。
async function assertTaskGenerated(key: string, businessKey: string, token: string): Promise<void> {
const started = await apiJson('POST', '/api/process/start', token, {
processDefinitionKey: key,
businessKey,
});
expect(started.status, 'start 应 200').toBe(200);
const iid = started.json?.id;
expect(iid, 'start 应返回流程实例 id').toBeTruthy();
await expect
.poll(
async () => {
const t = await apiJson('GET', `/api/flow/process/${iid}/trace`, token);
const rows = Array.isArray(t.json) ? t.json : (t.json?.data ?? []);
return (rows as any[]).filter((r) => r && r.current && r.taskId).length;
},
{ timeout: 15_000, message: `${key} start 后应有 current userTask(证部署流程含真 userTask)` },
)
.toBeGreaterThan(0);
}
test.afterAll(async () => {
try {
const tok = await adminToken();
for (const id of createdModelIds) {
await apiJson('DELETE', `/api/workflow/models/${id}`, tok);
}
} catch {
/* 清理尽力而为 */
}
});
// ────────────────────────────────────────────────────────────────────────────
// 场景 A:改存量全链(打开→会签保真读回→存草稿→发布→起实例→任务生成)
// ────────────────────────────────────────────────────────────────────────────
test('场景A 改存量全链:总包合同交底 打开→会签读回→存草稿→发布→起实例生成任务', async ({ page }) => {
test.setTimeout(150_000);
await loginAdmin(page);
// 打开存量会签流程(中文 key 必须 encodeURIComponent 进 URL)。
await page.goto(`/process-modeler?procKey=${encodeURIComponent(ZONGBAO_KEY)}`);
// 画布渲染完成:出现 bpmn 元素(.djs-element)。
await expect(page.locator('[data-testid="process-modeler-canvas"] .djs-element').first()).toBeVisible({
timeout: 30_000,
});
// 点会签 userTask「编写交底」→ EIP4 侧板会签控件可见 + 「启用会签」勾选(保真读回存量会签配置)。
await selectBpmnElement(page, COSIGN_TASK_ID);
await expect(page.getByTestId('process-modeler-eip4-panel')).toBeVisible();
await expect(page.getByTestId('eip4-cosign-toggle')).toBeChecked();
// 保存草稿 → URL 回填 ?modelId=(存量按 key 打开走 createDraft)。
await page.getByTestId('process-modeler-save-draft').click();
await page.waitForURL(/[?&]modelId=/, { timeout: 20_000 });
const modelId = rememberModelId(page);
expect(modelId, '存草稿后 URL 应回填 modelId').toBeTruthy();
// 存草稿会以 modelId 重载画布——等发布按钮重新可用(modelerReady)再点发布。
await expect(page.getByTestId('process-modeler-publish')).toBeEnabled({ timeout: 20_000 });
await page.getByTestId('process-modeler-publish').click();
// 同人确认弹窗:断言影响摘要含流程 key「总包合同交底」+ 版本迁移 + 运行中实例数。
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeVisible({ timeout: 20_000 });
await expect(page.getByTestId('publish-impact-key')).toContainText(ZONGBAO_KEY);
await expect(page.getByTestId('publish-impact-version')).toContainText(/首次发布|v\d+\s*→\s*v\d+/);
await expect(page.getByTestId('publish-impact-instances')).toHaveText(/\d/);
// 确认发布 → 成功后弹窗关闭(onPublished→onClose)。
await page.getByTestId('publish-confirm-btn').click();
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeHidden({ timeout: 30_000 });
// 起实例 + trace 断言:部署的新版本 start 后有 current userTask。
const tok = await adminToken();
await assertTaskGenerated(ZONGBAO_KEY, `E2E-A-${Date.now()}`, tok);
});
// ────────────────────────────────────────────────────────────────────────────
// 场景 B:新建全链(会签模板→填办理人→存草稿→发布→起实例→任务生成)
// ────────────────────────────────────────────────────────────────────────────
test('场景B 新建全链:会签模板新建→填办理人→存草稿→发布→起实例生成任务', async ({ page }) => {
test.setTimeout(150_000);
const newKey = `e2anew${Date.now()}`; // ASCII NCName → 直接作 process id,无需 idMap 还原
await loginAdmin(page);
await page.goto('/process-modeler');
// 打开器「+ 新建流程」→ NewProcessDialog。
await page.getByTestId('process-modeler-new').click();
await page.getByTestId('new-process-name').fill('会签E2E演示');
await page.getByTestId('new-process-key').fill(newKey);
await page.getByTestId('new-process-template').selectOption('cosign');
await page.getByTestId('new-process-confirm').click();
// 进编辑器:画布非空(模板实例化)。
await expect(page.locator('[data-testid="process-modeler-canvas"] .djs-element').first()).toBeVisible({
timeout: 20_000,
});
// 选会签 userTask(模板 id=task_cosign)→ 会签已启用(保真)→ 填办理人 content=ADMIN
//(会签集合非空,运行期才真产任务;空 content 会被 MI 跳过导致流程直接结束、无任务)。
await selectBpmnElement(page, 'task_cosign');
await expect(page.getByTestId('eip4-cosign-toggle')).toBeChecked();
await page.getByTestId('eip4-cosign-content-0').fill('ADMIN');
// 保存草稿 → URL 回填 modelId。
await page.getByTestId('process-modeler-save-draft').click();
await page.waitForURL(/[?&]modelId=/, { timeout: 20_000 });
rememberModelId(page);
// 发布。
await expect(page.getByTestId('process-modeler-publish')).toBeEnabled({ timeout: 20_000 });
await page.getByTestId('process-modeler-publish').click();
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeVisible({ timeout: 20_000 });
await expect(page.getByTestId('publish-impact-key')).toContainText(newKey);
await page.getByTestId('publish-confirm-btn').click();
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeHidden({ timeout: 30_000 });
// 起实例 + trace 断言:新建部署的会签流程 start 后有 current userTask。
const tok = await adminToken();
await assertTaskGenerated(newKey, `E2E-B-${Date.now()}`, tok);
});
// ────────────────────────────────────────────────────────────────────────────
// 场景 C:走查(中文节点/palette/双面板同屏)+ 权限(超管门 403)
// ────────────────────────────────────────────────────────────────────────────
test('场景C 走查+权限:中文节点/palette/标准面板+EIP4侧板同屏 + 超管门403', async ({ page }) => {
test.setTimeout(120_000);
await loginAdmin(page);
await page.goto(`/process-modeler?procKey=${encodeURIComponent(ZONGBAO_KEY)}`);
const canvas = page.locator('[data-testid="process-modeler-canvas"]');
await expect(canvas.locator('.djs-element').first()).toBeVisible({ timeout: 30_000 });
// ① 中文节点名渲染正常(存量会签流程节点「编写交底」「接收交底」)。
await expect(canvas.getByText('编写交底')).toBeVisible();
await expect(canvas.getByText('接收交底')).toBeVisible();
// ② palette 元素齐(bpmn-js Modeler 左侧工具箱有多个可拖建条目)。
await expect(page.locator('[data-testid="process-modeler-root"] .djs-palette').first()).toBeVisible();
expect(await page.locator('[data-testid="process-modeler-root"] .djs-palette .entry').count()).toBeGreaterThan(4);
// ③ 标准属性面板 + EIP4 侧板同屏(选中会签 userTask 后 EIP4 侧板出真控件,与标准面板宿主并存)。
await selectBpmnElement(page, COSIGN_TASK_ID);
await expect(page.getByTestId('process-modeler-eip4-panel')).toBeVisible();
await expect(page.getByTestId('eip4-cosign-toggle')).toBeVisible();
await expect(page.getByTestId('process-modeler-props')).toBeVisible();
// ④ 超管门 403:dev 库无 alice/123456 → 降级为「非超管凭据打 deploy/models → 403」等价断言。
const alice = await apiJson('POST', '/api/auth/login', undefined, { account: 'alice', password: '123456' });
expect(alice.json?.success, 'dev 库无 alice 账号(记录账号缺席)').toBeFalsy();
// 无 token(非超管)打 Modeler 网关端点 → requireSuperAdmin 拒 403(与合法非超管 token 同一拒绝分支)。
const denyDeploy = await apiJson('POST', '/api/workflow/models/nonexistent/deploy');
expect(denyDeploy.status, '非超管访问 deploy 端点应 403').toBe(403);
const denyModels = await apiJson('GET', '/api/workflow/models');
expect(denyModels.status, '非超管访问 models 列表应 403').toBe(403);
// 对照:admin(超管)打 models → 200,证超管门按身份区分放行,非一律拒。
const tok = await adminToken();
const allowModels = await apiJson('GET', '/api/workflow/models', tok);
expect(allowModels.status, 'admin 超管访问 models 应 200').toBe(200);
});

View File

@@ -0,0 +1,169 @@
/**
* AI recipe 渲染冒烟门(M-Gate 的可执行化)。
*
* 把「手动用浏览器验 AI 生成页是否真渲染成 house-style」codify 成一条可复用断言:
* 给定一个 templateId,从【已生成并 served】的页面 schema 自推期望(列/动作),再断言
* amis 真把它渲染成无错 DOM——补上 critic 点名「playwright-render 名实不符(从不真渲染)」的缺口。
*
* 断言(schema 驱动,recipe 无关):
* ① amis-host 可见 且 无 schema-error-card → 渲染无致命错
* ② body=crud,且 schema 每个数据列 label 出现在表头 → 列真渲染
* ③ schema 里每个 {type:button} 的 label 出现在页面 → 工具栏/节点动作真渲染
* ④ tbody 无裸 true/false、无裸 ISO 时间串 → 列渲染类型(是/否、日期格式)生效
* ⑤ 0 pageerror + 0 console.error → 无运行时报错
*
* 入参(env):RECIPE_SMOKE_TEMPLATE(必填,templateId)。
* 前置:localhost:5174(前端 dev)+ localhost:8093(后端 dev)。页面须已 served。
* 运行:RECIPE_SMOKE_TEMPLATE=<id> npx playwright test --config=playwright.recipe-smoke.config.ts
*/
import { expect, test, type Page, type ConsoleMessage } from '@playwright/test';
import * as http from 'node:http';
import * as path from 'node:path';
import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const TEMPLATE_ID = process.env.RECIPE_SMOKE_TEMPLATE ?? '';
const ARTIFACT_DIR = path.join(__dirname, 'artifacts', 'recipe-render-smoke');
let _tokenCache: string | null = null;
function getJson<T>(reqPath: string, body?: string): Promise<T> {
return new Promise((resolve, reject) => {
const req = http.request(
{
hostname: 'localhost',
port: 8093,
path: reqPath,
method: body ? 'POST' : 'GET',
headers: body
? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }
: {},
},
(res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => {
try {
resolve(JSON.parse(data) as T);
} catch (e) {
reject(new Error(`非 JSON 响应 ${reqPath}: ${data.slice(0, 200)}`));
}
});
},
);
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
async function getToken(): Promise<string> {
if (_tokenCache) return _tokenCache;
const parsed = await getJson<{ success: boolean; token: string }>(
'/api/auth/login',
JSON.stringify({ account: 'admin', password: '111111' }),
);
if (!parsed.success) throw new Error('登录失败');
_tokenCache = parsed.token;
return parsed.token;
}
async function seedAuth(page: Page) {
const token = await getToken();
await page.addInitScript(
({ t }: { t: string }) => {
localStorage.setItem('eip4_token', t);
localStorage.setItem(
'eip4_profile',
JSON.stringify({ userId: 'ADMIN', account: 'admin', name: '系统管理员', roles: [] }),
);
},
{ t: token },
);
}
/** 递归收集 schema 中所有 {type:'button'} 节点的 label —— 工具栏 + 节点操作动作。 */
function collectButtonLabels(node: unknown, out: Set<string>): void {
if (Array.isArray(node)) {
node.forEach((n) => collectButtonLabels(n, out));
return;
}
if (node && typeof node === 'object') {
const obj = node as Record<string, unknown>;
if (obj.type === 'button' && typeof obj.label === 'string' && obj.label.trim()) {
out.add(obj.label.trim());
}
Object.values(obj).forEach((v) => collectButtonLabels(v, out));
}
}
test.beforeAll(() => {
fs.mkdirSync(ARTIFACT_DIR, { recursive: true });
if (!TEMPLATE_ID) throw new Error('缺 env RECIPE_SMOKE_TEMPLATE');
});
test(`AI recipe 页 ${TEMPLATE_ID} 渲染成无错 house-style DOM`, async ({ page }) => {
// 0 console.error / pageerror 收集(house-style 页应零报错)。
const consoleErrors: string[] = [];
page.on('console', (m: ConsoleMessage) => {
if (m.type() === 'error') consoleErrors.push(m.text());
});
page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${e.message}`));
// 自推期望:从 served schema 拿数据列 label 与所有按钮 label。
const schema = await getJson<{
body?: { type?: string; columns?: Array<{ name?: string; label?: string; type?: string }> };
}>(`/api/page/schema/${TEMPLATE_ID}`);
expect(schema.body?.type, 'body.type 应为 crud').toBe('crud');
const dataColumnLabels = (schema.body?.columns ?? [])
.filter((c) => c.name && c.label && c.type !== 'operation')
.map((c) => c.label!) as string[];
const buttonLabels = new Set<string>();
collectButtonLabels(schema, buttonLabels);
await seedAuth(page);
await page.goto(`/page/${TEMPLATE_ID}`);
// ① 渲染完成且无致命错卡。
await expect(page.locator('[data-testid="amis-host"]')).toBeVisible({ timeout: 45_000 });
await expect(page.locator('[data-testid="schema-error-card"]')).not.toBeVisible();
await page
.waitForSelector(
'[data-testid="amis-host"] table, [data-testid="amis-host"] .cxd-CRUD',
{ timeout: 20_000 },
)
.catch(() => {/* 空表也算渲染成功,继续 */});
await page.screenshot({
path: path.join(ARTIFACT_DIR, `${TEMPLATE_ID}-full.png`),
fullPage: true,
});
const bodyText = (await page.textContent('body')) ?? '';
// ② 每个数据列 label 出现在页面(表头)。
for (const label of dataColumnLabels) {
expect(bodyText, `列「${label}」应渲染`).toContain(label);
}
// ③ 每个按钮 label 出现在页面(工具栏/节点动作真渲染)。
for (const label of Array.from(buttonLabels)) {
expect(bodyText, `动作「${label}」应渲染`).toContain(label);
}
// ④ 列渲染类型生效:表体无裸 true/false、无裸 ISO 时间串。
const tbodyText = await page
.evaluate(() => document.querySelector('tbody')?.textContent ?? '')
.catch(() => '');
if (tbodyText.trim()) {
expect(tbodyText, '布尔列应渲染为 是/否,而非裸 true').not.toMatch(/\btrue\b/);
expect(tbodyText, '布尔列应渲染为 是/否,而非裸 false').not.toMatch(/\bfalse\b/);
expect(tbodyText, '日期列应格式化,而非裸 ISO 串').not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
}
// ⑤ 0 console.error / pageerror。
expect(consoleErrors, `控制台报错:\n${consoleErrors.join('\n')}`).toHaveLength(0);
});

View File

@@ -5,12 +5,15 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EIP4 页面设计器</title> <title>EIP4 页面设计器</title>
<!-- amis-editor 独立入口:用 npm 包版 amis,与主应用 sdk-local 完全隔离 --> <!-- amis-editor 独立入口:用 npm 包版 amis,与主应用 sdk-local 完全隔离 -->
<!-- CSS 在 HTML 里直接引用,绕开 vite esbuild 对 amis-ui 包路径的解析 --> <!-- CSS 由 src/editor/main.tsx import 引入(vite build 收集进 dist,避免绝对包路径在生产构建 404)-->
<link rel="stylesheet" href="/node_modules/amis-editor-core/lib/style.css" />
<link rel="stylesheet" href="/node_modules/amis-ui/lib/themes/default.css" />
<link rel="stylesheet" href="/node_modules/amis-ui/lib/helper.css" />
<style> <style>
html, body, #editor-root { height: 100%; margin: 0; overflow: hidden; } html, body, #editor-root { height: 100%; margin: 0; overflow: hidden; }
/* amis-editor 自带 CSS 未把 .ae-Editor 约束到容器高度 → 它按内容自然撑高(高页面如
新闻管理可达 2800px)、超出被外层 overflow:hidden 裁掉、画布「滚不动、看不到底部」。
强制 .ae-Editor 填满父容器高度 → 编辑器适配视口,画布(.ae-Preview-body 本就
overflow:auto)自行内部滚动长页面,三栏框架固定不动。 */
.ae-Editor { height: 100% !important; }
.ae-Editor-inner { height: 100% !important; min-height: 0 !important; }
</style> </style>
</head> </head>
<body> <body>

1205
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,10 @@
"test": "vitest run" "test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@bpmn-io/properties-panel": "^3.47.0",
"axios": "1.7.9", "axios": "1.7.9",
"bpmn-js": "^17.11.1",
"bpmn-js-properties-panel": "^5.60.0",
"react": "18.3.1", "react": "18.3.1",
"react-dom": "18.3.1", "react-dom": "18.3.1",
"react-router-dom": "6.28.0" "react-router-dom": "6.28.0"
@@ -31,6 +34,7 @@
"amis-formula": "^6.13.0", "amis-formula": "^6.13.0",
"amis-theme-editor-helper": "^6.12.0-ab.1", "amis-theme-editor-helper": "^6.12.0-ab.1",
"amis-ui": "^6.13.0", "amis-ui": "^6.13.0",
"bpmn-moddle": "^8.1.0",
"i18n-runtime": "^1.0.13", "i18n-runtime": "^1.0.13",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"typescript": "5.6.3", "typescript": "5.6.3",

View File

@@ -0,0 +1,26 @@
import { defineConfig, devices } from '@playwright/test';
// 人走五环 UI 点穿 e2e 专用配置:webServer 反代到 8094(含本特性新代码),
// 与默认 playwright.config.ts(反代 8093 dev)隔离,不影响你正在跑的 8093。
// 先单独启动 8094 后端,再 `npx playwright test -c playwright.fivering.config.ts`。
export default defineConfig({
testDir: './e2e',
testMatch: /(five-ring|master-detail)\.spec\.ts/,
fullyParallel: false,
workers: 1,
timeout: 120_000,
reporter: [['list']],
use: {
baseURL: 'http://localhost:5174',
trace: 'off',
screenshot: 'only-on-failure',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
webServer: {
command:
'NODE_OPTIONS=--max-http-header-size=65536 VITE_BACKEND_TARGET=http://localhost:8094 npx vite --port 5174 --strictPort',
url: 'http://localhost:5174',
reuseExistingServer: false,
timeout: 120_000,
},
});

View File

@@ -0,0 +1,36 @@
import { defineConfig, devices } from '@playwright/test';
// 在线流程 Modeler live e2e 专用配置(T4.2)。
//
// 复用主会话已在跑的 vite dev(5173,vite.config 默认 proxy /api → http://localhost:8093),
// 后端指向当前 live 的 8093 网关 + 8089 flowable-service + 真库 eip4(含 T3.1/T3.2/T4.1 全部新代码)。
// 与 fivering 配置(自起 vite 5174 → 8094)隔离:本配置 reuseExistingServer 复用 5173,不新起端口。
//
// 依赖(跑前须在线,spec 头注释有 curl 自检):
// - 8093 网关/后端(curl -s -o /dev/null -w '%{http_code}' localhost:8093/v3/api-docs → 200)
// - 8089 flowable-service(经 8093 转发;start/trace 走它)
// - 5173 vite dev(curl localhost:5173 → 200;apiJson 直连 8093,与 UI 经 5173 代理同一后端)
// 跑法:npx playwright test -c playwright.process-modeler.config.ts
export default defineConfig({
testDir: './e2e',
testMatch: /process-modeler\.spec\.ts/,
fullyParallel: false,
workers: 1,
timeout: 180_000,
reporter: [['list']],
use: {
baseURL: 'http://localhost:5173',
trace: 'off',
screenshot: 'only-on-failure',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
webServer: {
// reuseExistingServer:true → 5173 已在跑(主会话 npm run dev)则复用、不新起;
// 未跑时按 dev 同口径(VITE_BACKEND_TARGET=8093)拉起。
command:
'NODE_OPTIONS=--max-http-header-size=65536 VITE_BACKEND_TARGET=http://localhost:8093 npx vite --port 5173 --strictPort',
url: 'http://localhost:5173',
reuseExistingServer: true,
timeout: 120_000,
},
});

View File

@@ -0,0 +1,30 @@
import { defineConfig, devices } from '@playwright/test';
// ────────────────────────────────────────────────────────────────────────────
// AI recipe 渲染冒烟门专属配置(M-Gate 可执行化)。
//
// 与默认 playwright.config.ts 的区别(关键):
// - 复用【已在跑】的 5174 dev server,不自拉 webServer(不重启任何服务)。
// - 仅匹配 recipe-render-smoke.spec.ts。
//
// 一键跑(含生成/清理):见 recipe-render-smoke.sh
// 单跑某页:RECIPE_SMOKE_TEMPLATE=<id> npx playwright test --config=playwright.recipe-smoke.config.ts
// 前置:localhost:5174(前端 dev)+ localhost:8093(后端 dev/eip4dev)。
// ────────────────────────────────────────────────────────────────────────────
export default defineConfig({
testDir: './e2e',
testMatch: /recipe-render-smoke\.spec\.ts/,
fullyParallel: false,
workers: 1,
timeout: 90_000,
reporter: [['list']],
outputDir: './e2e/artifacts/recipe-render-smoke/_pw-output',
use: {
baseURL: 'http://localhost:5174',
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
video: 'off',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
// 故意不配置 webServer —— 复用已在跑的 5174,不重启。
});

66
recipe-render-smoke.sh Executable file
View File

@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# AI recipe 渲染冒烟门 —— 一键端到端(M-Gate 可执行化)。
#
# 把「手动用浏览器验 AI 生成页渲染成 house-style」codify 成一条命令:
# 1) 登录拿 admin token
# 2) 经 AI pipeline 生成 1 个 maintenance + 1 个 tree 隔离样例(auto-develop)
# 3) 用 recipe-render-smoke.spec 断言两页真渲染成无错 house-style DOM
# 4) DROP 表 + 删三真相行清理(trap 保证失败也清,sys_ai_* 审计保留)
#
# 前置:localhost:8093(后端 dev/eip4dev)+ localhost:5174(前端 dev)+ psql:5433。
# 跑: cd eip4-web && ./recipe-render-smoke.sh
# ─────────────────────────────────────────────────────────────────────────────
set -uo pipefail
BACKEND="${BACKEND:-http://localhost:8093}"
PGHOST="${PGHOST:-localhost}"; PGPORT="${PGPORT:-5433}"; PGUSER="${PGUSER:-zhengwr}"; PGDB="${PGDB:-eip4dev}"
export PGPASSWORD="${PGPASSWORD:-}"
SMOKE_TABLES=(EIP4AI_SMOKE_M EIP4AI_SMOKE_T)
psql_run() { psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDB" -v ON_ERROR_STOP=1 -At "$@"; }
cleanup() {
for t in "${SMOKE_TABLES[@]}"; do
local tpl tbl
tpl="$(echo "$t" | tr 'A-Z_' 'a-z-')" # EIP4AI_SMOKE_M → eip4ai-smoke-m (templateId)
tbl="$(echo "$t" | tr 'A-Z' 'a-z')" # EIP4AI_SMOKE_M → eip4ai_smoke_m (物理表,PG 折叠小写)
psql_run -c "DROP TABLE IF EXISTS eip3.${tbl};
DELETE FROM eip3.sys_entity WHERE upper(tablename)='${t}';
DELETE FROM eip3.sys_page_schema WHERE template_id='${tpl}';
DELETE FROM eip3.sys_serviceflow WHERE upper(sys_serviceflow_id) LIKE '${t}\\_%';
DELETE FROM eip3.sys_menu WHERE view_templateid='${tpl}';" >/dev/null 2>&1
done
echo "🧹 清理完成(${SMOKE_TABLES[*]})"
}
trap cleanup EXIT
login() {
curl -s -X POST "$BACKEND/api/auth/login" -H 'Content-Type: application/json' \
-d '{"account":"admin","password":"111111"}' \
| python3 -c "import sys,json;print(json.load(sys.stdin).get('token',''))"
}
# auto_dev <table> <templateId> <entityName> <recipe>
auto_dev() {
local table="$1" tpl="$2" name="$3" recipe="$4"
curl -s -X POST "$BACKEND/api/ai/features/auto-develop" \
-H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
-d "{\"feature\":{\"objective\":\"render-smoke\",\"featureName\":\"${name}维护\",\"tableName\":\"${table}\",\"entityName\":\"${name}\",\"templateId\":\"${tpl}\",\"menuName\":\"${name}\",\"fields\":[{\"column\":\"NAME\",\"label\":\"名称\",\"type\":\"string\",\"length\":100,\"required\":true},{\"column\":\"ENABLED\",\"label\":\"启用\",\"type\":\"boolean\",\"required\":false}],\"pageRecipe\":\"${recipe}\"},\"baseUrl\":\"${BACKEND}\",\"generateDeploymentPackage\":true,\"maxRepairAttempts\":2}" \
| python3 -c "import sys,json;d=json.load(sys.stdin);print((d.get('applyRun') or {}).get('status','?'))"
}
echo "🔑 登录…"; TOKEN="$(login)"
[ -n "$TOKEN" ] || { echo "❌ 登录失败"; exit 1; }
echo "🏗 生成 maintenance 样例…"; [ "$(auto_dev EIP4AI_SMOKE_M eip4ai-smoke-m 列渲染样例 maintenance-crud-v1)" = "PASSED" ] || { echo "❌ maintenance apply 未 PASSED"; exit 1; }
echo "🌲 生成 tree 样例…"; [ "$(auto_dev EIP4AI_SMOKE_T eip4ai-smoke-t 树样例 tree-crud-v1)" = "PASSED" ] || { echo "❌ tree apply 未 PASSED"; exit 1; }
rc=0
for tpl in eip4ai-smoke-m eip4ai-smoke-t; do
echo "🖥 渲染断言 $tpl …"
RECIPE_SMOKE_TEMPLATE="$tpl" npx playwright test --config=playwright.recipe-smoke.config.ts || rc=1
done
[ "$rc" = 0 ] && echo "✅ recipe 渲染冒烟全绿" || echo "❌ recipe 渲染冒烟有失败"
exit "$rc"

48
src/App.routes.test.tsx Normal file
View File

@@ -0,0 +1,48 @@
import '@testing-library/jest-dom';
import { render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { vi, describe, it, expect } from 'vitest';
import { NewFeatureShell } from './pages/NewFeatureShell';
import { AiFeatureForm } from './pages/AiFeatureForm';
vi.mock('./auth/token', async (importOriginal) => ({
...(await importOriginal<typeof import('./auth/token')>()),
getProfile: () => ({ userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }),
}));
vi.mock('./api/meta', () => ({ listEntities: vi.fn().mockResolvedValue([]), createEntity: vi.fn() }));
vi.mock('./api/recipe', () => ({
listRecipes: () => [{ id: 'maintenance-crud-v1', label: '维护型 CRUD' }],
compileRecipe: vi.fn(),
}));
vi.mock('./api/publish', () => ({ publishFeature: vi.fn() }));
vi.mock('./api/menu', () => ({ fetchMenu: vi.fn().mockResolvedValue({ roots: [] }), collectLeaves: vi.fn() }));
vi.mock('./api/ai', async (io) => {
const actual = await io<typeof import('./api/ai')>();
return { ...actual, autoDevelop: vi.fn() };
});
describe('新路由可达', () => {
it('/new-feature 渲染 NewFeatureShell', async () => {
render(
<MemoryRouter initialEntries={['/new-feature']}>
<Routes>
<Route path="/new-feature" element={<NewFeatureShell />} />
<Route path="/ai-feature" element={<AiFeatureForm />} />
</Routes>
</MemoryRouter>,
);
await waitFor(() => expect(screen.getByTestId('new-feature-shell')).toBeInTheDocument());
});
it('/ai-feature 渲染 AiFeatureForm', () => {
render(
<MemoryRouter initialEntries={['/ai-feature']}>
<Routes>
<Route path="/new-feature" element={<NewFeatureShell />} />
<Route path="/ai-feature" element={<AiFeatureForm />} />
</Routes>
</MemoryRouter>,
);
expect(screen.getByTestId('ai-feature-form')).toBeInTheDocument();
});
});

View File

@@ -7,6 +7,11 @@ import { LoginPage } from './pages/LoginPage';
import { PageRenderPage } from './pages/PageRenderPage'; import { PageRenderPage } from './pages/PageRenderPage';
import { TodoPage } from './pages/TodoPage'; import { TodoPage } from './pages/TodoPage';
import { WorkbenchPage } from './pages/WorkbenchPage'; import { WorkbenchPage } from './pages/WorkbenchPage';
import { DesignCenterPage } from './pages/DesignCenterPage';
import { NewFeatureShell } from './pages/NewFeatureShell';
import { AiFeatureForm } from './pages/AiFeatureForm';
import { ModelerPage } from './pages/ModelerPage';
import { ProcessModelerPage } from './pages/ProcessModelerPage';
// 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate) // 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate)
function UnauthorizedBridge() { function UnauthorizedBridge() {
@@ -37,6 +42,15 @@ export default function App() {
<Route path="/workbench" element={<WorkbenchPage />} /> <Route path="/workbench" element={<WorkbenchPage />} />
<Route path="/todo" element={<TodoPage />} /> <Route path="/todo" element={<TodoPage />} />
<Route path="/page/:templateId" element={<PageRenderPage />} /> <Route path="/page/:templateId" element={<PageRenderPage />} />
{/* 设计中心(管理员集中式低代码设计入口,替代每页设计按钮)*/}
<Route path="/design-center" element={<DesignCenterPage />} />
{/* 人走五环统一编排壳(向导内选页面类型:单表/树/主子表)+ AI ①面入口(admin-gated)*/}
<Route path="/new-feature" element={<NewFeatureShell />} />
<Route path="/ai-feature" element={<AiFeatureForm />} />
{/* 建模器(五环第①环·元数据→表,仅管理员)*/}
<Route path="/modeler" element={<ModelerPage />} />
{/* 在线流程 Modeler(可编辑 BPMN 设计器,仅管理员)*/}
<Route path="/process-modeler" element={<ProcessModelerPage />} />
{/* 根路径默认跳工作台 */} {/* 根路径默认跳工作台 */}
<Route index element={<Navigate to="/workbench" replace />} /> <Route index element={<Navigate to="/workbench" replace />} />
</Route> </Route>

View File

@@ -0,0 +1,12 @@
export const OPEN_APPROVAL_DRAWER_EVENT = 'eip4:open-approval-drawer';
export const APPROVAL_COMPLETED_EVENT = 'eip4:approval-completed';
export interface ApprovalDrawerRequest {
taskId?: string;
taskName?: string;
processInstanceId?: string;
businessKey?: string;
businessTable?: string;
businessSummary?: Record<string, unknown>;
readOnly?: boolean;
}

View File

@@ -0,0 +1,9 @@
export const OPEN_MESSAGE_DETAIL_EVENT = 'eip4:open-message-detail';
export const MESSAGE_DETAIL_CHANGED_EVENT = 'eip4:message-detail-changed';
export interface MessageDetailRequest {
kind: 'received' | 'sent';
receiveId?: string;
messageId?: string;
title?: string;
}

View File

@@ -0,0 +1,122 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { OPEN_APPROVAL_DRAWER_EVENT } from './approvalActionEvents';
import { registerApprovalAction, __resetApprovalActionForTest } from './registerApprovalAction';
interface RunCtx {
run: (action: { args?: Record<string, unknown> }, renderer: unknown, event: unknown) => Promise<void>;
}
describe('registerApprovalAction', () => {
beforeEach(() => {
__resetApprovalActionForTest();
});
it('amis-core 缺 registerAction 时返回 false(静默降级)', () => {
expect(registerApprovalAction(null)).toBe(false);
expect(registerApprovalAction({})).toBe(false);
});
it('注册 openApprovalDrawer 动作(幂等)', () => {
const registerAction = vi.fn();
const core = { registerAction };
expect(registerApprovalAction(core)).toBe(true);
expect(registerAction).toHaveBeenCalledTimes(1);
expect(registerAction.mock.calls[0][0]).toBe('openApprovalDrawer');
expect(registerApprovalAction(core)).toBe(true);
expect(registerAction).toHaveBeenCalledTimes(1);
});
it('run 把 taskId 等参数派发为全局审批抽屉事件', async () => {
let captured: RunCtx | null = null;
registerApprovalAction({
registerAction: (_type: string, action: RunCtx) => {
captured = action;
},
});
expect(captured).not.toBeNull();
const seen: unknown[] = [];
const listener = (event: Event) => {
seen.push((event as CustomEvent).detail);
};
window.addEventListener(OPEN_APPROVAL_DRAWER_EVENT, listener);
try {
await captured!.run({
args: {
taskId: 'task-1',
taskName: '审核',
processInstanceId: 'pi-1',
businessKey: 'biz-1',
businessTable: 'PM_DEMO',
readOnly: 'true',
},
}, {}, {});
} finally {
window.removeEventListener(OPEN_APPROVAL_DRAWER_EVENT, listener);
}
expect(seen).toHaveLength(1);
expect(seen[0]).toEqual({
taskId: 'task-1',
taskName: '审核',
processInstanceId: 'pi-1',
businessKey: 'biz-1',
businessTable: 'PM_DEMO',
businessSummary: undefined,
readOnly: true,
});
});
it('缺 taskId 但有 businessKey 时仍派发只读历史审批事件', async () => {
let captured: RunCtx | null = null;
registerApprovalAction({
registerAction: (_type: string, action: RunCtx) => {
captured = action;
},
});
const seen: unknown[] = [];
const listener = (event: Event) => {
seen.push((event as CustomEvent).detail);
};
window.addEventListener(OPEN_APPROVAL_DRAWER_EVENT, listener);
try {
await captured!.run({
args: {
taskName: '审批详情',
businessKey: 'biz-1',
businessTable: 'PM_DEMO',
readOnly: true,
},
}, {}, {});
} finally {
window.removeEventListener(OPEN_APPROVAL_DRAWER_EVENT, listener);
}
expect(seen).toHaveLength(1);
expect(seen[0]).toEqual({
taskId: undefined,
taskName: '审批详情',
processInstanceId: undefined,
businessKey: 'biz-1',
businessTable: 'PM_DEMO',
businessSummary: undefined,
readOnly: true,
});
});
it('缺 taskId/businessKey/processInstanceId 时不派发事件', async () => {
let captured: RunCtx | null = null;
registerApprovalAction({
registerAction: (_type: string, action: RunCtx) => {
captured = action;
},
});
const listener = vi.fn();
window.addEventListener(OPEN_APPROVAL_DRAWER_EVENT, listener);
try {
await captured!.run({ args: { taskName: '审核' } }, {}, {});
} finally {
window.removeEventListener(OPEN_APPROVAL_DRAWER_EVENT, listener);
}
expect(listener).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,83 @@
import { OPEN_APPROVAL_DRAWER_EVENT, type ApprovalDrawerRequest } from './approvalActionEvents';
interface OpenApprovalActionArg {
args?: {
taskId?: unknown;
taskName?: unknown;
processInstanceId?: unknown;
businessKey?: unknown;
businessTable?: unknown;
businessSummary?: unknown;
readOnly?: unknown;
readonly?: unknown;
mode?: unknown;
};
[key: string]: unknown;
}
interface AmisRenderer {
[key: string]: unknown;
}
interface AmisEvent {
[key: string]: unknown;
}
interface AmisCore {
registerAction?: (type: string, action: unknown) => void;
}
let registered = false;
function asString(v: unknown): string | undefined {
if (v === null || v === undefined) return undefined;
const s = String(v).trim();
return s ? s : undefined;
}
function asRecord(v: unknown): Record<string, unknown> | undefined {
return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined;
}
function asBoolean(v: unknown): boolean {
return v === true || v === 'true' || v === 1 || v === '1';
}
/**
* 注册 converted amis 页使用的审批抽屉动作。
*
* 转换器只生成通用动作,不直接依赖 React 状态;这里把 amis click 转成应用级事件,
* 由 AppShell 挂载真实 ApprovalDrawer。
*/
export function registerApprovalAction(amisCore: AmisCore | undefined | null): boolean {
if (registered) return true;
if (!amisCore || typeof amisCore.registerAction !== 'function') return false;
amisCore.registerAction('openApprovalDrawer', {
async run(action: OpenApprovalActionArg, _renderer: AmisRenderer, _event: AmisEvent) {
const args = action?.args ?? {};
const taskId = asString(args.taskId);
const processInstanceId = asString(args.processInstanceId);
const businessKey = asString(args.businessKey);
if (!taskId && !processInstanceId && !businessKey) return;
const mode = asString(args.mode);
const detail: ApprovalDrawerRequest = {
taskId,
taskName: asString(args.taskName),
processInstanceId,
businessKey,
businessTable: asString(args.businessTable),
businessSummary: asRecord(args.businessSummary),
readOnly: asBoolean(args.readOnly) || asBoolean(args.readonly) || mode === 'read',
};
window.dispatchEvent(new CustomEvent<ApprovalDrawerRequest>(OPEN_APPROVAL_DRAWER_EVENT, { detail }));
},
});
registered = true;
return true;
}
export function __resetApprovalActionForTest(): void {
registered = false;
}

View File

@@ -0,0 +1,76 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { OPEN_MESSAGE_DETAIL_EVENT } from './messageActionEvents';
import { registerMessageAction, __resetMessageActionForTest } from './registerMessageAction';
interface RunCtx {
run: (action: { args?: Record<string, unknown> }, renderer: unknown, event: unknown) => Promise<void>;
}
describe('registerMessageAction', () => {
beforeEach(() => {
__resetMessageActionForTest();
});
it('amis-core 缺 registerAction 时返回 false', () => {
expect(registerMessageAction(null)).toBe(false);
expect(registerMessageAction({})).toBe(false);
});
it('注册 openMessageDetail 动作(幂等)', () => {
const registerAction = vi.fn();
const core = { registerAction };
expect(registerMessageAction(core)).toBe(true);
expect(registerAction).toHaveBeenCalledTimes(1);
expect(registerAction.mock.calls[0][0]).toBe('openMessageDetail');
expect(registerMessageAction(core)).toBe(true);
expect(registerAction).toHaveBeenCalledTimes(1);
});
it('received 消息派发 receiveId', async () => {
let captured: RunCtx | null = null;
registerMessageAction({
registerAction: (_type: string, action: RunCtx) => {
captured = action;
},
});
const seen: unknown[] = [];
const listener = (event: Event) => seen.push((event as CustomEvent).detail);
window.addEventListener(OPEN_MESSAGE_DETAIL_EVENT, listener);
try {
await captured!.run({
args: { kind: 'received', receiveId: 'recv-1', title: '消息' },
}, {}, {});
} finally {
window.removeEventListener(OPEN_MESSAGE_DETAIL_EVENT, listener);
}
expect(seen).toEqual([{ kind: 'received', receiveId: 'recv-1', messageId: undefined, title: '消息' }]);
});
it('sent 消息派发 messageId,缺 id 不派发', async () => {
let captured: RunCtx | null = null;
registerMessageAction({
registerAction: (_type: string, action: RunCtx) => {
captured = action;
},
});
const listener = vi.fn();
window.addEventListener(OPEN_MESSAGE_DETAIL_EVENT, listener);
try {
await captured!.run({ args: { kind: 'sent' } }, {}, {});
await captured!.run({ args: { kind: 'sent', messageId: 'msg-1' } }, {}, {});
} finally {
window.removeEventListener(OPEN_MESSAGE_DETAIL_EVENT, listener);
}
expect(listener).toHaveBeenCalledTimes(1);
expect((listener.mock.calls[0][0] as CustomEvent).detail).toEqual({
kind: 'sent',
receiveId: undefined,
messageId: 'msg-1',
title: undefined,
});
});
});

View File

@@ -0,0 +1,65 @@
import { OPEN_MESSAGE_DETAIL_EVENT, type MessageDetailRequest } from './messageActionEvents';
interface OpenMessageActionArg {
args?: {
kind?: unknown;
receiveId?: unknown;
messageId?: unknown;
title?: unknown;
};
[key: string]: unknown;
}
interface AmisRenderer {
[key: string]: unknown;
}
interface AmisEvent {
[key: string]: unknown;
}
interface AmisCore {
registerAction?: (type: string, action: unknown) => void;
}
let registered = false;
function asString(v: unknown): string | undefined {
if (v === null || v === undefined) return undefined;
const s = String(v).trim();
return s ? s : undefined;
}
function asKind(v: unknown): MessageDetailRequest['kind'] {
return asString(v) === 'sent' ? 'sent' : 'received';
}
export function registerMessageAction(amisCore: AmisCore | undefined | null): boolean {
if (registered) return true;
if (!amisCore || typeof amisCore.registerAction !== 'function') return false;
amisCore.registerAction('openMessageDetail', {
async run(action: OpenMessageActionArg, _renderer: AmisRenderer, _event: AmisEvent) {
const args = action?.args ?? {};
const kind = asKind(args.kind);
const receiveId = asString(args.receiveId);
const messageId = asString(args.messageId);
if (kind === 'received' && !receiveId) return;
if (kind === 'sent' && !messageId) return;
const detail: MessageDetailRequest = {
kind,
receiveId,
messageId,
title: asString(args.title),
};
window.dispatchEvent(new CustomEvent<MessageDetailRequest>(OPEN_MESSAGE_DETAIL_EVENT, { detail }));
},
});
registered = true;
return true;
}
export function __resetMessageActionForTest(): void {
registered = false;
}

View File

@@ -0,0 +1,88 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
normalizeUserTransferSchemaTree,
registerUserTransferPicker,
__resetUserTransferPickerForTest,
} from './registerUserTransferPicker';
describe('registerUserTransferPicker', () => {
beforeEach(() => {
__resetUserTransferPickerForTest();
});
it('amis-core 缺注册能力时返回 false(静默降级)', () => {
expect(registerUserTransferPicker(null)).toBe(false);
expect(registerUserTransferPicker({})).toBe(false);
});
it('注册 schema filter,把老单选用户框改成标准 picker', () => {
let filter: ((schema: Record<string, unknown>) => Record<string, unknown>) | null = null;
const addSchemaFilter = vi.fn((fn) => {
filter = fn;
});
const registerFormItem = vi.fn();
expect(registerUserTransferPicker({ addSchemaFilter, registerFormItem })).toBe(true);
expect(addSchemaFilter).toHaveBeenCalledTimes(1);
expect(filter).not.toBeNull();
const normalized = filter!({ type: 'user-transfer-picker', mode: 'controlled', name: 'AGENT' });
expect(normalized).toMatchObject({
type: 'picker',
name: 'AGENT',
source: '/api/picker/76d2f950-ef40-4eff-89ec-98ad9a4976b9/list',
labelField: '_label',
valueField: '_id',
modalMode: 'dialog',
modalSize: 'lg',
placeholder: '请点击右侧的图标',
});
expect(filter!({ type: 'select', mode: 'multiple' })).toEqual({ type: 'select', mode: 'multiple' });
});
it('只注册 schema filter,不再注册旧自定义控件', () => {
const registerFormItem = vi.fn();
const addSchemaFilter = vi.fn();
expect(registerUserTransferPicker({ addSchemaFilter, registerFormItem })).toBe(true);
expect(registerFormItem).not.toHaveBeenCalled();
expect(addSchemaFilter).toHaveBeenCalledTimes(1);
});
it('递归规范化页面 schema 中的老用户选择框', () => {
const schema = {
type: 'page',
body: [
{ type: 'select', mode: 'multiple', name: 'OTHER' },
{ type: 'user-transfer-picker', mode: 'controlled', name: 'AGENT' },
{ type: 'user-transfer-picker', mode: 'org', multiple: true, name: 'USERS' },
],
};
expect(normalizeUserTransferSchemaTree(schema)).toMatchObject({
type: 'page',
body: [
{ type: 'select', mode: 'multiple', name: 'OTHER' },
{
type: 'picker',
name: 'AGENT',
source: '/api/picker/76d2f950-ef40-4eff-89ec-98ad9a4976b9/list',
placeholder: '请点击右侧的图标',
},
{
type: 'picker',
multiple: true,
name: 'USERS',
source: '/api/picker/1b3bad0b-a24b-4347-9466-db78f7432756/list',
labelField: '_label',
valueField: '_id',
placeholder: '请点击右侧的图标',
overflowConfig: {
maxTagCount: 1,
displayPosition: ['select'],
},
},
],
});
});
});

View File

@@ -0,0 +1,107 @@
type AmisRendererRegistry = {
addSchemaFilter?: (filter: (schema: Record<string, unknown>) => Record<string, unknown>) => unknown;
};
let schemaFilterRegistered = false;
const USER_SELECT_MODES = new Set(['controlled', 'all', 'org', 'attendance']);
const USER_SELECT_DIALOG_IDS_BY_MODE: Record<string, string> = {
controlled: '76d2f950-ef40-4eff-89ec-98ad9a4976b9',
org: '1b3bad0b-a24b-4347-9466-db78f7432756',
all: '090981ba-0c10-4d84-92dc-80e226594480',
attendance: 'e31ce405-21c4-4892-94bb-e87e07b7f8e7',
};
function userPickerSchema(schema: Record<string, unknown>, mode: string, multiple: boolean): Record<string, unknown> {
const next = { ...schema };
delete next.userSelectMode;
delete next.mode;
delete next.multiple;
delete next.joinValues;
delete next.delimiter;
delete next.valueTpl;
delete next.pickerSize;
delete next.selectTitle;
delete next.resultTitle;
delete next.statistics;
next.type = 'picker';
next.clearable = next.clearable ?? true;
if (multiple) {
next.multiple = true;
next.overflowConfig = next.overflowConfig ?? {
maxTagCount: 1,
displayPosition: ['select'],
};
}
next.source = `/api/picker/${USER_SELECT_DIALOG_IDS_BY_MODE[mode] ?? USER_SELECT_DIALOG_IDS_BY_MODE.controlled}/list`;
next.labelField = '_label';
next.valueField = '_id';
next.modalMode = 'dialog';
next.modalSize = 'lg';
next.placeholder = next.placeholder === undefined || next.placeholder === '请选择'
? '请点击右侧的图标'
: next.placeholder;
next.pickerSchema = next.pickerSchema ?? {
mode: 'table',
headerToolbar: [{ type: 'search-box', name: 'q', placeholder: '输入关键字搜索' }],
footerToolbar: ['pagination'],
};
return next;
}
export function normalizeUserTransferSchema(schema: Record<string, unknown>): Record<string, unknown> {
if (schema?.type !== 'user-transfer-picker') return schema;
const next = { ...schema };
const mode = typeof schema.mode === 'string' ? schema.mode : '';
if (USER_SELECT_MODES.has(mode)) {
next.userSelectMode = next.userSelectMode ?? mode;
delete next.mode;
}
const userSelectMode = typeof next.userSelectMode === 'string' ? next.userSelectMode : 'controlled';
return userPickerSchema(
next,
USER_SELECT_MODES.has(userSelectMode) ? userSelectMode : 'controlled',
next.multiple === true,
);
}
export function normalizeUserTransferSchemaTree<T>(node: T): T {
if (Array.isArray(node)) {
let changed = false;
const next = node.map((item) => {
const normalized = normalizeUserTransferSchemaTree(item);
changed ||= normalized !== item;
return normalized;
});
return (changed ? next : node) as T;
}
if (!node || typeof node !== 'object') return node;
const objectNode = node as Record<string, unknown>;
let changed = false;
const next: Record<string, unknown> = {};
for (const [key, value] of Object.entries(objectNode)) {
const normalized = normalizeUserTransferSchemaTree(value);
next[key] = normalized;
changed ||= normalized !== value;
}
const normalizedObject = normalizeUserTransferSchema(next);
changed ||= normalizedObject !== next;
return (changed ? normalizedObject : node) as T;
}
export function registerUserTransferPicker(amisCore: AmisRendererRegistry | undefined | null): boolean {
if (!amisCore) return false;
if (!schemaFilterRegistered && typeof amisCore.addSchemaFilter === 'function') {
amisCore.addSchemaFilter(normalizeUserTransferSchema);
schemaFilterRegistered = true;
}
return schemaFilterRegistered;
}
export function __resetUserTransferPickerForTest(): void {
schemaFilterRegistered = false;
}

Some files were not shown because too many files have changed in this diff Show More