From 3dfb90f59beb51543e46bbbfce86de6351e328cb Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 2 Jul 2026 11:16:51 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat(modeler):=20=E5=8A=9E=E7=90=86?= =?UTF-8?q?=E4=BA=BA/=E4=BC=9A=E7=AD=BE=E8=A1=A8=E8=BE=BE=E5=BC=8F?= =?UTF-8?q?=E7=BC=96=E8=A7=A3=E7=A0=81=E5=99=A8(=E4=B8=8E=20BaseProperties?= =?UTF-8?q?Converter=20=E9=80=90=E5=AD=97=E5=AF=B9=E9=BD=90)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 纯前端纯函数 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 --- src/modeler/candidateExpression.test.ts | 202 ++++++++++++++++++++++++ src/modeler/candidateExpression.ts | 114 +++++++++++++ 2 files changed, 316 insertions(+) create mode 100644 src/modeler/candidateExpression.test.ts create mode 100644 src/modeler/candidateExpression.ts diff --git a/src/modeler/candidateExpression.test.ts b/src/modeler/candidateExpression.test.ts new file mode 100644 index 0000000..d9f3449 --- /dev/null +++ b/src/modeler/candidateExpression.test.ts @@ -0,0 +1,202 @@ +import { describe, it, expect } from 'vitest'; +import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn'; +import { + parseCandidateExpression, + buildCandidateExpression, + type UserPropertyItem, +} from './candidateExpression'; + +// ── 真实形态锚定 ──────────────────────────────────────────────────────────── +// 不手抄表达式:直接从 T1.1 逐字对照「总包合同交底」写就的 synthetic-full-surface +// fixture 里,运行时抽出 activiti:candidateUsers / activiti:collection 的属性值, +// 做 XML 实体解码("→")得到 businessObject 属性值层的真实表达式。这样测试 +// 与「真实形态的唯一真相」绑定,fixture 改则测试自动跟随,杜绝逐字漂移。 +function xmlDecode(s: string): string { + return s + .replace(/"/g, '"') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&'); +} +function extractAttr(attr: string): string { + const m = SYNTHETIC_BPMN.match(new RegExp(attr + '="([^"]*)"')); + if (!m) throw new Error('fixture 缺属性 ' + attr); + return xmlDecode(m[1]); +} + +// activiti:candidateUsers,单实例办理人,type=position,content 尾部 4 个 CHAR 补白空格, +// 外层 meta 含非空 taskSuccessService(真实服务钩子)。 +const REAL_CANDIDATE = extractAttr('activiti:candidateUsers'); +// activiti:collection,多实例(会签)办理人,type=projectRoleType,content 为逗号分隔的 +// 11 个布尔维度串,外层 meta 全部为空/false。 +const REAL_MULTI = extractAttr('activiti:collection'); + +describe('parseCandidateExpression — 真实形态解析', () => { + it('解析真实 candidate 表达式(全角【】,识别为 candidate 变体)', () => { + const r = parseCandidateExpression(REAL_CANDIDATE); + expect(r).not.toBeNull(); + expect(r!.variant).toBe('candidate'); + expect(r!.items).toHaveLength(1); + expect(r!.items[0]).toMatchObject({ + type: 'position', + isCandidate: true, + isSendMail: false, + isSendPhone: false, + isSendMessage: false, + }); + }); + + it('content 尾部 CHAR 补白空格原样保留(不 trim)', () => { + const r = parseCandidateExpression(REAL_CANDIDATE); + // 32 位十六进制 id + 4 个尾部空格 + expect(r!.items[0].content).toBe('402881343cd50391013d62ccd0c20f7d '); + expect(r!.items[0].content).toHaveLength(36); + }); + + it('multiInstance 前缀变体 multiInstanceUsersHandler.getUsers 同套解析', () => { + const r = parseCandidateExpression(REAL_MULTI); + expect(r).not.toBeNull(); + expect(r!.variant).toBe('multiInstance'); + expect(r!.items[0].type).toBe('projectRoleType'); + }); + + it('content 含逗号分隔多值原样保留', () => { + const r = parseCandidateExpression(REAL_MULTI); + expect(r!.items[0].content).toBe( + 'true,false,false,false,false,false,false,false,false,false,false', + ); + }); +}); + +describe('buildCandidateExpression — 与引擎口径逐字往返', () => { + it('candidate 真实表达式 round-trip 逐字一致(全角【】+前后缀逐字+meta 不丢)', () => { + const r = parseCandidateExpression(REAL_CANDIDATE)!; + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(REAL_CANDIDATE); + }); + + it('multiInstance 真实表达式 round-trip 逐字一致', () => { + const r = parseCandidateExpression(REAL_MULTI)!; + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(REAL_MULTI); + }); + + it('外层 meta(messageTemplate/taskSuccessService/isSkip* 等)往返一字不丢', () => { + const r = parseCandidateExpression(REAL_CANDIDATE)!; + // 真实服务钩子:侧板只改 items 时,taskSuccessService 等业务字段必须原样带回, + // 否则重新部署会打掉已部署流程的任务后置服务。 + expect(r.meta).toMatchObject({ + messageTemplate: '', + taskSuccessService: 'PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS', + isSkipInitiator: false, + isNoUserSkip: false, + isSkipBeforeTask: true, + }); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toContain( + 'PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS', + ); + }); + + it('构建输出前缀/后缀逐字对齐 BasePropertiesConverter 常量', () => { + const r = parseCandidateExpression(REAL_CANDIDATE)!; + const built = buildCandidateExpression(r.items, r.variant, r.meta); + expect(built.startsWith("${candidateUsersHandler.getCandidateUsers(execution,'")).toBe(true); + expect(built.endsWith("')}")).toBe(true); + const rm = parseCandidateExpression(REAL_MULTI)!; + const builtM = buildCandidateExpression(rm.items, rm.variant, rm.meta); + expect(builtM.startsWith("${multiInstanceUsersHandler.getUsers(execution,'")).toBe(true); + }); +}); + +describe('各 type 往返不丢字段(真实结构派生:同一真实外壳,仅换 type/content)', () => { + // 用真实 candidate 外壳(REAL_CANDIDATE 的 meta 与 item 键集),仅替换 type/content, + // 覆盖 §0 其余 type。结构逐字来自真实形态,值取真实业务样例。 + function reshape(type: string, content: string): string { + const r = parseCandidateExpression(REAL_CANDIDATE)!; + const item: UserPropertyItem = { ...r.items[0], type, content }; + return buildCandidateExpression([item], 'candidate', r.meta); + } + + it('scriptUser(content=${APPLYUSERS},真实会签办理人形态)往返不丢', () => { + const expr = reshape('scriptUser', '${APPLYUSERS}'); + const r = parseCandidateExpression(expr)!; + expect(r.items[0]).toMatchObject({ type: 'scriptUser', content: '${APPLYUSERS}' }); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(expr); + }); + + it('depart 往返不丢', () => { + const expr = reshape('depart', '402881343cd50391013d62ccd0c20f7d'); + const r = parseCandidateExpression(expr)!; + expect(r.items[0].type).toBe('depart'); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(expr); + }); + + it('beforeTaskLeader 往返不丢', () => { + const expr = reshape('beforeTaskLeader', ''); + const r = parseCandidateExpression(expr)!; + expect(r.items[0].type).toBe('beforeTaskLeader'); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(expr); + }); +}); + +describe('isSendMessage 可选字段', () => { + it('含 isSendMessage 往返保留', () => { + const r = parseCandidateExpression(REAL_CANDIDATE)!; + expect(r.items[0].isSendMessage).toBe(false); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(REAL_CANDIDATE); + }); + + it('缺 isSendMessage 的旧数据变体:parse 不填充,build 不凭空添加', () => { + // 引擎 BasePropertiesConverter:62-67 对 isCandidate/isSendMail/isSendPhone 无 null 守卫、 + // 唯 isSendMessage 有(:63),故存在无 isSendMessage 的合法历史数据。此变体无 meta。 + const NO_MSG = + "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[【\"type\":\"user\",\"content\":\"u1,u2\",\"isCandidate\":true,\"isSendMail\":false,\"isSendPhone\":false】]】')}"; + const r = parseCandidateExpression(NO_MSG)!; + expect(r.items[0].isSendMessage).toBeUndefined(); + expect('isSendMessage' in r.items[0]).toBe(false); + expect(Object.keys(r.meta)).toHaveLength(0); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(NO_MSG); + }); +}); + +describe('半角输入兼容 + build 恒全角', () => { + it('半角{}输入可解析,build 输出恒全角【】,回到真实全角形态', () => { + const halfWidth = REAL_CANDIDATE.split('【').join('{').split('】').join('}'); + expect(halfWidth).not.toBe(REAL_CANDIDATE); // 确认输入确是半角 + const r = parseCandidateExpression(halfWidth); + expect(r).not.toBeNull(); + expect(r!.items[0].type).toBe('position'); + // build 输出恒全角 → 等于真实全角原文 + expect(buildCandidateExpression(r!.items, r!.variant, r!.meta)).toBe(REAL_CANDIDATE); + }); +}); + +describe('非法/空输入返回 null 不抛', () => { + it('undefined → null', () => { + expect(parseCandidateExpression(undefined)).toBeNull(); + }); + + it('空串 → null', () => { + expect(parseCandidateExpression('')).toBeNull(); + }); + + it('缺前缀(非办理人表达式)→ null', () => { + expect(parseCandidateExpression('${someOtherExpr(execution)}')).toBeNull(); + }); + + it('有前缀但内容坏 JSON → null 不抛', () => { + const bad = + "${candidateUsersHandler.getCandidateUsers(execution,'【not a valid json】')}"; + expect(() => parseCandidateExpression(bad)).not.toThrow(); + expect(parseCandidateExpression(bad)).toBeNull(); + }); + + it('有前缀但缺后缀 → null', () => { + const noSuffix = "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[]】"; + expect(parseCandidateExpression(noSuffix)).toBeNull(); + }); + + it('JSON 合法但无 items 数组 → null', () => { + const noItems = + "${candidateUsersHandler.getCandidateUsers(execution,'【\"foo\":1】')}"; + expect(parseCandidateExpression(noItems)).toBeNull(); + }); +}); diff --git a/src/modeler/candidateExpression.ts b/src/modeler/candidateExpression.ts new file mode 100644 index 0000000..fcdc824 --- /dev/null +++ b/src/modeler/candidateExpression.ts @@ -0,0 +1,114 @@ +// 办理人 / 会签(多实例)办理人表达式的编解码器(纯函数)。 +// +// 处理的是 bpmn-js businessObject **属性值层**的表达式(XML 实体已解码:真引号、全角【】), +// 不是 XML 源码层(")。引擎侧唯一真相: +// - 前后缀常量逐字对齐 com.dsasp.server.wf.bean.BasePropertiesConverter:34-35 +// CANDIDATESERVICE / MULTIINSTANCESERVICE(见下 PREFIX 常量)。 +// - 存储态的对象花括号一律写作**全角【】**(方括号 [] 半角),运行期由 +// CandidateUsersHandler:54 以 `.replace("【","{").replace("】","}")`(全局字面替换) +// 还原为合法 JSON 再交 Jackson 解析。本编解码器 build 输出恒全角、parse 兼容全角/半角。 +// - 外层对象结构:{"items":[{...}],"messageTemplate","taskSuccessService", +// "isSkipInitiator","isNoUserSkip","isSkipBeforeTask"}。引擎运行期候选人解析 +// (convertToUserProperties)只读 items,但 taskSuccessService 等是任务后置服务钩子等 +// 运行期业务字段——侧板只改 items 时必须原样带回(meta),否则重新部署会打掉这些字段。 +// +// 逐字往返约定:content 不含花括号(与引擎的全局替换同约定),故 JSON.stringify 产出的 +// 结构性 {} 全局换成全角是安全的;content 里的逗号分隔多值与 CHAR 尾部补白空格原样保留。 + +const CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'"; +const MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'"; +const SUFFIX = "')}"; + +export type CandidateVariant = 'candidate' | 'multiInstance'; + +/** 单个办理人项。字段名逐字对齐 BasePropertiesConverter 常量(:21-27)。 */ +export interface UserPropertyItem { + type: string; + content: string; + isCandidate?: boolean; + isSendMail?: boolean; + isSendPhone?: boolean; + isSendMessage?: boolean; +} + +export interface ParsedCandidateExpression { + items: UserPropertyItem[]; + variant: CandidateVariant; + /** items 之外的外层字段(messageTemplate/taskSuccessService/isSkip* 等),原样保留以逐字往返。 */ + meta: Record; +} + +function fullToHalf(s: string): string { + return s.split('【').join('{').split('】').join('}'); +} + +function halfToFull(s: string): string { + return s.split('{').join('【').split('}').join('】'); +} + +/** 按固定规范键序重建 item,只输出存在的键(不凭空增删),保证逐字确定性。 */ +function normalizeItem(it: UserPropertyItem): UserPropertyItem { + const o = {} as UserPropertyItem; + o.type = it.type; + o.content = it.content; + if (it.isCandidate !== undefined) o.isCandidate = it.isCandidate; + if (it.isSendMail !== undefined) o.isSendMail = it.isSendMail; + if (it.isSendPhone !== undefined) o.isSendPhone = it.isSendPhone; + if (it.isSendMessage !== undefined) o.isSendMessage = it.isSendMessage; + return o; +} + +/** + * 解析办理人/会签表达式。识别 candidate / multiInstance 两种前缀,内容段全角【】→{} 后 JSON.parse。 + * 非办理人表达式、缺后缀、坏 JSON、无 items 数组、undefined/空串一律返回 null 不抛。 + */ +export function parseCandidateExpression( + expr: string | undefined | null, +): ParsedCandidateExpression | null { + if (typeof expr !== 'string' || expr.length === 0) return null; + + let variant: CandidateVariant; + let prefix: string; + if (expr.startsWith(CANDIDATE_PREFIX)) { + variant = 'candidate'; + prefix = CANDIDATE_PREFIX; + } else if (expr.startsWith(MULTI_PREFIX)) { + variant = 'multiInstance'; + prefix = MULTI_PREFIX; + } else { + return null; + } + if (!expr.endsWith(SUFFIX)) return null; + + const content = expr.slice(prefix.length, expr.length - SUFFIX.length); + let obj: unknown; + try { + obj = JSON.parse(fullToHalf(content)); + } catch { + return null; + } + if (obj === null || typeof obj !== 'object') return null; + const record = obj as Record; + if (!Array.isArray(record.items)) return null; + + const items = (record.items as UserPropertyItem[]).map(normalizeItem); + const meta: Record = { ...record }; + delete meta.items; + + return { items, variant, meta }; +} + +/** + * 构建办理人/会签表达式:重建外层对象 {items, ...meta} → JSON.stringify(紧凑无空白)→ + * 结构性 {} 换成全角【】(方括号保持半角)→ 套前后缀。round-trip 与真实表达式逐字一致。 + */ +export function buildCandidateExpression( + items: UserPropertyItem[], + variant: CandidateVariant, + meta?: Record, +): string { + const prefix = variant === 'multiInstance' ? MULTI_PREFIX : CANDIDATE_PREFIX; + const outer = { items: items.map(normalizeItem), ...(meta ?? {}) }; + const content = halfToFull(JSON.stringify(outer)); + return prefix + content + SUFFIX; +} From 6dc9075648aaacf0cc832dbcfc2a94fa763afe5a Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 2 Jul 2026 11:35:13 +0800 Subject: [PATCH 2/7] =?UTF-8?q?feat(modeler):=20EIP4=20=E4=BE=A7=E6=9D=BF?= =?UTF-8?q?=E4=BA=94=E6=8E=A7=E4=BB=B6(=E5=8A=9E=E7=90=86=E4=BA=BAmeta?= =?UTF-8?q?=E9=80=8F=E4=BC=A0/=E4=BC=9A=E7=AD=BE/formKey/=E6=89=A9?= =?UTF-8?q?=E5=B1=95=E5=B1=9E=E6=80=A7/=E7=9B=91=E5=90=AC=E5=99=A8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 选中 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 --- src/api/processModeler.ts | 24 + src/modeler/Eip4Panel.test.tsx | 350 +++++++++++++ src/modeler/Eip4Panel.tsx | 624 ++++++++++++++++++++++++ src/modeler/useSelectedElement.test.tsx | 55 +++ src/modeler/useSelectedElement.ts | 56 +++ src/pages/ProcessModelerPage.test.tsx | 24 +- src/pages/ProcessModelerPage.tsx | 14 +- 7 files changed, 1138 insertions(+), 9 deletions(-) create mode 100644 src/modeler/Eip4Panel.test.tsx create mode 100644 src/modeler/Eip4Panel.tsx create mode 100644 src/modeler/useSelectedElement.test.tsx create mode 100644 src/modeler/useSelectedElement.ts diff --git a/src/api/processModeler.ts b/src/api/processModeler.ts index 029b4a2..46e8003 100644 --- a/src/api/processModeler.ts +++ b/src/api/processModeler.ts @@ -95,6 +95,30 @@ interface RawOption { key?: unknown; } +/** + * formKey picker 的一条选项。数据源 `GET /api/workflow/wftemplates`(T2.2 网关端点), + * 契约 `{templates:[{id,name}]}`。id=view_wftemplate_id 裸 UUID(即 activiti:formKey 值,无前缀)。 + */ +export interface WfTemplateOption { + id: string; + name: string; +} + +/** GET /api/workflow/wftemplates —— 取表单模板列表供 formKey 下拉(防御性返回数组)。 */ +export async function fetchWfTemplates(): Promise { + const { data } = await http.get<{ templates?: unknown[] }>('/api/workflow/wftemplates'); + const raw = data?.templates ?? []; + if (!Array.isArray(raw)) return []; + return raw + .map((t) => { + const o = (t ?? {}) as { id?: unknown; name?: unknown }; + const id = o.id != null ? String(o.id) : ''; + const name = o.name != null ? String(o.name) : id; + return { id, name }; + }) + .filter((t) => t.id !== ''); +} + /** GET /api/process-select/options —— 取存量流程选项(解 amis 信封,防御性返回数组)。 */ export async function fetchProcessOptions(q?: string): Promise { const { data } = await http.get('/api/process-select/options', { diff --git a/src/modeler/Eip4Panel.test.tsx b/src/modeler/Eip4Panel.test.tsx new file mode 100644 index 0000000..983c88d --- /dev/null +++ b/src/modeler/Eip4Panel.test.tsx @@ -0,0 +1,350 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'; +import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn'; +import { parseCandidateExpression } from './candidateExpression'; + +// formKey 下拉数据源:mock,其中一个 id 对齐 fixture 的 formKey 值。 +vi.mock('../api/processModeler', () => ({ + fetchWfTemplates: vi.fn(() => + Promise.resolve([ + { id: '2098ce21-400b-4425-9c22-63e350974b98', name: '合同交底表单' }, + { id: 'aaaa-bbbb', name: '另一个表单' }, + ]), + ), +})); + +import { Eip4Panel } from './Eip4Panel'; + +// ── 真实办理人形态锚定(同 candidateExpression.test.ts:抽 fixture,做 XML 实体解码) ──── +function xmlDecode(s: string): string { + return s.replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'); +} +function extractAttr(attr: string): string { + const m = SYNTHETIC_BPMN.match(new RegExp(attr + '="([^"]*)"')); + if (!m) throw new Error('fixture 缺属性 ' + attr); + return xmlDecode(m[1]); +} +const REAL_CANDIDATE = extractAttr('activiti:candidateUsers'); // type=position + 非空 taskSuccessService + +// ── 假 modeler / element(vi.fn 捕获 updateProperties 载荷) ──────────────────── +function makeModeler() { + let handler: ((e: unknown) => void) | null = null; + const updateProperties = vi.fn(); + const created: Array> = []; + const moddle = { + create: vi.fn((type: string, props: Record = {}) => { + const o = { $type: type, ...props }; + created.push(o); + return o; + }), + }; + const modeling = { updateProperties }; + const on = vi.fn((ev: string, cb: (e: unknown) => void) => { + if (ev === 'selection.changed') handler = cb; + }); + const off = vi.fn(); + const get = (svc: string) => (svc === 'modeling' ? modeling : svc === 'moddle' ? moddle : {}); + const modeler = { on, off, get }; + // 选中同时 flush 微任务队列:fetchWfTemplates(mock 已 resolve)的 setState 在 act 内落定, + // 避免「update not wrapped in act」告警。 + const select = (element: unknown) => + act(async () => { + handler?.({ newSelection: element ? [element] : [] }); + await Promise.resolve(); + await Promise.resolve(); + }); + return { modeler, updateProperties, moddle, created, select }; +} + +/** 造一个 userTask element:map=businessObject.get(name) 源,$attrs=原始扩展属性袋。 */ +function userTask(map: Record = {}, $attrs?: Record) { + return { + id: map.__id ? String(map.__id) : 't1', + type: 'bpmn:UserTask', + businessObject: { $type: 'bpmn:UserTask', $attrs, get: (n: string) => map[n] }, + }; +} + +/** 造一个 moddle-ish 元素(taskListener/loop 等):$type + get(name) + 直读属性。 */ +function moddleEl(type: string, props: Record) { + return { $type: type, ...props, get: (n: string) => props[n] }; +} + +/** 取最后一次 updateProperties 载荷。 */ +function lastPayload(updateProperties: ReturnType): Record { + const calls = updateProperties.mock.calls; + return calls[calls.length - 1][1] as Record; +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe('Eip4Panel — 选择状态', () => { + it('未选中任何节点时提示选择', async () => { + const { modeler } = makeModeler(); + render(); + expect(screen.getByText(/请选择/)).toBeInTheDocument(); + // flush 挂载期 fetchWfTemplates 的 setState(避免 act 告警) + await act(async () => { + await Promise.resolve(); + }); + }); + + it('选中非 userTask 显示简短提示,不渲染办理人控件', async () => { + const { modeler, select } = makeModeler(); + render(); + await select({ id: 'g1', type: 'bpmn:ExclusiveGateway', businessObject: { get: () => undefined } }); + expect(screen.getByText(/不是用户任务|仅.*用户任务/)).toBeInTheDocument(); + expect(screen.queryByTestId('eip4-candidate-add')).not.toBeInTheDocument(); + }); +}); + +describe('Eip4Panel — 办理人(candidateUsers)', () => { + it('顶部灰字提示:引擎以本控件为准', async () => { + const { modeler, select } = makeModeler(); + render(); + await select(userTask()); + expect(screen.getByText(/引擎以本控件为准/)).toBeInTheDocument(); + }); + + it('set:改 content 写回 activiti:candidateUsers(可被 codec 解析)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); + const input = screen.getByTestId('eip4-candidate-content-0'); + fireEvent.change(input, { target: { value: 'newUser1,newUser2' } }); + const payload = lastPayload(updateProperties); + const written = payload['activiti:candidateUsers'] as string; + const parsed = parseCandidateExpression(written)!; + expect(parsed.items[0].content).toBe('newUser1,newUser2'); + expect(parsed.items[0].type).toBe('position'); + }); + + it('🔴 改 items 后 meta 逐字保留(taskSuccessService 等业务字段不丢)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + const original = parseCandidateExpression(REAL_CANDIDATE)!; + render(); + await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); + fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), { + target: { value: 'changed' }, + }); + const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string; + const parsed = parseCandidateExpression(written)!; + // meta 逐字保留 + expect(parsed.meta).toEqual(original.meta); + expect(parsed.meta.taskSuccessService).toBe('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS'); + // items 确已改 + expect(parsed.items[0].content).toBe('changed'); + }); + + it('清空最后一行:写回 undefined(清除属性)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); + fireEvent.click(screen.getByTestId('eip4-candidate-remove-0')); + expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined(); + expect('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true); + }); + + it('增行:改 type 下拉写回对应 type', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.click(screen.getByTestId('eip4-candidate-add')); + fireEvent.change(screen.getByTestId('eip4-candidate-type-0'), { + target: { value: 'scriptUser' }, + }); + fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), { + target: { value: '${APPLYUSERS}' }, + }); + const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string; + const parsed = parseCandidateExpression(written)!; + expect(parsed.items[0]).toMatchObject({ type: 'scriptUser', content: '${APPLYUSERS}' }); + }); +}); + +describe('Eip4Panel — 会签(multiInstance)', () => { + it('开:载荷含 loopCharacteristics(collection multiInstance 前缀+elementVariable+completionCondition 全票预设)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.click(screen.getByTestId('eip4-cosign-toggle')); + const loop = lastPayload(updateProperties).loopCharacteristics as Record; + expect(loop).toBeTruthy(); + expect(String(loop['activiti:collection'])).toContain('multiInstanceUsersHandler.getUsers'); + expect(loop['activiti:elementVariable']).toBe('assignee'); + expect((loop.completionCondition as { body: string }).body).toBe( + '${nrOfCompletedInstances/nrOfInstances==1}', + ); + expect(loop.isSequential).toBe(false); + }); + + it('关:已有会签 → 载荷 loopCharacteristics=undefined', async () => { + const { modeler, updateProperties, select } = makeModeler(); + const loop = moddleEl('bpmn:MultiInstanceLoopCharacteristics', { + 'activiti:collection': extractAttr('activiti:collection'), + 'activiti:elementVariable': 'assignee', + completionCondition: { body: '${nrOfCompletedInstances/nrOfInstances==1}' }, + }); + render(); + await select(userTask({ loopCharacteristics: loop })); + // 初始应为开 + expect((screen.getByTestId('eip4-cosign-toggle') as HTMLInputElement).checked).toBe(true); + fireEvent.click(screen.getByTestId('eip4-cosign-toggle')); + const payload = lastPayload(updateProperties); + expect('loopCharacteristics' in payload).toBe(true); + expect(payload.loopCharacteristics).toBeUndefined(); + }); + + it('指定数 N:completionCondition body 代入 N', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.click(screen.getByTestId('eip4-cosign-toggle')); + fireEvent.change(screen.getByTestId('eip4-cosign-completion-type'), { + target: { value: 'count' }, + }); + fireEvent.change(screen.getByTestId('eip4-cosign-completion-n'), { target: { value: '3' } }); + const loop = lastPayload(updateProperties).loopCharacteristics as Record; + expect((loop.completionCondition as { body: string }).body).toBe( + '${nrOfCompletedInstances>=3}', + ); + }); + + it('过半预设:body 为 >0.5', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.click(screen.getByTestId('eip4-cosign-toggle')); + fireEvent.change(screen.getByTestId('eip4-cosign-completion-type'), { + target: { value: 'majority' }, + }); + const loop = lastPayload(updateProperties).loopCharacteristics as Record; + expect((loop.completionCondition as { body: string }).body).toBe( + '${nrOfCompletedInstances/nrOfInstances>0.5}', + ); + }); +}); + +describe('Eip4Panel — formKey', () => { + it('选择模板 → 写回 activiti:formKey=裸 UUID', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + const sel = await screen.findByTestId('eip4-formkey-select'); + // 等待模板选项加载 + await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(2)); + fireEvent.change(sel, { target: { value: 'aaaa-bbbb' } }); + expect(lastPayload(updateProperties)['activiti:formKey']).toBe('aaaa-bbbb'); + }); + + it('选「无」→ 写回 undefined 清除', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ 'activiti:formKey': '2098ce21-400b-4425-9c22-63e350974b98' })); + const sel = await screen.findByTestId('eip4-formkey-select'); + fireEvent.change(sel, { target: { value: '' } }); + const payload = lastPayload(updateProperties); + expect('activiti:formKey' in payload).toBe(true); + expect(payload['activiti:formKey']).toBeUndefined(); + }); +}); + +describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => { + it('增:填 key/value 后写回命名空间键', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), { + target: { value: 'activiti:custom' }, + }); + fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'v1' } }); + fireEvent.click(screen.getByTestId('eip4-extattr-add')); + expect(lastPayload(updateProperties)).toEqual({ 'activiti:custom': 'v1' }); + }); + + it('删:已有扩展属性写回 undefined', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({}, { 'activiti:custom': 'v1' })); + expect(screen.getByTestId('eip4-extattr-key-0')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('eip4-extattr-remove-0')); + const payload = lastPayload(updateProperties); + expect('activiti:custom' in payload).toBe(true); + expect(payload['activiti:custom']).toBeUndefined(); + }); + + it('只列 activiti:/flowable: 前缀的 $attrs(其它前缀不显示)', async () => { + const { modeler, select } = makeModeler(); + render(); + await select(userTask({}, { 'activiti:custom': 'v1', 'xmlns:foo': 'bar' })); + expect(screen.getByTestId('eip4-extattr-key-0')).toHaveValue('activiti:custom'); + expect(screen.queryByTestId('eip4-extattr-key-1')).not.toBeInTheDocument(); + }); +}); + +describe('Eip4Panel — 任务监听器(taskListener)', () => { + it('增:新监听器写回 extensionElements,并保留已有监听器的 field(引用不动)', async () => { + const { modeler, updateProperties, moddle, select } = makeModeler(); + const fieldObj = moddleEl('activiti:field', { name: 'mailTemplate' }); + const existing = moddleEl('activiti:taskListener', { + event: 'complete', + class: 'com.dsasp.server.wf.user.listener.TaskCompleteListener', + fields: [fieldObj], + }); + render(); + await select(userTask({ extensionElements: { values: [existing] } })); + // 已有监听器显示 field 徽标 + expect(screen.getByText(/含 field 配置/)).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('eip4-listener-add')); + const ext = lastPayload(updateProperties).extensionElements as { values: Array> }; + expect(ext.$type).toBe('bpmn:ExtensionElements'); + expect(ext.values.length).toBe(2); + // 原监听器被重建但其 fields 数组引用与 field 元素引用原样保留 + const withFields = ext.values.find((v) => Array.isArray(v.fields)); + expect(withFields).toBeTruthy(); + expect((withFields!.fields as unknown[])[0]).toBe(fieldObj); + // moddle.create 被用于构造 taskListener 与 ExtensionElements + expect(moddle.create).toHaveBeenCalledWith('bpmn:ExtensionElements', expect.anything()); + }); + + it('编辑 event 下拉 + class 值写回', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.click(screen.getByTestId('eip4-listener-add')); + fireEvent.change(screen.getByTestId('eip4-listener-event-0'), { target: { value: 'assignment' } }); + fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: 'com.X.Listener' } }); + const ext = lastPayload(updateProperties).extensionElements as { values: Array> }; + const listener = ext.values.find((v) => v.$type === 'activiti:taskListener')!; + expect(listener.event).toBe('assignment'); + expect(listener.class).toBe('com.X.Listener'); + }); + + it('删:移除唯一监听器 → extensionElements=undefined', async () => { + const { modeler, updateProperties, select } = makeModeler(); + const existing = moddleEl('activiti:taskListener', { event: 'create', class: 'com.X' }); + render(); + await select(userTask({ extensionElements: { values: [existing] } })); + fireEvent.click(screen.getByTestId('eip4-listener-remove-0')); + const payload = lastPayload(updateProperties); + expect('extensionElements' in payload).toBe(true); + expect(payload.extensionElements).toBeUndefined(); + }); + + it('delegateExpression 模式:互斥写回 delegateExpression', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.click(screen.getByTestId('eip4-listener-add')); + fireEvent.change(screen.getByTestId('eip4-listener-mode-0'), { + target: { value: 'delegateExpression' }, + }); + fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: '${bean}' } }); + const ext = lastPayload(updateProperties).extensionElements as { values: Array> }; + const listener = ext.values.find((v) => v.$type === 'activiti:taskListener')!; + expect(listener.delegateExpression).toBe('${bean}'); + expect('class' in listener).toBe(false); + }); +}); diff --git a/src/modeler/Eip4Panel.tsx b/src/modeler/Eip4Panel.tsx new file mode 100644 index 0000000..5312200 --- /dev/null +++ b/src/modeler/Eip4Panel.tsx @@ -0,0 +1,624 @@ +// EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。 +// +// 设计要点(计划 T2.4 + §0.5 P5): +// - 全部写操作经 bpmn-js `modeling.updateProperties(element, {...})`,undo/redo 天然生效。 +// - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。 +// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 ref, +// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。 +// - 扩展属性只列长尾 $attrs(已声明属性如 formKey/candidateUsers 不进 $attrs,故不重复)。 +// - taskListener 重建时原样保留其 field 子元素(moddle 元素引用不动)。 +// - 原生标准属性面板照旧显示于本侧板下方,本控件顶部灰字提示以本控件为准。 +import { useEffect, useRef, useState } from 'react'; +import { + buildCandidateExpression, + parseCandidateExpression, + type CandidateVariant, + type UserPropertyItem, +} from './candidateExpression'; +import { fetchWfTemplates, type WfTemplateOption } from '../api/processModeler'; +import type { BpmnElement, SelectionModeler } from './useSelectedElement'; +import { useSelectedElement } from './useSelectedElement'; + +// ── bpmn-js 服务契约(最小) ─────────────────────────────────────────────────── +interface Modeling { + updateProperties(element: BpmnElement, props: Record): void; +} +interface Moddle { + create(type: string, props?: Record): Record; +} +export interface PanelModeler extends SelectionModeler { + get(service: string): unknown; +} + +// ── 办理人 type 取值(§0 实测 10 种)+ 中文标签 ──────────────────────────────── +const CANDIDATE_TYPES: Array<{ value: string; label: string }> = [ + { value: 'user', label: '指定人员' }, + { value: 'depart', label: '指定部门' }, + { value: 'position', label: '指定岗位' }, + { value: 'formSpecifiedDimension', label: '表单指定维度' }, + { value: 'initiator', label: '流程发起人' }, + { value: 'sameToTask', label: '同某任务办理人' }, + { value: 'beforeTaskLeader', label: '上一办理人领导' }, + { value: 'beforeTaskDepartManager', label: '上一办理人部门经理' }, + { value: 'scriptUser', label: '脚本/表达式' }, + { value: 'projectRoleType', label: '项目角色' }, +]; + +const LISTENER_EVENTS = ['create', 'assignment', 'complete', 'all']; + +// ── 会签完成条件预设 ───────────────────────────────────────────────────────── +type CompletionType = 'all' | 'majority' | 'count'; +const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}'; +const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}'; + +function completionBody(type: CompletionType, n: number): string { + if (type === 'majority') return COMPLETION_MAJORITY; + if (type === 'count') return '${nrOfCompletedInstances>=' + n + '}'; + return COMPLETION_ALL; +} +function parseCompletion(body: string | undefined): { type: CompletionType; n: number } { + if (!body) return { type: 'all', n: 2 }; + if (body.indexOf('>0.5') >= 0) return { type: 'majority', n: 2 }; + const m = body.match(/nrOfCompletedInstances>=(\d+)/); + if (m) return { type: 'count', n: Number(m[1]) }; + return { type: 'all', n: 2 }; +} + +// ── moddle 读值(兼容 .get(name) 与直读属性) ────────────────────────────────── +function mget(obj: unknown, name: string): unknown { + if (!obj || typeof obj !== 'object') return undefined; + const o = obj as Record & { get?: (n: string) => unknown }; + if (typeof o.get === 'function') return o.get(name); + return o[name]; +} + +function newCandidateItem(): UserPropertyItem { + return { + type: 'user', + content: '', + isCandidate: true, + isSendMail: false, + isSendPhone: false, + isSendMessage: false, + }; +} + +interface ListenerRow { + event: string; + mode: 'class' | 'delegateExpression'; + value: string; + /** 原监听器的 field 子元素数组(编辑时原样保留,引用不动)。 */ + fields?: unknown[]; +} + +interface CosignState { + enabled: boolean; + items: UserPropertyItem[]; + completionType: CompletionType; + completionN: number; +} + +// ── items 编辑器(办理人 / 会签人员复用) ────────────────────────────────────── +function ItemsEditor({ + idPrefix, + items, + onChange, +}: { + idPrefix: string; + items: UserPropertyItem[]; + onChange: (next: UserPropertyItem[]) => void; +}) { + const patch = (i: number, p: Partial) => + onChange(items.map((it, idx) => (idx === i ? { ...it, ...p } : it))); + const remove = (i: number) => onChange(items.filter((_, idx) => idx !== i)); + const add = () => onChange([...items, newCandidateItem()]); + + return ( +
+ {items.map((it, i) => ( +
+
+ + patch(i, { content: e.target.value })} + style={{ flex: 1, minWidth: 0 }} + /> + +
+
+ + + + +
+
+ ))} + +
+ ); +} + +function Section({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+
{title}
+ {children} +
+ ); +} + +export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { + const element = useSelectedElement(modeler); + const modeling = modeler ? (modeler.get('modeling') as Modeling | undefined) : undefined; + const moddle = modeler ? (modeler.get('moddle') as Moddle | undefined) : undefined; + + const isUserTask = element?.type === 'bpmn:UserTask'; + + // ── 本地编辑态(选中变更时从 businessObject 重新初始化) ────────────────────── + const [candidateItems, setCandidateItems] = useState([]); + const [cosign, setCosign] = useState({ + enabled: false, + items: [], + completionType: 'all', + completionN: 2, + }); + const [formKey, setFormKey] = useState(''); + const [extAttrs, setExtAttrs] = useState>([]); + const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' }); + const [listeners, setListeners] = useState([]); + const [templates, setTemplates] = useState([]); + + // meta 透传:codec parse 出的外层业务字段,写回时原样带回(不进 UI 渲染,只存 ref)。 + const candidateMetaRef = useRef>({}); + const cosignMetaRef = useRef>({}); + // 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。 + const otherExtRef = useRef([]); + + // formKey 数据源加载一次。 + useEffect(() => { + let alive = true; + Promise.resolve(fetchWfTemplates()) + .then((t) => alive && setTemplates(Array.isArray(t) ? t : [])) + .catch(() => alive && setTemplates([])); + return () => { + alive = false; + }; + }, []); + + // 选中变更 → 从 businessObject 重新初始化本地态。 + useEffect(() => { + if (!element || element.type !== 'bpmn:UserTask') { + setCandidateItems([]); + setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); + setFormKey(''); + setExtAttrs([]); + setNewAttr({ key: '', value: '' }); + setListeners([]); + candidateMetaRef.current = {}; + cosignMetaRef.current = {}; + otherExtRef.current = []; + return; + } + const bo = element.businessObject; + + // 办理人 + const cand = parseCandidateExpression(bo.get('activiti:candidateUsers') as string | undefined); + setCandidateItems(cand?.items ?? []); + candidateMetaRef.current = cand?.meta ?? {}; + + // 会签 + const loop = bo.get('loopCharacteristics'); + if (loop) { + const parsed = parseCandidateExpression(mget(loop, 'activiti:collection') as string | undefined); + const cc = parseCompletion((mget(loop, 'completionCondition') as { body?: string } | undefined)?.body); + setCosign({ + enabled: true, + items: parsed?.items ?? [], + completionType: cc.type, + completionN: cc.n, + }); + cosignMetaRef.current = parsed?.meta ?? {}; + } else { + setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); + cosignMetaRef.current = {}; + } + + // formKey + setFormKey((bo.get('activiti:formKey') as string) ?? ''); + + // 扩展属性(长尾 $attrs,只留 activiti:/flowable: 前缀) + const attrs = bo.$attrs ?? {}; + setExtAttrs( + Object.entries(attrs) + .filter(([k]) => k.startsWith('activiti:') || k.startsWith('flowable:')) + .map(([key, value]) => ({ key, value: String(value) })), + ); + setNewAttr({ key: '', value: '' }); + + // 任务监听器 + const extEl = bo.get('extensionElements') as { values?: unknown[] } | undefined; + const values = (extEl?.values ?? []) as unknown[]; + otherExtRef.current = values.filter((v) => (v as { $type?: string }).$type !== 'activiti:taskListener'); + setListeners( + values + .filter((v) => (v as { $type?: string }).$type === 'activiti:taskListener') + .map((v) => { + const cls = mget(v, 'class') as string | undefined; + const del = mget(v, 'delegateExpression') as string | undefined; + const fields = ((v as { fields?: unknown[] }).fields ?? mget(v, 'fields')) as unknown[] | undefined; + return { + event: (mget(v, 'event') as string) ?? 'create', + mode: cls ? 'class' : del ? 'delegateExpression' : 'class', + value: cls ?? del ?? '', + fields: fields && fields.length ? fields : undefined, + } as ListenerRow; + }), + ); + }, [element]); + + function update(props: Record) { + if (element && modeling) modeling.updateProperties(element, props); + } + + // ── 办理人写回 ───────────────────────────────────────────────────────────── + function writeCandidate(items: UserPropertyItem[]) { + setCandidateItems(items); + if (items.length === 0) { + update({ 'activiti:candidateUsers': undefined }); + return; + } + update({ + 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMetaRef.current), + }); + } + + // ── 会签写回 ─────────────────────────────────────────────────────────────── + function writeCosign(next: CosignState) { + setCosign(next); + if (!next.enabled) { + update({ loopCharacteristics: undefined }); + return; + } + if (!moddle) return; + const collection = buildCandidateExpression( + next.items, + 'multiInstance' as CandidateVariant, + cosignMetaRef.current, + ); + const completionCondition = moddle.create('bpmn:FormalExpression', { + body: completionBody(next.completionType, next.completionN), + }); + const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', { + isSequential: false, + 'activiti:collection': collection, + 'activiti:elementVariable': 'assignee', + completionCondition, + }); + update({ loopCharacteristics: loop }); + } + + // ── formKey 写回 ─────────────────────────────────────────────────────────── + function writeFormKey(value: string) { + setFormKey(value); + update({ 'activiti:formKey': value === '' ? undefined : value }); + } + + // ── 扩展属性写回 ─────────────────────────────────────────────────────────── + function addExtAttr() { + const key = newAttr.key.trim(); + if (!key) return; + setExtAttrs((prev) => { + const rest = prev.filter((a) => a.key !== key); + return [...rest, { key, value: newAttr.value }]; + }); + update({ [key]: newAttr.value }); + setNewAttr({ key: '', value: '' }); + } + function editExtAttr(key: string, value: string) { + setExtAttrs((prev) => prev.map((a) => (a.key === key ? { ...a, value } : a))); + update({ [key]: value }); + } + function removeExtAttr(key: string) { + setExtAttrs((prev) => prev.filter((a) => a.key !== key)); + update({ [key]: undefined }); + } + + // ── 任务监听器写回 ───────────────────────────────────────────────────────── + function writeListeners(next: ListenerRow[]) { + setListeners(next); + if (!moddle) return; + const listenerEls = next.map((l) => { + const props: Record = { event: l.event }; + props[l.mode] = l.value; + if (l.fields && l.fields.length) props.fields = l.fields; + return moddle.create('activiti:taskListener', props); + }); + const all = [...otherExtRef.current, ...listenerEls]; + const extEl = all.length ? moddle.create('bpmn:ExtensionElements', { values: all }) : undefined; + update({ extensionElements: extEl }); + } + function addListener() { + writeListeners([...listeners, { event: 'create', mode: 'class', value: '' }]); + } + function patchListener(i: number, p: Partial) { + writeListeners(listeners.map((l, idx) => (idx === i ? { ...l, ...p } : l))); + } + function removeListener(i: number) { + writeListeners(listeners.filter((_, idx) => idx !== i)); + } + + // ── 渲染 ─────────────────────────────────────────────────────────────────── + if (!element) { + return ( +
+ 请选择一个用户任务节点以编辑 EIP4 属性。 +
+ ); + } + if (!isUserTask) { + return ( +
+ 选中的不是用户任务节点。EIP4 定制控件仅对用户任务(办理人 / 会签 / formKey)可用。 +
+ ); + } + + return ( +
+
+ EIP4 引擎以本控件为准,下方标准面板原生字段仅供高级调试。 +
+ +
+ +
+ +
+ + {cosign.enabled ? ( +
+ writeCosign({ ...cosign, items })} + /> +
+ 完成条件 + + {cosign.completionType === 'count' ? ( + + writeCosign({ ...cosign, completionN: Number(e.target.value) || 1 }) + } + style={{ width: 64 }} + /> + ) : null} +
+
+ ) : null} +
+ +
+ +
+ +
+
+ {extAttrs.map((a, i) => ( +
+ + editExtAttr(a.key, e.target.value)} + style={{ flex: 1, minWidth: 0 }} + /> + +
+ ))} +
+ setNewAttr((s) => ({ ...s, key: e.target.value }))} + style={{ flex: '0 0 130px', minWidth: 0 }} + /> + setNewAttr((s) => ({ ...s, value: e.target.value }))} + style={{ flex: 1, minWidth: 0 }} + /> + +
+
+
+ +
+
+ {listeners.map((l, i) => ( +
+
+ + + +
+ patchListener(i, { value: e.target.value })} + /> + {l.fields && l.fields.length ? ( + + 含 field 配置({l.fields.length})· 编辑时原样保留 + + ) : null} +
+ ))} + +
+
+
+ ); +} + +const hintStyle: React.CSSProperties = { + padding: 12, + color: 'var(--text-3)', + fontSize: 12, + borderBottom: '1px solid var(--line)', +}; diff --git a/src/modeler/useSelectedElement.test.tsx b/src/modeler/useSelectedElement.test.tsx new file mode 100644 index 0000000..ba5d4cd --- /dev/null +++ b/src/modeler/useSelectedElement.test.tsx @@ -0,0 +1,55 @@ +import { describe, it, expect, vi } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useSelectedElement } from './useSelectedElement'; + +function makeModeler() { + let handler: ((e: unknown) => void) | null = null; + const on = vi.fn((ev: string, cb: (e: unknown) => void) => { + if (ev === 'selection.changed') handler = cb; + }); + const off = vi.fn(); + return { + modeler: { on, off }, + on, + off, + fire: (sel: unknown[]) => act(() => handler?.({ newSelection: sel })), + }; +} + +describe('useSelectedElement', () => { + it('单选返回该 element', () => { + const { modeler, fire } = makeModeler(); + const { result } = renderHook(() => useSelectedElement(modeler)); + const el = { id: 'a', type: 'bpmn:UserTask', businessObject: { get: () => undefined } }; + fire([el]); + expect(result.current).toBe(el); + }); + + it('多选返回 null', () => { + const { modeler, fire } = makeModeler(); + const { result } = renderHook(() => useSelectedElement(modeler)); + fire([{ id: 'a' }, { id: 'b' }]); + expect(result.current).toBeNull(); + }); + + it('空选返回 null', () => { + const { modeler, fire } = makeModeler(); + const { result } = renderHook(() => useSelectedElement(modeler)); + fire([{ id: 'a' }]); + expect(result.current).not.toBeNull(); + fire([]); + expect(result.current).toBeNull(); + }); + + it('卸载时解绑 selection.changed', () => { + const { modeler, off } = makeModeler(); + const { unmount } = renderHook(() => useSelectedElement(modeler)); + unmount(); + expect(off).toHaveBeenCalledWith('selection.changed', expect.any(Function)); + }); + + it('modeler 为 null 时返回 null 且不订阅', () => { + const { result } = renderHook(() => useSelectedElement(null)); + expect(result.current).toBeNull(); + }); +}); diff --git a/src/modeler/useSelectedElement.ts b/src/modeler/useSelectedElement.ts new file mode 100644 index 0000000..1ad76ea --- /dev/null +++ b/src/modeler/useSelectedElement.ts @@ -0,0 +1,56 @@ +// 订阅 bpmn-js 'selection.changed',返回当前单选 element(多选/空选返 null)。 +// 卸载时解绑;modeler 为 null 时不订阅、恒返 null。 +import { useEffect, useState } from 'react'; + +/** bpmn-js businessObject 的最小契约(本侧板用到的读法)。 */ +export interface BpmnBusinessObject { + $type?: string; + /** 未在 moddle 描述符中声明的长尾扩展属性(命名空间键→字符串值)。 */ + $attrs?: Record; + /** 读取声明属性(如 'activiti:candidateUsers'/'loopCharacteristics'/'extensionElements')。 */ + get(name: string): unknown; +} + +/** bpmn-js diagram element 的最小契约。 */ +export interface BpmnElement { + id: string; + /** moddle 类型,如 'bpmn:UserTask'。 */ + type: string; + businessObject: BpmnBusinessObject; +} + +/** 订阅所需的最小 modeler 契约(bpmn-js Modeler 天然满足)。 */ +export interface SelectionModeler { + on(event: string, cb: (e: unknown) => void): void; + off?(event: string, cb: (e: unknown) => void): void; +} + +interface SelectionChangedEvent { + newSelection?: unknown[]; +} + +/** + * 返回当前单选的 bpmn element;多选或空选返 null。modeler 变更/卸载自动重订阅、解绑。 + */ +export function useSelectedElement( + modeler: SelectionModeler | null | undefined, +): BpmnElement | null { + const [element, setElement] = useState(null); + + useEffect(() => { + if (!modeler) { + setElement(null); + return; + } + const handler = (e: unknown) => { + const sel = ((e as SelectionChangedEvent | undefined)?.newSelection ?? []) as BpmnElement[]; + setElement(sel.length === 1 ? sel[0] : null); + }; + modeler.on('selection.changed', handler); + return () => { + modeler.off?.('selection.changed', handler); + }; + }, [modeler]); + + return element; +} diff --git a/src/pages/ProcessModelerPage.test.tsx b/src/pages/ProcessModelerPage.test.tsx index 16005af..ce91aa3 100644 --- a/src/pages/ProcessModelerPage.test.tsx +++ b/src/pages/ProcessModelerPage.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, act } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { SYNTHETIC_BPMN } from '../modeler/moddle/fixtures/synthetic-full-surface.bpmn'; @@ -32,6 +32,8 @@ vi.mock('../api/processModeler', () => ({ fetchProcDefSource: vi.fn(), fetchProcDefSourceByKey: vi.fn(), fetchProcessOptions: vi.fn(), + // Eip4Panel(右栏叠板)挂载时拉 formKey 数据源——mock 成空列表避免真请求。 + fetchWfTemplates: vi.fn(() => Promise.resolve([])), })); vi.mock('../auth/token', async (importOriginal) => ({ ...(await importOriginal()), @@ -69,10 +71,14 @@ beforeEach(() => { }); describe('ProcessModelerPage', () => { - it('admin 渲染画布容器与标准属性面板容器', () => { + it('admin 渲染画布容器与标准属性面板容器', async () => { renderPage(); expect(screen.getByTestId('process-modeler-canvas')).toBeInTheDocument(); expect(screen.getByTestId('process-modeler-props')).toBeInTheDocument(); + // flush Eip4Panel 挂载期 fetchWfTemplates 的 setState(避免 act 告警) + await act(async () => { + await Promise.resolve(); + }); }); it('非 admin 降级为「仅管理员可用」文案,不渲染画布', () => { @@ -138,4 +144,18 @@ describe('ProcessModelerPage', () => { await waitFor(() => expect(mSource).toHaveBeenCalledWith('部署流程:3:uuid')); expect(mSourceByKey).not.toHaveBeenCalled(); }); + + // 🔴 红线回归(T1.5 评审遗留 + T2.4 顺带收口):双包冲突会静默丢弃 userTask, + // 故构造参数必须锁死——moddleExtensions 键恰为 ['activiti'],additionalModules 长度恰 2。 + // 防「顺手」加 Camunda provider / 双载 flowable 描述符导致静默回归。 + it('红线:Modeler 构造参数 moddleExtensions 键恰 [activiti] 且 additionalModules 长度 2', async () => { + renderPage('/process-modeler?procDefId=PD-1'); + await waitFor(() => expect(ModelerCtor).toHaveBeenCalledTimes(1)); + const opts = ModelerCtor.mock.calls[0][0] as { + moddleExtensions: Record; + additionalModules: unknown[]; + }; + expect(Object.keys(opts.moddleExtensions)).toEqual(['activiti']); + expect(opts.additionalModules).toHaveLength(2); + }); }); diff --git a/src/pages/ProcessModelerPage.tsx b/src/pages/ProcessModelerPage.tsx index 24bd158..ece88ba 100644 --- a/src/pages/ProcessModelerPage.tsx +++ b/src/pages/ProcessModelerPage.tsx @@ -18,6 +18,7 @@ import { fetchProcessOptions, type ProcessOption, } from '../api/processModeler'; +import { Eip4Panel, type PanelModeler } from '../modeler/Eip4Panel'; // bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON // 会与官方选项类型产生摩擦;照 ProcessDiagram 惯例把构造器收窄为本页用到的最小契约再实例化。 @@ -45,6 +46,8 @@ export function ProcessModelerPage() { const canvasRef = useRef(null); const panelRef = useRef(null); const modelerRef = useRef(null); + // Modeler 实例入 state 以驱动 Eip4Panel 重渲染(selection.changed 订阅需要真实例)。 + const [modelerReady, setModelerReady] = useState(null); // 净化映射 原id→净化id:本阶段仅暂存,发布还原(T3.x)时用。 const idMapRef = useRef>({}); @@ -116,6 +119,7 @@ export function ProcessModelerPage() { await modeler.importXML(src.bpmnXml); if (!alive) return; modelerRef.current = modeler; + setModelerReady(modeler); try { const canvas = modeler.get('canvas') as { zoom(mode: string, point?: string): void }; canvas.zoom('fit-viewport', 'auto'); @@ -141,6 +145,7 @@ export function ProcessModelerPage() { } } modelerRef.current = null; + setModelerReady(null); }; }, [isAdmin, procDefId, procKey]); @@ -263,13 +268,8 @@ export function ProcessModelerPage() { minHeight: 0, }} > - {/* EIP4 定制侧板占位(办理人/会签/formKey…由 T2.4 接入) */} -
- EIP4 定制控件(办理人 / 会签 / formKey)将在此叠加,下阶段接入。 -
+ {/* EIP4 定制侧板(办理人/会签/formKey/扩展属性/监听器)——选中 userTask 时叠加 */} + {/* 标准属性面板宿主(bpmn-js-properties-panel attachTo 进此容器) */}
From 11632b48019b7aa6fe7deb2a60f1b3c0f9c1829f Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 2 Jul 2026 11:36:53 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix(modeler):=20codec=20=E8=AF=84=E5=AE=A1?= =?UTF-8?q?=E6=94=B6=E5=8F=A3=E2=80=94=E2=80=94stringToJson=E5=BC=95?= =?UTF-8?q?=E5=8F=B7=E6=98=A0=E5=B0=84+=E5=8D=8A=E8=A7=92content=E5=8F=98?= =?UTF-8?q?=E4=BD=93+item=E6=9C=AA=E7=9F=A5=E9=94=AE=E9=80=8F=E4=BC=A0+?= =?UTF-8?q?=E5=BD=A2=E7=8A=B6=E5=AE=88=E5=8D=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 评审者跑全库 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 --- src/modeler/candidateExpression.test.ts | 103 ++++++++++++++ src/modeler/candidateExpression.ts | 80 ++++++++--- tools/codec-corpus-sweep.mjs | 178 ++++++++++++++++++++++++ 3 files changed, 340 insertions(+), 21 deletions(-) create mode 100644 tools/codec-corpus-sweep.mjs diff --git a/src/modeler/candidateExpression.test.ts b/src/modeler/candidateExpression.test.ts index d9f3449..c6fb8c2 100644 --- a/src/modeler/candidateExpression.test.ts +++ b/src/modeler/candidateExpression.test.ts @@ -199,4 +199,107 @@ describe('非法/空输入返回 null 不抛', () => { "${candidateUsersHandler.getCandidateUsers(execution,'【\"foo\":1】')}"; expect(parseCandidateExpression(noItems)).toBeNull(); }); + + // M-2 形状守卫 + it('items 元素非对象(字符串)→ null 不抛', () => { + const bad = + "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[\"notanobject\"]】')}"; + expect(() => parseCandidateExpression(bad)).not.toThrow(); + expect(parseCandidateExpression(bad)).toBeNull(); + }); + + it('items 元素 type 非字符串(数字)→ null', () => { + const bad = + "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[【\"type\":123,\"content\":\"x\"】]】')}"; + expect(parseCandidateExpression(bad)).toBeNull(); + }); + + it('items 元素为 null → null', () => { + const bad = + "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[null]】')}"; + expect(parseCandidateExpression(bad)).toBeNull(); + }); +}); + +describe('I-1 stringToJson 引号映射(T2.4 接用户输入前必须)', () => { + const CAND_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'"; + function body(built: string): string { + return built.slice(CAND_PREFIX.length, built.length - "')}".length); + } + + it("content 含 ' 和 \" → build 映射为 ‘/“,值层无裸 '/\"、外层 JUEL 定界符不被截断", () => { + const item: UserPropertyItem = { + type: 'user', + content: `O'Brien "Ann"`, + isCandidate: true, + isSendMail: false, + isSendPhone: false, + isSendMessage: false, + }; + const built = buildCandidateExpression([item], 'candidate'); + // JUEL 单引号字面量安全:整个内容段不得出现裸 ASCII 单引号(否则截断 execution,'...')。 + // 注意 " 是 JSON 结构定界符会合法出现于内容段,故只对 ' 断言整段无裸值。 + expect(body(built)).not.toContain("'"); + // JSON 结构安全:值里的 " 已映射走,build 产物仍是良构表达式,可无损 parse 回来。 + const r = parseCandidateExpression(built); + expect(r).not.toBeNull(); + const c = r!.items[0].content; + expect(c).toContain('‘'); // O‘Brien + expect(c).toContain('“'); // “Ann“(开闭同映射为左引号,与 stringToJson 逐字一致) + expect(c).not.toContain("'"); + expect(c).not.toContain('"'); + expect(built.startsWith(CAND_PREFIX)).toBe(true); + expect(built.endsWith("')}")).toBe(true); + }); + + it('引号映射幂等:build 产物再 parse→build 稳定不变', () => { + const built = buildCandidateExpression( + [{ type: 'user', content: `x'y"z`, isCandidate: true, isSendMail: false, isSendPhone: false }], + 'candidate', + ); + const r = parseCandidateExpression(built)!; + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(built); + }); + + it('meta 字符串叶子(messageTemplate)同样应用引号映射', () => { + const built = buildCandidateExpression( + [{ type: 'user', content: 'u1', isCandidate: true, isSendMail: false, isSendPhone: false }], + 'candidate', + { messageTemplate: `it's` }, + ); + expect(built).toContain('it‘s'); + expect(body(built)).not.toContain("'"); + }); +}); + +describe('I-2 半角 content 变体(scriptUser ${users})——运行期等价', () => { + // 语料实测 20 条:content 用半角 ${users}(非 stringToJson 产物)。parse 保留原值, + // build 把结构性 {} 连同 content 里半角 {} 一并规范化为全角——非字节逐字,但引擎运行期 + // 对整串全局 【→{ 还原后完全等价。 + const HALF = + "${multiInstanceUsersHandler.getUsers(execution,'【\"items\":[【\"type\":\"scriptUser\",\"content\":\"${users}\",\"isCandidate\":true,\"isSendMail\":false,\"isSendPhone\":false】]】')}"; + // 镜像引擎 CandidateUsersHandler:54 的全局字面替换 + const engineRestore = (s: string): string => s.split('【').join('{').split('】').join('}'); + + it('半角 content 可解析,原值保留', () => { + const r = parseCandidateExpression(HALF)!; + expect(r.items[0]).toMatchObject({ type: 'scriptUser', content: '${users}' }); + }); + + it('build 输出恒全角(content 半角{}被规范化),但引擎全局替换后与原文等价', () => { + const r = parseCandidateExpression(HALF)!; + const built = buildCandidateExpression(r.items, r.variant, r.meta); + expect(built).toContain('$【users】'); // 非字节逐字 + expect(engineRestore(built)).toBe(engineRestore(HALF)); // 运行期等价 + }); +}); + +describe('M-1 item 未知键透传(不静默丢未来扩展键,与 meta 全量保留对称)', () => { + it('未知 item 键排在已知键之后,往返逐字不丢', () => { + const WITH_UNKNOWN = + "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[【\"type\":\"user\",\"content\":\"u1\",\"isCandidate\":true,\"isSendMail\":false,\"isSendPhone\":false,\"futureFlag\":true】]】')}"; + const r = parseCandidateExpression(WITH_UNKNOWN)!; + expect((r.items[0] as Record).futureFlag).toBe(true); + expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(WITH_UNKNOWN); + }); }); diff --git a/src/modeler/candidateExpression.ts b/src/modeler/candidateExpression.ts index fcdc824..f409bfc 100644 --- a/src/modeler/candidateExpression.ts +++ b/src/modeler/candidateExpression.ts @@ -8,12 +8,22 @@ // CandidateUsersHandler:54 以 `.replace("【","{").replace("】","}")`(全局字面替换) // 还原为合法 JSON 再交 Jackson 解析。本编解码器 build 输出恒全角、parse 兼容全角/半角。 // - 外层对象结构:{"items":[{...}],"messageTemplate","taskSuccessService", -// "isSkipInitiator","isNoUserSkip","isSkipBeforeTask"}。引擎运行期候选人解析 -// (convertToUserProperties)只读 items,但 taskSuccessService 等是任务后置服务钩子等 -// 运行期业务字段——侧板只改 items 时必须原样带回(meta),否则重新部署会打掉这些字段。 +// "isSkipInitiator","isNoUserSkip","isSkipBeforeTask"}(语料实测 meta 键集有多种子集)。 +// 引擎运行期候选人解析(convertToUserProperties)只读 items,但 taskSuccessService 等是 +// 任务后置服务钩子等运行期业务字段——侧板只改 items 时必须原样带回(meta),否则重新部署 +// 会打掉这些字段。 +// - 字符串叶子值(content/messageTemplate 等)的转义逐字对齐原版 stringToJson +// (BasePropertiesConverter.java:235-280):`'`→‘(U+2018)、`"`→“(U+201C)、 +// `{`→【、`}`→】,反斜杠与控制字符走标准 JSON 转义。build 对新值应用此契约,防用户输入 +// 含 `'`(截断外层 JUEL 单引号字面量)或 `"`(截断内层 JSON)导致部署后表达式解析即断。 // -// 逐字往返约定:content 不含花括号(与引擎的全局替换同约定),故 JSON.stringify 产出的 -// 结构性 {} 全局换成全角是安全的;content 里的逗号分隔多值与 CHAR 尾部补白空格原样保留。 +// 逐字往返口径(全量 1512 流 4794 条真实表达式实测,见 tools/codec-corpus-sweep.mjs): +// - 4774/4794 build(parse(x))===x 逐字一致;`‘`/`“`/`\/` 在语料 0 命中,故新增引号 +// 转义对存量表达式为 no-op(合法存量叶子值不含裸 ' / ",否则会截断 JUEL/JSON)。 +// - 余 20 条 content 用**半角** `${users}`(scriptUser 会签变体,非 stringToJson 产物): +// parse 保留原值,build 把结构性 {} 连同 content 里的半角 {} 一并规范化为全角【】。此非字节 +// 逐字,但**运行期等价**——引擎 :54 对整串做全局 【→{ 还原,`$【users】` 复原为 `${users}`。 +// - content 里的逗号分隔多值与 CHAR 尾部补白空格原样保留。 const CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'"; const MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'"; @@ -38,6 +48,10 @@ export interface ParsedCandidateExpression { meta: Record; } +/** item 的规范键序;未知键在其后按原序透传(与 meta 全量保留对称,不静默丢未来扩展键)。 */ +const KNOWN_ITEM_KEYS = ['type', 'content', 'isCandidate', 'isSendMail', 'isSendPhone', 'isSendMessage']; +const KNOWN_ITEM_KEY_SET = new Set(KNOWN_ITEM_KEYS); + function fullToHalf(s: string): string { return s.split('【').join('{').split('】').join('}'); } @@ -46,21 +60,31 @@ function halfToFull(s: string): string { return s.split('{').join('【').split('}').join('】'); } -/** 按固定规范键序重建 item,只输出存在的键(不凭空增删),保证逐字确定性。 */ -function normalizeItem(it: UserPropertyItem): UserPropertyItem { - const o = {} as UserPropertyItem; - o.type = it.type; - o.content = it.content; - if (it.isCandidate !== undefined) o.isCandidate = it.isCandidate; - if (it.isSendMail !== undefined) o.isSendMail = it.isSendMail; - if (it.isSendPhone !== undefined) o.isSendPhone = it.isSendPhone; - if (it.isSendMessage !== undefined) o.isSendMessage = it.isSendMessage; +/** + * 字符串叶子值转义,逐字对齐原版 stringToJson 里 JSON.stringify **未覆盖**的两处值级映射: + * `'`→‘、`"`→“。(反斜杠/控制字符由 JSON.stringify 覆盖;`{`/`}`→【/】由 halfToFull 覆盖。) + * 对合法存量叶子值(不含裸 ' / ")为 no-op,故不破坏逐字往返;仅对面板新输入生效。 + */ +function escapeLeaf(v: string): string { + return v.split("'").join('‘').split('"').join('“'); +} + +/** 按规范键序重建 item:已知键在前(存在才输出,不凭空增删),未知键按原序透传。 */ +function reorderItem(src: Record): Record { + const o: Record = {}; + for (const k of KNOWN_ITEM_KEYS) { + if (src[k] !== undefined) o[k] = src[k]; + } + for (const k of Object.keys(src)) { + if (!KNOWN_ITEM_KEY_SET.has(k) && src[k] !== undefined) o[k] = src[k]; + } return o; } /** * 解析办理人/会签表达式。识别 candidate / multiInstance 两种前缀,内容段全角【】→{} 后 JSON.parse。 - * 非办理人表达式、缺后缀、坏 JSON、无 items 数组、undefined/空串一律返回 null 不抛。 + * 非办理人表达式、缺后缀、坏 JSON、无 items 数组、items 元素非对象或 type 非字符串、 + * undefined/空串一律返回 null 不抛。 */ export function parseCandidateExpression( expr: string | undefined | null, @@ -91,7 +115,15 @@ export function parseCandidateExpression( const record = obj as Record; if (!Array.isArray(record.items)) return null; - const items = (record.items as UserPropertyItem[]).map(normalizeItem); + // 形状守卫:元素必须是普通对象且 type 为字符串,否则整体返 null(对齐「非法返 null 不抛」)。 + for (const el of record.items) { + if (el === null || typeof el !== 'object' || Array.isArray(el)) return null; + if (typeof (el as Record).type !== 'string') return null; + } + + const items = (record.items as Record[]).map( + reorderItem, + ) as unknown as UserPropertyItem[]; const meta: Record = { ...record }; delete meta.items; @@ -99,8 +131,9 @@ export function parseCandidateExpression( } /** - * 构建办理人/会签表达式:重建外层对象 {items, ...meta} → JSON.stringify(紧凑无空白)→ - * 结构性 {} 换成全角【】(方括号保持半角)→ 套前后缀。round-trip 与真实表达式逐字一致。 + * 构建办理人/会签表达式:重建外层对象 {items, ...meta} → JSON.stringify(紧凑无空白,replacer + * 对字符串叶子应用 stringToJson 引号映射)→ 结构性 {} 换成全角【】(方括号保持半角)→ 套前后缀。 + * round-trip 与真实表达式逐字一致(半角 content 变体除外,见文件头运行期等价说明)。 */ export function buildCandidateExpression( items: UserPropertyItem[], @@ -108,7 +141,12 @@ export function buildCandidateExpression( meta?: Record, ): string { const prefix = variant === 'multiInstance' ? MULTI_PREFIX : CANDIDATE_PREFIX; - const outer = { items: items.map(normalizeItem), ...(meta ?? {}) }; - const content = halfToFull(JSON.stringify(outer)); - return prefix + content + SUFFIX; + const outer = { + items: items.map((it) => reorderItem(it as unknown as Record)), + ...(meta ?? {}), + }; + const json = JSON.stringify(outer, (_key, value) => + typeof value === 'string' ? escapeLeaf(value) : value, + ); + return prefix + halfToFull(json) + SUFFIX; } diff --git a/tools/codec-corpus-sweep.mjs b/tools/codec-corpus-sweep.mjs new file mode 100644 index 0000000..e788690 --- /dev/null +++ b/tools/codec-corpus-sweep.mjs @@ -0,0 +1,178 @@ +#!/usr/bin/env node +/** + * 语料级办理人/会签表达式 codec 往返核查(T2.3 评审加分项) + * + * 对本地 eip4 库(5433, search_path=eip3)里 act_ge_bytearray 的全部真实 BPMN,抽出每个 + * activiti/flowable 的 candidateUsers / collection 属性值(实体解码到 businessObject 属性 + * 值层),跑与 src/modeler/candidateExpression.ts **逐字镜像**的 parse/build,统计: + * - byteIdentical : build(parse(x)) === x 逐字一致 + * - engineEquiv : 非逐字但引擎运行期等价(整串全局 【→{ 、】→} 还原后相同) + * —— 覆盖 content 用半角 ${users} 的 scriptUser 会签变体(build 归一为全角, + * 引擎 CandidateUsersHandler:54 全局替换后复原,语义无损) + * - parseNull : 前缀匹配但解析失败(硬失败) + * - hardMismatch : 既非逐字亦非引擎等价(硬失败) + * + * ⚠️ 本文件内联的 parse/build 必须与 candidateExpression.ts 保持一致;单测 + * (candidateExpression.test.ts)是编解码契约的权威来源,本工具是全语料回归的旁证。 + * + * 取数:psql 子进程(不引 pg 依赖),同 tools/modeler-fidelity-sweep.mjs。 + * 用法:node tools/codec-corpus-sweep.mjs + * 环境变量:PG_HOST(localhost) PG_PORT(5433) PG_DB(eip4) PG_SCHEMA(eip3) EXPECTED_TOTAL(1512) + */ +import { execFileSync } from 'node:child_process'; + +const PG_HOST = process.env.PG_HOST || 'localhost'; +const PG_PORT = process.env.PG_PORT || '5433'; +const PG_DB = process.env.PG_DB || 'eip4'; +const PG_SCHEMA = process.env.PG_SCHEMA || 'eip3'; +const EXPECTED_TOTAL = Number(process.env.EXPECTED_TOTAL || 1512); + +// ── 镜像 src/modeler/candidateExpression.ts(逐字)──────────────────────────── +const CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'"; +const MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'"; +const SUFFIX = "')}"; +const KNOWN_ITEM_KEYS = ['type', 'content', 'isCandidate', 'isSendMail', 'isSendPhone', 'isSendMessage']; +const KNOWN_ITEM_KEY_SET = new Set(KNOWN_ITEM_KEYS); +const fullToHalf = (s) => s.split('【').join('{').split('】').join('}'); +const halfToFull = (s) => s.split('{').join('【').split('}').join('】'); +const escapeLeaf = (v) => v.split("'").join('‘').split('"').join('“'); +function reorderItem(src) { + const o = {}; + for (const k of KNOWN_ITEM_KEYS) if (src[k] !== undefined) o[k] = src[k]; + for (const k of Object.keys(src)) if (!KNOWN_ITEM_KEY_SET.has(k) && src[k] !== undefined) o[k] = src[k]; + return o; +} +function parse(expr) { + if (typeof expr !== 'string' || expr.length === 0) return null; + let variant, prefix; + if (expr.startsWith(CANDIDATE_PREFIX)) { variant = 'candidate'; prefix = CANDIDATE_PREFIX; } + else if (expr.startsWith(MULTI_PREFIX)) { variant = 'multiInstance'; prefix = MULTI_PREFIX; } + else return null; + if (!expr.endsWith(SUFFIX)) return null; + const content = expr.slice(prefix.length, expr.length - SUFFIX.length); + let obj; + try { obj = JSON.parse(fullToHalf(content)); } catch { return null; } + if (obj === null || typeof obj !== 'object') return null; + if (!Array.isArray(obj.items)) return null; + for (const el of obj.items) { + if (el === null || typeof el !== 'object' || Array.isArray(el)) return null; + if (typeof el.type !== 'string') return null; + } + const items = obj.items.map(reorderItem); + const meta = { ...obj }; + delete meta.items; + return { items, variant, meta }; +} +function build(items, variant, meta) { + const prefix = variant === 'multiInstance' ? MULTI_PREFIX : CANDIDATE_PREFIX; + const outer = { items: items.map(reorderItem), ...(meta ?? {}) }; + const json = JSON.stringify(outer, (_k, v) => (typeof v === 'string' ? escapeLeaf(v) : v)); + return prefix + halfToFull(json) + SUFFIX; +} +// 镜像引擎 CandidateUsersHandler:54 的整串全局字面替换 +const engineRestore = (s) => s.split('【').join('{').split('】').join('}'); +// ───────────────────────────────────────────────────────────────────────── + +function decodeEntities(s) { + return String(s) + .replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16))) + .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10))) + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&'); +} + +function pullCorpus() { + const sql = + `set search_path=${PG_SCHEMA},public; ` + + `select b.id_||'|'||translate(encode(b.bytes_,'base64'),E'\\n','') ` + + `from act_ge_bytearray b where b.name_ like '%.bpmn%' or b.name_ like '%.xml';`; + const out = execFileSync( + 'psql', + ['-h', PG_HOST, '-p', PG_PORT, '-d', PG_DB, '-tA', '-c', sql], + { encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024 }, + ); + const docs = []; + for (const line of out.split('\n')) { + if (!line) continue; + const i = line.indexOf('|'); + if (i < 0) continue; + docs.push({ id: line.slice(0, i), b64: line.slice(i + 1) }); + } + return docs; +} + +function main() { + process.stdout.write(`连库拉取语料 (${PG_HOST}:${PG_PORT}/${PG_DB}, schema=${PG_SCHEMA}) ...\n`); + const docs = pullCorpus(); + process.stdout.write(`取到 ${docs.length} 个 .bpmn/.xml 文档,开始 codec 往返扫描 ...\n\n`); + + const EXPR_RE = /(?:activiti|flowable):(?:candidateUsers|collection)="([^"]*)"/g; + let exprs = 0; + let byteIdentical = 0; + let engineEquiv = 0; + let parseNull = 0; + let hardMismatch = 0; + const itemKeySets = new Map(); + const metaKeySets = new Map(); + const hardSamples = []; + const parseNullSamples = []; + + for (const doc of docs) { + const xml = Buffer.from(doc.b64, 'base64').toString('utf8'); + let m; + EXPR_RE.lastIndex = 0; + while ((m = EXPR_RE.exec(xml)) !== null) { + const val = decodeEntities(m[1]); + if (!val.includes('Handler')) continue; // collection 也可是普通变量名,非 handler 表达式 + exprs++; + const r = parse(val); + if (!r) { + parseNull++; + if (parseNullSamples.length < 5) parseNullSamples.push(val.slice(0, 200)); + continue; + } + for (const it of r.items) itemKeySets.set(Object.keys(it).join(','), (itemKeySets.get(Object.keys(it).join(',')) || 0) + 1); + metaKeySets.set(Object.keys(r.meta).join(','), (metaKeySets.get(Object.keys(r.meta).join(',')) || 0) + 1); + const rebuilt = build(r.items, r.variant, r.meta); + if (rebuilt === val) byteIdentical++; + else if (engineRestore(rebuilt) === engineRestore(val)) engineEquiv++; + else { + hardMismatch++; + if (hardSamples.length < 5) hardSamples.push({ val: val.slice(0, 300), rebuilt: rebuilt.slice(0, 300) }); + } + } + } + + const line = '─'.repeat(60); + process.stdout.write(`${line}\ncodec 往返扫描结果\n${line}\n`); + process.stdout.write(`总文档 ${docs.length}(预期 ${EXPECTED_TOTAL})|表达式 ${exprs}\n`); + process.stdout.write(`逐字一致 ${byteIdentical}|引擎运行期等价 ${engineEquiv}|解析失败 ${parseNull}|硬不匹配 ${hardMismatch}\n`); + process.stdout.write(`\nitem 键集分布:\n`); + for (const [k, c] of [...itemKeySets].sort((a, b) => b[1] - a[1])) process.stdout.write(` ${c.toString().padStart(6)} [${k}]\n`); + process.stdout.write(`\nmeta 键集分布:\n`); + for (const [k, c] of [...metaKeySets].sort((a, b) => b[1] - a[1])) process.stdout.write(` ${c.toString().padStart(6)} [${k || '(空)'}]\n`); + if (parseNullSamples.length) { + process.stdout.write(`\n解析失败样本:\n`); + for (const s of parseNullSamples) process.stdout.write(` ${s}\n`); + } + if (hardSamples.length) { + process.stdout.write(`\n硬不匹配样本(既非逐字亦非引擎等价):\n`); + for (const s of hardSamples) process.stdout.write(` 原文: ${s.val}\n 重建: ${s.rebuilt}\n`); + } + process.stdout.write(`${line}\n`); + + // 硬门:每条表达式都能解析,且要么逐字要么引擎等价(无硬失败),且语料规模符合预期。 + const gateOk = parseNull === 0 && hardMismatch === 0 && docs.length === EXPECTED_TOTAL; + process.exit(gateOk ? 0 : 1); +} + +try { + main(); +} catch (e) { + if (e && e.stderr) process.stderr.write(String(e.stderr)); + process.stderr.write(`扫描崩溃: ${(e && e.stack) || e}\n`); + process.exit(2); +} From 6fceff784d06196802d4c6f7dd51ec8140e55ea0 Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 2 Jul 2026 11:38:08 +0800 Subject: [PATCH 4/7] =?UTF-8?q?test(modeler):=20=E4=BE=A7=E6=9D=BF?= =?UTF-8?q?=E5=8A=9E=E7=90=86=E4=BA=BA=E8=A1=A5=E6=92=87=E5=8F=B7=E8=BD=AC?= =?UTF-8?q?=E4=B9=89=E7=94=A8=E4=BE=8B(=E6=B6=88=E8=B4=B9=20codec=20?= =?UTF-8?q?=E5=BC=95=E5=8F=B7=E8=BD=AC=E4=B9=89,=E9=98=B2=E6=88=AA?= =?UTF-8?q?=E6=96=AD=20JUEL)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 1 例:content 含撇号 O'Brien → 写回载荷内容段(剥离 JUEL 前后缀定界引号) 无裸 ASCII 单引号、含全角‘,验证侧板经 codec build 受引号转义保护。 Eip4Panel 测试 20→21;仅提交本测试文件,codec 由并行 T2.3 收口。 Co-Authored-By: Claude Fable 5 --- src/modeler/Eip4Panel.test.tsx | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/modeler/Eip4Panel.test.tsx b/src/modeler/Eip4Panel.test.tsx index 983c88d..2e9a8df 100644 --- a/src/modeler/Eip4Panel.test.tsx +++ b/src/modeler/Eip4Panel.test.tsx @@ -162,6 +162,24 @@ describe('Eip4Panel — 办理人(candidateUsers)', () => { const parsed = parseCandidateExpression(written)!; expect(parsed.items[0]).toMatchObject({ type: 'scriptUser', content: '${APPLYUSERS}' }); }); + + // codec build 对叶子值应用引擎 stringToJson 转义(' → ‘、" → “),防用户输入含撇号/双引号 + // 截断外层 JUEL 单引号字面量或内层 JSON。侧板消费 codec 即受保护——断言写回载荷的内容段 + // (剥离 JUEL 前后缀定界引号后)无裸 ASCII 撇号、有全角‘。 + it("content 含撇号 O'Brien:写回载荷转义为‘、内容段无裸单引号(防截断 JUEL 字面量)", async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); + fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), { + target: { value: "O'Brien" }, + }); + const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string; + const PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'"; + const SUFFIX = "')}"; + const content = written.slice(PREFIX.length, written.length - SUFFIX.length); + expect(content).toContain('O‘Brien'); // U+2018 全角撇号 + expect(content.includes("'")).toBe(false); // 内容段完全无裸 ASCII 单引号 + }); }); describe('Eip4Panel — 会签(multiInstance)', () => { From a9a304ab3da47012c4fde72b73c56531d5e49ccc Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 2 Jul 2026 12:01:26 +0800 Subject: [PATCH 5/7] =?UTF-8?q?fix(modeler):=20=E4=BE=A7=E6=9D=BF=E8=AF=84?= =?UTF-8?q?=E5=AE=A1=E6=94=B6=E5=8F=A3=E2=80=94=E2=80=94=E4=BC=9A=E7=AD=BE?= =?UTF-8?q?=E4=BF=9D=E7=9C=9F=E8=AF=BB=E5=9B=9E/=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E5=9B=9E=E5=BD=92=E6=B5=8B=E8=AF=95/meta?= =?UTF-8?q?=E5=8F=AF=E8=A7=81=E6=80=A7+=E6=B8=85=E9=99=A4=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/modeler/Eip4Panel.test.tsx | 225 ++++++++++++++++++++++++++++-- src/modeler/Eip4Panel.tsx | 242 +++++++++++++++++++++++++-------- 2 files changed, 406 insertions(+), 61 deletions(-) diff --git a/src/modeler/Eip4Panel.test.tsx b/src/modeler/Eip4Panel.test.tsx index 2e9a8df..c5592f7 100644 --- a/src/modeler/Eip4Panel.test.tsx +++ b/src/modeler/Eip4Panel.test.tsx @@ -1,7 +1,11 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'; import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn'; -import { parseCandidateExpression } from './candidateExpression'; +import { + parseCandidateExpression, + buildCandidateExpression, + type UserPropertyItem, +} from './candidateExpression'; // formKey 下拉数据源:mock,其中一个 id 对齐 fixture 的 formKey 值。 vi.mock('../api/processModeler', () => ({ @@ -28,7 +32,8 @@ const REAL_CANDIDATE = extractAttr('activiti:candidateUsers'); // type=position // ── 假 modeler / element(vi.fn 捕获 updateProperties 载荷) ──────────────────── function makeModeler() { - let handler: ((e: unknown) => void) | null = null; + let selHandler: ((e: unknown) => void) | null = null; + let cmdHandler: (() => void) | null = null; const updateProperties = vi.fn(); const created: Array> = []; const moddle = { @@ -40,7 +45,8 @@ function makeModeler() { }; const modeling = { updateProperties }; const on = vi.fn((ev: string, cb: (e: unknown) => void) => { - if (ev === 'selection.changed') handler = cb; + if (ev === 'selection.changed') selHandler = cb; + if (ev === 'commandStack.changed') cmdHandler = cb as () => void; }); const off = vi.fn(); const get = (svc: string) => (svc === 'modeling' ? modeling : svc === 'moddle' ? moddle : {}); @@ -49,11 +55,38 @@ function makeModeler() { // 避免「update not wrapped in act」告警。 const select = (element: unknown) => act(async () => { - handler?.({ newSelection: element ? [element] : [] }); + selHandler?.({ newSelection: element ? [element] : [] }); await Promise.resolve(); await Promise.resolve(); }); - return { modeler, updateProperties, moddle, created, select }; + // 模拟外部 undo/redo:commandStack.changed。 + const fireCommandStack = () => + act(async () => { + cmdHandler?.(); + await Promise.resolve(); + }); + return { modeler, updateProperties, moddle, created, select, fireCommandStack }; +} + +/** 全项目 window.confirm 默认放行(具体测试可再 spy 覆盖);afterEach 复原。 */ +let confirmSpy: ReturnType; +beforeEach(() => { + confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); +}); +afterEach(() => { + confirmSpy.mockRestore(); +}); + +/** 一个内容非空、meta 为空的合法办理人表达式(清空时不触发 confirm)。 */ +function candidateNoMeta(content = 'u1'): string { + const item: UserPropertyItem = { + type: 'user', + content, + isCandidate: true, + isSendMail: false, + isSendPhone: false, + }; + return buildCandidateExpression([item], 'candidate', {}); } /** 造一个 userTask element:map=businessObject.get(name) 源,$attrs=原始扩展属性袋。 */ @@ -138,13 +171,51 @@ describe('Eip4Panel — 办理人(candidateUsers)', () => { expect(parsed.items[0].content).toBe('changed'); }); - it('清空最后一行:写回 undefined(清除属性)', async () => { + it('清空最后一行(meta 为空):无 confirm,直接写回 undefined', async () => { const { modeler, updateProperties, select } = makeModeler(); render(); + await select(userTask({ 'activiti:candidateUsers': candidateNoMeta() })); + fireEvent.click(screen.getByTestId('eip4-candidate-remove-0')); + expect(confirmSpy).not.toHaveBeenCalled(); + expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined(); + expect('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true); + }); + + it('I-3 清空含非空业务 meta:confirm=确认 → 写回 undefined', async () => { + const { modeler, updateProperties, select } = makeModeler(); + confirmSpy.mockReturnValue(true); + render(); await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); fireEvent.click(screen.getByTestId('eip4-candidate-remove-0')); + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect(String(confirmSpy.mock.calls[0][0])).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS'); expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined(); - expect('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true); + }); + + it('I-3 清空含非空业务 meta:confirm=取消 → 不写回、行仍在', async () => { + const { modeler, updateProperties, select } = makeModeler(); + confirmSpy.mockReturnValue(false); + render(); + await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); + fireEvent.click(screen.getByTestId('eip4-candidate-remove-0')); + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect(updateProperties).not.toHaveBeenCalled(); // 引擎未变 + expect(screen.getByTestId('eip4-candidate-content-0')).toBeInTheDocument(); // 行未删 + }); + + it('I-3 非空业务 meta 顶部只读徽标显示任务后置服务', async () => { + const { modeler, select } = makeModeler(); + render(); + await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); + const badge = screen.getByTestId('eip4-candidate-meta-badge'); + expect(badge.textContent).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS'); + }); + + it('顺手:非标准办理人表达式显示「编辑将覆盖」警示', async () => { + const { modeler, select } = makeModeler(); + render(); + await select(userTask({ 'activiti:candidateUsers': '${someOtherExpr(execution)}' })); + expect(screen.getByTestId('eip4-candidate-nonstandard')).toBeInTheDocument(); }); it('增行:改 type 下拉写回对应 type', async () => { @@ -243,6 +314,69 @@ describe('Eip4Panel — 会签(multiInstance)', () => { '${nrOfCompletedInstances/nrOfInstances>0.5}', ); }); + + // ── I-1 会签保真:读回并原样保留 isSequential / elementVariable / 非预设完成条件 ────── + // 真实库存在 isSequential=true、elementVariable=assign、完成条件 >0.6 等形态;强写会静默改坏。 + function cosignLoop() { + return moddleEl('bpmn:MultiInstanceLoopCharacteristics', { + isSequential: true, + 'activiti:collection': extractAttr('activiti:collection'), + 'activiti:elementVariable': 'assign', + completionCondition: { body: '${nrOfCompletedInstances/nrOfInstances>0.6}' }, + }); + } + + it('I-1 串行会签往返保 isSequential=true(不被强写 false)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ loopCharacteristics: cosignLoop() })); + expect((screen.getByTestId('eip4-cosign-sequential') as HTMLInputElement).checked).toBe(true); + // 触发一次写(编辑会签人员 content),断言 isSequential 保留 true + fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } }); + const loop = lastPayload(updateProperties).loopCharacteristics as Record; + expect(loop.isSequential).toBe(true); + }); + + it('I-1 elementVariable=assign 往返保 assign(不被强写 assignee)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ loopCharacteristics: cosignLoop() })); + expect((screen.getByTestId('eip4-cosign-element-variable') as HTMLInputElement).value).toBe('assign'); + fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } }); + const loop = lastPayload(updateProperties).loopCharacteristics as Record; + expect(loop['activiti:elementVariable']).toBe('assign'); + }); + + it('I-1 非预设完成条件 >0.6 不被归一为全票(自定义态保留原 body)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask({ loopCharacteristics: cosignLoop() })); + // 下拉显「自定义(保留)」+ 原 body 展示 + expect(screen.getByText(/自定义(保留)/)).toBeInTheDocument(); + expect(screen.getByTestId('eip4-cosign-completion-custom').textContent).toContain( + '${nrOfCompletedInstances/nrOfInstances>0.6}', + ); + fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } }); + const loop = lastPayload(updateProperties).loopCharacteristics as Record; + expect((loop.completionCondition as { body: string }).body).toBe( + '${nrOfCompletedInstances/nrOfInstances>0.6}', + ); + }); + + it('I-1 缺 elementVariable 的会签:写回省略该属性(不凭空写空)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + const loop = moddleEl('bpmn:MultiInstanceLoopCharacteristics', { + isSequential: false, + 'activiti:collection': extractAttr('activiti:collection'), + // 无 activiti:elementVariable、无 completionCondition + }); + render(); + await select(userTask({ loopCharacteristics: loop })); + fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } }); + const written = lastPayload(updateProperties).loopCharacteristics as Record; + expect('activiti:elementVariable' in written).toBe(false); // 缺省态不写 + expect('completionCondition' in written).toBe(false); // 原本无完成条件不发出 + }); }); describe('Eip4Panel — formKey', () => { @@ -300,6 +434,28 @@ describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => { expect(screen.getByTestId('eip4-extattr-key-0')).toHaveValue('activiti:custom'); expect(screen.queryByTestId('eip4-extattr-key-1')).not.toBeInTheDocument(); }); + + it('顺手:无 activiti:/flowable: 前缀的新键被拒(不写回)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), { target: { value: 'foo' } }); + fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'v' } }); + fireEvent.click(screen.getByTestId('eip4-extattr-add')); + expect(updateProperties).not.toHaveBeenCalled(); + }); + + it('顺手:拉黑有专用控件的键(activiti:formKey)不允许从扩展属性写', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + await select(userTask()); + fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), { + target: { value: 'activiti:formKey' }, + }); + fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'x' } }); + fireEvent.click(screen.getByTestId('eip4-extattr-add')); + expect(updateProperties).not.toHaveBeenCalled(); + }); }); describe('Eip4Panel — 任务监听器(taskListener)', () => { @@ -366,3 +522,56 @@ describe('Eip4Panel — 任务监听器(taskListener)', () => { expect('class' in listener).toBe(false); }); }); + +describe('Eip4Panel — 切换节点 / undo-redo 重灌(评审 I-2 + 顺手)', () => { + it('I-2 A(meta X)→B(meta Y)→编辑 B→写回 meta===Y 且 ≠X', async () => { + const { modeler, updateProperties, select } = makeModeler(); + const item = (c: string): UserPropertyItem => ({ + type: 'user', + content: c, + isCandidate: true, + isSendMail: false, + isSendPhone: false, + isSendMessage: false, + }); + const exprA = buildCandidateExpression([item('a')], 'candidate', { taskSuccessService: 'SVC_X' }); + const exprB = buildCandidateExpression([item('b')], 'candidate', { taskSuccessService: 'SVC_Y' }); + render(); + await select(userTask({ __id: 'A', 'activiti:candidateUsers': exprA })); + await select(userTask({ __id: 'B', 'activiti:candidateUsers': exprB })); + // 编辑 B 的 content + fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), { target: { value: 'b2' } }); + const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string; + const meta = parseCandidateExpression(written)!.meta; + expect(meta.taskSuccessService).toBe('SVC_Y'); // 用 B 的 meta + expect(meta.taskSuccessService).not.toBe('SVC_X'); // 不串到 A 的 meta + }); + + it('顺手:commandStack.changed(外部 undo)对当前选中重灌本地态', async () => { + const { modeler, select, fireCommandStack } = makeModeler(); + const item = (c: string): UserPropertyItem => ({ + type: 'user', + content: c, + isCandidate: true, + isSendMail: false, + isSendPhone: false, + isSendMessage: false, + }); + // 可变 map:模拟外部 undo 改写 businessObject。 + const map: Record = { + 'activiti:candidateUsers': buildCandidateExpression([item('X')], 'candidate', {}), + }; + const el = { + id: 't1', + type: 'bpmn:UserTask', + businessObject: { $type: 'bpmn:UserTask', get: (n: string) => map[n] }, + }; + render(); + await select(el); + expect((screen.getByTestId('eip4-candidate-content-0') as HTMLInputElement).value).toBe('X'); + // 外部 undo 改了 businessObject → commandStack.changed → 重灌 + map['activiti:candidateUsers'] = buildCandidateExpression([item('Y')], 'candidate', {}); + await fireCommandStack(); + expect((screen.getByTestId('eip4-candidate-content-0') as HTMLInputElement).value).toBe('Y'); + }); +}); diff --git a/src/modeler/Eip4Panel.tsx b/src/modeler/Eip4Panel.tsx index 5312200..d046d1f 100644 --- a/src/modeler/Eip4Panel.tsx +++ b/src/modeler/Eip4Panel.tsx @@ -1,13 +1,18 @@ // EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。 // -// 设计要点(计划 T2.4 + §0.5 P5): -// - 全部写操作经 bpmn-js `modeling.updateProperties(element, {...})`,undo/redo 天然生效。 +// 设计要点(计划 T2.4 + §0.5 P5 + 评审收口): +// - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。 // - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。 -// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 ref, -// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。 -// - 扩展属性只列长尾 $attrs(已声明属性如 formKey/candidateUsers 不进 $attrs,故不重复)。 +// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 state, +// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。顶部只读徽标显示, +// 删光 items 时 confirm 确认才写 undefined(评审 I-3)。 +// - 🔴 会签保真(评审 I-1):isSequential/elementVariable/completionCondition 原始值读进 state、 +// 写回用读到的值(真实库有 isSequential=true / elementVariable=assign / 完成条件 >0.6 等 +// 非预设形态,强写会静默改坏派任);完成条件 body 不匹配预设时置「自定义(保留)」态, +// 仅用户主动选预设才改写。 +// - 扩展属性只列长尾 $attrs;新增强制 activiti:/flowable: 前缀并拉黑有专用控件的键。 // - taskListener 重建时原样保留其 field 子元素(moddle 元素引用不动)。 -// - 原生标准属性面板照旧显示于本侧板下方,本控件顶部灰字提示以本控件为准。 +// - undo/redo:订阅 commandStack.changed,非自身写入时对当前选中重灌本地态。 import { useEffect, useRef, useState } from 'react'; import { buildCandidateExpression, @@ -16,6 +21,7 @@ import { type UserPropertyItem, } from './candidateExpression'; import { fetchWfTemplates, type WfTemplateOption } from '../api/processModeler'; +import { toast } from '../components/ui'; import type { BpmnElement, SelectionModeler } from './useSelectedElement'; import { useSelectedElement } from './useSelectedElement'; @@ -46,22 +52,31 @@ const CANDIDATE_TYPES: Array<{ value: string; label: string }> = [ const LISTENER_EVENTS = ['create', 'assignment', 'complete', 'all']; +// 有专用控件的属性,禁止再从「扩展属性」兜底编辑器写入(去重、防冲突)。 +const RESERVED_EXT_LOCALNAMES = new Set(['candidateUsers', 'formKey', 'collection', 'elementVariable']); + // ── 会签完成条件预设 ───────────────────────────────────────────────────────── -type CompletionType = 'all' | 'majority' | 'count'; +type CompletionType = 'all' | 'majority' | 'count' | 'custom'; const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}'; const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}'; -function completionBody(type: CompletionType, n: number): string { - if (type === 'majority') return COMPLETION_MAJORITY; - if (type === 'count') return '${nrOfCompletedInstances>=' + n + '}'; +function completionBodyFor(s: CosignState): string { + if (s.completionType === 'majority') return COMPLETION_MAJORITY; + if (s.completionType === 'count') return '${nrOfCompletedInstances>=' + s.completionN + '}'; + if (s.completionType === 'custom') return s.completionCustomBody; return COMPLETION_ALL; } -function parseCompletion(body: string | undefined): { type: CompletionType; n: number } { - if (!body) return { type: 'all', n: 2 }; - if (body.indexOf('>0.5') >= 0) return { type: 'majority', n: 2 }; - const m = body.match(/nrOfCompletedInstances>=(\d+)/); - if (m) return { type: 'count', n: Number(m[1]) }; - return { type: 'all', n: 2 }; +// 精确匹配预设串(不用子串,否则 >0.55 会误判为过半);非预设/无 body → 自定义(保留)。 +function parseCompletion(body: string | undefined): { + type: CompletionType; + n: number; + custom: string; +} { + if (body === COMPLETION_ALL) return { type: 'all', n: 2, custom: '' }; + if (body === COMPLETION_MAJORITY) return { type: 'majority', n: 2, custom: '' }; + const m = body ? body.match(/^\$\{nrOfCompletedInstances>=(\d+)\}$/) : null; + if (m) return { type: 'count', n: Number(m[1]), custom: '' }; + return { type: 'custom', n: 2, custom: body ?? '' }; } // ── moddle 读值(兼容 .get(name) 与直读属性) ────────────────────────────────── @@ -72,6 +87,18 @@ function mget(obj: unknown, name: string): unknown { return o[name]; } +// 非空业务 meta → 只读徽标/确认文案(用于「删光办理人会一并移除 X」)。 +function notableMeta(meta: Record): string[] { + const out: string[] = []; + if (typeof meta.taskSuccessService === 'string' && meta.taskSuccessService) + out.push('任务后置服务:' + meta.taskSuccessService); + if (typeof meta.messageTemplate === 'string' && meta.messageTemplate) out.push('消息模板'); + if (meta.isSkipInitiator === true) out.push('跳过发起人'); + if (meta.isNoUserSkip === true) out.push('无办理人自动跳过'); + if (meta.isSkipBeforeTask === true) out.push('跳过前置任务办理人'); + return out; +} + function newCandidateItem(): UserPropertyItem { return { type: 'user', @@ -94,10 +121,26 @@ interface ListenerRow { interface CosignState { enabled: boolean; items: UserPropertyItem[]; + /** 保真:串行/并行,读回原值(真实库有 isSequential=true)。 */ + isSequential: boolean; + /** 保真:循环变量名,读回原值(真实库有 assign/loop_assign/缺省);为空则写回时省略该属性。 */ + elementVariable: string; completionType: CompletionType; completionN: number; + /** completionType==='custom' 时保留的原始 body;'' 表示原本无 completionCondition。 */ + completionCustomBody: string; } +const FRESH_COSIGN: CosignState = { + enabled: false, + items: [], + isSequential: false, + elementVariable: 'assignee', + completionType: 'all', + completionN: 2, + completionCustomBody: '', +}; + // ── items 编辑器(办理人 / 会签人员复用) ────────────────────────────────────── function ItemsEditor({ idPrefix, @@ -219,25 +262,24 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { const isUserTask = element?.type === 'bpmn:UserTask'; - // ── 本地编辑态(选中变更时从 businessObject 重新初始化) ────────────────────── + // ── 本地编辑态(选中变更 / undo-redo 时从 businessObject 重新初始化) ───────── const [candidateItems, setCandidateItems] = useState([]); - const [cosign, setCosign] = useState({ - enabled: false, - items: [], - completionType: 'all', - completionN: 2, - }); + const [candidateMeta, setCandidateMeta] = useState>({}); + const [candidateNonStandard, setCandidateNonStandard] = useState(false); + const [cosign, setCosign] = useState(FRESH_COSIGN); + const [cosignMeta, setCosignMeta] = useState>({}); const [formKey, setFormKey] = useState(''); const [extAttrs, setExtAttrs] = useState>([]); const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' }); const [listeners, setListeners] = useState([]); const [templates, setTemplates] = useState([]); + // undo/redo 重灌计数:commandStack.changed(非自身写入)时自增,触发 init 重跑。 + const [syncTick, setSyncTick] = useState(0); - // meta 透传:codec parse 出的外层业务字段,写回时原样带回(不进 UI 渲染,只存 ref)。 - const candidateMetaRef = useRef>({}); - const cosignMetaRef = useRef>({}); // 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。 const otherExtRef = useRef([]); + // 自身写入标记:updateProperties 会触发 commandStack.changed,借此跳过自触发重灌。 + const selfWriteRef = useRef(false); // formKey 数据源加载一次。 useEffect(() => { @@ -250,42 +292,66 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { }; }, []); - // 选中变更 → 从 businessObject 重新初始化本地态。 + // undo/redo 脱同步防线:非自身写入的 commandStack 变更 → 对当前选中重灌本地态。 + useEffect(() => { + if (!modeler) return; + const handler = () => { + if (selfWriteRef.current) { + selfWriteRef.current = false; // 自身 updateProperties 触发,不重灌(避免规范化闪烁) + return; + } + setSyncTick((t) => t + 1); + }; + modeler.on('commandStack.changed', handler); + return () => { + modeler.off?.('commandStack.changed', handler); + }; + }, [modeler]); + + // 选中变更 / 外部命令 → 从 businessObject 重新初始化本地态。 useEffect(() => { if (!element || element.type !== 'bpmn:UserTask') { setCandidateItems([]); - setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); + setCandidateMeta({}); + setCandidateNonStandard(false); + setCosign(FRESH_COSIGN); + setCosignMeta({}); setFormKey(''); setExtAttrs([]); setNewAttr({ key: '', value: '' }); setListeners([]); - candidateMetaRef.current = {}; - cosignMetaRef.current = {}; otherExtRef.current = []; return; } const bo = element.businessObject; // 办理人 - const cand = parseCandidateExpression(bo.get('activiti:candidateUsers') as string | undefined); + const rawCand = bo.get('activiti:candidateUsers') as string | undefined; + const cand = parseCandidateExpression(rawCand); setCandidateItems(cand?.items ?? []); - candidateMetaRef.current = cand?.meta ?? {}; + setCandidateMeta(cand?.meta ?? {}); + setCandidateNonStandard(!!rawCand && !cand); // 非空但解析失败=非标准表达式 - // 会签 + // 会签(保真读回 isSequential/elementVariable/completionCondition 原值) const loop = bo.get('loopCharacteristics'); if (loop) { const parsed = parseCandidateExpression(mget(loop, 'activiti:collection') as string | undefined); - const cc = parseCompletion((mget(loop, 'completionCondition') as { body?: string } | undefined)?.body); + const cc = parseCompletion( + (mget(loop, 'completionCondition') as { body?: string } | undefined)?.body, + ); setCosign({ enabled: true, items: parsed?.items ?? [], + isSequential: Boolean(mget(loop, 'isSequential')), + elementVariable: (mget(loop, 'activiti:elementVariable') as string) ?? '', completionType: cc.type, completionN: cc.n, + completionCustomBody: cc.custom, }); - cosignMetaRef.current = parsed?.meta ?? {}; + setCosignMeta(parsed?.meta ?? {}); } else { - setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); - cosignMetaRef.current = {}; + setCosign(FRESH_COSIGN); + setCosignMeta({}); } // formKey @@ -319,22 +385,33 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { } as ListenerRow; }), ); - }, [element]); + }, [element, syncTick]); function update(props: Record) { - if (element && modeling) modeling.updateProperties(element, props); + if (element && modeling) { + selfWriteRef.current = true; + modeling.updateProperties(element, props); + } } // ── 办理人写回 ───────────────────────────────────────────────────────────── function writeCandidate(items: UserPropertyItem[]) { - setCandidateItems(items); if (items.length === 0) { + // 删光 items:若外层含非空业务 meta,confirm 确认才写 undefined(否则连带清除业务字段)。 + const notable = notableMeta(candidateMeta); + if ( + notable.length > 0 && + typeof window !== 'undefined' && + !window.confirm('清空办理人将一并移除:' + notable.join('、') + '。确认清空?') + ) { + return; // 取消:本地态与引擎均不变 + } + setCandidateItems([]); update({ 'activiti:candidateUsers': undefined }); return; } - update({ - 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMetaRef.current), - }); + setCandidateItems(items); + update({ 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMeta) }); } // ── 会签写回 ─────────────────────────────────────────────────────────────── @@ -348,17 +425,18 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { const collection = buildCandidateExpression( next.items, 'multiInstance' as CandidateVariant, - cosignMetaRef.current, + cosignMeta, ); - const completionCondition = moddle.create('bpmn:FormalExpression', { - body: completionBody(next.completionType, next.completionN), - }); - const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', { - isSequential: false, + const props: Record = { + isSequential: next.isSequential, 'activiti:collection': collection, - 'activiti:elementVariable': 'assignee', - completionCondition, - }); + }; + // elementVariable 为空(真实库缺省态)则省略,不凭空写空属性。 + if (next.elementVariable) props['activiti:elementVariable'] = next.elementVariable; + const body = completionBodyFor(next); + // body 为空(原本无 completionCondition)则不发出该子元素,保真。 + if (body) props.completionCondition = moddle.create('bpmn:FormalExpression', { body }); + const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', props); update({ loopCharacteristics: loop }); } @@ -372,6 +450,15 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { function addExtAttr() { const key = newAttr.key.trim(); if (!key) return; + if (!key.startsWith('activiti:') && !key.startsWith('flowable:')) { + toast('扩展属性键必须以 activiti: 或 flowable: 开头', 'warn'); + return; + } + const local = key.slice(key.indexOf(':') + 1); + if (RESERVED_EXT_LOCALNAMES.has(local)) { + toast('该属性有专用控件,请用上方对应控件编辑', 'warn'); + return; + } setExtAttrs((prev) => { const rest = prev.filter((a) => a.key !== key); return [...rest, { key, value: newAttr.value }]; @@ -428,6 +515,8 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { ); } + const candidateBadges = notableMeta(candidateMeta); + return (
+ {candidateBadges.length > 0 ? ( +
+ 含业务配置:{candidateBadges.join('、')}(清空办理人会一并移除) +
+ ) : null} + {candidateNonStandard ? ( +
+ 当前为非标准办理人表达式,编辑将覆盖原表达式。 +
+ ) : null}
@@ -453,12 +558,31 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { {cosign.enabled ? (
+ + writeCosign({ ...cosign, items })} /> -
+
完成条件 setFormKeyFilter(e.target.value)} + style={{ width: '100%', marginBottom: 6 }} + /> diff --git a/src/pages/ProcessModelerPage.test.tsx b/src/pages/ProcessModelerPage.test.tsx index ce91aa3..f68c6b8 100644 --- a/src/pages/ProcessModelerPage.test.tsx +++ b/src/pages/ProcessModelerPage.test.tsx @@ -3,9 +3,10 @@ import { render, screen, waitFor, fireEvent, act } from '@testing-library/react' import { MemoryRouter } from 'react-router-dom'; import { SYNTHETIC_BPMN } from '../modeler/moddle/fixtures/synthetic-full-surface.bpmn'; -// bpmn-js Modeler:jsdom 跑不动真渲染,stub 成类(可断言 importXML/destroy 调用)。 -const { importXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor } = vi.hoisted(() => { +// bpmn-js Modeler:jsdom 跑不动真渲染,stub 成类(可断言 importXML/saveXML/destroy 调用)。 +const { importXMLMock, saveXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor } = vi.hoisted(() => { const importXMLMock = vi.fn(); + const saveXMLMock = vi.fn(); const destroyMock = vi.fn(); const attachToMock = vi.fn(); const getMock = vi.fn((service: string) => { @@ -16,11 +17,12 @@ const { importXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor } const onMock = vi.fn(); const ModelerCtor = vi.fn().mockImplementation(() => ({ importXML: importXMLMock, + saveXML: saveXMLMock, destroy: destroyMock, get: getMock, on: onMock, })); - return { importXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor }; + return { importXMLMock, saveXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor }; }); vi.mock('bpmn-js/lib/Modeler', () => ({ default: ModelerCtor })); // 标准属性面板模块只作为 additionalModules 配置项传入被 mock 的 Modeler,永不真正执行。 @@ -33,7 +35,13 @@ vi.mock('../api/processModeler', () => ({ fetchProcDefSourceByKey: vi.fn(), fetchProcessOptions: vi.fn(), // Eip4Panel(右栏叠板)挂载时拉 formKey 数据源——mock 成空列表避免真请求。 - fetchWfTemplates: vi.fn(() => Promise.resolve([])), + fetchWfTemplates: vi.fn(() => Promise.resolve({ templates: [], degraded: false })), + listModels: vi.fn(() => Promise.resolve([])), + getModel: vi.fn(), + createDraft: vi.fn(() => Promise.resolve('NEW-1')), + saveDraft: vi.fn(() => Promise.resolve()), + draftFromProcDef: vi.fn(() => Promise.resolve('FP-1')), + deleteDraft: vi.fn(() => Promise.resolve()), })); vi.mock('../auth/token', async (importOriginal) => ({ ...(await importOriginal()), @@ -41,12 +49,28 @@ vi.mock('../auth/token', async (importOriginal) => ({ })); import { ProcessModelerPage } from './ProcessModelerPage'; -import { fetchProcDefSource, fetchProcDefSourceByKey, fetchProcessOptions } from '../api/processModeler'; +import { + fetchProcDefSource, + fetchProcDefSourceByKey, + fetchProcessOptions, + listModels, + getModel, + createDraft, + saveDraft, + draftFromProcDef, + deleteDraft, +} from '../api/processModeler'; import { getProfile } from '../auth/token'; const mSource = vi.mocked(fetchProcDefSource); const mSourceByKey = vi.mocked(fetchProcDefSourceByKey); const mOptions = vi.mocked(fetchProcessOptions); +const mListModels = vi.mocked(listModels); +const mGetModel = vi.mocked(getModel); +const mCreateDraft = vi.mocked(createDraft); +const mSaveDraft = vi.mocked(saveDraft); +const mFromProcDef = vi.mocked(draftFromProcDef); +const mDeleteDraft = vi.mocked(deleteDraft); const mProfile = vi.mocked(getProfile); function renderPage(initialPath = '/process-modeler') { @@ -59,6 +83,7 @@ function renderPage(initialPath = '/process-modeler') { beforeEach(() => { importXMLMock.mockReset().mockResolvedValue(undefined); + saveXMLMock.mockReset().mockResolvedValue({ xml: '' }); destroyMock.mockReset(); attachToMock.mockReset(); getMock.mockClear(); @@ -67,6 +92,17 @@ beforeEach(() => { mSource.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } }); mSourceByKey.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } }); mOptions.mockReset().mockResolvedValue([]); + mListModels.mockReset().mockResolvedValue([]); + mGetModel.mockReset().mockResolvedValue({ + found: true, + bpmnXml: SYNTHETIC_BPMN, + metaInfo: JSON.stringify({ eip4IdMap: { '总包合同交底': 'Proc_zbht' } }), + key: '总包合同交底', + }); + mCreateDraft.mockReset().mockResolvedValue('NEW-1'); + mSaveDraft.mockReset().mockResolvedValue(undefined); + mFromProcDef.mockReset().mockResolvedValue('FP-1'); + mDeleteDraft.mockReset().mockResolvedValue(undefined); mProfile.mockReset().mockReturnValue({ userId: 'ADMIN', account: 'admin', name: '管理员', roles: [] }); }); @@ -158,4 +194,90 @@ describe('ProcessModelerPage', () => { expect(Object.keys(opts.moddleExtensions)).toEqual(['activiti']); expect(opts.additionalModules).toHaveLength(2); }); + + // ── T2.5 存草稿 ──────────────────────────────────────────────────────────── + const saveBtn = () => screen.getByTestId('process-modeler-save-draft'); + + it('存草稿(存量按 key,无 modelId):createDraft 带 eip4IdMap 进 metaInfo,不走 from-procdef', async () => { + renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底')); + await waitFor(() => expect(importXMLMock).toHaveBeenCalled()); + await waitFor(() => expect(saveBtn()).not.toBeDisabled()); + fireEvent.click(saveBtn()); + await waitFor(() => expect(mCreateDraft).toHaveBeenCalled()); + const body = mCreateDraft.mock.calls[0][0]; + expect(body.bpmnXml).toBe(''); + expect(JSON.parse(body.metaInfo!).eip4IdMap).toEqual({ '总包合同交底': 'Proc_zbht' }); + expect(mFromProcDef).not.toHaveBeenCalled(); + }); + + it('存草稿(存量按 procDefId,无 modelId):from-procdef 建草稿(后端 metaInfo)再 PUT', async () => { + renderPage('/process-modeler?procDefId=PD-1'); + await waitFor(() => expect(importXMLMock).toHaveBeenCalled()); + await waitFor(() => expect(saveBtn()).not.toBeDisabled()); + fireEvent.click(saveBtn()); + await waitFor(() => expect(mFromProcDef).toHaveBeenCalledWith('PD-1')); + await waitFor(() => expect(mSaveDraft).toHaveBeenCalledWith('FP-1', { bpmnXml: '' })); + expect(mCreateDraft).not.toHaveBeenCalled(); + }); + + it('第二次保存(已有 modelId):走 saveDraft(PUT),不重发 metaInfo', async () => { + renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底')); + await waitFor(() => expect(importXMLMock).toHaveBeenCalled()); + await waitFor(() => expect(saveBtn()).not.toBeDisabled()); + fireEvent.click(saveBtn()); // 首次:createDraft → modelId=NEW-1 + await waitFor(() => expect(mCreateDraft).toHaveBeenCalled()); + await waitFor(() => expect(saveBtn()).not.toBeDisabled()); // saving 复位 + fireEvent.click(saveBtn()); // 二次:PUT NEW-1 + await waitFor(() => expect(mSaveDraft).toHaveBeenCalledWith('NEW-1', { bpmnXml: '' })); + const putBody = mSaveDraft.mock.calls[mSaveDraft.mock.calls.length - 1][1]; + expect('metaInfo' in putBody).toBe(false); // 不重发 metaInfo,保住 eip4IdMap + }); + + it('打开草稿(?modelId=)走 getModel→importXML', async () => { + renderPage('/process-modeler?modelId=MD-7'); + await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('MD-7')); + await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN)); + expect(mSource).not.toHaveBeenCalled(); + expect(mSourceByKey).not.toHaveBeenCalled(); + }); + + // ── T2.5 草稿列表打开 ────────────────────────────────────────────────────── + it('草稿 tab:列出草稿→点「打开」→setParams(modelId)→getModel→importXML', async () => { + mListModels.mockResolvedValue([{ id: 'MD-1', name: '草稿甲', key: 'k1' }]); + renderPage(); + fireEvent.click(screen.getByTestId('process-modeler-tab-draft')); + await waitFor(() => expect(mListModels).toHaveBeenCalled()); + expect(await screen.findByText('草稿甲')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('process-modeler-draft-open-0')); + await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('MD-1')); + await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN)); + }); + + // ── T2.5 草稿删除(前端;后端 DELETE 端点待补) ────────────────────────────── + it('草稿删除:confirm=确认→deleteDraft→列表刷新', async () => { + const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); + mListModels.mockResolvedValue([{ id: 'MD-1', name: '草稿甲', key: 'k1' }]); + renderPage(); + fireEvent.click(screen.getByTestId('process-modeler-tab-draft')); + await screen.findByText('草稿甲'); + const before = mListModels.mock.calls.length; + fireEvent.click(screen.getByTestId('process-modeler-draft-delete-0')); + await waitFor(() => expect(mDeleteDraft).toHaveBeenCalledWith('MD-1')); + await waitFor(() => expect(mListModels.mock.calls.length).toBeGreaterThan(before)); // 刷新 + confirmSpy.mockRestore(); + }); + + it('草稿删除:confirm=取消→不调 deleteDraft', async () => { + const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false); + mListModels.mockResolvedValue([{ id: 'MD-1', name: '草稿甲', key: 'k1' }]); + renderPage(); + fireEvent.click(screen.getByTestId('process-modeler-tab-draft')); + await screen.findByText('草稿甲'); + fireEvent.click(screen.getByTestId('process-modeler-draft-delete-0')); + await act(async () => { + await Promise.resolve(); + }); + expect(mDeleteDraft).not.toHaveBeenCalled(); + confirmSpy.mockRestore(); + }); }); diff --git a/src/pages/ProcessModelerPage.tsx b/src/pages/ProcessModelerPage.tsx index ece88ba..71f5f69 100644 --- a/src/pages/ProcessModelerPage.tsx +++ b/src/pages/ProcessModelerPage.tsx @@ -1,7 +1,8 @@ -// 在线流程 Modeler(B3)——可编辑 BPMN 设计器页骨架。 -// 本阶段(T1.5)只做:admin 门 + 三栏布局 + bpmn-js Modeler 挂载 + 存量流程只读载入。 -// EIP4 定制侧板(办理人/会签/formKey…)是 T2.4,本页右上只放占位容器; -// 「保存草稿」「发布」是 T2.5/T3.3,本页顶栏先放 disabled 占位按钮。 +// 在线流程 Modeler(B3)——可编辑 BPMN 设计器页。 +// T1.5 骨架:admin 门 + 三栏布局 + bpmn-js Modeler + 存量只读载入。 +// T2.4:右栏叠 EIP4 定制侧板(办理人/会签/formKey…)。 +// T2.5:顶栏「保存草稿」可用(saveXML→create/from-procdef→PUT,metaInfo 带 eip4IdMap); +// 打开器加「草稿」tab(listModels→?modelId=→getModel→importXML)+ 草稿删除。 import { useEffect, useRef, useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import Modeler from 'bpmn-js/lib/Modeler'; @@ -16,14 +17,23 @@ import { fetchProcDefSource, fetchProcDefSourceByKey, fetchProcessOptions, + listModels, + getModel, + createDraft, + saveDraft, + draftFromProcDef, + deleteDraft, type ProcessOption, + type ModelSummary, } from '../api/processModeler'; import { Eip4Panel, type PanelModeler } from '../modeler/Eip4Panel'; +import { toast } from '../components/ui'; // bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON // 会与官方选项类型产生摩擦;照 ProcessDiagram 惯例把构造器收窄为本页用到的最小契约再实例化。 interface ModelerLike { importXML(xml: string): Promise; + saveXML(opts?: { format?: boolean }): Promise<{ xml: string }>; destroy(): void; get(service: string): unknown; on(event: string, cb: (e: unknown) => void): void; @@ -32,33 +42,56 @@ const ModelerCtor = Modeler as unknown as new (options: Record) type LoadState = 'idle' | 'loading' | 'ready' | 'error'; +/** 从草稿 metaInfo JSON 串取 eip4IdMap(发布还原用;防御性)。 */ +function parseMetaIdMap(metaInfo?: string): Record { + if (!metaInfo) return {}; + try { + const o = JSON.parse(metaInfo) as { eip4IdMap?: unknown }; + return o && typeof o.eip4IdMap === 'object' && o.eip4IdMap + ? (o.eip4IdMap as Record) + : {}; + } catch { + return {}; + } +} + export function ProcessModelerPage() { const profile = getProfile(); const isAdmin = isAdminProfile(profile); const navigate = useNavigate(); const [params, setParams] = useSearchParams(); - // 打开存量流程两条路:?procDefId=(source=processDefinition,id 即 procDefId) - // 或 ?procKey=(source=model/history,按流程 key 载入最新版)。 + // 打开三条路:?procDefId=(source=processDefinition)/ ?procKey=(存量按 key)/ ?modelId=(草稿)。 const procDefId = params.get('procDefId') ?? ''; const procKey = params.get('procKey') ?? ''; - const hasTarget = !!procDefId || !!procKey; + const modelIdParam = params.get('modelId') ?? ''; + const hasTarget = !!procDefId || !!procKey || !!modelIdParam; const canvasRef = useRef(null); const panelRef = useRef(null); const modelerRef = useRef(null); // Modeler 实例入 state 以驱动 Eip4Panel 重渲染(selection.changed 订阅需要真实例)。 const [modelerReady, setModelerReady] = useState(null); - // 净化映射 原id→净化id:本阶段仅暂存,发布还原(T3.x)时用。 + // 净化映射 原id→净化id:存量载入时暂存,保存草稿写进 metaInfo、发布还原(T3.x)时用。 const idMapRef = useRef>({}); + // 当前草稿 modelId(打开草稿或首次保存后写入);空=尚未落草稿。 + const modelIdRef = useRef(''); + // 当前载入流程的 key(存量 procDefKey / 草稿 key)——新建草稿的 name/key 源。 + const loadedKeyRef = useRef(''); const [loadState, setLoadState] = useState('idle'); const [loadError, setLoadError] = useState(''); + const [saving, setSaving] = useState(false); const [options, setOptions] = useState([]); const [optionsError, setOptionsError] = useState(''); + // 打开器 tab:存量流程 / 草稿。 + const [openTab, setOpenTab] = useState<'existing' | 'draft'>('existing'); + const [drafts, setDrafts] = useState([]); + const [draftsError, setDraftsError] = useState(''); + const [draftsReload, setDraftsReload] = useState(0); - // 未打开任何流程时拉存量流程选项(数据源复用旧 ProcessSelectDialog 端点)。 + // 未打开任何流程 + 存量 tab 时拉存量流程选项(复用旧 ProcessSelectDialog 端点)。 useEffect(() => { - if (!isAdmin || hasTarget) return; + if (!isAdmin || hasTarget || openTab !== 'existing') return; let alive = true; fetchProcessOptions() .then((opts) => alive && setOptions(opts)) @@ -66,9 +99,22 @@ export function ProcessModelerPage() { return () => { alive = false; }; - }, [isAdmin, hasTarget]); + }, [isAdmin, hasTarget, openTab]); - // 有目标(procDefId 或 procKey)时挂载 Modeler 并载入净化后的存量 BPMN。 + // 未打开任何流程 + 草稿 tab 时拉草稿列表。 + useEffect(() => { + if (!isAdmin || hasTarget || openTab !== 'draft') return; + let alive = true; + setDraftsError(''); + listModels() + .then((d) => alive && setDrafts(d)) + .catch(() => alive && setDraftsError('草稿列表加载失败')); + return () => { + alive = false; + }; + }, [isAdmin, hasTarget, openTab, draftsReload]); + + // 有目标时挂载 Modeler 并载入 BPMN(草稿→getModel / 存量→source)。 useEffect(() => { if (!isAdmin || !hasTarget) return; let alive = true; @@ -78,10 +124,18 @@ export function ProcessModelerPage() { (async () => { try { - // procDefId 优先(source=processDefinition);否则按 key(source=model/history)。 - const src = procDefId - ? await fetchProcDefSource(procDefId) - : await fetchProcDefSourceByKey(procKey); + // 三条路统一成 {found,bpmnXml,idMap,key}。 + let src: { found: boolean; bpmnXml?: string; idMap?: Record; key?: string }; + if (modelIdParam) { + const m = await getModel(modelIdParam); + src = { found: m.found, bpmnXml: m.bpmnXml, idMap: parseMetaIdMap(m.metaInfo), key: m.key }; + } else if (procDefId) { + const s = await fetchProcDefSource(procDefId); + src = { found: s.found, bpmnXml: s.bpmnXml, idMap: s.idMap, key: s.procDefKey }; + } else { + const s = await fetchProcDefSourceByKey(procKey); + src = { found: s.found, bpmnXml: s.bpmnXml, idMap: s.idMap, key: s.procDefKey }; + } if (!alive) return; if (!src.found || !src.bpmnXml) { setLoadError('未找到该流程的 BPMN 源(可能未部署或无布局信息)'); @@ -105,9 +159,7 @@ export function ProcessModelerPage() { // 扩展属性冲突静默丢弃 userTask;单载 activiti 时 flowable 文档经 moddle lax 往返零丢失。 moddleExtensions: { activiti: activitiModdle }, }); - // ⚠️ 显式 attachTo:live 实证——只靠构造参数 propertiesPanel.parent,面板从不挂载 - // (.bio-properties-panel 在 document 中为 0;构造时 ref 时序/传对象非 element 皆可致此)。 - // attachTo 容器 DOM 是 bpmn-js-properties-panel 的规范补救。放在 importXML 前,alive 内。 + // ⚠️ 显式 attachTo:live 实证——只靠构造参数 propertiesPanel.parent,面板从不挂载。 if (panelRef.current) { try { (modeler.get('propertiesPanel') as { attachTo(el: HTMLElement): void }).attachTo(panelRef.current); @@ -116,6 +168,9 @@ export function ProcessModelerPage() { } } idMapRef.current = src.idMap ?? {}; + loadedKeyRef.current = src.key ?? ''; + // 草稿路:记住 modelId(后续保存走 PUT);存量路:清空(首次保存新建草稿)。 + modelIdRef.current = modelIdParam || ''; await modeler.importXML(src.bpmnXml); if (!alive) return; modelerRef.current = modeler; @@ -147,7 +202,37 @@ export function ProcessModelerPage() { modelerRef.current = null; setModelerReady(null); }; - }, [isAdmin, procDefId, procKey]); + }, [isAdmin, procDefId, procKey, modelIdParam]); + + // 保存草稿:saveXML → 有 modelId 走 PUT(不重发 metaInfo,保住 eip4IdMap); + // 无 modelId:存量按 procDefId 走 from-procdef(后端写 metaInfo)再 PUT 覆盖为编辑源; + // 存量按 key / 新建走 create(前端带 eip4IdMap 进 metaInfo)。 + async function handleSaveDraft() { + const modeler = modelerRef.current; + if (!modeler || saving) return; + setSaving(true); + try { + const { xml } = await modeler.saveXML({ format: true }); + let modelId = modelIdRef.current; + if (modelId) { + await saveDraft(modelId, { bpmnXml: xml }); + } else if (procDefId) { + modelId = await draftFromProcDef(procDefId); + await saveDraft(modelId, { bpmnXml: xml }); + modelIdRef.current = modelId; + } else { + const key = loadedKeyRef.current || procKey || 'new_process'; + const metaInfo = JSON.stringify({ eip4IdMap: idMapRef.current, originalKey: key }); + modelId = await createDraft({ name: key, key, bpmnXml: xml, metaInfo }); + modelIdRef.current = modelId; + } + toast('已保存草稿', 'ok'); + } catch { + toast('保存草稿失败', 'err'); + } finally { + setSaving(false); + } + } if (!isAdmin) { return
流程设计器仅管理员可用。
; @@ -159,7 +244,6 @@ export function ProcessModelerPage() { ); // 选择器按 source 分派:processDefinition→?procDefId=;其余→?procKey=。 - // 用索引取回选项对象(避免把 id/key 直接塞进